From 198e62944f99239a755ef22bfd3fb960d9cf13c8 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Tue, 18 Aug 2026 09:16:27 -0500 Subject: [PATCH] fix(shutdown): arm the teardown timer before the callback that clears it MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `runTeardown` declared `finish` above the `timer` it clears, so the reference held only because every caller — the timer's own callback and `teardown.run().then()` — happens to be asynchronous. That is correct by timing rather than by construction, which is what #20 asked to remove from this file; `closeApp` twenty lines below already arms its timer first and carries a comment explaining why that direction is the safe one. Reversing the order here leaves both shutdown paths resting the same forward reference on the same guarantee: setTimeout cannot invoke its callback synchronously. No behaviour changes. Closes #20 Signed-off-by: Diego Resendez --- src/app/index.ts | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/app/index.ts b/src/app/index.ts index 836bff1..8c6e291 100644 --- a/src/app/index.ts +++ b/src/app/index.ts @@ -1095,13 +1095,9 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe return new Promise((resolve) => { let settled = false; - const finish = (): void => { - if (settled) return; - settled = true; - clearTimeout(timer); - resolve(); - }; - + // Armed before `finish` exists, for the reason spelled out in `closeApp` below: setTimeout + // cannot fire synchronously, so the forward reference to `finish` rests on a guarantee, while + // the reverse ordering would rest on `teardown.run().then()` deferring. const timer = setTimeout( () => { if (settled) return; @@ -1114,6 +1110,14 @@ function runTeardown(teardown: TeardownRegistry, logger: Logger, budgetMs: numbe ); timer.unref?.(); + + const finish = (): void => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(); + }; + void teardown.run(logger).then(finish, finish); }); } -- 2.54.1