Files
clean-architecture-frontend…/tests/e2e/service-worker-update.spec.ts
DongHyeonka c6d7f43ab9 perf(e2e): fixture build를 브라우저 project마다가 아니라 run에 한 번 만든다
문제: fixture spec 여섯(old-tab-chunk-recovery, generated-feature,
preload-use, boot-module-failure, service-worker-update·recovery)이
beforeAll에서 저장소를 복사해 vite build를 동기로 돈다. chromium·
firefox·webkit project가 그 hook을 따로 돌아, e2e 한 번에 같은 build를
세 번(약 9 build × 3) 만든다. 그 build는 옆 worker의 브라우저와 CPU를
다툰다. FE-GATE-008이 가끔 떨어진 firefox 시험(runner run 127,
desktop p5·fea-v8: `old-tab-chunk-recovery`·`app-shell`·`accessibility`의
첫 goto 뒤 요소 없음)은 이 build가 도는 구간과 겹쳤다. 다만 아래
6회 실행에서 고치기 전·후 모두 재현되지 않아, 이것이 원인이라고는
확정하지 못했다.

고른 방법: e2e 설정의 global setup이 run마다 공유 폴더를 만들고
(`SHARED_FIXTURE_BUILD_ROOT`), `prepareFixtureBuilds`와
`prepareServiceWorkerBuilds`가 key마다 처음 닿은 worker만 build한다.
나머지 worker는 그 결과를 기다려 쓴다(`mkdir` 잠금, 결과 JSON을
rename으로 공개, 실패는 `.failed`로 전한다). 같은 key를 다른 정의로
부르면 거절한다. build는 엔진과 무관하고 시험이 build 폴더에 쓰는
곳은 없다(edit는 build 전에만 돈다). global teardown이 폴더를 지운다.
- old-tab spec은 edit 안에서 정하던 기능 목록을 build 뒤에 root에서도
  읽는다. 다른 project의 build를 쓴 worker는 edit를 돌지 않는다.
- 공유 폴더가 없으면(Vitest 시험, 다른 Playwright 설정) 예전처럼
  호출마다 자기 사본을 만든다.
- 버린 대안: expect timeout 늘리기·worker 줄이기(규칙 밖), fixture
  spec을 한 브라우저만 돌리기(브라우저별 계약이 줄어든다).

위험·한계: build를 기다리는 worker는 자기 hook timeout(180~300초)
안에서 기다린다. build한 worker가 죽으면 기다리는 쪽은 그 timeout으로
실패한다. 2026-11-01 리뷰의 R-1(두 helper 중복 정리)은 하지 않았다.

검증(desktop, `taskset -c 0-5` + worker 6으로 runner 모양, 같은 세션에서
고치기 전·후 번갈아 3회): e2e 전체 벽시계 172/150/141 → 123/141/113초
(중앙값 150 → 123초), 6회 모두 183개 통과. 공유 시험 6개 통과,
check:types·eslint rc=0. 로그 /tmp/claude-gates/w2fe2-e2eab/,
w2fe2-shared1/.
2026-11-12 23:19:43 +09:00

361 lines
13 KiB
TypeScript

