Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(boot): keep the teardown bound of a failed boot alive
Yudhi Armyndharisba07f0252f9e
diff --git a/src/config/bootstrap-fatal.spec.ts b/src/config/bootstrap-fatal.spec.tsindex 4d7fbe2fc..5e0bf5d19 100644--- a/src/config/bootstrap-fatal.spec.ts+++ b/src/config/bootstrap-fatal.spec.ts@@ -46,6 +46,33 @@ describe('runBootstrapOrExit', () => {expect(order).toEqual(['close', 'exit']);});+ // A teardown parked on a promise that holds no handle leaves nothing to keep the event loop alive but+ // this timer. If it were unref'd the process would exit 0, a clean exit of a boot that failed.+ it('holds the event loop open with its bound on a teardown that never settles', async () => {+ const { deps, exitCalls } = makeDeps();+ const timers: NodeJS.Timeout[] = [];+ const realSetTimeout = global.setTimeout;+ const spy = jest.spyOn(global, 'setTimeout').mockImplementation((...args: Parameters<typeof setTimeout>) => {+ const timer = realSetTimeout(...args);+ timers.push(timer);+ return timer;+ });++ try {+ await runBootstrapOrExit(() => Promise.reject(new Error('listen EADDRINUSE')), {+ ...deps,+ closeApp: () => new Promise<void>(() => undefined),+ closeTimeoutMs: 20,+ });+ } finally {+ spy.mockRestore();+ }++ expect(exitCalls).toEqual([1]);+ expect(timers.length).toBeGreaterThan(0);+ expect(timers.every(timer => timer.hasRef())).toBe(true);+ });+it('never logs, tears down, or exits on a successful boot', async () => {const { deps, logs, exitCalls } = makeDeps();const closeApp = jest.fn().mockResolvedValue(undefined);diff --git a/src/config/bootstrap-fatal.ts b/src/config/bootstrap-fatal.tsindex e1f0e63c4..e6ce6eafe 100644--- a/src/config/bootstrap-fatal.ts+++ b/src/config/bootstrap-fatal.ts@@ -60,8 +60,10 @@ export async function runBootstrapOrExit(bootstrap: () => Promise<unknown>, depsconst closeApp = deps.closeApp;await Promise.race([Promise.resolve().then(() => closeApp()),+ // Not unref'd: a teardown parked on a promise that holds no handle would let the loop drain, and+ // the process would exit 0 on its own before the exit below ran.new Promise<void>(resolve => {- setTimeout(resolve, deps.closeTimeoutMs ?? DEFAULT_BOOTSTRAP_CLOSE_TIMEOUT_MS).unref();+ setTimeout(resolve, deps.closeTimeoutMs ?? DEFAULT_BOOTSTRAP_CLOSE_TIMEOUT_MS);}),]);} catch {