From a5e6719b18319430f9322f719c4ff3cd468c07a4 Mon Sep 17 00:00:00 2001 From: DongHyeonka Date: Fri, 13 Nov 2026 18:58:02 +0900 Subject: [PATCH] =?UTF-8?q?fix(service-worker):=20=EC=A0=9C=ED=92=88=20?= =?UTF-8?q?=ED=99=9C=EC=84=B1=ED=99=94=20=EC=B9=B8=EC=9D=84=20=EC=97=B4?= =?UTF-8?q?=EA=B3=A0=20=EA=B0=B1=EC=8B=A0=20=EC=8B=A4=ED=8C=A8=EB=A5=BC=20?= =?UTF-8?q?=EA=B4=80=EC=B8=A1=ED=95=9C=EB=8B=A4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 문제: SW를 켠 제품이 새 버전 안내·reload 안내를 붙이려면 템플릿 파일을 고쳐야 한다(1103/09-05). 설치에 실패한 갱신(redundant)과 실패한 주기 검사는 아무 기록도 남기지 않는다(0925/06-05). build.assetsDir를 바꾸면 사전 캐시가 조용히 빈다(0925/06-08). 릴리스마다 바뀌지 않은 자산까지 no-store로 다시 받는다(1101/06-05). 쓰지 않는 protocol kind 셋과 reload guard 상수, void 참조, 손으로 쓴 protocol 버전 1, web-push의 fence 검사 두 벌이 남았다(1101/06-03, R1~R3). 고른 방법: - ProductServiceWorkerWiring에 onUpdateWaiting(activate)· onReloadRequired()를 더한다(추가만). create-runtime-composition이 worker 시작 전에 host 이벤트를 구독해 부르고, 던지면 버린다. page controller는 시작 때 이미 기다리던 갱신도 onUpdateWaiting 구독자에게 알린다. - page controller가 update_install REDUNDANT, update_check FAILED를 observe로 낸다. - 사전 캐시 생성기와 SW 설치가 빈 asset 목록을 거절하고, 시험이 vite.config.ts의 build.assetsDir와 BUILD_ASSET_DIRECTORY를 대조한다 (vite.config.ts는 그룹 C가 고치는 파일이라 건드리지 않았다). - 설치가 이전 릴리스 캐시의 같은 URL을 digest로 다시 확인해 복사하고, 없거나 맞지 않을 때만 받는다. - PAGE_HELLO·WORKER_HELLO_ACK·UPDATE_READY, reloadGuard*· retainedPreviousCaches를 지운다. sync 알림은 createServiceWorkerMessage로 만든다. fence 검사는 push-association-fence-store.ts 하나다. 버린 대안: 활성화 화면을 presentation 슬롯으로 열기 — 화면 문구와 흐름은 제품 것이라 조합 계약의 함수 칸이 작다. 위험·한계: 지운 kind는 보내는 곳이 없었다. 다른 빌드의 worker가 보내도 UNKNOWN_KIND로 관측만 된다. 재사용은 이전 캐시를 읽는 비용이 들고, 읽기 실패는 다운로드로 돌아간다. 검증: desktop check:types·lint·check:architecture· check:adapter-inventory rc=0, SW 시험 묶음 통과 (/tmp/claude-gates/r9b-pr1-quick). merge 단계는 PR 본문. Refs: 1103/09-05, 0925/06-05, 0925/06-08, 1101/06-03, 1101/06-05, 1101/R1, 1101/R2, 1101/R3 --- docs/architecture/optional-adapter-recipes.md | 24 +- docs/manual/03-outside-feature-folder.md | 4 +- scripts/generate-service-worker-assets.ts | 7 + .../service-worker/service-worker-entry.ts | 19 +- .../service-worker-lifecycle.ts | 2 +- .../service-worker-page-controller.ts | 11 +- .../service-worker/service-worker-protocol.ts | 3 - .../service-worker-static-assets.ts | 94 ++++++- .../inbound/notification-click-adapter.ts | 32 +-- .../web-push/inbound/push-event-adapter.ts | 26 +- .../web-push/push-association-fence-store.ts | 26 ++ src/bootstrap/create-runtime-composition.ts | 45 ++++ src/bootstrap/product-composition-contract.ts | 16 ++ src/contracts/service-worker.ts | 6 - ...tion-service-worker-product-wiring.test.ts | 97 ++++++- .../service-worker-asset-directory.test.ts | 25 ++ .../service-worker-update-observation.test.ts | 239 ++++++++++++++++++ 17 files changed, 592 insertions(+), 84 deletions(-) create mode 100644 tests/unit/service-worker-asset-directory.test.ts create mode 100644 tests/unit/service-worker-update-observation.test.ts diff --git a/docs/architecture/optional-adapter-recipes.md b/docs/architecture/optional-adapter-recipes.md index 19e66d3b..1f593690 100644 --- a/docs/architecture/optional-adapter-recipes.md +++ b/docs/architecture/optional-adapter-recipes.md @@ -124,9 +124,8 @@ type은 facade 밖으로 노출하지 않는다. SSOT다. 문서와 catalog가 다르면 gate가 검사하는 catalog를 우선 고치고 이 표도 같이 갱신한다. -Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7, 2의 시작 실패 -이벤트, 2의 `observe`와 3을 제품 소유 파일에서 잇는 자리를 갖고 있다. 4·5를 -잇는 제품 소유 자리는 아직 없다. +Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7·8, 2의 시작 실패 +이벤트를 갖고 있다. 2의 `observe`와 3·4·5는 제품 소유 파일에서 잇는 자리가 있다. 1. 제품 소유 파일 `src/features/product-capabilities.ts`의 `SERVICE_WORKER`를 `ACTIVE`로 바꾼다. `scripts/build-frontend.ts`가 worker 빌드를 추가로 돈다. @@ -138,9 +137,7 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7, 2의 시 (`src/bootstrap/optional-runtime-host.ts`). 실제 composition에서 첫 설치가 실패하면 이벤트가 1건 나가는 것은 `tests/component/runtime-composition-service-worker-telemetry.test.ts`가 - 확인한다. 템플릿이 연결하지 않은 것은 셋이다. 업데이트 설치 실패 - (`watchForUpdates`, `src/adapters/service-worker/service-worker-page-controller.ts`)는 - 이벤트를 남기지 않는다. page controller의 `observe`는 제품이 + 확인한다. 템플릿이 연결하지 않은 것은 둘이다. page controller의 `observe`는 제품이 `src/bootstrap/product-composition.ts`의 `composeProduct`에서 `serviceWorker.observe`로 돌려준다(1103/09-05). 템플릿 조립이 그것을 optional host에 넘기고, 던지면 무시한다. `OptionalRuntimeHost.health()`는 `src` 안에서 @@ -152,12 +149,17 @@ Service Worker를 켤 때 확인할 것(06-05). 템플릿은 1·6·7, 2의 시 값이 page controller에 닿는 것은 `tests/component/runtime-composition-service-worker-product-wiring.test.ts`가 확인한다. -4. 활성화 UI: `ServiceWorkerRuntimeHost.onUpdateWaiting`을 구독하고, 사용자가 - 동의하면 `requestActivation()`을 부른다(`src/contracts/service-worker.ts`). -5. reload 처리: `onReloadRequired`를 구독해 reload를 안내한다. -6. 끄기·롤백·제거: `docs/operations/release-cache-rollback.md`의 Service Worker +4. 활성화 UI: `composeProduct`가 `serviceWorker.onUpdateWaiting`을 돌려준다. 템플릿 + 조립이 `ServiceWorkerRuntimeHost.onUpdateWaiting`을 worker 시작 전에 구독해 그것을 + 부르고, 받은 `activate()`는 `requestActivation()`이다. 사용자가 동의하면 부른다 + (1103/09-05). +5. reload 처리: `serviceWorker.onReloadRequired`로 reload를 안내한다. 템플릿 조립이 + `onReloadRequired`를 구독해 부른다. +6. 갱신 실패: 설치에 실패한 갱신(`update_install` `REDUNDANT`)과 실패한 주기 검사 + (`update_check` `FAILED`)도 `observe`로 온다(0925/06-05). +7. 끄기·롤백·제거: `docs/operations/release-cache-rollback.md`의 Service Worker 절차. `service-worker.js`는 `Cache-Control: no-cache`로 서빙한다. -7. 실제 브라우저 검사: `tests/e2e/service-worker-update.spec.ts`와 +8. 실제 브라우저 검사: `tests/e2e/service-worker-update.spec.ts`와 `service-worker-recovery.spec.ts`를 제품 구성으로 돌린다. helper는 이미 `ACTIVE`인 선택을 그대로 쓰고, 캐시 단언은 빌드가 만든 사전 캐시 목록과 비교한다. 준비 단계에서 실패하면 helper(`tests/e2e/support/service-worker-builds.ts`) diff --git a/docs/manual/03-outside-feature-folder.md b/docs/manual/03-outside-feature-folder.md index 18b69456..196db5aa 100644 --- a/docs/manual/03-outside-feature-folder.md +++ b/docs/manual/03-outside-feature-folder.md @@ -177,12 +177,14 @@ src/features/product-capabilities.ts (SERVICE_WORKER = ACTIVE) serviceWorker: { blockers: [() => hasUnsavedEdits()], observe: (observation) => reportServiceWorker(observation), + onUpdateWaiting: (activate) => showUpdateNotice({ onAccept: activate }), + onReloadRequired: () => showReloadNotice(), }, } satisfies ProductComposition; } ``` -- 템플릿이 아직 연결하지 않은 것: 활성화 화면(`onUpdateWaiting`·`requestActivation()`). 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다. +- 활성화 화면도 같은 자리다(1103/09-05). `onUpdateWaiting`은 새 버전이 설치되어 기다릴 때(worker가 시작할 때 이미 기다리고 있던 것도) 불리고, 받은 `activate()`가 `requestActivation()`이다. 그래서 `blockers`가 그대로 걸린다. `onReloadRequired`는 다른 빌드의 worker가 넘겨받았을 때 불린다. 둘 다 던져도 worker 흐름은 바뀌지 않는다. 화면(`showUpdateNotice` 등)은 제품 것이다. 확인할 것 목록은 `docs/architecture/optional-adapter-recipes.md`의 "Service Worker를 켤 때 확인할 것"에 있다. - realtime·Web Worker·오프라인 명령을 고르면 조립이 `Selected optional capabilities have no runtime to start them`로 거절한다. 템플릿 조립에 아직 그 런타임이 없다. ### Web Worker를 들일 때 tsconfig 더하기 diff --git a/scripts/generate-service-worker-assets.ts b/scripts/generate-service-worker-assets.ts index 7f949d13..62c601e1 100644 --- a/scripts/generate-service-worker-assets.ts +++ b/scripts/generate-service-worker-assets.ts @@ -94,6 +94,13 @@ export async function collectStaticAssets( }); } + // 0925/06-08. Nothing under the directory means vite.config.ts moved the + // hashed files (`build.assetsDir`) away from the one the worker reads. + if (assets.length === 0) { + throw new Error( + `No hashed static asset under ${BUILD_ASSET_DIRECTORY} in the build: vite.config.ts build.assetsDir must name the directory BUILD_ASSET_DIRECTORY (src/contracts/service-worker.ts) names.`, + ); + } // 1112/06-02. The count and the bound, so the failure says how far over // it is. Each generated feature adds its lazy chunks here: with the Service // Worker on, the asset bound can come before the initial JavaScript budget. diff --git a/src/adapters/service-worker/service-worker-entry.ts b/src/adapters/service-worker/service-worker-entry.ts index de2614d6..35dd72a7 100644 --- a/src/adapters/service-worker/service-worker-entry.ts +++ b/src/adapters/service-worker/service-worker-entry.ts @@ -9,7 +9,10 @@ import { createServiceWorkerRuntime, type WorkerScopeLike, } from "./service-worker-lifecycle.ts"; -import { parseServiceWorkerMessage } from "./service-worker-protocol.ts"; +import { + createServiceWorkerMessage, + parseServiceWorkerMessage, +} from "./service-worker-protocol.ts"; /** * §17.1. The one physical worker entry for this scope. @@ -166,12 +169,14 @@ if (handlers.includes("OFFLINE_SYNC_WAKEUP")) { event.waitUntil( self.clients.matchAll({ type: "window" }).then((clients) => { for (const client of clients) { - client.postMessage({ - protocolVersion: 1, - kind: "SYNC_WAKE_OBSERVED", - messageId: crypto.randomUUID(), - sourceBuildId: identity.buildId, - }); + // 1101 R3. Built like every other message, so a protocol version + // change reaches this one too. + client.postMessage( + createServiceWorkerMessage({ + kind: "SYNC_WAKE_OBSERVED", + sourceBuildId: identity.buildId, + }), + ); } }), ); diff --git a/src/adapters/service-worker/service-worker-lifecycle.ts b/src/adapters/service-worker/service-worker-lifecycle.ts index 61ece109..eda14a52 100644 --- a/src/adapters/service-worker/service-worker-lifecycle.ts +++ b/src/adapters/service-worker/service-worker-lifecycle.ts @@ -161,12 +161,12 @@ export function createServiceWorkerRuntime( const previous = highestOld?.cacheName ?? oldCaches.at(-1) ?? null; // Q-6.6-9. Stale caches go first: when storage is full the marker write // below is what fails, and deleting is the only way space comes back. + // The current cache and one previous one (the rollback target) stay. const stale = selectCachesToDelete(names, current, previous); let deleted = 0; for (const name of stale) { if (await scope.caches.delete(name).catch(() => false)) deleted += 1; } - void SERVICE_WORKER_BOUNDS.retainedPreviousCaches; if ( !currentMarker || currentMarker.activationSequence < (highestOld?.activationSequence ?? 0) diff --git a/src/adapters/service-worker/service-worker-page-controller.ts b/src/adapters/service-worker/service-worker-page-controller.ts index c9c5f1e1..016025f6 100644 --- a/src/adapters/service-worker/service-worker-page-controller.ts +++ b/src/adapters/service-worker/service-worker-page-controller.ts @@ -188,6 +188,9 @@ export function createServiceWorkerPageController( if (registration.waiting) { observe("register", "UPDATE_WAITING"); + // 1103/09-05. The waiting update was installed before this page looked; + // its listeners hear it as they hear one found later. + notify(updateWaitingListeners); return Object.freeze({ kind: "UPDATE_WAITING" as const }); } // R-6.4. On a first visit `register()` resolves while the only worker is @@ -339,6 +342,10 @@ export function createServiceWorkerPageController( watched.active ) { notify(updateWaitingListeners); + } else if (worker.state === "redundant" && watched.active) { + // 0925/06-05. An update that failed to install leaves this page on + // its build with nothing waiting; only this record says why. + observe("update_install", "REDUNDANT"); } }); }; @@ -357,7 +364,9 @@ export function createServiceWorkerPageController( updateTimer = setInterval(() => { if (page?.visibilityState === "hidden") return; void registration?.update().catch(() => { - // A failed update check never fails a product flow. + // A failed update check never fails a product flow. 0925/06-05: it is + // recorded, so a deployment that never updates says so. + observe("update_check", "FAILED"); }); }, SERVICE_WORKER_BOUNDS.updateCheckIntervalMs); } diff --git a/src/adapters/service-worker/service-worker-protocol.ts b/src/adapters/service-worker/service-worker-protocol.ts index 45ebec3b..2146446d 100644 --- a/src/adapters/service-worker/service-worker-protocol.ts +++ b/src/adapters/service-worker/service-worker-protocol.ts @@ -13,9 +13,6 @@ import { */ const MESSAGE_KINDS: ReadonlySet = new Set([ - "PAGE_HELLO", - "WORKER_HELLO_ACK", - "UPDATE_READY", "ACTIVATE_REQUEST", "ACTIVATE_ACCEPTED", "ACTIVATE_REJECTED", diff --git a/src/adapters/service-worker/service-worker-static-assets.ts b/src/adapters/service-worker/service-worker-static-assets.ts index 4affcdb0..51955ebe 100644 --- a/src/adapters/service-worker/service-worker-static-assets.ts +++ b/src/adapters/service-worker/service-worker-static-assets.ts @@ -125,6 +125,9 @@ export function validateStaticAssetManifest( ) { return rejected("MANIFEST_INVALID"); } + // 0925/06-08. A build whose `build.assetsDir` left `BUILD_ASSET_DIRECTORY` + // generates no assets; installing that would serve nothing, silently. + if (manifest.assets.length === 0) return rejected("MANIFEST_INVALID"); if (manifest.assets.length > bounds.assets) { return rejected("ASSET_COUNT_EXCEEDED"); } @@ -233,6 +236,7 @@ async function installCandidate( const queue = [...manifest.assets]; let failure: InstallOutcome | null = null; + const previous = await previousStaticCaches(dependencies.caches, cacheName); const worker = async (): Promise => { for (;;) { @@ -244,7 +248,9 @@ async function installCandidate( } const asset = queue.shift(); if (!asset) return; - const outcome = await storeAsset(asset, cache, dependencies, signal); + const outcome = (await reuseVerifiedAsset(asset, cache, previous, dependencies, signal)) + ? null + : await storeAsset(asset, cache, dependencies, signal); if (outcome) { failure ??= outcome; abortController.abort(); @@ -265,6 +271,67 @@ async function installCandidate( }); } +/** + * 1101/06-05. The verified caches of earlier releases still in this origin, + * newest last. Each asset URL is content-hashed, so an unchanged file keeps + * its URL from release to release. + */ +async function previousStaticCaches( + caches: InstallDependencies["caches"], + cacheName: string, +): Promise { + try { + const names = ((await caches.keys?.()) ?? []).filter( + (name) => isOwnedStaticCacheName(name) && name !== cacheName, + ); + return Object.freeze(await Promise.all(names.map((name) => caches.open(name)))); + } catch { + return Object.freeze([]); + } +} + +/** + * 1101/06-05. Copies an asset an earlier release already cached instead of + * downloading it again, after checking its bytes against this manifest's + * digest exactly as a download is checked. Anything else (no copy, another + * size or digest, a cache that throws) is a miss and the asset is fetched. + */ +async function reuseVerifiedAsset( + asset: StaticAssetManifestV1["assets"][number], + cache: Cache, + previous: readonly Cache[], + dependencies: InstallDependencies, + signal: AbortSignal, +): Promise { + for (const candidate of [...previous].reverse()) { + if (signal.aborted) return false; + try { + const found = await abortable(Promise.resolve(candidate.match(asset.url)), signal); + if (found === ABORTED) return false; + if (!found || found.status !== 200) continue; + // The copy keeps its stored headers, so they pass the download's check. + if (!contentTypeMatches(found, asset.contentType)) continue; + const body = await readBoundedBody(found, asset.bytes, signal); + if (!body.ok) continue; + const digest = await abortable(Promise.resolve(dependencies.digest(body.bytes)), signal); + if (digest === ABORTED) return false; + if (digest !== asset.sha256) continue; + await cache.put( + asset.url, + new Response(body.bytes.slice(), { + status: found.status, + statusText: found.statusText, + headers: found.headers, + }), + ); + return true; + } catch { + // A broken earlier cache is a miss, never an install failure. + } + } + return false; +} + async function storeAsset( asset: StaticAssetManifestV1["assets"][number], cache: Cache, @@ -298,18 +365,7 @@ async function storeAsset( if (response.status !== 200 || response.type === "opaque") { return rejected("STATUS_INVALID"); } - const contentType = - response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? - ""; - const expectedType = asset.contentType.toLowerCase(); - if ( - contentType !== expectedType && - // R-6.5. Servers still send `application/javascript` for `.js`. - !( - JAVASCRIPT_MIME_TYPES.has(contentType) && - JAVASCRIPT_MIME_TYPES.has(expectedType) - ) - ) { + if (!contentTypeMatches(response, asset.contentType)) { return rejected("CONTENT_TYPE_INVALID"); } @@ -347,6 +403,18 @@ async function storeAsset( return null; } +function contentTypeMatches(response: Response, expected: string): boolean { + const contentType = + response.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase() ?? + ""; + const expectedType = expected.toLowerCase(); + return ( + contentType === expectedType || + // R-6.5. Servers still send `application/javascript` for `.js`. + (JAVASCRIPT_MIME_TYPES.has(contentType) && JAVASCRIPT_MIME_TYPES.has(expectedType)) + ); +} + /** WHATWG MIME Sniffing: every essence that denotes a JavaScript MIME type. */ const JAVASCRIPT_MIME_TYPES: ReadonlySet = new Set([ "application/ecmascript", diff --git a/src/adapters/web-push/inbound/notification-click-adapter.ts b/src/adapters/web-push/inbound/notification-click-adapter.ts index 4faab467..af343889 100644 --- a/src/adapters/web-push/inbound/notification-click-adapter.ts +++ b/src/adapters/web-push/inbound/notification-click-adapter.ts @@ -7,7 +7,10 @@ import { type WebPushObserver, type WebPushResult, } from "../../../contracts/web-push.ts"; -import type { PushAssociationFenceStore } from "../push-association-fence-store.ts"; +import { + type PushAssociationFenceStore, + validateActivePushFence, +} from "../push-association-fence-store.ts"; import { decodeNotificationClickData } from "../push-codec.ts"; import type { WebPushNotificationRegistry } from "../notification-registry.ts"; import { @@ -353,30 +356,17 @@ export function createNotificationClickAdapter(dependencies: Readonly<{ ); } - async function validateActiveFence( + function validateActiveFence( associationEpoch: string, releaseEpoch: string, signal: AbortSignal, ): Promise> { - const control = await dependencies.fenceStore.read({ signal }); - if (!control.ok) return control; - if ( - !control.value || - control.value.control.association.state !== "ACTIVE" || - control.value.control.association.associationEpoch !== - associationEpoch - ) { - return webPushFailure( - "ASSOCIATION_MISMATCH", - "NOTIFICATION_CLICK", - ); - } - return control.value.control.releaseEpoch === releaseEpoch - ? webPushSuccess(undefined) - : webPushFailure( - "RELEASE_MISMATCH", - "NOTIFICATION_CLICK", - ); + return validateActivePushFence( + dependencies.fenceStore, + { associationEpoch, releaseEpoch }, + "NOTIFICATION_CLICK", + signal, + ); } } diff --git a/src/adapters/web-push/inbound/push-event-adapter.ts b/src/adapters/web-push/inbound/push-event-adapter.ts index 9b15f5b0..0ced1eaa 100644 --- a/src/adapters/web-push/inbound/push-event-adapter.ts +++ b/src/adapters/web-push/inbound/push-event-adapter.ts @@ -6,7 +6,10 @@ import { type WebPushObserver, type WebPushResult, } from "../../../contracts/web-push.ts"; -import type { PushAssociationFenceStore } from "../push-association-fence-store.ts"; +import { + type PushAssociationFenceStore, + validateActivePushFence, +} from "../push-association-fence-store.ts"; import { clickDataFromHint, decodeWebPushHint, @@ -193,23 +196,16 @@ export function createPushEventAdapter(dependencies: Readonly<{ return webPushSuccess(undefined); } - async function validateActiveFence( + function validateActiveFence( associationEpoch: string, releaseEpoch: string, signal: AbortSignal, ): Promise> { - const control = await dependencies.fenceStore.read({ signal }); - if (!control.ok) return control; - if ( - !control.value || - control.value.control.association.state !== "ACTIVE" || - control.value.control.association.associationEpoch !== - associationEpoch - ) { - return webPushFailure("ASSOCIATION_MISMATCH", "PUSH_HANDLE"); - } - return control.value.control.releaseEpoch === releaseEpoch - ? webPushSuccess(undefined) - : webPushFailure("RELEASE_MISMATCH", "PUSH_HANDLE"); + return validateActivePushFence( + dependencies.fenceStore, + { associationEpoch, releaseEpoch }, + "PUSH_HANDLE", + signal, + ); } } diff --git a/src/adapters/web-push/push-association-fence-store.ts b/src/adapters/web-push/push-association-fence-store.ts index 6bf49044..5cfb5f39 100644 --- a/src/adapters/web-push/push-association-fence-store.ts +++ b/src/adapters/web-push/push-association-fence-store.ts @@ -144,6 +144,32 @@ export interface PushAssociationFenceStore { close(): void; } +/** + * 1101 R2. The fence a push and a notification click both pass before they + * act: an ACTIVE association with the same epoch, then the same release. + * One copy, so the two inbound adapters cannot drift apart. + */ +export async function validateActivePushFence( + fenceStore: Pick, + expected: Readonly<{ associationEpoch: string; releaseEpoch: string }>, + operation: WebPushOperation, + signal: AbortSignal, +): Promise> { + const control = await fenceStore.read({ signal }); + if (!control.ok) return control; + if ( + !control.value || + control.value.control.association.state !== "ACTIVE" || + control.value.control.association.associationEpoch !== + expected.associationEpoch + ) { + return webPushFailure("ASSOCIATION_MISMATCH", operation); + } + return control.value.control.releaseEpoch === expected.releaseEpoch + ? webPushSuccess(undefined) + : webPushFailure("RELEASE_MISMATCH", operation); +} + export type PushAssociationFenceStoreDependencies = Readonly<{ repository: PushControlRepository; idempotencyKeyFactory?: () => string; diff --git a/src/bootstrap/create-runtime-composition.ts b/src/bootstrap/create-runtime-composition.ts index a6eea582..e6a660d3 100644 --- a/src/bootstrap/create-runtime-composition.ts +++ b/src/bootstrap/create-runtime-composition.ts @@ -68,11 +68,17 @@ export async function createRuntimeComposition( : {}), }); + const disconnectProductServiceWorker = connectProductServiceWorker( + optional.serviceWorker, + productServiceWorker, + ); + return Object.freeze({ ...root, capabilities, optional, async dispose(): Promise { + disconnectProductServiceWorker(); // §20.3. Optional runtime first, then the base infrastructure: the query // cache is cleared only after realtime and worker admission has closed, // so a late effect cannot repopulate a cleared cache. @@ -113,3 +119,42 @@ function serviceWorkerWiring( : {}), }; } + +/** + * 1103/09-05. The product's update notice and reload prompt, subscribed + * before the worker starts so a waiting update found at start reaches them. + * Their throws are product code and are dropped. Returns the unsubscribe. + */ +function connectProductServiceWorker( + host: OptionalRuntimeHost["serviceWorker"], + wiring: ProductServiceWorkerWiring | null | undefined, +): () => void { + if (!host || !wiring) return () => {}; + const unsubscribes: (() => void)[] = []; + const { onUpdateWaiting, onReloadRequired } = wiring; + if (onUpdateWaiting && host.onUpdateWaiting) { + unsubscribes.push( + host.onUpdateWaiting(() => { + try { + onUpdateWaiting(() => host.requestActivation()); + } catch { + // A failing product notice never changes the worker's outcome. + } + }), + ); + } + if (onReloadRequired && host.onReloadRequired) { + unsubscribes.push( + host.onReloadRequired(() => { + try { + onReloadRequired(); + } catch { + // As above. + } + }), + ); + } + return () => { + for (const unsubscribe of unsubscribes.splice(0)) unsubscribe(); + }; +} diff --git a/src/bootstrap/product-composition-contract.ts b/src/bootstrap/product-composition-contract.ts index 7d39f85c..1a47e27f 100644 --- a/src/bootstrap/product-composition-contract.ts +++ b/src/bootstrap/product-composition-contract.ts @@ -3,6 +3,7 @@ import type { ContractHttpExecutorDependencies, InstalledHttpOperationExecutor, } from "../adapters/http/index.ts"; +import type { ServiceWorkerActivationOutcome } from "../contracts/service-worker.ts"; import type { FeaturePlatformCapabilities } from "../features/feature-adapter-contribution.ts"; import type { RuntimeConfig } from "./runtime-config-schema.ts"; @@ -162,6 +163,21 @@ export type ProductServiceWorkerWiring = Readonly<{ * `client_drain`, ...), each with its outcome. A throw is ignored. */ observe?(observation: Readonly<{ event: string; outcome: string }>): void; + /** + * 1103/09-05. An update finished installing and waits for this tab, found + * when the worker starts or later: show the product's "new version" notice + * and call `activate()` when the user agrees. `activate()` is + * `requestActivation()`, so `blockers` still apply. A throw is ignored. + */ + onUpdateWaiting?( + activate: () => Promise, + ): void; + /** + * 1103/09-05. A worker of another build took over (this tab asked, or + * another one did), so this page runs old code: ask the user to reload, or + * reload. A throw is ignored. + */ + onReloadRequired?(): void; }>; export type ProductComposition = Readonly<{ diff --git a/src/contracts/service-worker.ts b/src/contracts/service-worker.ts index 85d4deeb..8140fbe3 100644 --- a/src/contracts/service-worker.ts +++ b/src/contracts/service-worker.ts @@ -23,9 +23,6 @@ export const SERVICE_WORKER_BOUNDS = Object.freeze({ */ activationReplySlackMs: 5_000, updateCheckIntervalMs: 6 * 60 * 60 * 1_000, - retainedPreviousCaches: 1, - reloadGuardBytes: 512, - reloadGuardTtlMs: 10 * 60 * 1_000, }); export type ServiceWorkerHandlerId = @@ -64,9 +61,6 @@ export type ServiceWorkerProtocolIdentity = Readonly<{ }>; export type ServiceWorkerMessageKind = - | "PAGE_HELLO" - | "WORKER_HELLO_ACK" - | "UPDATE_READY" | "ACTIVATE_REQUEST" | "ACTIVATE_ACCEPTED" | "ACTIVATE_REJECTED" diff --git a/tests/component/runtime-composition-service-worker-product-wiring.test.ts b/tests/component/runtime-composition-service-worker-product-wiring.test.ts index 440de1f3..995c61dc 100644 --- a/tests/component/runtime-composition-service-worker-product-wiring.test.ts +++ b/tests/component/runtime-composition-service-worker-product-wiring.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from "vitest"; +import { createServiceWorkerMessage } from "../../src/adapters/service-worker/service-worker-protocol.ts"; import { createRuntimeComposition } from "../../src/bootstrap/create-runtime-composition.ts"; import type { ProductComposition } from "../../src/bootstrap/product-composition-contract.ts"; @@ -16,6 +17,9 @@ import type { ProductComposition } from "../../src/bootstrap/product-composition const product = vi.hoisted(() => ({ observed: [] as Array>, dirty: true, + /** 1103/09-05. Each `activate` the product's update notice received. */ + updates: [] as Array<() => Promise>, + reloads: 0, })); vi.mock("../../src/features/installed-runtime-capabilities.ts", async (importOriginal) => { @@ -46,6 +50,14 @@ vi.mock("../../src/bootstrap/product-composition.ts", () => ({ // The composition drops a throwing product sink. throw new Error("product sink failure"); }, + onUpdateWaiting(activate) { + product.updates.push(activate); + throw new Error("product notice failure"); + }, + onReloadRequired() { + product.reloads += 1; + throw new Error("product prompt failure"); + }, }, }), })); @@ -98,7 +110,10 @@ async function fetcher(input: RequestInfo | URL): Promise { } /** This page's worker is active and the next build's is waiting. */ -function updateWaitingContainer(): ServiceWorkerContainer { +function updateWaitingContainer(): ServiceWorkerContainer & { + /** Delivers a worker message to the page, as from the waiting worker. */ + dispatchFromWaiting(data: unknown): void; +} { const worker = (scriptURL: string, state: string) => ({ scriptURL, state, @@ -106,13 +121,16 @@ function updateWaitingContainer(): ServiceWorkerContainer { addEventListener() {}, removeEventListener() {}, }); + let waiting: ReturnType | null = null; + const messageListeners = new Set<(event: MessageEvent) => void>(); const register = vi.fn( async (scriptURL: string | URL, options?: RegistrationOptions) => { const script = new URL(scriptURL, origin).href; + waiting = worker(script, "installed"); return { scope: new URL(options?.scope ?? "/", origin).href, installing: null, - waiting: worker(script, "installed"), + waiting, active: worker(script, "activated"), addEventListener() {}, removeEventListener() {}, @@ -125,9 +143,17 @@ function updateWaitingContainer(): ServiceWorkerContainer { register, getRegistration: vi.fn(async () => undefined), getRegistrations: vi.fn(async () => []), - addEventListener() {}, - removeEventListener() {}, - } as unknown as ServiceWorkerContainer; + addEventListener(type: string, listener: (event: MessageEvent) => void) { + if (type === "message") messageListeners.add(listener); + }, + removeEventListener(type: string, listener: (event: MessageEvent) => void) { + if (type === "message") messageListeners.delete(listener); + }, + dispatchFromWaiting(data: unknown) { + const event = { data, origin, source: waiting } as unknown as MessageEvent; + for (const listener of messageListeners) listener(event); + }, + } as unknown as ServiceWorkerContainer & { dispatchFromWaiting(data: unknown): void }; } describe("1103/09-05 the product wires the worker in product-composition.ts", () => { @@ -160,3 +186,64 @@ describe("1103/09-05 the product wires the worker in product-composition.ts", () } }); }); + +describe("1103/09-05 the product's update notice and reload prompt", () => { + it("are called from product-composition.ts alone, and their throws are dropped", async () => { + product.updates = []; + product.reloads = 0; + product.dirty = false; + const container = updateWaitingContainer(); + const composition = await createRuntimeComposition({ + fetcher, + host: { + location: { origin }, + navigator: { serviceWorker: container }, + }, + }); + + try { + await composition.optional.startAfterMount(); + // The update was waiting when the worker started. + expect(product.updates).toHaveLength(1); + + container.dispatchFromWaiting( + createServiceWorkerMessage({ + kind: "ACTIVATED_RELOAD_REQUIRED", + sourceBuildId: "next-build", + }), + ); + expect(product.reloads).toBe(1); + } finally { + await composition.dispose(); + product.dirty = true; + } + // Disposed: the product hears nothing more. + container.dispatchFromWaiting( + createServiceWorkerMessage({ + kind: "ACTIVATED_RELOAD_REQUIRED", + sourceBuildId: "next-build", + }), + ); + expect(product.reloads).toBe(1); + }); + + it("hands the notice an activate that is requestActivation, blockers included", async () => { + product.updates = []; + const composition = await createRuntimeComposition({ + fetcher, + host: { + location: { origin }, + navigator: { serviceWorker: updateWaitingContainer() }, + }, + }); + + try { + await composition.optional.startAfterMount(); + await expect(product.updates[0]?.()).resolves.toEqual({ + kind: "BLOCKED_DIRTY_CLIENT", + }); + } finally { + await composition.dispose(); + } + }); +}); diff --git a/tests/unit/service-worker-asset-directory.test.ts b/tests/unit/service-worker-asset-directory.test.ts new file mode 100644 index 00000000..29f725f5 --- /dev/null +++ b/tests/unit/service-worker-asset-directory.test.ts @@ -0,0 +1,25 @@ +import { describe, expect, it } from "vitest"; + +import { BUILD_ASSET_DIRECTORY } from "../../src/contracts/service-worker.ts"; +import viteConfig from "../../vite.config.ts"; + +/** + * 0925/06-08. The Service Worker precache, its previous-release fallback and + * the hosting probe read `BUILD_ASSET_DIRECTORY`; Vite writes the hashed + * files to `build.assetsDir`. A product that changed only the Vite setting + * got a worker with an empty precache and a probe that checked nothing, with + * every gate green. The two are held equal here, and the worker generator and + * install refuse an empty asset set besides. + */ +const VITE_DEFAULT_ASSETS_DIR = "assets"; + +describe("0925/06-08 the build's asset directory is the worker's", () => { + it("vite.config.ts build.assetsDir names BUILD_ASSET_DIRECTORY", async () => { + const config = + typeof viteConfig === "function" + ? await viteConfig({ command: "build", mode: "production", isSsrBuild: false, isPreview: false }) + : viteConfig; + + expect(`${config.build?.assetsDir ?? VITE_DEFAULT_ASSETS_DIR}/`).toBe(BUILD_ASSET_DIRECTORY); + }); +}); diff --git a/tests/unit/service-worker-update-observation.test.ts b/tests/unit/service-worker-update-observation.test.ts new file mode 100644 index 00000000..871f9bf2 --- /dev/null +++ b/tests/unit/service-worker-update-observation.test.ts @@ -0,0 +1,239 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { createServiceWorkerPageController } from "../../src/adapters/service-worker/index.ts"; +import { installStaticAssets } from "../../src/adapters/service-worker/service-worker-static-assets.ts"; +import { + SERVICE_WORKER_BOUNDS, + SERVICE_WORKER_SCRIPT_PATH, +} from "../../src/contracts/service-worker.ts"; + +/** + * 0925/06-05. An update that failed to install (the new worker went + * `redundant`) and a periodic update check that failed left no record: the + * page stayed on its build and nothing said why. + * + * 1103/09-05. An update already waiting when the page registered was reported + * only as the start outcome, so a product notice subscribed to + * `onUpdateWaiting` never heard of it. + */ + +const ORIGIN = "https://app.example"; + +class FakeWorker extends EventTarget { + readonly scriptURL = `${ORIGIN}/${SERVICE_WORKER_SCRIPT_PATH}`; + constructor(public state: ServiceWorkerState) { + super(); + } + postMessage(): void {} + move(state: ServiceWorkerState): void { + this.state = state; + this.dispatchEvent(new Event("statechange")); + } +} + +function browser(options: Readonly<{ waiting?: boolean; update?: () => Promise }> = {}) { + const registration = Object.assign(new EventTarget(), { + scope: `${ORIGIN}/`, + installing: null as FakeWorker | null, + waiting: options.waiting ? new FakeWorker("installed") : null, + active: new FakeWorker("activated"), + update: vi.fn(options.update ?? (async () => {})), + }); + const container = { + controller: registration.active, + register: vi.fn(async () => registration), + addEventListener() {}, + removeEventListener() {}, + }; + return { registration, container }; +} + +function controllerFor(container: unknown) { + const observed: Array> = []; + const controller = createServiceWorkerPageController({ + selection: { mode: "ACTIVE", scriptPath: SERVICE_WORKER_SCRIPT_PATH, handlers: [] }, + disabledCleanup: false, + routerBasePath: "/", + origin: ORIGIN, + buildId: "page-build", + container: container as ServiceWorkerContainer, + observe: (observation) => observed.push(observation), + }); + return { controller, observed }; +} + +afterEach(() => { + vi.useRealTimers(); +}); + +describe("0925/06-05 update failures are observed", () => { + it("records an update whose install failed", async () => { + const { registration, container } = browser(); + const { controller, observed } = controllerFor(container); + await controller.start(); + + const update = new FakeWorker("installing"); + registration.installing = update; + registration.dispatchEvent(new Event("updatefound")); + update.move("redundant"); + + expect(observed).toContainEqual({ event: "update_install", outcome: "REDUNDANT" }); + await controller.stop(); + }); + + it("records a periodic update check that failed", async () => { + vi.useFakeTimers(); + const { container } = browser({ + update: async () => { + throw new TypeError("network"); + }, + }); + const { controller, observed } = controllerFor(container); + await controller.start(); + + await vi.advanceTimersByTimeAsync(SERVICE_WORKER_BOUNDS.updateCheckIntervalMs); + + expect(observed).toContainEqual({ event: "update_check", outcome: "FAILED" }); + await controller.stop(); + }); + + it("records nothing for an update that installed", async () => { + const { registration, container } = browser(); + const { controller, observed } = controllerFor(container); + const waiting = vi.fn(); + controller.onUpdateWaiting?.(waiting); + await controller.start(); + + const update = new FakeWorker("installing"); + registration.installing = update; + registration.dispatchEvent(new Event("updatefound")); + registration.waiting = update; + update.move("installed"); + + expect(waiting).toHaveBeenCalledOnce(); + expect(observed.some(({ event }) => event.startsWith("update_"))).toBe(false); + await controller.stop(); + }); +}); + +describe("1103/09-05 an update waiting at start reaches onUpdateWaiting", () => { + it("tells the listener once, with the UPDATE_WAITING start outcome", async () => { + const { container } = browser({ waiting: true }); + const { controller } = controllerFor(container); + const waiting = vi.fn(); + controller.onUpdateWaiting?.(waiting); + + await expect(controller.start()).resolves.toEqual({ kind: "UPDATE_WAITING" }); + + expect(waiting).toHaveBeenCalledOnce(); + await controller.stop(); + }); +}); + +/** + * 1101/06-05. Every release downloaded the whole asset set again with + * `no-store`, even the files whose content-hashed names it shared with the + * release before. A verified copy in an earlier release's cache is reused; + * the download stays for a file that is new, missing or no longer matches. + */ +describe("1101/06-05 an earlier release's verified asset is reused", () => { + const CURRENT = `ca-static-v1-${"a".repeat(16)}`; + const PREVIOUS = `ca-static-v1-${"c".repeat(16)}`; + const kept = new TextEncoder().encode("kept"); + const fresh = new TextEncoder().encode("fresh"); + /** A fake digest: one hex digit per content. */ + const DIGESTS: Readonly> = { kept: "1", fresh: "2", tamp: "3" }; + const digestOf = (bytes: Uint8Array) => + `sha256:${(DIGESTS[new TextDecoder().decode(bytes)] ?? "f").repeat(64)}`; + const asset = (name: string, bytes: Uint8Array) => ({ + url: `${ORIGIN}/assets/${name}`, + sha256: digestOf(bytes) as `sha256:${string}`, + bytes: bytes.byteLength, + contentType: "text/javascript", + }); + const manifest = { + schemaVersion: 1 as const, + buildId: "worker-build", + releaseId: "release-2", + setDigest: `sha256:${"a".repeat(64)}` as const, + assets: [asset("kept", kept), asset("fresh", fresh)], + }; + + async function install( + previous: Readonly>, + previousContentType = "text/javascript", + ) { + const put = vi.fn(async () => {}); + const previousCache = { + match: vi.fn(async (url: string) => { + const bytes = previous[url]; + return bytes + ? new Response(bytes.slice(), { headers: { "content-type": previousContentType } }) + : undefined; + }), + }; + const fetcher = vi.fn(async (input: RequestInfo | URL) => { + const bytes = String(input).endsWith("kept") ? kept : fresh; + return new Response(bytes.slice(), { headers: { "content-type": "text/javascript" } }); + }); + const result = await installStaticAssets(manifest, { + caches: { + open: vi.fn(async (name: string) => + (name === PREVIOUS ? previousCache : { put }) as unknown as Cache, + ), + delete: vi.fn(async () => true), + keys: vi.fn(async () => [PREVIOUS]), + }, + fetcher: fetcher as unknown as typeof fetch, + digest: vi.fn(async (bytes: Uint8Array) => digestOf(bytes)), + }); + return { result, fetched: fetcher.mock.calls.map(([input]) => String(input)), put }; + } + + it("copies the unchanged file and downloads only the new one", async () => { + const { result, fetched, put } = await install({ [`${ORIGIN}/assets/kept`]: kept }); + + expect(result).toEqual({ kind: "INSTALLED", cacheName: CURRENT, assets: 2 }); + expect(fetched).toEqual([`${ORIGIN}/assets/fresh`]); + expect(put).toHaveBeenCalledTimes(2); + }); + + it("downloads a file whose earlier copy was stored with another content type", async () => { + const { fetched } = await install({ [`${ORIGIN}/assets/kept`]: kept }, "text/css"); + + expect(fetched.sort()).toEqual([`${ORIGIN}/assets/fresh`, `${ORIGIN}/assets/kept`]); + }); + + it("downloads a file whose earlier copy no longer matches its digest", async () => { + const { result, fetched } = await install({ + [`${ORIGIN}/assets/kept`]: new TextEncoder().encode("tamp"), + }); + + expect(result).toMatchObject({ kind: "INSTALLED" }); + expect(fetched.sort()).toEqual([`${ORIGIN}/assets/fresh`, `${ORIGIN}/assets/kept`]); + }); +}); + +describe("0925/06-08 an empty asset manifest is refused", () => { + it("does not install a worker that would serve nothing", async () => { + const fetcher = vi.fn(); + + await expect( + installStaticAssets( + { + schemaVersion: 1, + buildId: "worker-build", + releaseId: "release-2", + setDigest: `sha256:${"a".repeat(64)}`, + assets: [], + }, + { + caches: { open: vi.fn(), delete: vi.fn(async () => true) }, + fetcher: fetcher as unknown as typeof fetch, + digest: vi.fn(), + }, + ), + ).resolves.toEqual({ kind: "REJECTED", code: "MANIFEST_INVALID" }); + expect(fetcher).not.toHaveBeenCalled(); + }); +});