Files
clean-architecture-frontend…/tests/e2e/old-tab-chunk-recovery.spec.ts
DongHyeonka aad005cbce fix(test): 브라우저 테스트가 WebKit의 3초 preload 추정 대신 실제 사용을 검사한다
문제: FE-GATE-008이 webkit에서 가끔 "The resource … was preloaded using
link preload but not used within a few seconds from the window's load
event" 경고로 떨어졌다(desktop 부하 0.68, i18n.spec.ts:60, 반복 10회 중
3회). 부하 탓이 아니었다. WebKit은 load 3초 뒤 한 번, 아직 아무 요청도 쓰지
않은 preload를 경고한다. 플랫폼 구성 화면은 들어갈 때 기능 실행부를 모두
불러오고(15-01), Vite는 그 청크와 정적 의존 청크를 한꺼번에 modulepreload
한다. 화면을 load 뒤 2.5초쯤 열면 module graph가 가장 깊은
reference-schemas에 닿기 전에 WebKit 검사가 돈다. 그 청크는 곧 쓰인다(표가
그려지고 link로 한 번만 받는다). 반대로 정말 안 쓰는 preload는 Chromium·
Firefox에서 늘, WebKit에서도 test가 3초 전에 끝나면 아무도 잡지 않았다
(1103/11-09).

고른 방법:
- strict fixture가 WebKit의 그 문구 하나만 정확한 패턴으로 무시한다. 다른
  console warning·error는 그대로 실패다.
- 대신 tests/support/browser/preload-use.ts가 세 엔진에서 같은 방법으로
  "preload한 script가 실제로 실행됐는가"를 본다.
  - 문서가 받은 `<link rel=modulepreload|preload>`를 첫 바이트 전부터
    MutationObserver로 적고, 끝에 남은 link도 더한다.
  - page.route로 build script(`/assets/*.js`)에 "이 URL이 평가됐다"를 적는
    문장 하나를 앞에 붙인다.
  - test 끝에 preload됐는데 평가되지 않은 script를 `preloadunused:`로
    실패시킨다. 진행 중인 dynamic import는 5초까지 기다린다.
- "사용"을 평가로 판정하는 이유: preload는 받기만 하거나(WebKit·Firefox)
  받아서 parse만 한다(Chromium). 어느 엔진도 평가하지 않는다. 그래서 그
  문장은 module graph가 그 청크를 실제로 실행했을 때만 돈다. WebKit의
  "참조됨"과 달리 시각에 기대지 않는다.
- 볼 수 없는 것은 따로 이름을 붙여 실패시킨다(fail closed).
  - script가 아닌 preload는 `preloadunverifiable:<as>:`.
  - Service Worker가 문서를 제어할 때 만든 preload는
    `preloadunverifiable:service-worker:`. 그 요청은 worker가 답해서
    page.route가 못 본다. context.route로 worker가 받는 것을 표시하면
    release manifest의 sha256 대조가 깨진다.
  - route.fetch가 세 번 실패해 표시 없이 넘어간 script는
    `preloadunverifiable:unmarked:`. 처음 구현은 이때 조용히
    route.continue()로 넘겨 쓰인 청크를 안 쓴 것으로 보고했다(webkit
    reference-form 1건).
- 일부러 실패를 일으키는 spec은 그 실패가 남기는 preload만 허용한다.
  - boot-module-failure: 깨진 build의 boot 정적 closure.
  - old-tab-chunk-recovery: 없어진 청크와 함께 preload된 청크. 전에는 이
    허용이 WebKit 경고 문구로만 있었다.
  - service-worker-update: worker 제어 중 preload만.
  - production-csp는 build script를 직접 fulfill하므로, 표시를 유지하는
    fulfillBuildScript를 쓴다.

버린 대안:
- (A) lazy dynamic import의 JS 의존성 preload를 끈다. 경고는 원리상 없어지지만
  test의 추정에 맞춰 제품을 바꾸는 것이다. lazy 라우트 첫 진입마다 1~2 RTT가
  늘고, 그 화면은 lab이 재는 화면(FE-GATE-026)이다.
- 청크 단계를 줄인다. 창이 좁아질 뿐이다.
- 3초 뒤에 화면에 들어간다. 사용자가 보는 경고를 test에서 숨긴다.

위험·한계:
- 모든 strict fixture test가 build script를 page.route로 받는다.
- 끝에 열려 있는 문서만 검사한다. 이동해 버린 문서의 기록은 같이 사라진다.
- fixture가 검사하는 것은 fixture의 page 하나다(console 검사와 같다).
- worker가 제어하는 문서의 preload는 검사하지 못한다(이름을 붙여 실패,
  service-worker-update만 허용).

검증 (desktop, CI=true와 workflow env):
- RED(검사 stub): 새 preload-use.spec 9건 중 7건 실패.
  - 변이 test는 세 엔진 모두 Expected
    ["preloadunused:/assets/async-state-Cxfod8c-.js"], Received [].
  - 부모 청크 3.5초 지연 scenario는 webkit만 "console:warning:The resource
    …/reference-schemas-DICBcHlO.js was preloaded using link preload but not
    used …"로 실패.
