diff --git a/src/adapters/service-worker/service-worker-lifecycle.ts b/src/adapters/service-worker/service-worker-lifecycle.ts index bae8ebf7..296edcc7 100644 --- a/src/adapters/service-worker/service-worker-lifecycle.ts +++ b/src/adapters/service-worker/service-worker-lifecycle.ts @@ -119,7 +119,6 @@ export function createServiceWorkerRuntime( ); const consumedNonces = new Set(); type PendingActivation = Readonly<{ - requesterBuildId: string; expectedClientIds: ReadonlySet; acknowledgedClientIds: Set; resolve(drained: boolean): void; @@ -276,11 +275,7 @@ export function createServiceWorkerRuntime( const clients = candidates.filter((client) => isClientWithinRegistrationScope(client.url, scope.registrationScope), ); - const drained = await drainClients( - clients, - nonce, - parsed.message.sourceBuildId, - ); + const drained = await drainClients(clients, nonce); if (!drained) { notifyClients(clients, "ACTIVATE_REJECTED", parsed.message.sourceBuildId, nonce); return "REJECTED"; @@ -335,7 +330,6 @@ export function createServiceWorkerRuntime( async function drainClients( clients: readonly WorkerClientLike[], nonce: string, - requesterBuildId: string, ): 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. @@ -348,7 +342,6 @@ export function createServiceWorkerRuntime( pendingActivations.set( nonce, Object.freeze({ - requesterBuildId, expectedClientIds: new Set(clients.map((client) => client.id)), acknowledgedClientIds: new Set(), resolve, @@ -359,13 +352,15 @@ 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. + // 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. for (const client of clients) { try { client.postMessage( createServiceWorkerMessage({ kind: "CLIENT_DRAIN_REQUEST", sourceBuildId: config.identity.buildId, - targetBuildId: requesterBuildId, nonce, }), ); @@ -389,11 +384,7 @@ export function createServiceWorkerRuntime( return; } const pending = pendingActivations.get(parsed.message.nonce); - if ( - !pending || - parsed.message.sourceBuildId !== pending.requesterBuildId || - !pending.expectedClientIds.has(sourceClientId) - ) { + if (!pending || !pending.expectedClientIds.has(sourceClientId)) { return; } if (parsed.message.kind === "ACTIVATE_REJECTED") { diff --git a/tests/unit/service-worker-runtime.test.ts b/tests/unit/service-worker-runtime.test.ts index 5b2fe33c..02b2cf20 100644 --- a/tests/unit/service-worker-runtime.test.ts +++ b/tests/unit/service-worker-runtime.test.ts @@ -980,6 +980,129 @@ describe("service worker static asset install", () => { }); }); +/** + * Page controllers and the worker runtime wired together. Each tab sees the + * waiting worker through its own `ServiceWorker` object; messages are + * delivered asynchronously in both directions, like postMessage. + */ +function activationSeam(tabBuildIds: readonly string[]) { + const workerScope = { + caches: { open: vi.fn(), keys: vi.fn(async () => []), delete: vi.fn() }, + clients: { + matchAll: vi.fn(async () => tabs.map((tab) => tab.client)), + }, + registrationScope: `${ORIGIN}/`, + skipWaiting: vi.fn(async () => { + for (const tab of tabs) { + tab.registration.active = tab.waiting; + tab.registration.waiting = null; + } + }), + fetcher: vi.fn(), + digest: vi.fn(), + }; + const runtime = createServiceWorkerRuntime(workerScope as never, { + identity, + handlers: [], + manifest: null, + runtimeConfigUrl: "/runtime-config.json", + releaseManifestUrl: "/release-manifest.json", + }); + const tabs = tabBuildIds.map((buildId, index) => { + const id = `tab-${index}`; + const listeners = new Set<(event: MessageEvent) => void>(); + // Page → worker, routed like `service-worker-entry.ts` does. + const waiting = { + scriptURL: SCRIPT_URL, + postMessage(message: { kind: string }) { + queueMicrotask(() => { + if (message.kind === "ACTIVATE_REQUEST") { + void runtime.onActivateRequest(message); + } else { + runtime.onClientMessage(message, id); + } + }); + }, + }; + const registration: { + scope: string; + installing: null; + waiting: typeof waiting | null; + active: typeof waiting | null; + update(): Promise; + } = { + scope: `${ORIGIN}/`, + installing: null, + waiting, + active: null, + update: async () => {}, + }; + const container = { + controller: null, + register: vi.fn(async () => registration), + addEventListener(_type: string, listener: (event: MessageEvent) => void) { + listeners.add(listener); + }, + removeEventListener( + _type: string, + listener: (event: MessageEvent) => void, + ) { + listeners.delete(listener); + }, + }; + // Worker → page: the sender is this tab's view of the waiting worker. + const client = { + id, + url: `${ORIGIN}/page-${index}`, + postMessage(data: unknown) { + queueMicrotask(() => { + const event = { data, origin: ORIGIN, source: waiting }; + for (const listener of [...listeners]) { + listener(event as unknown as MessageEvent); + } + }); + }, + }; + const controller = createServiceWorkerPageController({ + selection: { + mode: "ACTIVE", + scriptPath: SERVICE_WORKER_SCRIPT_PATH, + handlers: [], + }, + disabledCleanup: false, + routerBasePath: "/", + origin: ORIGIN, + buildId, + container: container as unknown as ServiceWorkerContainer, + blockers: [() => false], + }); + return { id, waiting, registration, client, controller }; + }); + return { runtime, workerScope, tabs }; +} + +describe("page ↔ worker activation seam", () => { + it("drains tabs of another build and completes the activation (R-6.2)", async () => { + vi.useFakeTimers(); + try { + const seam = activationSeam(["page-build-n", "page-build-n1"]); + for (const tab of seam.tabs) await tab.controller.start(); + + // The freshly reloaded tab (build N+1) asks; the older tab must drain. + const activation = seam.tabs[1]!.controller.requestActivation(); + await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.clientDrainMs); + + await expect(activation).resolves.toEqual({ + kind: "ACTIVATED_RELOAD_REQUIRED", + }); + expect(seam.workerScope.skipWaiting).toHaveBeenCalledTimes(1); + for (const tab of seam.tabs) await tab.controller.stop(); + } finally { + vi.useRealTimers(); + } + }); +}); + /** * SW-01. The marker read must be bounded in bytes, not only in logic. Adding a * whole chunk and *then* comparing the running total meant a corrupt body could