diff --git a/src/adapters/service-worker/service-worker-lifecycle.ts b/src/adapters/service-worker/service-worker-lifecycle.ts index 296edcc7..e11ec0c7 100644 --- a/src/adapters/service-worker/service-worker-lifecycle.ts +++ b/src/adapters/service-worker/service-worker-lifecycle.ts @@ -277,7 +277,7 @@ export function createServiceWorkerRuntime( ); const drained = await drainClients(clients, nonce); if (!drained) { - notifyClients(clients, "ACTIVATE_REJECTED", parsed.message.sourceBuildId, nonce); + notifyClients(clients, "ACTIVATE_REJECTED", nonce); return "REJECTED"; } @@ -287,28 +287,25 @@ export function createServiceWorkerRuntime( try { await scope.skipWaiting(); } catch { - notifyClients(clients, "ACTIVATE_REJECTED", parsed.message.sourceBuildId, nonce); + notifyClients(clients, "ACTIVATE_REJECTED", nonce); return "REJECTED"; } // Post-commit notifications are per-client best effort. - notifyClients(clients, "ACTIVATE_ACCEPTED", parsed.message.sourceBuildId, nonce); - notifyClients( - clients, - "ACTIVATED_RELOAD_REQUIRED", - parsed.message.sourceBuildId, - nonce, - ); + notifyClients(clients, "ACTIVATE_ACCEPTED", nonce); + notifyClients(clients, "ACTIVATED_RELOAD_REQUIRED", nonce); return "ACCEPTED"; } /** * SW-08. One client's `postMessage()` throwing must not break the whole * activation event; delivery is isolated per client. + * + * R-6.3. Untargeted: every tab, whatever build it runs, has to see + * ACTIVATED_RELOAD_REQUIRED. The requester pairs its reply by nonce. */ function notifyClients( clients: readonly WorkerClientLike[], kind: "ACTIVATE_REJECTED" | "ACTIVATE_ACCEPTED" | "ACTIVATED_RELOAD_REQUIRED", - targetBuildId: string, nonce: string, ): void { for (const client of clients) { @@ -317,7 +314,6 @@ export function createServiceWorkerRuntime( createServiceWorkerMessage({ kind, sourceBuildId: config.identity.buildId, - targetBuildId, nonce, }), ); diff --git a/src/adapters/service-worker/service-worker-page-controller.ts b/src/adapters/service-worker/service-worker-page-controller.ts index 43146096..0e0d483a 100644 --- a/src/adapters/service-worker/service-worker-page-controller.ts +++ b/src/adapters/service-worker/service-worker-page-controller.ts @@ -63,6 +63,9 @@ export function createServiceWorkerPageController( let resetInFlight: Promise | null = null; let stopped = false; const pendingStops = new Set<() => void>(); + let updateFoundListener: (() => void) | null = null; + const reloadRequiredListeners = new Set<() => void>(); + const updateWaitingListeners = new Set<() => void>(); const observe = (event: string, outcome: string) => dependencies.observe?.({ event, outcome }); @@ -178,6 +181,7 @@ export function createServiceWorkerPageController( } attachMessageListener(container); + watchForUpdates(registration); scheduleUpdateChecks(); if (registration.waiting) { @@ -239,6 +243,13 @@ export function createServiceWorkerPageController( observe("client_drain", rejected ? "BLOCKED" : "DRAINED"); return; } + // R-6.3. Sent to every tab once any tab's activation committed. + if ( + parsed.message.kind === "ACTIVATED_RELOAD_REQUIRED" && + isExpectedWorkerSource(event.source) + ) { + notify(reloadRequiredListeners); + } observe("message", parsed.message.kind); }; container.addEventListener("message", messageListener); @@ -261,6 +272,35 @@ export function createServiceWorkerPageController( ); } + /** + * R-6.3. An update found by the periodic check (or by another tab) reaches + * `waiting` without any message, so the registration's own events are + * watched. A first install has no active worker and activates on its own, + * so it is never announced as waiting. + */ + function watchForUpdates(watched: ServiceWorkerRegistration): void { + if (updateFoundListener) return; + let lastWatched: ServiceWorker | null = null; + const watchInstalling = () => { + const worker = watched.installing; + if (!worker || worker === lastWatched) return; + lastWatched = worker; + worker.addEventListener("statechange", () => { + if ( + worker.state === "installed" && + watched.waiting === worker && + watched.active + ) { + notify(updateWaitingListeners); + } + }); + }; + updateFoundListener = watchInstalling; + watched.addEventListener("updatefound", updateFoundListener); + // The update may have been found before this listener existed. + watchInstalling(); + } + function scheduleUpdateChecks(): void { // §17.14. At most one check per 6 hours, and none while the page is hidden. if (updateTimer) return; @@ -485,10 +525,45 @@ export function createServiceWorkerPageController( dependencies.container.removeEventListener("message", messageListener); messageListener = null; } + if (updateFoundListener && registration) { + registration.removeEventListener("updatefound", updateFoundListener); + updateFoundListener = null; + } + reloadRequiredListeners.clear(); + updateWaitingListeners.clear(); nonces.clear(); } - return Object.freeze({ start, requestActivation, resetOwnedCaches, stop }); + return Object.freeze({ + start, + requestActivation, + resetOwnedCaches, + stop, + onReloadRequired: (listener: () => void) => + subscribe(reloadRequiredListeners, listener), + onUpdateWaiting: (listener: () => void) => + subscribe(updateWaitingListeners, listener), + }); +} + +function subscribe( + listeners: Set<() => void>, + listener: () => void, +): () => void { + listeners.add(listener); + return () => { + listeners.delete(listener); + }; +} + +function notify(listeners: ReadonlySet<() => void>): void { + for (const listener of [...listeners]) { + try { + listener(); + } catch { + // A failing subscriber cannot break the message or event handler. + } + } } function canPostMessage( diff --git a/src/contracts/service-worker.ts b/src/contracts/service-worker.ts index c92b7c05..1e5437bf 100644 --- a/src/contracts/service-worker.ts +++ b/src/contracts/service-worker.ts @@ -149,4 +149,15 @@ export interface ServiceWorkerRuntimeHost { requestActivation(): Promise; resetOwnedCaches(): Promise; stop(): Promise; + /** + * R-6.3. A new worker was activated (by any tab), so this page runs under a + * worker of another build and should reload. Every tab is told, including + * the one that asked. Returns the unsubscribe function. + */ + onReloadRequired?(listener: () => void): () => void; + /** + * R-6.3. An update finished installing and waits for `requestActivation()`. + * Returns the unsubscribe function. + */ + onUpdateWaiting?(listener: () => void): () => void; } diff --git a/tests/unit/service-worker-runtime.test.ts b/tests/unit/service-worker-runtime.test.ts index 02b2cf20..a1917552 100644 --- a/tests/unit/service-worker-runtime.test.ts +++ b/tests/unit/service-worker-runtime.test.ts @@ -16,27 +16,44 @@ import { const ORIGIN = "https://app.example"; const SCRIPT_URL = `${ORIGIN}/service-worker.js`; +/** A `ServiceWorker` stand-in that can fire `statechange`. */ +function fakeWorker( + messages: unknown[] = [], + state: ServiceWorkerState = "activated", +) { + return Object.assign(new EventTarget(), { + scriptURL: SCRIPT_URL, + state, + postMessage(message: unknown) { + messages.push(message); + }, + }); +} + +function setWorkerState( + worker: ReturnType, + state: ServiceWorkerState, +) { + worker.state = state; + worker.dispatchEvent(new Event("statechange")); +} + function pageContainer(options: { waiting?: boolean; controlled?: boolean } = {}) { const listeners = new Set<(event: MessageEvent) => void>(); const waitingMessages: unknown[] = []; const controllerMessages: unknown[] = []; - const worker = (messages: unknown[]) => - ({ - scriptURL: SCRIPT_URL, - postMessage(message: unknown) { - messages.push(message); - }, - }) as unknown as ServiceWorker; - const waiting = options.waiting ? worker(waitingMessages) : null; + const worker = (messages: unknown[], state?: ServiceWorkerState) => + fakeWorker(messages, state) as unknown as ServiceWorker; + const waiting = options.waiting ? worker(waitingMessages, "installed") : null; const active = options.waiting ? null : worker([]); const controlled = options.controlled ? worker(controllerMessages) : null; - const registration = { + const registration = Object.assign(new EventTarget(), { scope: `${ORIGIN}/`, installing: null, waiting, active, update: vi.fn(async () => {}), - } as unknown as ServiceWorkerRegistration; + }) as unknown as ServiceWorkerRegistration; const container = { controller: controlled, register: vi.fn(async () => registration), @@ -916,6 +933,31 @@ describe("service worker static asset install", () => { await controller.stop(); }); + it("announces an update that finished installing as waiting (R-6.3)", async () => { + const browser = pageContainer({ controlled: true }); + const controller = pageController(browser.container); + await expect(controller.start()).resolves.toMatchObject({ kind: "ACTIVE" }); + const updateWaiting = vi.fn(); + controller.onUpdateWaiting?.(updateWaiting); + + // What the browser does after a periodic `registration.update()` finds a + // new worker. + const registration = browser.registration as unknown as EventTarget & { + installing: ServiceWorker | null; + waiting: ServiceWorker | null; + }; + const update = fakeWorker([], "installing"); + registration.installing = update as unknown as ServiceWorker; + registration.dispatchEvent(new Event("updatefound")); + expect(updateWaiting).not.toHaveBeenCalled(); + registration.installing = null; + registration.waiting = update as unknown as ServiceWorker; + setWorkerState(update, "installed"); + + expect(updateWaiting).toHaveBeenCalledTimes(1); + await controller.stop(); + }); + it("accepts a post-commit reply after the waiting worker was promoted (R-6.1)", async () => { const browser = pageContainer({ waiting: true }); const controller = pageController(browser.container); @@ -1024,19 +1066,19 @@ function activationSeam(tabBuildIds: readonly string[]) { }); }, }; - const registration: { + const registration: EventTarget & { scope: string; installing: null; waiting: typeof waiting | null; active: typeof waiting | null; update(): Promise; - } = { + } = Object.assign(new EventTarget(), { scope: `${ORIGIN}/`, installing: null, - waiting, - active: null, + waiting: waiting as typeof waiting | null, + active: null as typeof waiting | null, update: async () => {}, - }; + }); const container = { controller: null, register: vi.fn(async () => registration), @@ -1101,6 +1143,27 @@ describe("page ↔ worker activation seam", () => { vi.useRealTimers(); } }); + + it("tells a tab that did not ask that a reload is required (R-6.3)", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + const reloadRequired = vi.fn(); + seam.tabs[0]!.controller.onReloadRequired?.(reloadRequired); + + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs); + + await expect(activation).resolves.toEqual({ + kind: "ACTIVATED_RELOAD_REQUIRED", + }); + expect(reloadRequired).toHaveBeenCalledTimes(1); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); }); /**