문제: 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 통과.
290 lines
11 KiB
TypeScript
290 lines
11 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({
|
|
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();
|
|
}
|
|
});
|
|
|
|
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 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.");
|
|
|
|
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();
|
|
}
|
|
});
|
|
|
|
// `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");
|
|
}
|
|
});
|