문제: 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/.
335 lines
12 KiB
TypeScript
335 lines
12 KiB
TypeScript
import { spawnSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import {
|
|
cp,
|
|
readFile,
|
|
rename,
|
|
rm,
|
|
writeFile,
|
|
} from "node:fs/promises";
|
|
import { createServer, type Server } from "node:http";
|
|
import type { AddressInfo } from "node:net";
|
|
import path from "node:path";
|
|
import { pathToFileURL } from "node:url";
|
|
import { gzipSync } from "node:zlib";
|
|
|
|
import { SERVICE_WORKER_ASSETS_OUTPUT } from "../../../scripts/generate-service-worker-assets.ts";
|
|
import { localBuildEnvironment } from "../../../scripts/lib/build-environment.ts";
|
|
import { linkFixtureNodeModules } from "../../../scripts/lib/fixture-node-modules.ts";
|
|
import { selectRepositoryPaths } from "../../../scripts/lib/repository-layout.ts";
|
|
import type { StaticAssetManifestV1 } from "../../../src/contracts/service-worker.ts";
|
|
import { sharedFixtureBuild } from "./shared-fixture-builds.ts";
|
|
|
|
/**
|
|
* R3-6 test helper: two real production builds with the Service Worker on,
|
|
* and a static server that can switch which one it serves.
|
|
*
|
|
* The template ships with `serviceWorker: null`. The supported way to turn the
|
|
* worker on is the static capability selection in the product-owned
|
|
* `src/features/product-capabilities.ts` (`mode: "ACTIVE"` with the
|
|
* `PWA_STATIC_ASSETS` handler); `scripts/build-frontend.ts` then runs the
|
|
* two-pass worker build. Runtime Config can only disable it. So the helper
|
|
* copies the repo to a temp dir, edits the selection there, and runs the
|
|
* repo's own build scripts twice with different `VITE_BUILD_ID`s. The working
|
|
* tree and its `dist` (served by the e2e preview server) are never touched.
|
|
*
|
|
* The app composes the worker host but nothing subscribes to it yet, and it is
|
|
* not reachable from outside. The copy therefore also wraps
|
|
* `createServiceWorkerRuntimeHost` so the page records the host's own
|
|
* `onUpdateWaiting` / `onReloadRequired` callbacks and `start()` outcome on
|
|
* `globalThis.__caServiceWorkerTest`. Only the temp copy is edited.
|
|
*
|
|
* 0929/11-03. What the copy relies on, and where to change it when a product
|
|
* changes that code:
|
|
* 1. `src/features/product-capabilities.ts` has one
|
|
* `const SERVICE_WORKER: InstalledServiceWorkerSelection | null = …;`.
|
|
* A selection that is already `ACTIVE` (a product that turned the worker
|
|
* on) is kept as it is; anything else becomes `ACTIVE_VALUE`.
|
|
* 2. `src/bootstrap/register-service-worker.ts` declares
|
|
* `export function createServiceWorkerRuntimeHost(` once (the probe).
|
|
* 3. The build writes its precache list to `SERVICE_WORKER_ASSETS_OUTPUT`.
|
|
* `precached` is read from there, so a product that precaches more than
|
|
* `dist/assets` still compares against what its worker installs.
|
|
* A broken premise fails `prepareServiceWorkerBuilds` with the file and the
|
|
* text it expected.
|
|
*/
|
|
|
|
const repoRoot = path.resolve(import.meta.dirname, "../../..");
|
|
// 1105/12-04. `.tmp` holds other runs' builds and results (.tmp/runs/<id>),
|
|
// which change while this copy is made; fixture-builds.ts skips it too.
|
|
const skipped = new Set(selectRepositoryPaths("checkout-copy-skip"));
|
|
|
|
export type BuildName = "a" | "b";
|
|
export type ServiceWorkerBuilds = Readonly<{
|
|
root: string;
|
|
dist: Readonly<Record<BuildName, string>>;
|
|
/** Sorted URLs of each build's generated precache list (premise 3). */
|
|
precached: Readonly<Record<BuildName, readonly string[]>>;
|
|
/** One copy for the whole e2e run (shared-fixture-builds.ts); the run removes it. */
|
|
shared: boolean;
|
|
}>;
|
|
|
|
const SELECTION_FILE = "src/features/product-capabilities.ts";
|
|
const SELECTION_DECLARATION =
|
|
/(const SERVICE_WORKER: InstalledServiceWorkerSelection \| null = )([\s\S]*?);\n/gu;
|
|
|
|
export const ACTIVE_VALUE = `{
|
|
mode: "ACTIVE",
|
|
scriptPath: "service-worker.js",
|
|
handlers: ["PWA_STATIC_ASSETS"],
|
|
}`;
|
|
|
|
const HOST_PROBE = `
|
|
export function createServiceWorkerRuntimeHost(
|
|
input: ServiceWorkerHostInput,
|
|
): ServiceWorkerRuntimeHost | null {
|
|
const host = createServiceWorkerRuntimeHostUnobserved(input);
|
|
if (!host) return host;
|
|
const events: string[] = [];
|
|
host.onUpdateWaiting(() => events.push("update-waiting"));
|
|
host.onReloadRequired(() => events.push("reload-required"));
|
|
const observed: ServiceWorkerRuntimeHost = Object.freeze({
|
|
...host,
|
|
start: async () => {
|
|
const outcome = await host.start();
|
|
events.push("start:" + JSON.stringify(outcome));
|
|
return outcome;
|
|
},
|
|
});
|
|
Object.assign(globalThis, { __caServiceWorkerTest: { host: observed, events } });
|
|
return observed;
|
|
}
|
|
`;
|
|
|
|
export async function replaceOnce(
|
|
file: string,
|
|
search: string,
|
|
replacement: string,
|
|
): Promise<void> {
|
|
const source = await readFile(file, "utf8");
|
|
if (source.split(search).length !== 2) {
|
|
throw new Error(`Expected exactly one "${search}" in ${file}.`);
|
|
}
|
|
await writeFile(file, source.replace(search, replacement));
|
|
}
|
|
|
|
/**
|
|
* Premise 1. Replaces the value of the one `SERVICE_WORKER` declaration in
|
|
* the temp copy with `next(current)`, whatever the value is now.
|
|
*/
|
|
export async function setServiceWorkerSelection(
|
|
root: string,
|
|
next: (current: string) => string,
|
|
): Promise<void> {
|
|
const file = path.join(root, SELECTION_FILE);
|
|
const source = await readFile(file, "utf8");
|
|
if ([...source.matchAll(SELECTION_DECLARATION)].length !== 1) {
|
|
throw new Error(
|
|
`Expected exactly one "const SERVICE_WORKER: InstalledServiceWorkerSelection | null = …;" in ${file} (premise 1 of tests/e2e/support/service-worker-builds.ts).`,
|
|
);
|
|
}
|
|
await writeFile(
|
|
file,
|
|
source.replace(
|
|
SELECTION_DECLARATION,
|
|
(_declaration, head: string, current: string) =>
|
|
`${head}${next(current)};\n`,
|
|
),
|
|
);
|
|
}
|
|
|
|
/**
|
|
* 0929/06-04, 0929/11-03. Turns the copy's worker on whatever the selection is
|
|
* now, but keeps a selection a product already set to `ACTIVE`, so the specs
|
|
* exercise that product's own handlers rather than the template's.
|
|
*/
|
|
export async function turnOnServiceWorker(root: string): Promise<void> {
|
|
await setServiceWorkerSelection(root, (current) =>
|
|
/\bmode:\s*"ACTIVE"/u.test(current) ? current : ACTIVE_VALUE,
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Premise 3. The build wrote this list; the worker installs exactly it. A
|
|
* build without an `ACTIVE` worker (06-03's `REMOVE_REGISTRATION` release)
|
|
* writes none and precaches nothing: `scripts/build-frontend.ts` deletes the
|
|
* directory before every build, so a missing file is that build's answer.
|
|
*/
|
|
async function precachedUrls(root: string, name: BuildName): Promise<string[]> {
|
|
const file = path.join(root, SERVICE_WORKER_ASSETS_OUTPUT);
|
|
if (!existsSync(file)) return [];
|
|
const generated = pathToFileURL(file);
|
|
// Both builds write the same file; the query keeps B from reusing A's module.
|
|
generated.search = `build=${name}`;
|
|
const { SERVICE_WORKER_ASSETS } = (await import(generated.href)) as {
|
|
SERVICE_WORKER_ASSETS: StaticAssetManifestV1;
|
|
};
|
|
return SERVICE_WORKER_ASSETS.assets.map((asset) => asset.url).sort();
|
|
}
|
|
|
|
function run(cwd: string, script: string, buildId: string): void {
|
|
const result = spawnSync("node", [script], {
|
|
cwd,
|
|
encoding: "utf8",
|
|
// 1103/11-08. A local build, not the CI job's release build.
|
|
env: { ...localBuildEnvironment(), VITE_BUILD_ID: buildId, RELEASE_ID: buildId },
|
|
});
|
|
if (result.status !== 0) {
|
|
throw new Error(
|
|
`${script} failed for ${buildId}:\n${result.stdout}\n${result.stderr}`,
|
|
);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* `beforeBuild` edits the temp copy right before build `name` (06-03: a
|
|
* broken worker A, then a `REMOVE_REGISTRATION` release B). Edits persist
|
|
* into the later build. `key` names this pair of builds in the e2e run
|
|
* (shared-fixture-builds.ts); each spec passes its own.
|
|
*/
|
|
export async function prepareServiceWorkerBuilds(
|
|
options: Readonly<{
|
|
key: string;
|
|
beforeBuild?: (name: BuildName, root: string) => Promise<void>;
|
|
}>,
|
|
): Promise<ServiceWorkerBuilds> {
|
|
const { root, value, shared } = await sharedFixtureBuild(
|
|
`sw-${options.key}`,
|
|
options.beforeBuild?.toString() ?? "",
|
|
async (root) => {
|
|
await cp(repoRoot, root, {
|
|
recursive: true,
|
|
filter: (source) =>
|
|
!skipped.has(path.relative(repoRoot, source).split(path.sep)[0]!),
|
|
});
|
|
await linkFixtureNodeModules(root, repoRoot);
|
|
await turnOnServiceWorker(root);
|
|
const hostFile = path.join(root, "src/bootstrap/register-service-worker.ts");
|
|
await replaceOnce(
|
|
hostFile,
|
|
"export function createServiceWorkerRuntimeHost(",
|
|
"function createServiceWorkerRuntimeHostUnobserved(",
|
|
);
|
|
await writeFile(hostFile, (await readFile(hostFile, "utf8")) + HOST_PROBE);
|
|
|
|
const dist = { a: path.join(root, "dist-a"), b: path.join(root, "dist-b") };
|
|
const precached: Record<BuildName, readonly string[]> = { a: [], b: [] };
|
|
for (const name of ["a", "b"] as const) {
|
|
await options.beforeBuild?.(name, root);
|
|
run(root, "scripts/generate-product-feature-index.ts", `sw-e2e-${name}`);
|
|
run(root, "scripts/build-frontend.ts", `sw-e2e-${name}`);
|
|
await rename(path.join(root, "dist"), dist[name]);
|
|
precached[name] = await precachedUrls(root, name);
|
|
}
|
|
return { dist, precached };
|
|
},
|
|
);
|
|
return { root, ...value, shared };
|
|
}
|
|
|
|
export async function removeServiceWorkerBuilds(
|
|
builds: ServiceWorkerBuilds | undefined,
|
|
): Promise<void> {
|
|
if (builds && !builds.shared) await rm(builds.root, { recursive: true, force: true });
|
|
}
|
|
|
|
export type AssetHeaders = Readonly<{
|
|
/** Sent for every `.js` file, the worker script included. */
|
|
javascriptContentType: string;
|
|
/** gzip every `/assets/*` body; Content-Length is the compressed size. */
|
|
gzip: boolean;
|
|
}>;
|
|
|
|
export type ServedResponse = Readonly<{
|
|
path: string;
|
|
contentType: string;
|
|
contentEncoding: string | null;
|
|
contentLength: number;
|
|
decodedLength: number;
|
|
}>;
|
|
|
|
const CONTENT_TYPES: Readonly<Record<string, string>> = {
|
|
".html": "text/html; charset=utf-8",
|
|
".css": "text/css",
|
|
".json": "application/json",
|
|
".svg": "image/svg+xml",
|
|
".png": "image/png",
|
|
".webp": "image/webp",
|
|
".woff2": "font/woff2",
|
|
};
|
|
|
|
/**
|
|
* Serves one dist directory at a time from an ephemeral 127.0.0.1 port, so
|
|
* every test gets its own origin (and its own Service Worker registration).
|
|
* Paths without an extension get `index.html`; a missing file is a plain 404,
|
|
* never the SPA fallback, so a chunk that the served build lacks really 404s.
|
|
*/
|
|
export async function startBuildServer(
|
|
dist: Readonly<Record<BuildName, string>>,
|
|
headers: AssetHeaders = {
|
|
javascriptContentType: "text/javascript",
|
|
gzip: false,
|
|
},
|
|
) {
|
|
let current: BuildName = "a";
|
|
const served: ServedResponse[] = [];
|
|
const server: Server = createServer((request, response) => {
|
|
void (async () => {
|
|
const pathname = decodeURIComponent(
|
|
new URL(request.url ?? "/", "http://127.0.0.1").pathname,
|
|
);
|
|
const root = dist[current];
|
|
const file = path.extname(pathname)
|
|
? path.join(root, path.normalize(pathname))
|
|
: path.join(root, "index.html");
|
|
let body: Buffer;
|
|
try {
|
|
if (!file.startsWith(root + path.sep)) throw new Error("outside root");
|
|
body = await readFile(file);
|
|
} catch {
|
|
response.writeHead(404, { "cache-control": "no-store" }).end();
|
|
return;
|
|
}
|
|
const extension = path.extname(file);
|
|
const contentType =
|
|
extension === ".js"
|
|
? headers.javascriptContentType
|
|
: (CONTENT_TYPES[extension] ?? "application/octet-stream");
|
|
const encoded = headers.gzip && pathname.startsWith("/assets/");
|
|
const payload = encoded ? gzipSync(body) : body;
|
|
served.push({
|
|
path: pathname,
|
|
contentType,
|
|
contentEncoding: encoded ? "gzip" : null,
|
|
contentLength: payload.byteLength,
|
|
decodedLength: body.byteLength,
|
|
});
|
|
response
|
|
.writeHead(200, {
|
|
"content-type": contentType,
|
|
"content-length": String(payload.byteLength),
|
|
"cache-control": "no-cache",
|
|
...(encoded
|
|
? { "content-encoding": "gzip", vary: "Accept-Encoding" }
|
|
: {}),
|
|
})
|
|
.end(request.method === "HEAD" ? undefined : payload);
|
|
})();
|
|
});
|
|
await new Promise<void>((resolve) =>
|
|
server.listen(0, "127.0.0.1", () => resolve()),
|
|
);
|
|
const { port } = server.address() as AddressInfo;
|
|
return {
|
|
origin: `http://127.0.0.1:${port}`,
|
|
served,
|
|
serve(name: BuildName) {
|
|
current = name;
|
|
},
|
|
async close() {
|
|
server.closeAllConnections();
|
|
await new Promise<void>((resolve) => server.close(() => resolve()));
|
|
},
|
|
};
|
|
}
|