fix(service-worker): 제품 활성화 칸을 열고 갱신 실패를 관측한다
frontend-quality-gates / merge / static checks (pull_request) Successful in 1m17s
frontend-quality-gates / merge / tests (pull_request) Successful in 11m53s
frontend-quality-gates / merge / browser tests (pull_request) Successful in 5m36s
frontend-quality-gates / FE-GATE-017 / diagram-review (pull_request) Skipped
frontend-quality-gates / main / self-tests and removal drills (pull_request) Skipped
frontend-quality-gates / FE-GATE-014 / config-compatibility (pull_request) Skipped
frontend-quality-gates / FE-GATE-028 / manual-accessibility-review (pull_request) Skipped
frontend-quality-gates / FE-GATE-026 / lab-performance (pull_request) Skipped
frontend-quality-gates / FE-GATE-015 / immutable-release-candidate (pull_request) Skipped
frontend-quality-gates / external-vulnerability-provider (pull_request) Skipped
frontend-quality-gates / external-provenance-provider (pull_request) Skipped
frontend-quality-gates / promote-verified-immutable-candidate (pull_request) Skipped
frontend-quality-gates / deploy-promoted-release (pull_request) Skipped
frontend-quality-gates / FE-GATE-019 / hosting-header (pull_request) Skipped
frontend-quality-gates / FE-GATE-021 / runbook-boot-config (pull_request) Skipped
frontend-quality-gates / FE-GATE-022 / runbook-chunk-mismatch (pull_request) Skipped
frontend-quality-gates / FE-GATE-023 / runbook-api-degradation (pull_request) Skipped
frontend-quality-gates / FE-GATE-024 / runbook-telemetry (pull_request) Skipped
frontend-quality-gates / FE-GATE-025 / runbook-release-rollback (pull_request) Skipped
frontend-quality-gates / FE-GATE-018 / field-web-vitals (pull_request) Skipped

문제: 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
This commit is contained in:
DongHyeonka
2026-11-13 19:02:07 +09:00
parent 762393a940
commit a5e6719b18
17 changed files with 592 additions and 84 deletions
+13 -11
View File
@@ -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`)
+3 -1
View File
@@ -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 더하기
@@ -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.
@@ -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,
}),
);
}
}),
);
@@ -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)
@@ -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);
}
@@ -13,9 +13,6 @@ import {
*/
const MESSAGE_KINDS: ReadonlySet<string> = new Set<ServiceWorkerMessageKind>([
"PAGE_HELLO",
"WORKER_HELLO_ACK",
"UPDATE_READY",
"ACTIVATE_REQUEST",
"ACTIVATE_ACCEPTED",
"ACTIVATE_REJECTED",
@@ -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<void> => {
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<readonly Cache[]> {
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<boolean> {
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<string> = new Set([
"application/ecmascript",
@@ -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<WebPushResult<void>> {
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,
);
}
}
@@ -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<WebPushResult<void>> {
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,
);
}
}
@@ -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<PushAssociationFenceStore, "read">,
expected: Readonly<{ associationEpoch: string; releaseEpoch: string }>,
operation: WebPushOperation,
signal: AbortSignal,
): Promise<WebPushResult<void>> {
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;
@@ -68,11 +68,17 @@ export async function createRuntimeComposition(
: {}),
});
const disconnectProductServiceWorker = connectProductServiceWorker(
optional.serviceWorker,
productServiceWorker,
);
return Object.freeze({
...root,
capabilities,
optional,
async dispose(): Promise<void> {
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();
};
}
@@ -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<ServiceWorkerActivationOutcome>,
): 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<{
-6
View File
@@ -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"
@@ -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<Readonly<{ event: string; outcome: string }>>,
dirty: true,
/** 1103/09-05. Each `activate` the product's update notice received. */
updates: [] as Array<() => Promise<unknown>>,
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<Response> {
}
/** 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<typeof worker> | 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();
}
});
});
@@ -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);
});
});
@@ -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<void> }> = {}) {
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<Readonly<{ event: string; outcome: string }>> = [];
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<Record<string, string>> = { 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<Record<string, Uint8Array>>,
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();
});
});