Files
tech-log-frontend/tests/browser-capabilities/public-cache-storage.spec.ts
DongHyeonka c80320dfc7 chore: sync the frontend template from ebea300 to af3d8e6
Carries 359 template commits, tag v0.2.0 plus one documentation commit: the
generator-built feature index with its app, bounded-context and feature
declarations, the src/platform kernel and scale tooling, the 2026-09-24 src
review fixes, and the 2026-09-25 maturity review round with its CHANGELOG
[보안]/[계약] rows. 691 of the 824 template paths are applied, 85 of them
merged with product changes; 127 are not carried.

Product identity is unchanged: name, version 0.1.0, routes, design and the
TechLog domain.

Three decisions worth naming. TechLog stays composed directly, as the last
two syncs recorded; its directory carries a NOT_INSTALLED marker that says so,
and every installed-* composer takes the template's projection with TechLog
added on top. The reference sample is no longer installed: the template now
installs a feature only through feature-module.ts and context-routes.ts,
which load the screens this product deleted, so its three operations, six
schemas and one topic leave the registries, recorded as registry change
evidence. And AppRouter mounts the platform and TechLog routes only; the
template's bounded-context route gateway waits for a generator-installed
feature.

Required fixes: readSubject on the BFF session owner (without it every HTTP
Studio session would close as integration-failed), zod through the facade in
nine TechLog files, noUnusedLocals, and public/config.json written out to
match the local profile. Derived baselines were recomputed after reproducing
both sides' values: CI contract 101 commands / 106 references / 141
artifacts, gate shape c9adcf85; registry approval 2dc6c3a3; the runtime
config schema baseline equals the schema at 8210d48.

Verified here: types, lint, architecture, adapter inventory, CI contract,
i18n, design system, diagnostics, browser security, dev release manifest,
TechLog contract and build pass; 220 component, 155 integration, 15
contract, 418 TechLog, 43 reference-feature, 18 recipe and 46
release-coherence tests pass, and 2381 of 2383 unit tests. Reproduced at
8210d48 first and unchanged: check:registries (byte-identical),
test:runtime-schema, verify:documentation. Brought by the template and
escalated rather than suppressed: check:request-fanout on TechLog's cursor
pagination, check:remediation-ledger (fails upstream too), the shared-chunk
hash test, and the registry-dependent sample removal and second-feature
tests. Playwright suites were not run.

Full record, the five open questions and the follow-ups in
docs/operations/template-sync-2026-09-29.md.

(cherry picked from commit b2170cf265dea45dc9cc05d3c61e627e97f31cdb)
2026-11-12 08:28:54 +09:00

452 lines
14 KiB
TypeScript