import { appendFile, readdir, readFile } from "node:fs/promises";
import path from "node:path";
import { expect, test, type Page } from "../support/browser/strict-browser-test.ts";
import {
prepareServiceWorkerBuilds,
removeServiceWorkerBuilds,
startBuildServer,
type ServiceWorkerBuilds,
} from "./support/service-worker-builds.ts";
/**
* R3-6. Real-browser Service Worker checks, against real production builds.
*
* How the worker is enabled: the template's default build has
* `serviceWorker: null`, and the only supported switch is the static
* capability selection in `src/features/product-capabilities.ts`
* (`{ mode: "ACTIVE", scriptPath: "service-worker.js", handlers:
* ["PWA_STATIC_ASSETS"] }`); `scripts/build-frontend.ts` then adds the worker
* build. `support/service-worker-builds.ts` applies that selection in a temp
* copy of the repo, builds it twice (`VITE_BUILD_ID` sw-e2e-a / sw-e2e-b),
* and serves either dist from its own port per test. The copy also records
* the worker host's `onUpdateWaiting` / `onReloadRequired` callbacks, which
* the app itself does not subscribe to yet.
*
* The preview server of this suite is not used; each test uses absolute URLs.
*
* Premises (0929/11-03): the helper's three, listed in
* `support/service-worker-builds.ts`, plus one here: build B changes
* `CHANGED_ROUTE_SOURCE`, so a product that deletes that page points the
* constant at another route page. Run both Service Worker specs after turning
* the worker on (Service Worker checklist in
* `docs/architecture/optional-adapter-recipes.md`).
*/
type Probe = typeof globalThis & {
__caServiceWorkerTest?: {
host: { requestActivation(): Promise<unknown> };
events: string[];
};
};
let builds: ServiceWorkerBuilds | undefined;
// 1103/11-09. Once a worker controls the page it answers the page's script
// requests, so the fixture cannot mark them and cannot tell whether a
// preload made then was run. It names those preloads instead of calling them
// unused; here they are expected. Preloads made before the worker took
// control are still checked.
test.use({
allowedBrowserFailure: /^preloadunverifiable:service-worker:\/assets\/[\w-]+\.js$/u,
});
// B changes one route chunk on purpose. Route chunks used to differ only
// because they embedded the build ID; since 09-02 they do not, so two builds
// of the same source emit the same route chunks. A dynamically imported
// module keeps all its exports, so the extra export survives the bundler.
const CHANGED_ROUTE_SOURCE =
"src/presentation/pages/not-found-page.tsx";
test.beforeAll(async () => {
test.setTimeout(180_000);
builds = await prepareServiceWorkerBuilds({
key: "update",
beforeBuild: async (name, root) => {
if (name !== "b") return;
await appendFile(
path.join(root, CHANGED_ROUTE_SOURCE),
'\nexport const serviceWorkerE2eBuild = "b";\n',
);
},
});
});
test.afterAll(async () => {
await removeServiceWorkerBuilds(builds);
});
function requireBuilds(): ServiceWorkerBuilds {
if (!builds) throw new Error("Service Worker builds were not prepared.");
return builds;
}
async function waitForEvent(page: Page, prefix: string): Promise<string> {
await page.waitForFunction(
(expected) =>
(globalThis as Probe).__caServiceWorkerTest?.events.some((event) =>
event.startsWith(expected),
) === true,
prefix,
{ timeout: 60_000 },
);
const events = await page.evaluate(() => [
...((globalThis as Probe).__caServiceWorkerTest?.events ?? []),
]);
return events.find((event) => event.startsWith(prefix))!;
}
async function startOutcome(page: Page): Promise<unknown> {
return JSON.parse((await waitForEvent(page, "start:")).slice("start:".length));
}
async function hashedAssets(dist: string): Promise<string[]> {
return (await readdir(path.join(dist, "assets")))
.map((file) => `/assets/${file}`)
.sort();
}
const headerCases = [
{
name: "Content-Type: application/javascript",
headers: { javascriptContentType: "application/javascript", gzip: false },
},
{
name: "Content-Encoding: gzip with the compressed Content-Length",
headers: { javascriptContentType: "text/javascript", gzip: true },
},
] as const;
for (const { name, headers } of headerCases) {
test(`installs the static asset set served with ${name}`, async ({ page }) => {
const { dist } = requireBuilds();
const server = await startBuildServer(dist, headers);
try {
await page.goto(`${server.origin}/`);
// A failed install (CONTENT_TYPE_INVALID, BYTES_MISMATCH, ...) ends as
// FAILED/INSTALL_FAILED; a first install that worked asks for a reload.
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
const cached = await page.evaluate(async () => {
const names = (await caches.keys()).filter((cacheName) =>
cacheName.startsWith("ca-static-v1-"),
);
const cache = await caches.open(names[0] ?? "missing");
const paths = (await cache.keys())
.map((request) => new URL(request.url))
.filter((url) => url.origin === location.origin)
.map((url) => url.pathname);
return { names, paths };
});
expect(cached.names).toHaveLength(1);
// 0929/11-03. The list A's build generated, not `dist/assets`: a product
// may precache more (or fewer) files than the template does.
expect(cached.paths.sort()).toEqual(requireBuilds().precached.a);
// The server really sent the headers under test.
const assets = server.served.filter((response) =>
response.path.startsWith("/assets/"),
);
expect(assets.length).toBeGreaterThan(0);
if (headers.gzip) {
expect(assets.every((response) => response.contentEncoding === "gzip"))
.toBe(true);
expect(
assets.some(
(response) => response.contentLength < response.decodedLength,
),
).toBe(true);
} else {
expect(
assets
.filter((response) => response.path.endsWith(".js"))
.every(
(response) => response.contentType === "application/javascript",
),
).toBe(true);
}
} finally {
await server.close();
}
});
}
type BuildServer = Awaited<ReturnType<typeof startBuildServer>>;
// Playwright's Firefox never lets a worker control a page: even a trivial
// classic worker leaves `navigator.serviceWorker.controller` null after a new
// navigation (checked by hand with Playwright 1.62). With no controlled
// client, B skips `waiting` and activates by itself (`requestActivation()` then
// returns NO_WAITING_WORKER), and the fetch handler is never reached. The
// update tests therefore run where a page can be controlled. Not a product
// defect.
// quarantine(owner=frontend-platform, defect=playwright-firefox-no-sw-control, expires=2027-03-31)
const NO_CONTROLLED_PAGES =
"Playwright Firefox pages are never controlled by a service worker.";
/**
* Loads build A twice (first install, then a normal navigation), switches the
* server to B, runs the update check and activates B through the app host.
* Returns whether the second load of A was controlled by the worker.
*/
async function updateFromAToB(
page: Page,
server: BuildServer,
): Promise<{ secondLoad: unknown; controlled: boolean }> {
await page.goto(`${server.origin}/`);
expect(await startOutcome(page)).toEqual({ kind: "RELOAD_TO_ENABLE" });
await page.evaluate(async () => {
await navigator.serviceWorker.ready;
});
// A normal navigation. (`page.reload()` would not change anything here.)
await page.goto(`${server.origin}/`);
const secondLoad = await startOutcome(page);
const controlled = await page.evaluate(
() => navigator.serviceWorker.controller !== null,
);
server.serve("b");
await page.evaluate(async () => {
await (await navigator.serviceWorker.getRegistration())?.update();
});
await waitForEvent(page, "update-waiting");
const activation = await page.evaluate(() =>
(globalThis as Probe).__caServiceWorkerTest!.host.requestActivation(),
);
expect(activation).toEqual({ kind: "ACTIVATED_RELOAD_REQUIRED" });
await waitForEvent(page, "reload-required");
return { secondLoad, controlled };
}
test("announces update-waiting and reload-required through the host when build B replaces A", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const server = await startBuildServer(requireBuilds().dist);
try {
await updateFromAToB(page, server);
const registration = await page.evaluate(async () => {
const current = await navigator.serviceWorker.getRegistration();
return {
active: current?.active?.state ?? null,
waiting: current?.waiting ?? null,
};
});
expect(registration).toEqual({ active: "activated", waiting: null });
} finally {
await server.close();
}
});
/** The route chunk of A that B no longer has: `CHANGED_ROUTE_SOURCE`'s. */
async function removedRouteChunk(
dist: ServiceWorkerBuilds["dist"],
): Promise<string> {
const routeChunks = Object.values(
(
JSON.parse(
await readFile(path.join(dist.a, "release-manifest.json"), "utf8"),
) as { routeChunks: Record<string, string> }
).routeChunks,
);
const inB = new Set(await hashedAssets(dist.b));
const removedChunk = routeChunks
.map((chunk) => `/${chunk}`)
.find((chunk) => !inB.has(chunk));
if (!removedChunk) throw new Error("Build B kept every route chunk of A.");
return removedChunk;
}
test("serves A's removed chunk from the previous cache once B controls the page", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const { dist } = requireBuilds();
const removedChunk = await removedRouteChunk(dist);
const server = await startBuildServer(dist);
try {
const { secondLoad, controlled } = await updateFromAToB(page, server);
expect(secondLoad).toEqual({ kind: "ACTIVE", buildId: "sw-e2e-a" });
expect(controlled).toBe(true);
// B's worker now controls the page. The chunk is not in B's manifest and
// not on the server any more, so only A's retained cache can answer.
const fromWorker = await page.evaluate(async (url) => {
const response = await fetch(url);
return { status: response.status, body: await response.text() };
}, removedChunk);
expect(fromWorker).toEqual({
status: 200,
body: await readFile(path.join(dist.a, removedChunk), "utf8"),
});
expect((await page.request.get(`${server.origin}${removedChunk}`)).status())
.toBe(404);
} finally {
await server.close();
}
});
type SameDocumentProbe = typeof globalThis & { __swE2eSameDocument?: boolean };
// 1105/06-03. The old tab's real path, not only `fetch()`: A's page, now
// controlled by B's worker, opens the route whose chunk B removed
// (`CHANGED_ROUTE_SOURCE` is the not-found page, so any unmatched path
// imports it). Under the worker the preload fixture cannot judge preloads
// (the 11-09 allowance above), so this test asserts the outcome: the route
// renders in the same document, the chunk never reaches the server, and the
// strict fixture sees no failure outside the allowance. A worker that cannot
// answer the chunk makes the app's chunk recovery reload into B, which also
// renders the not-found page; only the same-document check tells them apart
// (review 06-R10).
test("opens A's removed route in the old tab without a reload once B controls it", async ({
page,
browserName,
}) => {
test.skip(browserName === "firefox", NO_CONTROLLED_PAGES);
const { dist } = requireBuilds();
const removedChunk = await removedRouteChunk(dist);
const server = await startBuildServer(dist);
try {
const { controlled } = await updateFromAToB(page, server);
expect(controlled).toBe(true);
const entryScript = () =>
page.evaluate(
() =>
document.querySelector<HTMLScriptElement>('script[type="module"][src]')
?.src ?? null,
);
const entryBefore = await entryScript();
await page.evaluate(() => {
(globalThis as SameDocumentProbe).__swE2eSameDocument = true;
});
const servedBefore = server.served.length;
// A client-side navigation, as a link inside the app makes.
await page.evaluate(() => {
history.pushState({}, "", "/sw-e2e-removed-route");
dispatchEvent(new PopStateEvent("popstate"));
});
await expect(
page.getByRole("heading", { name: /페이지를 찾을 수 없습니다|Page not found/u }),
).toBeVisible({ timeout: 30_000 });
const after = await page.evaluate((chunk) => ({
sameDocument:
(globalThis as SameDocumentProbe).__swE2eSameDocument === true,
chunkRequested:
performance.getEntriesByName(new URL(chunk, location.origin).href)
.length > 0,
}), removedChunk);
expect(after).toEqual({ sameDocument: true, chunkRequested: true });
expect(await entryScript()).toBe(entryBefore);
expect(
server.served.slice(servedBefore).map((response) => response.path),
).not.toContain(removedChunk);
} finally {
await server.close();
}
});
// `beforeAll` already ran `scripts/build-frontend.ts` unmodified (default
// `bundle` config loader); this pins that both builds emitted the worker.
test("builds the ACTIVE worker with the repo's unmodified build script", async () => {
const { dist } = requireBuilds();
for (const root of [dist.a, dist.b]) {
expect(await readdir(root)).toContain("service-worker.js");
}
});