fix(web-push): serialize push control across tabs with a Web Lock (06-02)

Tabs share one native subscription and one origin fence. enable, reconcile
and revoke now run under the `web-push-control` Web Lock (D-4), and a
compensation unsubscribes only a subscription its own call created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-26 00:06:48 +09:00
co-authored by Claude Opus 5.5
parent 8522cb5256
commit e6c683eb4f
3 changed files with 271 additions and 14 deletions
@@ -1281,6 +1281,16 @@ user opt-in
`matchAll()`이 signal을 따르지 않거나 `waitUntil()`이 동기 예외를 내도 늦은
`postMessage`를 허용하지 않고 degraded observation으로 닫는다.
- re-subscribe가 실패하면 notification을 끄고 foreground fallback을 유지한다.
- 여러 tab은 native subscription(worker registration당 1개)과 origin의 fence
record를 공유한다. 그래서 `enable`·`reconcile`·`revoke`는 origin 단위 Web Lock
`web-push-control` 안에서 하나씩 실행한다. `inspect`는 읽기만 하므로 lock을
잡지 않는다. composition이 `navigator.locks`를 `lockManager`로 넘기고, Web
Locks가 없으면 `PUSH_UNSUPPORTED`로 보고한다
(`src/adapters/web-push/push-subscription-adapter.ts`의 `exclusive`,
`supportReadiness`). activate 실패나 session binding 불일치의 보상은 backend
association을 revoke하지만 native `unsubscribe()`는 그 호출이 새로 만든
subscription에만 한다. 이미 있던 subscription은 다른 tab의 association일 수
있다(`activateCommit`, 06-02).
`associationEpoch`은 backend registration authority가 발급한다.
`releaseEpoch`은 signed/verified release manifest에서 온다. backend registration
@@ -88,6 +88,13 @@ export function createWebPushSubscriptionAdapter(
backendOperationDeadlineMs?: number;
scheduler?: TimeoutScheduler;
observer?: WebPushObserver;
/**
* 06-02 (D-4). The composition passes `navigator.locks`. Every tab shares
* one native subscription and one origin fence, so enable, reconcile and
* revoke run under the origin-wide `web-push-control` lock. Without Web
* Locks the adapter reports `PUSH_UNSUPPORTED`.
*/
lockManager?: Pick<LockManager, "request">;
}>,
): WebPushControlPort {
const decodedVapidPublicKey = decodeVapidPublicKey(
@@ -119,6 +126,11 @@ export function createWebPushSubscriptionAdapter(
}
const idempotencyKeyFactory =
dependencies.idempotencyKeyFactory ?? (() => globalThis.crypto.randomUUID());
const lockManager = dependencies.lockManager;
const requestLock =
typeof lockManager?.request === "function"
? lockManager.request.bind(lockManager)
: null;
let closed = false;
let busy = false;
let lifecycleGeneration = 0;
@@ -383,6 +395,7 @@ export function createWebPushSubscriptionAdapter(
commit: reconciled.value,
signal: operationSignal,
generation,
created: false,
});
},
);
@@ -507,15 +520,22 @@ export function createWebPushSubscriptionAdapter(
const generation = lifecycleGeneration;
const operation = createLinkedAbortController(signal);
inFlight.add(operation);
const run = () => task(generation, operation.signal);
try {
try {
return await task(generation, operation.signal);
// 06-02 (D-4). Inspection only reads; mutations wait for other tabs.
return failureOperation === "SUBSCRIPTION_INSPECT" || !requestLock
? await run()
: await requestLock(
WEB_PUSH_CONTROL_LOCK,
{ signal: operation.signal },
run,
);
} catch {
return webPushFailure(
"NATIVE_FAILURE",
failureOperation,
true,
);
// An abort while waiting for the lock rejects the request.
return operation.signal.aborted
? webPushFailure("ABORTED", failureOperation)
: webPushFailure("NATIVE_FAILURE", failureOperation, true);
}
} finally {
operation.dispose();
@@ -525,7 +545,7 @@ export function createWebPushSubscriptionAdapter(
}
function supportReadiness(): WebPushReadiness | null {
if (!dependencies.secureContext) {
if (!dependencies.secureContext || !requestLock) {
return readiness("PUSH_UNSUPPORTED");
}
if (!dependencies.registration.active) {
@@ -703,6 +723,7 @@ export function createWebPushSubscriptionAdapter(
commit: registered.value,
signal: input.signal,
generation: input.generation,
created: input.created,
});
}
@@ -713,13 +734,17 @@ export function createWebPushSubscriptionAdapter(
commit: WebPushRegistrationCommit;
signal: AbortSignal | undefined;
generation: number;
created: boolean;
}>): Promise<WebPushResult<WebPushReadiness>> {
// 06-02 (D-4). A subscription this call did not create may carry another
// tab's association, so compensation leaves it in place.
const createdSubscription = input.created ? input.subscription : null;
if (
input.commit.sessionBindingEpoch !==
input.authority.sessionBindingEpoch ||
stale(input.signal, input.generation)
) {
await compensate(input.subscription, input.commit.associationEpoch);
await compensate(createdSubscription, input.commit.associationEpoch);
return webPushSuccess(
unavailable("SESSION_AUTHORITY_CHANGED"),
);
@@ -732,21 +757,23 @@ export function createWebPushSubscriptionAdapter(
signal: input.signal,
});
if (!activated.ok) {
await compensate(input.subscription, input.commit.associationEpoch);
await compensate(createdSubscription, input.commit.associationEpoch);
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
}
return webPushSuccess(readiness("PUSH_READY"));
}
async function compensate(
subscription: WindowPushSubscriptionFacade,
createdSubscription: WindowPushSubscriptionFacade | null,
associationEpoch: string,
): Promise<void> {
await withAbortableDeadline(
async (signal) => {
await Promise.allSettled([
boundedBackendRevoke(associationEpoch, signal),
safeUnsubscribe(subscription),
createdSubscription
? safeUnsubscribe(createdSubscription)
: Promise.resolve(true),
]);
return webPushSuccess(undefined);
},
@@ -1007,6 +1034,9 @@ export function createWebPushSubscriptionAdapter(
}
}
/** 06-02 (D-4). Origin-wide Web Lock name shared by every tab. */
const WEB_PUSH_CONTROL_LOCK = "web-push-control";
function readiness(
state: WebPushReadiness["state"],
): WebPushReadiness {
@@ -153,6 +153,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway({ register }),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
idempotencyKeyFactory: () => "idempotency_01",
});
@@ -207,6 +208,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway({ register }),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
});
@@ -224,7 +226,12 @@ describe("Web Push window subscription adapter", () => {
expect(await fenceStore.read()).toEqual({ ok: true, value: null });
});
it("compensates a stale backend session binding without activating local authority", async () => {
// 06-02 (D-4). Only a subscription this call created is unsubscribed; an
// existing one may belong to another tab's association.
it.each([
{ existing: true, unsubscribeCalls: 0 },
{ existing: false, unsubscribeCalls: 1 },
])("compensates a stale backend session binding without activating local authority (existing native: $existing)", async ({ existing, unsubscribeCalls }) => {
const fenceStore = createPushAssociationFenceStore(
createFakePushControlStoreDependencies(),
);
@@ -241,7 +248,7 @@ describe("Web Push window subscription adapter", () => {
registration: {
active: true,
pushManager: {
getSubscription: async () => native,
getSubscription: async () => (existing ? native : null),
subscribe: async () => native,
},
getNotifications: async () => [],
@@ -256,6 +263,7 @@ describe("Web Push window subscription adapter", () => {
revoke,
}),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
idempotencyKeyFactory: () => "idempotency_01",
});
@@ -276,7 +284,7 @@ describe("Web Push window subscription adapter", () => {
associationEpoch: "association_stale",
signal: expect.any(AbortSignal),
});
expect(unsubscribe).toHaveBeenCalledOnce();
expect(unsubscribe).toHaveBeenCalledTimes(unsubscribeCalls);
expect(await fenceStore.read()).toMatchObject({
ok: true,
value: {
@@ -346,6 +354,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway({ revoke }),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
});
@@ -417,6 +426,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway(),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
});
@@ -486,6 +496,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway({ revoke }),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
});
@@ -553,6 +564,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway({ revoke }),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
});
@@ -609,6 +621,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway({ revoke }),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
});
@@ -658,6 +671,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway(),
vapidPublicKey,
lockManager: navigator.locks,
nativeOperationDeadlineMs: 1,
scheduler: clock.scheduler,
});
@@ -694,6 +708,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway(),
vapidPublicKey,
lockManager: navigator.locks,
});
const inspection = adapter.inspect({ authority });
@@ -729,6 +744,7 @@ describe("Web Push window subscription adapter", () => {
fenceStore,
gateway: gateway(),
vapidPublicKey,
lockManager: navigator.locks,
});
for (let attempt = 0; attempt < 2; attempt += 1) {
@@ -792,6 +808,7 @@ describe("Web Push window subscription adapter", () => {
revoke,
}),
vapidPublicKey,
lockManager: navigator.locks,
backendOperationDeadlineMs: 1,
scheduler: clock.scheduler,
idempotencyKeyFactory: () => "idempotency_01",
@@ -862,6 +879,7 @@ describe("Web Push reconcile with a server ABSENT association (R-6.7)", () => {
reconcile: async () => webPushSuccess({ state: "ABSENT" as const }),
}),
vapidPublicKey,
lockManager: navigator.locks,
now: () => now,
idempotencyKeyFactory: () => "idempotency_02",
});
@@ -943,3 +961,202 @@ describe("Web Push reconcile with a server ABSENT association (R-6.7)", () => {
},
);
});
/**
* 06-02 (D-4). The native subscription is one per service worker registration
* and the fence record one per origin, so every tab shares both. enable,
* reconcile and revoke hold the origin-wide `web-push-control` Web Lock
* (Node's `navigator.locks` here, shared by both adapters like two tabs), and
* a compensation unsubscribes only a subscription its own call created.
*/
describe("06-02 two tabs share one native subscription and one fence", () => {
function sharedTabs(
reconcileAnswer: (
serverAssociation: string | null,
) => Promise<"WAIT_FOR_REGISTER" | "NOW">,
lockManager: Pick<LockManager, "request"> | null = navigator.locks,
) {
const dependencies = createFakePushControlStoreDependencies();
const unsubscribe = vi.fn(async () => {
current = null;
return true;
});
const native = subscription(unsubscribe);
let current: WindowPushSubscriptionFacade | null = null;
const server: { association: string | null } = { association: null };
let releaseRegister!: () => void;
const registerGate = new Promise<void>((resolve) => {
releaseRegister = resolve;
});
let registerReached!: () => void;
const registerStarted = new Promise<void>((resolve) => {
registerReached = resolve;
});
const shared: WebPushRegistrationGateway = {
async register() {
registerReached();
await registerGate;
server.association = "association_01";
return webPushSuccess({
associationEpoch: "association_01",
sessionBindingEpoch: "session_01",
});
},
async reconcile() {
if ((await reconcileAnswer(server.association)) === "WAIT_FOR_REGISTER") {
await registerGate;
}
return webPushSuccess(
server.association
? {
state: "ACTIVE" as const,
associationEpoch: server.association,
sessionBindingEpoch: "session_01",
}
: { state: "ABSENT" as const },
);
},
async revoke(input) {
if (server.association === input.associationEpoch) {
server.association = null;
}
return webPushSuccess({ state: "REVOKED" as const });
},
};
function tab(activation: boolean) {
return createWebPushSubscriptionAdapter({
secureContext: true,
userActivationIsActive: () => activation,
permission: {
permission: () => "granted",
requestPermission: async () => "granted",
},
registration: {
active: true,
pushManager: {
getSubscription: async () => current,
subscribe: async () => {
current = native;
return native;
},
},
getNotifications: async () => [],
},
fenceStore: createPushAssociationFenceStore(dependencies),
gateway: shared,
vapidPublicKey,
now: () => now,
...(lockManager ? { lockManager } : {}),
});
}
return {
tab,
server,
unsubscribe,
registerStarted,
releaseRegister: () => releaseRegister(),
nativeAlive: () => current === native,
fence: async () =>
await createPushAssociationFenceStore(dependencies).read(),
};
}
async function raceEnableWithReconcile(
tabs: ReturnType<typeof sharedTabs>,
) {
const tab1 = tabs.tab(true);
const tab2 = tabs.tab(false);
const enabling = tab1.enable({
authority,
signal: new AbortController().signal,
});
// Tab 1 prepared the fence, subscribed and is waiting on register.
await tabs.registerStarted;
const reconciling = tab2.reconcile({ authority });
await new Promise((resolve) => setTimeout(resolve, 0));
tabs.releaseRegister();
return await Promise.all([enabling, reconciling]);
}
function expectReadyTabsStillReceive(
tabs: ReturnType<typeof sharedTabs>,
results: readonly unknown[],
) {
const ready = { ok: true, value: { state: "PUSH_READY" } };
expect(results).toContainEqual(ready);
expect(tabs.unsubscribe).not.toHaveBeenCalled();
expect(tabs.nativeAlive()).toBe(true);
expect(tabs.server.association).toBe("association_01");
}
it("keeps the shared state when the reconciling tab would win the fence CAS", async () => {
// Order 1: the server commits tab 1's register, tab 2 sees it first.
const tabs = sharedTabs(async () => "WAIT_FOR_REGISTER");
const results = await raceEnableWithReconcile(tabs);
expect(results).toEqual([
{ ok: true, value: { state: "PUSH_READY" } },
{ ok: true, value: { state: "PUSH_READY" } },
]);
expectReadyTabsStillReceive(tabs, results);
expect(await tabs.fence()).toMatchObject({
ok: true,
value: {
control: {
association: {
state: "ACTIVE",
associationEpoch: "association_01",
},
},
},
});
});
it("keeps the shared state when a tab reconciles during another tab's unfinished opt-in", async () => {
// Order 2: the server still answers ABSENT while tab 1's register runs.
const tabs = sharedTabs(async () => "NOW");
const results = await raceEnableWithReconcile(tabs);
expect(results[0]).toEqual({ ok: true, value: { state: "PUSH_READY" } });
expectReadyTabsStillReceive(tabs, results);
});
it("aborts a tab that is still waiting for another tab's lock", async () => {
const tabs = sharedTabs(async () => "NOW");
const enabling = tabs.tab(true).enable({
authority,
signal: new AbortController().signal,
});
await tabs.registerStarted;
const waiting = new AbortController();
const reconciling = tabs.tab(false).reconcile({
authority,
signal: waiting.signal,
});
await new Promise((resolve) => setTimeout(resolve, 0));
waiting.abort();
expect(await reconciling).toMatchObject({
ok: false,
error: { code: "ABORTED", operation: "SUBSCRIPTION_RECONCILE" },
});
tabs.releaseRegister();
expect(await enabling).toEqual({
ok: true,
value: { state: "PUSH_READY" },
});
expect(tabs.unsubscribe).not.toHaveBeenCalled();
});
it("reports PUSH_UNSUPPORTED without side effects when Web Locks are missing", async () => {
const tabs = sharedTabs(async () => "NOW", null);
expect(
await tabs.tab(true).enable({
authority,
signal: new AbortController().signal,
}),
).toEqual({ ok: true, value: { state: "PUSH_UNSUPPORTED" } });
expect(tabs.nativeAlive()).toBe(false);
expect(await tabs.fence()).toEqual({ ok: true, value: null });
});
});