import { expect, test } from "../support/browser/strict-browser-test.ts";
test("keeps A active across a failed B stage, activates B with A rollback, and cleans only owned stale caches", async ({
page,
}) => {
await page.goto("/");
const result = await page.evaluate(async () => {
const adapterModulePath =
"/src/adapters/cache-storage/public-response-cache-adapter.ts";
const policyModulePath =
"/src/adapters/cache-storage/public-cache-policy.ts";
const {
computePublicCacheManifestDigestHex,
createPublicCacheWebLock,
createPublicResponseCacheAdapter,
} = (await import(
/* @vite-ignore */ adapterModulePath
)) as typeof import("../../src/adapters/cache-storage/public-response-cache-adapter.ts");
const { createDefaultPublicCachePolicy } = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/cache-storage/public-cache-policy.ts");
const suffix = crypto.randomUUID().replaceAll("-", "");
const releaseAId = `browser-a-${suffix.slice(0, 20)}`;
const releaseBId = `browser-b-${suffix.slice(0, 20)}`;
const unrelatedName = `unrelated-${suffix}`;
const policy = {
...createDefaultPublicCachePolicy(location.origin),
ownedCachePrefix: `cap-${suffix.slice(0, 24)}:`,
mutationLockName: `cap-${suffix}:mutation`,
};
const payloads = {
[`${location.origin}/cache-${suffix}-a.js`]: {
bytes: new TextEncoder().encode("verified-release-a"),
contentType: "application/javascript",
},
[`${location.origin}/cache-${suffix}-b.js`]: {
bytes: new TextEncoder().encode("verified-release-b"),
contentType: "application/javascript",
},
[`${location.origin}/cache-${suffix}-b.css`]: {
bytes: new TextEncoder().encode(".release-b{display:block}"),
contentType: "text/css",
},
} as const;
const [aUrl, bUrl, bSecondUrl] = Object.keys(payloads);
const digestHex = async (bytes: Uint8Array): Promise<string> => {
const digest = await crypto.subtle.digest(
"SHA-256",
Uint8Array.from(bytes),
);
return Array.from(
new Uint8Array(digest),
(byte) => byte.toString(16).padStart(2, "0"),
).join("");
};
const asset = async (absoluteUrl: string) => {
const payload = payloads[absoluteUrl as keyof typeof payloads];
return {
absoluteUrl,
expectedByteLength: payload.bytes.byteLength,
expectedContentType: payload.contentType,
integrity: {
algorithm: "SHA-256" as const,
digestHex: await digestHex(payload.bytes),
},
};
};
const assetsA = [await asset(aUrl!)];
const assetsB = [
await asset(bUrl!),
await asset(bSecondUrl!),
];
const manifestA = {
releaseRegistryId: releaseAId,
assets: assetsA,
manifestDigestHex:
await computePublicCacheManifestDigestHex(
crypto,
releaseAId,
assetsA,
policy,
),
};
const manifestB = {
releaseRegistryId: releaseBId,
assets: assetsB,
manifestDigestHex:
await computePublicCacheManifestDigestHex(
crypto,
releaseBId,
assetsB,
policy,
),
};
let corruptSecondBAsset = true;
const adapter = createPublicResponseCacheAdapter({
cacheStorage: caches,
crypto,
mutationLock: createPublicCacheWebLock(
navigator.locks,
policy.mutationLockName,
),
policy,
fetcher: async (request) => {
if (request.signal.aborted) {
throw new DOMException("Aborted.", "AbortError");
}
const payload =
payloads[request.url as keyof typeof payloads];
if (!payload) throw new TypeError("Unexpected cache URL.");
const responseBytes =
corruptSecondBAsset && request.url === bSecondUrl
? new Uint8Array(payload.bytes.byteLength)
: Uint8Array.from(payload.bytes);
return new Response(responseBytes, {
status: 200,
headers: {
"cache-control":
"public, max-age=31536000, immutable",
"content-type": payload.contentType,
"x-account-id": "must-not-persist",
},
});
},
});
const readActive = async (absoluteUrl: string) => {
const matched = await adapter.responses.matchActiveExact({
absoluteUrl,
});
if (!matched.ok || !matched.value) return matched;
const streamed: number[] = [];
for await (const chunk of matched.value.body.stream(
new AbortController().signal,
)) {
if (!chunk.ok) return chunk;
streamed.push(...chunk.value);
}
return {
ok: true as const,
streamed,
headerNames: matched.value.headers.map(([name]) => name),
};
};
try {
const stageA = await adapter.admin.stageRelease(manifestA);
const activateA = await adapter.admin.activateRelease(
manifestA.releaseRegistryId,
manifestA.manifestDigestHex,
);
const matchedABeforeFailedB = await readActive(aUrl!);
const failedStageB =
await adapter.admin.stageRelease(manifestB);
const afterFailedB = await adapter.admin.inspect();
const matchedAAfterFailedB = await readActive(aUrl!);
corruptSecondBAsset = false;
const stageB = await adapter.admin.stageRelease(manifestB);
const activateB = await adapter.admin.activateRelease(
manifestB.releaseRegistryId,
manifestB.manifestDigestHex,
);
const matchedB = await readActive(bUrl!);
const afterActivateB = await adapter.admin.inspect();
const releaseBCacheName = (await caches.keys()).find((name) =>
name.startsWith(
`${policy.ownedCachePrefix}release:${releaseBId}:`,
),
);
if (!releaseBCacheName) {
throw new Error("B release cache not found.");
}
const releaseBCache = await caches.open(releaseBCacheName);
await releaseBCache.put(
new Request(bUrl!),
new Response(new Uint8Array([0]), {
status: 200,
headers: {
"cache-control": "public",
"content-type": "application/javascript",
},
}),
);
const poisoned = await adapter.responses.matchActiveExact({
absoluteUrl: bUrl!,
});
await caches.open(`${policy.ownedCachePrefix}stale`);
await caches.open(unrelatedName);
const cleanup = await adapter.admin.cleanupOwned();
const names = await caches.keys();
return {
stageA,
activateA,
matchedABeforeFailedB,
failedStageB,
afterFailedB,
matchedAAfterFailedB,
stageB,
activateB,
matchedB,
afterActivateB,
poisoned,
cleanup,
unrelatedPreserved: names.includes(unrelatedName),
activeBPreserved: names.some((name) =>
name.startsWith(
`${policy.ownedCachePrefix}release:${releaseBId}:`,
),
),
rollbackAPreserved: names.some((name) =>
name.startsWith(
`${policy.ownedCachePrefix}release:${releaseAId}:`,
),
),
remainingOwnedCount: names.filter((name) =>
name.startsWith(policy.ownedCachePrefix),
).length,
expectedABytes: [...payloads[aUrl! as keyof typeof payloads].bytes],
expectedBBytes: [...payloads[bUrl! as keyof typeof payloads].bytes],
};
} finally {
for (const name of await caches.keys()) {
if (
name.startsWith(policy.ownedCachePrefix) ||
name === unrelatedName
) {
await caches.delete(name);
}
}
}
});
expect(result.stageA).toMatchObject({
ok: true,
value: { entryCount: 1 },
});
expect(result.activateA).toMatchObject({ ok: true });
expect(result.matchedABeforeFailedB).toMatchObject({
ok: true,
streamed: result.expectedABytes,
});
expect(result.failedStageB).toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED" },
});
expect(result.afterFailedB).toMatchObject({
ok: true,
value: {
activeReleaseRegistryId: expect.stringMatching(/^browser-a-/u),
releaseCandidates: [
expect.objectContaining({
releaseRegistryId: expect.stringMatching(/^browser-a-/u),
verified: true,
}),
],
},
});
expect(result.matchedAAfterFailedB).toMatchObject({
ok: true,
streamed: result.expectedABytes,
});
expect(result.stageB).toMatchObject({
ok: true,
value: { entryCount: 2 },
});
expect(result.activateB).toMatchObject({ ok: true });
expect(result.matchedB).toMatchObject({
ok: true,
streamed: result.expectedBBytes,
});
expect(
(
result.matchedB as Readonly<{
headerNames: readonly string[];
}>
).headerNames,
).not.toContain("x-account-id");
expect(result.afterActivateB).toMatchObject({
ok: true,
value: {
activeReleaseRegistryId: expect.stringMatching(/^browser-b-/u),
releaseCandidates: expect.arrayContaining([
expect.objectContaining({
releaseRegistryId: expect.stringMatching(/^browser-a-/u),
verified: true,
}),
expect.objectContaining({
releaseRegistryId: expect.stringMatching(/^browser-b-/u),
verified: true,
}),
]),
},
});
expect(result.poisoned).toMatchObject({
ok: false,
error: { code: "INTEGRITY_FAILED" },
});
expect(result.cleanup).toMatchObject({
ok: true,
value: { deletedOwnedCaches: 1, retainedOwnedCaches: 3 },
});
expect(result.unrelatedPreserved).toBe(true);
expect(result.activeBPreserved).toBe(true);
expect(result.rollbackAPreserved).toBe(true);
expect(result.remainingOwnedCount).toBe(3);
});
/**
* R3-6. The real Cache API applies `Vary` on `match()`, which the in-memory
* fakes do not. A public asset served with `Vary: Accept-Encoding` must stage,
* activate and still be found by the exact lookup.
*/
test("stages, activates, and looks up a Vary: Accept-Encoding response in the real Cache API", async ({
page,
}) => {
await page.goto("/");
const result = await page.evaluate(async () => {
const adapterModulePath =
"/src/adapters/cache-storage/public-response-cache-adapter.ts";
const policyModulePath =
"/src/adapters/cache-storage/public-cache-policy.ts";
const {
computePublicCacheManifestDigestHex,
createPublicCacheWebLock,
createPublicResponseCacheAdapter,
} = (await import(
/* @vite-ignore */ adapterModulePath
)) as typeof import("../../src/adapters/cache-storage/public-response-cache-adapter.ts");
const { createDefaultPublicCachePolicy } = (await import(
/* @vite-ignore */ policyModulePath
)) as typeof import("../../src/adapters/cache-storage/public-cache-policy.ts");
const suffix = crypto.randomUUID().replaceAll("-", "");
const releaseId = `browser-vary-${suffix.slice(0, 20)}`;
const policy = {
...createDefaultPublicCachePolicy(location.origin),
ownedCachePrefix: `cap-${suffix.slice(0, 24)}:`,
mutationLockName: `cap-${suffix}:mutation`,
};
const url = `${location.origin}/cache-${suffix}-vary.js`;
const bytes = new TextEncoder().encode("export const vary = 1;");
const digest = await crypto.subtle.digest("SHA-256", bytes);
const assets = [
{
absoluteUrl: url,
expectedByteLength: bytes.byteLength,
expectedContentType: "application/javascript",
integrity: {
algorithm: "SHA-256" as const,
digestHex: Array.from(new Uint8Array(digest), (byte) =>
byte.toString(16).padStart(2, "0"),
).join(""),
},
},
];
const manifest = {
releaseRegistryId: releaseId,
assets,
manifestDigestHex: await computePublicCacheManifestDigestHex(
crypto,
releaseId,
assets,
policy,
),
};
const adapter = createPublicResponseCacheAdapter({
cacheStorage: caches,
crypto,
mutationLock: createPublicCacheWebLock(
navigator.locks,
policy.mutationLockName,
),
policy,
fetcher: async (request) => {
if (request.url !== url) throw new TypeError("Unexpected cache URL.");
return new Response(Uint8Array.from(bytes), {
status: 200,
headers: {
"cache-control": "public, max-age=31536000, immutable",
"content-type": "application/javascript",
vary: "Accept-Encoding",
},
});
},
});
try {
const staged = await adapter.admin.stageRelease(manifest);
const activated = await adapter.admin.activateRelease(
manifest.releaseRegistryId,
manifest.manifestDigestHex,
);
const matched = await adapter.responses.matchActiveExact({
absoluteUrl: url,
});
const streamed: number[] = [];
if (matched.ok && matched.value) {
for await (const chunk of matched.value.body.stream(
new AbortController().signal,
)) {
if (!chunk.ok) return { staged, activated, matched: chunk };
streamed.push(...chunk.value);
}
}
// What the browser itself stored, read back through the raw Cache API.
const releaseCacheName = (await caches.keys()).find((name) =>
name.startsWith(`${policy.ownedCachePrefix}release:${releaseId}:`),
);
const raw = releaseCacheName
? await (await caches.open(releaseCacheName)).match(url)
: undefined;
return {
staged,
activated,
matched: matched.ok
? {
ok: true,
found: matched.value !== null,
vary:
matched.value?.headers.find(
([name]) => name.toLowerCase() === "vary",
)?.[1] ?? null,
}
: matched,
streamed,
rawVary: raw?.headers.get("vary") ?? null,
expected: Array.from(bytes),
};
} finally {
for (const name of await caches.keys()) {
if (name.startsWith(policy.ownedCachePrefix)) await caches.delete(name);
}
}
});
expect(result.staged).toMatchObject({ ok: true, value: { entryCount: 1 } });
expect(result.activated).toMatchObject({ ok: true });
expect(result.matched).toEqual({
ok: true,
found: true,
vary: "Accept-Encoding",
});
expect(result.streamed).toEqual(result.expected);
expect(result.rawVary).toBe("Accept-Encoding");
});