Files
clean-architecture-frontend…/tests/component/runtime-composition-service-worker-product-wiring.test.ts
T
DongHyeonka a5e6719b18
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
fix(service-worker): 제품 활성화 칸을 열고 갱신 실패를 관측한다
문제: 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
2026-11-13 19:02:07 +09:00

250 lines
7.9 KiB
TypeScript

// @vitest-environment jsdom
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";
/**
* 1103/09-05. A product that turns the worker on wires its activation blockers
* (a tab with unsaved edits) and the page controller's observer in its own
* `product-composition.ts`, not in the template's composition file. This runs
* the real composition with an ACTIVE selection, a product composition that
* returns `serviceWorker`, and a registration whose update is waiting.
*/
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) => {
const original =
await importOriginal<typeof import("../../src/features/installed-runtime-capabilities.ts")>();
return {
INSTALLED_RUNTIME_CAPABILITIES: Object.freeze({
...original.INSTALLED_RUNTIME_CAPABILITIES,
serviceWorker: Object.freeze({
mode: "ACTIVE",
scriptPath: "service-worker.js",
handlers: Object.freeze(["PWA_STATIC_ASSETS"]),
}),
}),
};
});
/** The product's `src/bootstrap/product-composition.ts`. */
vi.mock("../../src/bootstrap/product-composition.ts", () => ({
composeProductSessionOwner: () => null,
composeProduct: (): ProductComposition => ({
capabilities: {},
credentialProviders: {},
serviceWorker: {
blockers: [() => product.dirty],
observe(observation) {
product.observed.push(observation);
// 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");
},
},
}),
}));
const origin = "http://localhost";
const runtimeConfig = {
APP_ENV: "local",
API_BASE_URL: "http://localhost:8080",
REQUEST_TIMEOUT_MS: 10_000,
MAX_RETRY_ATTEMPTS: 2,
TELEMETRY_ENABLED: false,
AUTH_MODE: "demo",
CONFIG_SCHEMA_VERSION: "1",
API_CONTRACT_VERSION: "1",
RELEASE_MANIFEST_URL: "/release-manifest.json",
BUILD_ID: "local-build",
RELEASE_ID: "local-release",
};
const releaseManifest = {
schemaVersion: 1,
appVersion: "0.2.0",
buildId: "local-build",
commitSha: "local",
configSchemaVersion: "1",
apiContractVersion: "1",
assetManifestHash: "test-hash",
releaseId: "local-release",
builtAt: "2026-07-26T00:00:00.000Z",
routeChunks: {
"route-home": "assets/home.js",
"route-examples-ui": "assets/ui.js",
"route-examples-states": "assets/states.js",
"route-examples-auth": "assets/auth.js",
"route-not-found": "assets/not-found.js",
},
};
async function fetcher(input: RequestInfo | URL): Promise<Response> {
const url =
typeof input === "string"
? input
: input instanceof URL
? input.href
: input.url;
return Response.json(
url.includes("release-manifest") ? releaseManifest : runtimeConfig,
);
}
/** This page's worker is active and the next build's is waiting. */
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,
postMessage: vi.fn(),
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,
active: worker(script, "activated"),
addEventListener() {},
removeEventListener() {},
update: vi.fn(async () => {}),
} as unknown as ServiceWorkerRegistration;
},
);
return {
controller: null,
register,
getRegistration: vi.fn(async () => undefined),
getRegistrations: vi.fn(async () => []),
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", () => {
it("passes the product's blockers and observer to the page controller", async () => {
const container = updateWaitingContainer();
const composition = await createRuntimeComposition({
fetcher,
host: {
location: { origin },
navigator: { serviceWorker: container },
},
});
try {
await composition.optional.startAfterMount();
expect(container.register).toHaveBeenCalledTimes(1);
expect(product.observed).toEqual([
{ event: "register", outcome: "UPDATE_WAITING" },
]);
await expect(
composition.optional.serviceWorker!.requestActivation(),
).resolves.toEqual({ kind: "BLOCKED_DIRTY_CLIENT" });
expect(product.observed.at(-1)).toEqual({
event: "activation",
outcome: "BLOCKED_DIRTY_CLIENT",
});
} finally {
await composition.dispose();
}
});
});
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();
}
});
});