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 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-26 00:36:28 +09:00
co-authored by Claude Opus 5.5
parent 996a9591c8
commit f2e14af0a8
5 changed files with 121 additions and 17 deletions
@@ -119,10 +119,12 @@ export function createServiceWorkerRuntime(
),
);
const consumedNonces = new Set<string>();
/** 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<string>;
acknowledgedClientIds: Set<string>;
resolve(drained: boolean): void;
resolve(outcome: DrainOutcome): void;
timer: ReturnType<typeof setTimeout>;
}>;
const pendingActivations = new Map<string, PendingActivation>();
@@ -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<boolean> {
): Promise<DrainOutcome> {
// 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<boolean>((resolve) => {
if (clients.length === 0) return "DRAINED";
const drained = new Promise<DrainOutcome>((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);
}
}
@@ -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 = () =>
@@ -19,6 +19,8 @@ const MESSAGE_KINDS: ReadonlySet<string> = new Set<ServiceWorkerMessageKind>([
"ACTIVATE_REQUEST",
"ACTIVATE_ACCEPTED",
"ACTIVATE_REJECTED",
"ACTIVATE_DRAIN_TIMEOUT",
"ACTIVATE_COMMIT_FAILED",
"CLIENT_DRAIN_REQUEST",
"CLIENT_DRAINED",
"ACTIVATED_RELOAD_REQUIRED",
+6
View File
@@ -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"
+73
View File
@@ -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();
}
});
});
/**