- GREEN: 9 passed.
- 변이를 fixture에 직접 넣은 probe(커밋 안 함), 안 쓰는 modulepreload 하나:
  - 이전 fixture(8a3b16a): chromium·firefox·webkit 3/3 통과(놓침).
  - 새 fixture: 3/3 실패,
    "preloadunused:/assets/async-state-Cxfod8c-.js".
- 부모 청크 3.5초 지연 probe:
  - 이전 fixture: webkit 실패.
  - 새 fixture: 3/3 통과. webkit은 여전히 reference-schemas 경고를 냈다
    (probe guesses ["reference-schemas-DICBcHlO.js was preloa…"]).
- 전체 e2e(playwright.config.ts): 202 passed, 3 skipped(기존 firefox SW skip).
- check:types:test, 바꾼 파일 eslint 통과.
2026-11-05 08:13:56 +09:00

226 lines
8.6 KiB
TypeScript

import { appendFile, readFile } from "node:fs/promises";
import path from "node:path";
import type { RouteDefinition } from "../../src/contracts/routes.ts";
import {
ROUTE_REGISTRY,
ROUTE_RUNTIME_CONTRACT,
} from "../../src/features/installed-feature-contracts.ts";
import { expect, test } from "../support/browser/strict-browser-test.ts";
import {
prepareFixtureBuilds,
removeFixtureBuilds,
type FixtureBuilds,
} from "./support/fixture-builds.ts";
import { startBuildServer } from "./support/service-worker-builds.ts";
/**
* 11-05. A tab opened on build A, in the default configuration (no Service
* Worker), after build B is deployed. B changes two lazy route pages, so their
* A chunks no longer exist on the server. The first missing chunk reloads the
* tab once, into B. A second missing chunk (the server alternates back to A,
* as mismatched replicas do) must not reload again: the tab shows the
* recovery failure instead.
*/
// 1103/09-04. The platform overview is a platform route; the UI gallery is
// a feature route now, reached through its context gateway. Route ids only:
// the page sources are read from build A's Vite manifest, so this spec names
// no feature folder.
const installedRoutes: Readonly<Record<string, RouteDefinition>> = ROUTE_REGISTRY;
const runtimeContracts: Readonly<Record<string, { moduleId: string }>> =
ROUTE_RUNTIME_CONTRACT;
function installedRoute(routeId: string): RouteDefinition {
const definition = installedRoutes[routeId];
if (!definition) throw new Error(`${routeId} is not installed.`);
return definition;
}
const PLATFORM = installedRoute("EXAMPLES_PLATFORM");
const UI = installedRoute("EXAMPLES_UI");
type ViteManifest = Record<
string,
{
file: string;
name?: string;
isDynamicEntry?: boolean;
imports?: string[];
dynamicImports?: string[];
}
>;
async function viteManifest(dist: string): Promise<ViteManifest> {
return JSON.parse(
await readFile(path.join(dist, ".vite/manifest.json"), "utf8"),
) as ViteManifest;
}
/** The source of a route's page: the dynamic entry named by its module id. */
function pageSource(manifest: ViteManifest, route: RouteDefinition): string {
const moduleId = runtimeContracts[route.routeId]?.moduleId;
const sources = Object.entries(manifest)
.filter(([, entry]) => entry.isDynamicEntry && entry.name === moduleId)
.map(([source]) => source);
if (sources.length !== 1) {
throw new Error(`Expected one page chunk for ${route.routeId}: ${sources.join(", ")}`);
}
return sources[0]!;
}
/** The context routes module that lazy-loads `page`. */
function routesSource(manifest: ViteManifest, page: string): string {
const sources = Object.entries(manifest)
.filter(([, entry]) => entry.isDynamicEntry && entry.dynamicImports?.includes(page))
.map(([source]) => source);
if (sources.length !== 1) {
throw new Error(`Expected one routes module for ${page}: ${sources.join(", ")}`);
}
return sources[0]!;
}
let builds: FixtureBuilds<"a" | "b"> | undefined;
test.beforeAll(async () => {
test.setTimeout(300_000);
builds = await prepareFixtureBuilds("chunk-recovery", [
{ name: "a" },
{
name: "b",
edit: async (root) => {
const manifest = await viteManifest(path.join(root, "dist-a"));
for (const route of [PLATFORM, UI]) {
await appendFile(
path.join(root, pageSource(manifest, route)),
'\n(globalThis as Record<string, unknown>).__caFixtureBuild = "b";\n',
);
}
},
},
]);
});
test.afterAll(async () => {
await removeFixtureBuilds(builds);
});
async function routeChunk(dist: string, chunkId: string): Promise<string> {
const manifest = JSON.parse(
await readFile(path.join(dist, "release-manifest.json"), "utf8"),
) as { routeChunks: Record<string, string> };
return `/${manifest.routeChunks[chunkId]}`;
}
// Each missing chunk fails its request and the dynamic import. Chromium may
// also log the 404 itself (without its URL), Firefox logs the error object
// React caught, and WebKit logs its own import error without the URL. Nothing
// else is allowed, but for the WebKit warning below. 1103/09-04: the B tab
// misses the UI gallery's context routes module before its page: that module
// names B's new page chunk, so its hash changed too.
const MISSING_PAGE = String.raw`/assets/(?:platform-overview-page|ui-gallery-page|context-routes)-[\w-]+\.js`;
const MISSING_PAGE_FAILURES = [
String.raw`^requestfailed:GET:${MISSING_PAGE}:`,
String.raw`^console:error:TypeError: Failed to fetch dynamically imported module: http://127\.0\.0\.1:\d+${MISSING_PAGE}$`,
String.raw`^console:error:\[JavaScript Error: "Loading module from “http://127\.0\.0\.1:\d+${MISSING_PAGE}” was blocked`,
String.raw`^console:error:Failed to load resource: the server responded with a status of 404 \(Not Found\)$`,
String.raw`^console:error:JSHandle@object$`,
String.raw`^console:error:TypeError: Importing a module script failed\.$`,
];
/** The chunks Vite preloads with `page`: its static imports in `dist`. */
async function preloadedWith(dist: string, page: string): Promise<string[]> {
const manifest = await viteManifest(dist);
if (!manifest[page]) throw new Error(`${page} is not in ${dist}'s manifest.`);
const files = new Set<string>();
const pending = [...(manifest[page].imports ?? [])];
for (let key = pending.pop(); key !== undefined; key = pending.pop()) {
const entry = manifest[key];
if (!entry || files.has(entry.file)) continue;
files.add(entry.file);
pending.push(...(entry.imports ?? []));
}
return [...files];
}
// 1103/11-09. Vite preloads a chunk together with the chunks it imports, so a
// missing chunk leaves itself and the chunks preloaded with it unused: in the
// A tab those of A's platform page (the tab is still on A while recovery
// reads the release manifest), in the B tab those of B's context routes
// module for the UI page. The fixture's preload check reports them in every
// engine (WebKit's own three-second warning only did when its timer ran
// before the test ended). They are the provoked failure's own effect; only
// those chunks are allowed.
test.use({
allowedBrowserFailure: async ({ browserName: _engine }, provide) => {
if (!builds) throw new Error("Fixture builds were not prepared.");
const aManifest = await viteManifest(builds.dist.a);
const bManifest = await viteManifest(builds.dist.b);
const files = [
...(await preloadedWith(builds.dist.a, pageSource(aManifest, PLATFORM))),
...(await preloadedWith(
builds.dist.b,
routesSource(bManifest, pageSource(bManifest, UI)),
)),
].map((file) => file.replaceAll(".", String.raw`\.`));
await provide(
new RegExp(
[
...MISSING_PAGE_FAILURES,
String.raw`^preloadunused:${MISSING_PAGE}$`,
String.raw`^preloadunused:/(?:${files.join("|")})$`,
].join("|"),
"u",
),
);
},
});
test("an old tab reloads once into the new build, then stops reloading", async ({
page,
}) => {
if (!builds) throw new Error("Fixture builds were not prepared.");
const aPlatform = await routeChunk(builds.dist.a, PLATFORM.chunkId);
const bPlatform = await routeChunk(builds.dist.b, PLATFORM.chunkId);
const bUi = await routeChunk(builds.dist.b, UI.chunkId);
expect(bPlatform).not.toBe(aPlatform);
expect(bUi).not.toBe(await routeChunk(builds.dist.a, UI.chunkId));
const server = await startBuildServer(builds.dist);
try {
await page.goto(`${server.origin}/`);
await expect(
page.getByRole("link", { name: PLATFORM.navigationLabel!, exact: true }),
).toBeVisible();
let loads = 0;
page.on("load", () => {
loads += 1;
});
// Build B is deployed while the A tab stays open.
server.serve("b");
await page
.getByRole("link", { name: PLATFORM.navigationLabel!, exact: true })
.click();
await expect(page.getByRole("heading", { name: PLATFORM.title })).toBeVisible();
expect(loads).toBe(1);
const served = server.served.map((entry) => entry.path);
expect(served).not.toContain(aPlatform);
expect(served).toContain(bPlatform);
await expect
.poll(() => page.evaluate(() => (globalThis as Record<string, unknown>).__caFixtureBuild))
.toBe("b");
// The replicas alternate: the B tab now meets A, which lacks B's chunk.
server.serve("a");
await page.getByRole("link", { name: UI.navigationLabel!, exact: true }).click();
await expect(page.getByRole("alert")).toContainText(
"화면 자산을 복구하지 못했습니다.",
);
expect(loads).toBe(1);
expect(page.url()).toBe(`${server.origin}${UI.path}`);
} finally {
await server.close();
}
});