From f2e14af0a80a526699272e8c2b1f3054ef47f91d Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Sat, 26 Sep 2026 00:36:28 +0900 Subject: [PATCH] fix(service-worker): report a drain timeout as CLIENT_DRAIN_TIMEOUT (06-07) The worker sent ACTIVATE_REJECTED for a client refusal, a drain timeout and a failed skipWaiting() alike, so the page blamed a dirty tab. Two worker reply kinds now carry the timeout and the commit failure. Co-Authored-By: Claude Opus 5.5 --- .../service-worker-lifecycle.ts | 41 +++++++---- .../service-worker-page-controller.ts | 16 +++- .../service-worker/service-worker-protocol.ts | 2 + src/contracts/service-worker.ts | 6 ++ tests/unit/service-worker-runtime.test.ts | 73 +++++++++++++++++++ 5 files changed, 121 insertions(+), 17 deletions(-) diff --git a/src/adapters/service-worker/service-worker-lifecycle.ts b/src/adapters/service-worker/service-worker-lifecycle.ts index 7b633be9..9d7641c3 100644 --- a/src/adapters/service-worker/service-worker-lifecycle.ts +++ b/src/adapters/service-worker/service-worker-lifecycle.ts @@ -119,10 +119,12 @@ export function createServiceWorkerRuntime( ), ); const consumedNonces = new Set(); + /** 06-07. Why a drain ended, so the requester is told the real reason. */ + type DrainOutcome = "DRAINED" | "REJECTED" | "TIMED_OUT"; type PendingActivation = Readonly<{ expectedClientIds: ReadonlySet; acknowledgedClientIds: Set; - resolve(drained: boolean): void; + resolve(outcome: DrainOutcome): void; timer: ReturnType; }>; const pendingActivations = new Map(); @@ -346,8 +348,12 @@ export function createServiceWorkerRuntime( isClientWithinRegistrationScope(client.url, scope.registrationScope), ); const drained = await drainClients(clients, nonce); - if (!drained) { - notifyClients(clients, "ACTIVATE_REJECTED", nonce); + if (drained !== "DRAINED") { + notifyClients( + clients, + drained === "REJECTED" ? "ACTIVATE_REJECTED" : "ACTIVATE_DRAIN_TIMEOUT", + nonce, + ); return "REJECTED"; } @@ -357,7 +363,7 @@ export function createServiceWorkerRuntime( try { await scope.skipWaiting(); } catch { - notifyClients(clients, "ACTIVATE_REJECTED", nonce); + notifyClients(clients, "ACTIVATE_COMMIT_FAILED", nonce); return "REJECTED"; } // Post-commit notifications are per-client best effort. @@ -375,7 +381,12 @@ export function createServiceWorkerRuntime( */ function notifyClients( clients: readonly WorkerClientLike[], - kind: "ACTIVATE_REJECTED" | "ACTIVATE_ACCEPTED" | "ACTIVATED_RELOAD_REQUIRED", + kind: + | "ACTIVATE_REJECTED" + | "ACTIVATE_DRAIN_TIMEOUT" + | "ACTIVATE_COMMIT_FAILED" + | "ACTIVATE_ACCEPTED" + | "ACTIVATED_RELOAD_REQUIRED", nonce: string, ): void { for (const client of clients) { @@ -396,14 +407,14 @@ export function createServiceWorkerRuntime( async function drainClients( clients: readonly WorkerClientLike[], nonce: string, - ): Promise { + ): Promise { // SW-07. No in-scope client means nothing dirty to drain, so the set is // vacuously drained. A `clients.matchAll()` failure still rejects upstream. - if (clients.length === 0) return true; - const drained = new Promise((resolve) => { + if (clients.length === 0) return "DRAINED"; + const drained = new Promise((resolve) => { const timer = setTimeout(() => { pendingActivations.delete(nonce); - resolve(false); + resolve("TIMED_OUT"); }, SERVICE_WORKER_BOUNDS.clientDrainMs); pendingActivations.set( nonce, @@ -417,7 +428,7 @@ export function createServiceWorkerRuntime( }); // SW-08. A client that cannot receive the drain request can never // acknowledge it, so it fails immediately instead of holding the pending - // state until the timeout. + // state until the timeout. Like a silent client it did not refuse (06-07). // R-6.2. Clients run whatever build they loaded, which is usually not the // requester's. The request is untargeted; replies are paired by this // worker's buildId, the nonce and the exact client id. @@ -432,7 +443,7 @@ export function createServiceWorkerRuntime( ); } catch { const pending = pendingActivations.get(nonce); - if (pending) settlePendingActivation(nonce, pending, false); + if (pending) settlePendingActivation(nonce, pending, "TIMED_OUT"); return await drained; } } @@ -454,14 +465,14 @@ export function createServiceWorkerRuntime( return; } if (parsed.message.kind === "ACTIVATE_REJECTED") { - settlePendingActivation(parsed.message.nonce, pending, false); + settlePendingActivation(parsed.message.nonce, pending, "REJECTED"); return; } pending.acknowledgedClientIds.add(sourceClientId); if ( pending.acknowledgedClientIds.size === pending.expectedClientIds.size ) { - settlePendingActivation(parsed.message.nonce, pending, true); + settlePendingActivation(parsed.message.nonce, pending, "DRAINED"); } } @@ -516,11 +527,11 @@ export function createServiceWorkerRuntime( function settlePendingActivation( nonce: string, pending: PendingActivation, - drained: boolean, + outcome: DrainOutcome, ): void { clearTimeout(pending.timer); pendingActivations.delete(nonce); - pending.resolve(drained); + pending.resolve(outcome); } } diff --git a/src/adapters/service-worker/service-worker-page-controller.ts b/src/adapters/service-worker/service-worker-page-controller.ts index 5f33b034..c9c5f1e1 100644 --- a/src/adapters/service-worker/service-worker-page-controller.ts +++ b/src/adapters/service-worker/service-worker-page-controller.ts @@ -417,6 +417,8 @@ export function createServiceWorkerPageController( if ( parsed.message.nonce !== nonce || (kind !== "ACTIVATE_REJECTED" && + kind !== "ACTIVATE_DRAIN_TIMEOUT" && + kind !== "ACTIVATE_COMMIT_FAILED" && kind !== "ACTIVATE_ACCEPTED" && kind !== "ACTIVATED_RELOAD_REQUIRED") ) { @@ -438,7 +440,9 @@ export function createServiceWorkerPageController( } // R-6.1. ACCEPTED and RELOAD_REQUIRED are sent after skipWaiting(), // so the registration may already show this worker as active. - const committed = kind !== "ACTIVATE_REJECTED"; + const committed = + kind === "ACTIVATE_ACCEPTED" || + kind === "ACTIVATED_RELOAD_REQUIRED"; if ( registration?.waiting !== waiting && !(committed && registration?.active === waiting) @@ -446,10 +450,18 @@ export function createServiceWorkerPageController( finish(Object.freeze({ kind: "PROTOCOL_MISMATCH" as const })); return; } + // 06-07. Only a client's explicit refusal is a dirty client. finish( committed ? Object.freeze({ kind: "ACTIVATED_RELOAD_REQUIRED" as const }) - : Object.freeze({ kind: "BLOCKED_DIRTY_CLIENT" as const }), + : kind === "ACTIVATE_DRAIN_TIMEOUT" + ? Object.freeze({ kind: "CLIENT_DRAIN_TIMEOUT" as const }) + : kind === "ACTIVATE_COMMIT_FAILED" + ? Object.freeze({ + kind: "FAILED" as const, + code: "ACTIVATION_COMMIT_FAILED", + }) + : Object.freeze({ kind: "BLOCKED_DIRTY_CLIENT" as const }), ); }; const onStop = () => diff --git a/src/adapters/service-worker/service-worker-protocol.ts b/src/adapters/service-worker/service-worker-protocol.ts index 74d86d03..45ebec3b 100644 --- a/src/adapters/service-worker/service-worker-protocol.ts +++ b/src/adapters/service-worker/service-worker-protocol.ts @@ -19,6 +19,8 @@ const MESSAGE_KINDS: ReadonlySet = new Set([ "ACTIVATE_REQUEST", "ACTIVATE_ACCEPTED", "ACTIVATE_REJECTED", + "ACTIVATE_DRAIN_TIMEOUT", + "ACTIVATE_COMMIT_FAILED", "CLIENT_DRAIN_REQUEST", "CLIENT_DRAINED", "ACTIVATED_RELOAD_REQUIRED", diff --git a/src/contracts/service-worker.ts b/src/contracts/service-worker.ts index 51004f16..b0f1f62a 100644 --- a/src/contracts/service-worker.ts +++ b/src/contracts/service-worker.ts @@ -70,6 +70,12 @@ export type ServiceWorkerMessageKind = | "ACTIVATE_REQUEST" | "ACTIVATE_ACCEPTED" | "ACTIVATE_REJECTED" + /** + * 06-07. Worker replies that are not a client's refusal. A page of an older + * build does not know them and ends at its own CLIENT_DRAIN_TIMEOUT. + */ + | "ACTIVATE_DRAIN_TIMEOUT" + | "ACTIVATE_COMMIT_FAILED" | "CLIENT_DRAIN_REQUEST" | "CLIENT_DRAINED" | "ACTIVATED_RELOAD_REQUIRED" diff --git a/tests/unit/service-worker-runtime.test.ts b/tests/unit/service-worker-runtime.test.ts index a2fd62fa..d797d6c6 100644 --- a/tests/unit/service-worker-runtime.test.ts +++ b/tests/unit/service-worker-runtime.test.ts @@ -1575,6 +1575,79 @@ describe("page ↔ worker activation seam", () => { vi.useRealTimers(); } }); + + // 06-07. A window without a page controller (a tab showing /config.json, a + // frozen background tab) never answers the drain. That is a timeout, not a + // tab with unsaved edits. + it("reports a window that never answers as CLIENT_DRAIN_TIMEOUT", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + seam.workerScope.clients.matchAll.mockResolvedValue([ + ...seam.tabs.map((tab) => tab.client), + { id: "raw-json", url: `${ORIGIN}/config.json`, postMessage() {} }, + ]); + + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs); + + await expect(activation).resolves.toEqual({ + kind: "CLIENT_DRAIN_TIMEOUT", + }); + expect(seam.workerScope.skipWaiting).not.toHaveBeenCalled(); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); + + it("reports a failed skipWaiting() as FAILED, not as a dirty tab", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + seam.workerScope.skipWaiting.mockRejectedValue(new Error("commit")); + + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(0); + + await expect(activation).resolves.toEqual({ + kind: "FAILED", + code: "ACTIVATION_COMMIT_FAILED", + }); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); + + it("still reports a tab that refuses the drain as BLOCKED_DIRTY_CLIENT", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + // Tab 0 answers the drain with an explicit rejection (unsaved edits). + const dirtyTab = seam.tabs[0]!.waiting; + const deliver = dirtyTab.postMessage.bind(dirtyTab); + dirtyTab.postMessage = (message) => + deliver( + message.kind === "CLIENT_DRAINED" + ? { ...message, kind: "ACTIVATE_REJECTED" } + : message, + ); + + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(0); + + await expect(activation).resolves.toEqual({ + kind: "BLOCKED_DIRTY_CLIENT", + }); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); }); /**