Merge lane/F: service worker / web push (06-01~06-10, F-8)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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>();
|
||||
@@ -263,7 +265,8 @@ export function createServiceWorkerRuntime(
|
||||
/**
|
||||
* R-6.6 / Q-6.6-6b. Synchronous, so the fetch listener decides before it
|
||||
* calls `respondWith`. Only a manifest asset of this release or a
|
||||
* same-origin content-hashed URL (an old build's chunk) is answered;
|
||||
* content-hashed URL under the build asset directory (an old build's chunk,
|
||||
* 06-08) is answered;
|
||||
* navigations, API calls, cross-origin and unhashed URLs are left alone.
|
||||
*/
|
||||
function intercepts(request: FetchRequest): boolean {
|
||||
@@ -346,8 +349,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 +364,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 +382,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 +408,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 +429,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 +444,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 +466,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 +528,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",
|
||||
|
||||
@@ -20,9 +20,10 @@ export type FetchClassification =
|
||||
| "NETWORK_ONLY"
|
||||
| "VERIFIED_CACHE_FIRST"
|
||||
/**
|
||||
* Q-6.6-6b. A same-origin content-hashed URL this release does not list,
|
||||
* typically a lazy chunk of the build a tab still runs. Only the previous
|
||||
* release cache may answer it; otherwise it goes to the network.
|
||||
* Q-6.6-6b. A content-hashed URL under the build asset directory that this
|
||||
* release does not list, typically a lazy chunk of the build a tab still
|
||||
* runs. Only the previous release cache may answer it; otherwise it goes to
|
||||
* the network.
|
||||
*/
|
||||
| "PREVIOUS_RELEASE_FALLBACK";
|
||||
|
||||
@@ -57,11 +58,18 @@ export function classifyFetch(input: ClassificationInput): FetchClassification {
|
||||
return "NETWORK_PASSTHROUGH";
|
||||
}
|
||||
|
||||
/**
|
||||
* 06-08. Vite's default `build.assetsDir`, under the app base that is also the
|
||||
* registration scope. A hashed-looking API or download name elsewhere is not an
|
||||
* old build chunk and is left to the browser.
|
||||
*/
|
||||
const BUILD_ASSET_DIRECTORY = "assets/";
|
||||
|
||||
function isSameOriginHashedAsset(requestUrl: string, scopeUrl: string): boolean {
|
||||
try {
|
||||
const request = new URL(requestUrl);
|
||||
return (
|
||||
request.origin === new URL(scopeUrl).origin &&
|
||||
request.href.startsWith(new URL(BUILD_ASSET_DIRECTORY, scopeUrl).href) &&
|
||||
HASHED_STATIC_ASSET_NAME.test(request.pathname)
|
||||
);
|
||||
} catch {
|
||||
|
||||
@@ -84,6 +84,11 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
|
||||
fenceStore: PushAssociationFenceStore;
|
||||
clients: WorkerClientsFacade;
|
||||
origin: string;
|
||||
/**
|
||||
* 06-09. Where a refused click opens: the registration scope, which is the
|
||||
* router base path. Defaults to the origin root; must be same-origin.
|
||||
*/
|
||||
appRootUrl?: string;
|
||||
now?: () => number;
|
||||
handlerDeadlineMs?: number;
|
||||
scheduler?: TimeoutScheduler;
|
||||
@@ -104,6 +109,11 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
|
||||
throw new TypeError("Web Push click adapter configuration is invalid.");
|
||||
}
|
||||
const origin: string = parsedOrigin;
|
||||
const parsedAppRootUrl = safeTarget(origin, dependencies.appRootUrl ?? "/");
|
||||
if (!parsedAppRootUrl) {
|
||||
throw new TypeError("Web Push click adapter configuration is invalid.");
|
||||
}
|
||||
const appRootUrl: string = parsedAppRootUrl;
|
||||
|
||||
return Object.freeze({
|
||||
handle(event) {
|
||||
@@ -246,9 +256,10 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
|
||||
/**
|
||||
* Q-6.6-11 / D-14. A click whose data or authority was refused (expired,
|
||||
* fence or release mismatch, unreadable fence, unknown route) still opens
|
||||
* the app, at the same-origin root and with no handoff data, so the user's
|
||||
* tap is never silently dropped. The refusal stays the result. Native
|
||||
* failures (the browser refused a window) and aborts are not retried.
|
||||
* the app at its root (06-09: the router base path) with no handoff data,
|
||||
* so the user's tap is never silently dropped. The refusal stays the
|
||||
* result. Native failures (the browser refused a window) and aborts are not
|
||||
* retried.
|
||||
*/
|
||||
async function openAppRootIfRejected(
|
||||
result: WebPushResult<void>,
|
||||
@@ -265,8 +276,7 @@ export function createNotificationClickAdapter(dependencies: Readonly<{
|
||||
) {
|
||||
return result;
|
||||
}
|
||||
// `origin` is already a parsed origin, so this is its root URL.
|
||||
await openWindowBounded(`${origin}/`, signal, effect).catch(() => {
|
||||
await openWindowBounded(appRootUrl, signal, effect).catch(() => {
|
||||
// The native call threw: whether a window opened is unknown.
|
||||
});
|
||||
return result;
|
||||
|
||||
@@ -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;
|
||||
@@ -131,33 +143,8 @@ export function createWebPushSubscriptionAdapter(
|
||||
return exclusive(
|
||||
"SUBSCRIPTION_INSPECT",
|
||||
input.signal,
|
||||
async (generation, operationSignal) => {
|
||||
const supported = supportReadiness();
|
||||
if (supported) return webPushSuccess(supported);
|
||||
const permission = permissionReadiness();
|
||||
if (permission) return webPushSuccess(permission);
|
||||
const native = await getSubscription(operationSignal, generation);
|
||||
if (!native.ok) return native;
|
||||
if (!native.value) {
|
||||
return webPushSuccess(
|
||||
unavailable("NATIVE_SUBSCRIPTION_MISSING"),
|
||||
);
|
||||
}
|
||||
if (!subscriptionUsesKey(native.value, vapidPublicKey)) {
|
||||
return webPushSuccess(
|
||||
unavailable("SUBSCRIPTION_KEY_MISMATCH"),
|
||||
);
|
||||
}
|
||||
const control = await dependencies.fenceStore.read({
|
||||
signal: operationSignal,
|
||||
});
|
||||
if (!control.ok) return control;
|
||||
return webPushSuccess(
|
||||
isActiveFor(control.value?.control ?? null, input.authority)
|
||||
? readiness("PUSH_READY")
|
||||
: unavailable("SESSION_AUTHORITY_CHANGED"),
|
||||
);
|
||||
},
|
||||
(generation, operationSignal) =>
|
||||
inspectReadiness(input.authority, generation, operationSignal),
|
||||
);
|
||||
},
|
||||
|
||||
@@ -383,6 +370,7 @@ export function createWebPushSubscriptionAdapter(
|
||||
commit: reconciled.value,
|
||||
signal: operationSignal,
|
||||
generation,
|
||||
created: false,
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -408,62 +396,54 @@ export function createWebPushSubscriptionAdapter(
|
||||
) {
|
||||
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
||||
}
|
||||
const capturedNative = await captureNativeForCleanup(
|
||||
return await revokeReceipt(
|
||||
current.value,
|
||||
input.previousAuthority,
|
||||
input.nextAuthority,
|
||||
generation,
|
||||
operationSignal,
|
||||
generation,
|
||||
);
|
||||
const previousAssociation =
|
||||
current.value.control.association.state === "UNASSOCIATED"
|
||||
? null
|
||||
: current.value.control.association.associationEpoch;
|
||||
const fenced = await dependencies.fenceStore.rotateAndRevoke({
|
||||
expectedRevision: current.value.revision,
|
||||
previousAuthority: input.previousAuthority,
|
||||
nextAuthority: input.nextAuthority,
|
||||
updatedAt: instantNow(),
|
||||
signal: operationSignal,
|
||||
});
|
||||
if (!fenced.ok) {
|
||||
if (previousAssociation) {
|
||||
await boundedBackendRevoke(previousAssociation);
|
||||
}
|
||||
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
|
||||
let revokeAmbiguous = false;
|
||||
if (previousAssociation) {
|
||||
const backend = await boundedBackendRevoke(
|
||||
previousAssociation,
|
||||
revokeForeign(input) {
|
||||
return exclusive(
|
||||
"SUBSCRIPTION_REVOKE",
|
||||
input.signal,
|
||||
async (generation, operationSignal) => {
|
||||
const current = await dependencies.fenceStore.read({
|
||||
signal: operationSignal,
|
||||
});
|
||||
if (!current.ok) {
|
||||
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
||||
}
|
||||
// 06-06. Only another session generation's fence is foreign. The
|
||||
// next authority's own fence (another tab of the same session opted
|
||||
// in, or a new release of it) keeps its association.
|
||||
if (
|
||||
!current.value ||
|
||||
current.value.control.fenceGeneration ===
|
||||
input.nextAuthority.fenceGeneration
|
||||
) {
|
||||
return await inspectReadiness(
|
||||
input.nextAuthority,
|
||||
generation,
|
||||
operationSignal,
|
||||
);
|
||||
}
|
||||
const stored = current.value.control;
|
||||
return await revokeReceipt(
|
||||
current.value,
|
||||
Object.freeze({
|
||||
fenceGeneration: stored.fenceGeneration,
|
||||
sessionBindingEpoch: stored.sessionBindingEpoch,
|
||||
releaseEpoch: stored.releaseEpoch,
|
||||
}),
|
||||
input.nextAuthority,
|
||||
generation,
|
||||
operationSignal,
|
||||
);
|
||||
revokeAmbiguous = !backend.ok;
|
||||
}
|
||||
const nativeClean = await cleanupNative(
|
||||
previousAssociation,
|
||||
generation,
|
||||
capturedNative,
|
||||
fenced.value,
|
||||
);
|
||||
observeWebPush(dependencies.observer, {
|
||||
event: "web_push_association_revoked",
|
||||
outcome:
|
||||
revokeAmbiguous || !nativeClean ? "DEGRADED" : "SUCCEEDED",
|
||||
...(revokeAmbiguous
|
||||
? { reason: "BACKEND_REVOKE_AMBIGUOUS" }
|
||||
: !nativeClean
|
||||
? { reason: "NATIVE_UNSUBSCRIBE_AMBIGUOUS" }
|
||||
: {}),
|
||||
});
|
||||
if (revokeAmbiguous) {
|
||||
return webPushSuccess(
|
||||
unavailable("BACKEND_REVOKE_AMBIGUOUS"),
|
||||
);
|
||||
}
|
||||
if (!nativeClean) {
|
||||
return webPushSuccess(
|
||||
unavailable("NATIVE_UNSUBSCRIBE_AMBIGUOUS"),
|
||||
);
|
||||
}
|
||||
return webPushSuccess(unavailable("REVOKED"));
|
||||
},
|
||||
);
|
||||
},
|
||||
@@ -507,15 +487,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();
|
||||
@@ -524,8 +511,99 @@ export function createWebPushSubscriptionAdapter(
|
||||
}
|
||||
}
|
||||
|
||||
async function inspectReadiness(
|
||||
authority: PushAuthoritySnapshot,
|
||||
generation: number,
|
||||
operationSignal: AbortSignal,
|
||||
): Promise<WebPushResult<WebPushReadiness>> {
|
||||
const supported = supportReadiness();
|
||||
if (supported) return webPushSuccess(supported);
|
||||
const permission = permissionReadiness();
|
||||
if (permission) return webPushSuccess(permission);
|
||||
const native = await getSubscription(operationSignal, generation);
|
||||
if (!native.ok) return native;
|
||||
if (!native.value) {
|
||||
return webPushSuccess(unavailable("NATIVE_SUBSCRIPTION_MISSING"));
|
||||
}
|
||||
if (!subscriptionUsesKey(native.value, vapidPublicKey)) {
|
||||
return webPushSuccess(unavailable("SUBSCRIPTION_KEY_MISMATCH"));
|
||||
}
|
||||
const control = await dependencies.fenceStore.read({
|
||||
signal: operationSignal,
|
||||
});
|
||||
if (!control.ok) return control;
|
||||
return webPushSuccess(
|
||||
isActiveFor(control.value?.control ?? null, authority)
|
||||
? readiness("PUSH_READY")
|
||||
: unavailable("SESSION_AUTHORITY_CHANGED"),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Logout order: rotate the fence to REVOKED first, then revoke the captured
|
||||
* association, unsubscribe the captured native subscription and close its
|
||||
* notifications.
|
||||
*/
|
||||
async function revokeReceipt(
|
||||
current: PushControlReceipt,
|
||||
previousAuthority: PushAuthoritySnapshot,
|
||||
nextAuthority: PushAuthoritySnapshot,
|
||||
generation: number,
|
||||
operationSignal: AbortSignal,
|
||||
): Promise<WebPushResult<WebPushReadiness>> {
|
||||
const capturedNative = await captureNativeForCleanup(
|
||||
operationSignal,
|
||||
generation,
|
||||
);
|
||||
const previousAssociation =
|
||||
current.control.association.state === "UNASSOCIATED"
|
||||
? null
|
||||
: current.control.association.associationEpoch;
|
||||
const fenced = await dependencies.fenceStore.rotateAndRevoke({
|
||||
expectedRevision: current.revision,
|
||||
previousAuthority,
|
||||
nextAuthority,
|
||||
updatedAt: instantNow(),
|
||||
signal: operationSignal,
|
||||
});
|
||||
if (!fenced.ok) {
|
||||
if (previousAssociation) {
|
||||
await boundedBackendRevoke(previousAssociation);
|
||||
}
|
||||
return webPushSuccess(unavailable("LOCAL_FENCE_UNSAFE"));
|
||||
}
|
||||
|
||||
let revokeAmbiguous = false;
|
||||
if (previousAssociation) {
|
||||
const backend = await boundedBackendRevoke(previousAssociation);
|
||||
revokeAmbiguous = !backend.ok;
|
||||
}
|
||||
const nativeClean = await cleanupNative(
|
||||
previousAssociation,
|
||||
generation,
|
||||
capturedNative,
|
||||
fenced.value,
|
||||
);
|
||||
observeWebPush(dependencies.observer, {
|
||||
event: "web_push_association_revoked",
|
||||
outcome: revokeAmbiguous || !nativeClean ? "DEGRADED" : "SUCCEEDED",
|
||||
...(revokeAmbiguous
|
||||
? { reason: "BACKEND_REVOKE_AMBIGUOUS" }
|
||||
: !nativeClean
|
||||
? { reason: "NATIVE_UNSUBSCRIBE_AMBIGUOUS" }
|
||||
: {}),
|
||||
});
|
||||
if (revokeAmbiguous) {
|
||||
return webPushSuccess(unavailable("BACKEND_REVOKE_AMBIGUOUS"));
|
||||
}
|
||||
if (!nativeClean) {
|
||||
return webPushSuccess(unavailable("NATIVE_UNSUBSCRIBE_AMBIGUOUS"));
|
||||
}
|
||||
return webPushSuccess(unavailable("REVOKED"));
|
||||
}
|
||||
|
||||
function supportReadiness(): WebPushReadiness | null {
|
||||
if (!dependencies.secureContext) {
|
||||
if (!dependencies.secureContext || !requestLock) {
|
||||
return readiness("PUSH_UNSUPPORTED");
|
||||
}
|
||||
if (!dependencies.registration.active) {
|
||||
@@ -703,6 +781,7 @@ export function createWebPushSubscriptionAdapter(
|
||||
commit: registered.value,
|
||||
signal: input.signal,
|
||||
generation: input.generation,
|
||||
created: input.created,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -713,13 +792,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 +815,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 +1092,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 {
|
||||
|
||||
@@ -60,6 +60,8 @@ type ServiceWorkerClientsFacade = Readonly<{
|
||||
*/
|
||||
export type ServiceWorkerEventHost = Readonly<{
|
||||
origin: string;
|
||||
/** 06-09. `registration.scope`, the app root a refused click opens. */
|
||||
scope?: string;
|
||||
registration: ServiceWorkerRegistrationFacade;
|
||||
clients: ServiceWorkerClientsFacade;
|
||||
addEventListener(type: string, listener: (event: unknown) => void): void;
|
||||
@@ -118,6 +120,9 @@ export function createWebPushServiceWorkerRuntime(
|
||||
},
|
||||
},
|
||||
origin: dependencies.host.origin,
|
||||
...(dependencies.host.scope === undefined
|
||||
? {}
|
||||
: { appRootUrl: dependencies.host.scope }),
|
||||
now: dependencies.now,
|
||||
scheduler: dependencies.scheduler,
|
||||
observer: dependencies.observer,
|
||||
@@ -273,7 +278,9 @@ function notificationClickEventFacade(
|
||||
typeof value.waitUntil !== "function" ||
|
||||
!isRecord(value.notification) ||
|
||||
typeof value.notification.close !== "function" ||
|
||||
!Object.hasOwn(value.notification, "data")
|
||||
// 06-01. `data` is a WebIDL getter on `Notification.prototype`, never an
|
||||
// own property, so the check must follow the prototype chain.
|
||||
!("data" in value.notification)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -19,6 +19,7 @@ type MatchAllOptions = Parameters<
|
||||
export type NativeWorkerScope = Readonly<{
|
||||
location: Readonly<{ origin: string }>;
|
||||
registration: Readonly<{
|
||||
scope: string;
|
||||
showNotification(title: string, options: unknown): Promise<void>;
|
||||
}>;
|
||||
clients: Readonly<{
|
||||
@@ -36,6 +37,7 @@ export function createServiceWorkerScopeHost(
|
||||
): ServiceWorkerEventHost {
|
||||
return Object.freeze({
|
||||
origin: scope.location.origin,
|
||||
scope: scope.registration.scope,
|
||||
registration: Object.freeze({
|
||||
showNotification: (title: string, options: NotificationOptions) =>
|
||||
scope.registration.showNotification(title, {
|
||||
|
||||
@@ -26,6 +26,21 @@ export interface WebPushControlPort {
|
||||
signal?: AbortSignal;
|
||||
}>): Promise<WebPushResult<WebPushReadiness>>;
|
||||
|
||||
/**
|
||||
* 06-06. The session changed without `revoke` (expiry, cleared cookies, a
|
||||
* crash during logout), so the caller cannot name the stored authority. A
|
||||
* fence held by another `fenceGeneration` is rotated to `nextAuthority` as
|
||||
* REVOKED and the association it held is revoked, as `revoke` does. A fence
|
||||
* `nextAuthority`'s generation already holds is left alone and reported as
|
||||
* `inspect` reports it. Call it only with the authority the BFF has just
|
||||
* confirmed for the current session: a tab holding a stale session would
|
||||
* otherwise revoke the current account's association.
|
||||
*/
|
||||
revokeForeign(input: Readonly<{
|
||||
nextAuthority: PushAuthoritySnapshot;
|
||||
signal?: AbortSignal;
|
||||
}>): Promise<WebPushResult<WebPushReadiness>>;
|
||||
|
||||
dispose(): void;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { resolveRuntimeCapabilities } from "../contracts/runtime-capabilities.ts";
|
||||
import { INSTALLED_RUNTIME_CAPABILITIES } from "../features/installed-runtime-capabilities.ts";
|
||||
import type { TelemetryPort } from "../application/ports/telemetry-port.ts";
|
||||
import { createCompositionRoot } from "./composition-root.ts";
|
||||
import { loadReleaseManifest } from "./load-release-manifest.ts";
|
||||
import { loadRuntimeConfig } from "./load-runtime-config.ts";
|
||||
@@ -23,17 +24,23 @@ export type RuntimeCompositionDependencies = Readonly<{
|
||||
export async function createRuntimeComposition(
|
||||
dependencies: RuntimeCompositionDependencies = {},
|
||||
) {
|
||||
// 06-05. The optional host reports a Service Worker that did not start
|
||||
// through the same telemetry port as the application.
|
||||
let telemetry: TelemetryPort | undefined;
|
||||
const root = await createCompositionRoot({
|
||||
loadConfig: () => loadRuntimeConfig({ fetcher: dependencies.fetcher }),
|
||||
loadRelease: (runtime) =>
|
||||
loadReleaseManifest(runtime, { fetcher: dependencies.fetcher }),
|
||||
createAdapters: ({ config: runtime, release }) =>
|
||||
createRuntimeAdapters({
|
||||
createAdapters: async ({ config: runtime, release }) => {
|
||||
const adapters = await createRuntimeAdapters({
|
||||
runtime,
|
||||
release,
|
||||
fetcher: dependencies.fetcher,
|
||||
host: dependencies.host,
|
||||
}),
|
||||
});
|
||||
telemetry = adapters.outputPorts.telemetry;
|
||||
return adapters;
|
||||
},
|
||||
});
|
||||
|
||||
const capabilities = resolveRuntimeCapabilities(
|
||||
@@ -44,6 +51,7 @@ export async function createRuntimeComposition(
|
||||
capabilities,
|
||||
routerBasePath: root.config.build.routerBasePath,
|
||||
buildId: root.release.buildId,
|
||||
...(telemetry ? { telemetry } : {}),
|
||||
...(dependencies.host
|
||||
? {
|
||||
host: dependencies.host as Parameters<
|
||||
|
||||
@@ -8,6 +8,7 @@ import type {
|
||||
RuntimeStopReason,
|
||||
} from "../contracts/runtime-capabilities.ts";
|
||||
import type { ServiceWorkerRuntimeHost } from "../contracts/service-worker.ts";
|
||||
import type { TelemetryPort } from "../application/ports/telemetry-port.ts";
|
||||
import { createServiceWorkerRuntimeHost } from "./register-service-worker.ts";
|
||||
|
||||
/**
|
||||
@@ -39,6 +40,8 @@ export type OptionalRuntimeHostInput = Readonly<{
|
||||
host?: Parameters<typeof createServiceWorkerRuntimeHost>[0]["host"];
|
||||
blockers?: readonly (() => boolean)[];
|
||||
observe?: (observation: Readonly<{ event: string; outcome: string }>) => void;
|
||||
/** 06-05. Receives `service-worker.start.failed`. */
|
||||
telemetry?: TelemetryPort;
|
||||
}>;
|
||||
|
||||
export function createOptionalRuntimeHost(
|
||||
@@ -107,6 +110,13 @@ export function createOptionalRuntimeHost(
|
||||
: outcome.kind === "INCOMPATIBLE"
|
||||
? "INCOMPATIBLE"
|
||||
: "DEGRADED";
|
||||
if (outcome.kind === "FAILED" || outcome.kind === "INCOMPATIBLE") {
|
||||
input.telemetry?.emit("service-worker.start.failed", {
|
||||
error_kind:
|
||||
outcome.kind === "FAILED" ? outcome.code : outcome.kind,
|
||||
build_id: input.buildId,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!stopRequested) started = true;
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -85,6 +85,13 @@ export const TELEMETRY_REGISTRY = Object.freeze({
|
||||
"release tuple mismatch",
|
||||
["build_id", "active_release_id", "mismatch_kind"],
|
||||
),
|
||||
// 06-05. An ACTIVE worker that did not start (install failure, ownership
|
||||
// mismatch) is otherwise visible nowhere.
|
||||
"service-worker.start.failed": event(
|
||||
"service-worker.start.failed",
|
||||
"Service Worker start ended FAILED or INCOMPATIBLE",
|
||||
["error_kind", "build_id"],
|
||||
),
|
||||
"telemetry.delivery.dropped": event(
|
||||
"telemetry.delivery.dropped",
|
||||
"queue or sink failure",
|
||||
|
||||
Reference in New Issue
Block a user