fix: address cleanup review lifecycle and connection settings

This commit is contained in:
Boki 2026-10-26 16:53:53 -04:00
parent 512f2f1c32
commit 9d3e1a7bb9
11 changed files with 264 additions and 17 deletions

View file

@ -34,14 +34,33 @@ export class ServiceLifecycleManager {
if (!service) {
return Promise.resolve();
}
if (this.initializing.has(service)) {
throw new Error(`${name} initialization is already in progress`);
}
this.initializing.add(service);
const entry = { name, service, settled: false };
started.push(entry);
// A timeout cannot cancel connect(). Keep ownership until it settles,
// including resources allocated by an initializer that later rejects.
const initialization = this.initializeService(name, service).finally(async () => {
const initialization = (async () => {
// A completed shutdown belongs to the preceding connection lifetime.
// Wait for an in-flight close before starting a fresh lifetime.
const previousCleanup = this.cleanup.get(service);
if (previousCleanup) {
await previousCleanup;
}
if (!failed) {
this.cleanup.delete(service);
await this.initializeService(name, service);
}
})().finally(async () => {
entry.settled = true;
if (failed) {
await this.cleanupOnce(name, service);
try {
if (failed) {
await this.cleanupOnce(name, service);
}
} finally {
this.initializing.delete(service);
}
});
let timer: ReturnType<typeof setTimeout>;
@ -61,12 +80,28 @@ export class ServiceLifecycleManager {
failed = true;
// Only settled work can be released finally. Pending work retains the
// cleanup continuation above, so startup need not wait on a hung connect.
await Promise.allSettled(
const rollback = Promise.allSettled(
started
.filter(entry => entry.settled)
.reverse()
.map(({ name, service }) => this.cleanupOnce(name, service))
);
let cleanupTimer: ReturnType<typeof setTimeout> | undefined;
try {
// A hanging disconnect must not turn a bounded startup failure into a
// permanently pending build. Keep the cleanup promise owned after this cap.
await Promise.race([
rollback,
new Promise<void>(resolve => {
cleanupTimer = setTimeout(() => {
this.logger.warn(`Startup rollback still pending after ${timeout}ms`);
resolve();
}, timeout);
}),
]);
} finally {
clearTimeout(cleanupTimer);
}
throw error;
} finally {
for (const clear of cancelTimers) {
@ -75,6 +110,7 @@ export class ServiceLifecycleManager {
}
}
private readonly initializing = new WeakSet<ServiceWithLifecycle>();
private readonly cleanup = new WeakMap<ServiceWithLifecycle, Promise<void>>();
private cleanupOnce(name: string, service: ServiceWithLifecycle): Promise<void> {