fix(service-worker): let the app subscribe to reload-required and update-waiting (R-6.3)
Tabs that did not request an activation only observe()d
ACTIVATED_RELOAD_REQUIRED, and the host contract had no way to tell the
app. Worse, the worker targeted that broadcast at the requester's build,
so a tab on another build dropped it as TARGET_BUILD_MISMATCH. A waiting
worker produced by the periodic registration.update() was never reported
either.
- ServiceWorkerRuntimeHost gains optional onReloadRequired/onUpdateWaiting
(additive; existing host implementations still type-check).
- The page controller notifies reload subscribers when an expected worker
source sends ACTIVATED_RELOAD_REQUIRED, and watches `updatefound` +
`statechange` to announce an update that reached `installed` while an
active worker exists (a first install is never announced). Listeners
are removed on stop(); a throwing subscriber is isolated.
- Worker post-commit/reject notifications are untargeted; the requester
still pairs by nonce.
- Test fixtures: registration and workers are now EventTarget-backed.
RED before fix (listener called 0 times):
- announces an update that finished installing as waiting (R-6.3)
- page ↔ worker activation seam > tells a tab that did not ask that a
reload is required (R-6.3)
Gates: check:architecture, check:types:{app,test,service-worker}, lint,
test:component pass. test:unit passes except the pre-existing
removal-fixture.test.ts case that needs generated release evidence
under artifacts/ (absent in a fresh worktree; unrelated to this diff).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
47832fbe65
commit
fb8a3b5e1d
@@ -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,
|
||||
}),
|
||||
);
|
||||
|
||||
@@ -63,6 +63,9 @@ export function createServiceWorkerPageController(
|
||||
let resetInFlight: Promise<ServiceWorkerResetOutcome> | 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(
|
||||
|
||||
@@ -149,4 +149,15 @@ export interface ServiceWorkerRuntimeHost {
|
||||
requestActivation(): Promise<ServiceWorkerActivationOutcome>;
|
||||
resetOwnedCaches(): Promise<ServiceWorkerResetOutcome>;
|
||||
stop(): Promise<void>;
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
@@ -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<typeof fakeWorker>,
|
||||
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<void>;
|
||||
} = {
|
||||
} = 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();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user