문제: active pointer를 읽을 때 rollback 목록 길이를 현재
retainedPreviousReleaseCount와 비교한다. 3에서 1로 줄이는 정상 설정
변경이나 pointer JSON 손상 뒤에는 읽기가 CORRUPT_DATA가 되고, 조회·
활성화·정리·inspect가 모두 여기서 멈춘다. control cache를 지우는 API가
없어 사용자가 사이트 데이터를 지우기 전까지 오프라인 캐시가 꺼진 채로
남고, cleanup이 막혀 배포마다 release cache가 쌓인다. 이번 라운드에도
Node와 실제 Cache API 3엔진에서 재현됐다.
고른 방법(지난 리뷰 4.1절의 (나)+(다)):
- (다) isActivePointer는 목록 길이를 현재 값이 아니라 정책이 허용하는
최댓값(5, MAX_RETAINED_PREVIOUS_RELEASE_COUNT)과만 비교한다. 정책
검증과 같은 상수를 쓴다. 다음 activation이 이미 하던 slice로 목록을
현재 값으로 자른다.
- (나) activateRelease는 이전 pointer 읽기가 CORRUPT_DATA면 없는
것으로 보고, 전체 재검증을 통과한 후보로 rollback 목록 없이
덮어쓴다. 일시 오류(UNAVAILABLE 등)는 지금처럼 활성화를 멈춘다.
버린 대안:
- 현상 유지 + "사이트 데이터 삭제" 안내. 운영자가 원인을 알 수 없고
캐시가 계속 쌓인다.
- control을 지우는 admin API. 포트가 늘고 호출자가 언제 불러야 하는지
알아야 한다.
- (다)만 적용. 정책 변경은 풀리지만 JSON 손상은 풀리지 않는다.
위험·한계:
- 지키던 성질은 그대로다. 검증한 후보만 활성화하고(재검증은 pointer
읽기 전에 끝난다), 조회는 manifest digest가 맞는 바이트만 돌려준다.
읽을 수 있는 pointer가 가리키는 캐시는 cleanup이 지우지 않는다.
손상 pointer 상태의 조회와 cleanup은 다음 activation까지 여전히
CORRUPT_DATA다.
- 덮어쓰면 손상 pointer의 rollback 목록을 잃는다. 원래 읽을 수 없던
값이다. 덮어쓴 뒤 cleanup이 구버전 탭이 쓰던 캐시를 지울 수 있다.
그 탭의 조회는 네트워크로 떨어진다. Service Worker drain(VD-15)을
구현하면 이 규칙을 다시 본다(지난 리뷰 4.1절 7).
- 리뷰가 "가능하면"으로 적은 3엔진 browser spec(E-2)은 추가하지
않았다. 단위 테스트(MemoryCacheStorage)로만 확인했다.
- service-worker-pwa 레시피 번들 9,665 → 9,716 / 10,000 gzip bytes.
검증:
- RED(수정 전): public-response-cache-repair.test.ts 새 2건 실패.
retained 3 → 1 뒤 조회가 { ok: false }(기대 ok:true), 잘린 pointer
뒤 다음 배포의 activate가 { ok: false }.
- GREEN: 같은 파일 8건 통과. 일시 오류 가드 테스트 1건을 함께 넣었다.
activate가 모든 pointer 실패를 무시하도록 바꾼 변이를 이 테스트가
잡는다(1건 실패 확인 뒤 되돌림).
- 회귀: public-response-cache 단위 3파일 40건 통과. tsc app·test·
service-worker·recipes 통과. 바꾼 파일 eslint 통과.
verify-documentation-readiness PASS_SCOPED. check-optional-recipes
(source) PASS.
Refs: docs/reviews/2026-09-29-maturity-review/02-adapters-browser-files-cache.md
401 lines
14 KiB
TypeScript
401 lines
14 KiB
TypeScript
import { describe, expect, it } from "vitest";
|
|
|
|
import type { PublicCacheAsset } from "../../src/application/ports/browser-file-storage/cache-storage-ports.ts";
|
|
import {
|
|
activePointerRequest,
|
|
controlCacheName,
|
|
} from "../../src/adapters/cache-storage/public-cache-codec.ts";
|
|
import {
|
|
createDefaultPublicCachePolicy,
|
|
resolvePublicCachePolicy,
|
|
type PublicCacheRuntimePolicy,
|
|
} from "../../src/adapters/cache-storage/public-cache-policy.ts";
|
|
import { createPublicResponseCacheAdapter } from "../../src/adapters/cache-storage/public-response-cache-adapter.ts";
|
|
import {
|
|
MemoryCacheStorage,
|
|
digestHex,
|
|
immediateLock,
|
|
manifestFor,
|
|
} from "./public-response-cache-fixture.ts";
|
|
|
|
/**
|
|
* STO-RR-04 / STO-RR-05. A release cache that is currently serving traffic is
|
|
* the last thing a repair may destroy. A transient marker read failure is not
|
|
* evidence of damage, and a repair that has not yet fetched anything has not
|
|
* yet earned the right to delete what still works.
|
|
*/
|
|
describe("public response cache repair is failure-atomic", () => {
|
|
async function stagedRelease(
|
|
releaseRegistryId: string,
|
|
observer?: (event: unknown) => void,
|
|
) {
|
|
const policy = createDefaultPublicCachePolicy(
|
|
"https://assets.example.test",
|
|
);
|
|
const firstBytes = new Uint8Array([1, 1, 1, 1]);
|
|
const secondBytes = new Uint8Array([2, 2, 2, 2]);
|
|
const assets: readonly PublicCacheAsset[] = [
|
|
{
|
|
absoluteUrl: "https://assets.example.test/first.js",
|
|
expectedByteLength: firstBytes.byteLength,
|
|
expectedContentType: "application/javascript",
|
|
integrity: {
|
|
algorithm: "SHA-256",
|
|
digestHex: await digestHex(firstBytes),
|
|
},
|
|
},
|
|
{
|
|
absoluteUrl: "https://assets.example.test/second.js",
|
|
expectedByteLength: secondBytes.byteLength,
|
|
expectedContentType: "application/javascript",
|
|
integrity: {
|
|
algorithm: "SHA-256",
|
|
digestHex: await digestHex(secondBytes),
|
|
},
|
|
},
|
|
];
|
|
const bodies = new Map<string, Uint8Array>([
|
|
[assets[0]!.absoluteUrl, firstBytes],
|
|
[assets[1]!.absoluteUrl, secondBytes],
|
|
]);
|
|
const cacheStorage = new MemoryCacheStorage();
|
|
const fetchLog: string[] = [];
|
|
let failFrom: string | null = null;
|
|
const adapter = createPublicResponseCacheAdapter({
|
|
cacheStorage: cacheStorage as unknown as CacheStorage,
|
|
crypto: globalThis.crypto,
|
|
mutationLock: immediateLock,
|
|
policy,
|
|
...(observer ? { observer } : {}),
|
|
fetcher: async (request: Request) => {
|
|
fetchLog.push(request.url);
|
|
if (failFrom !== null && request.url === failFrom) {
|
|
throw new TypeError("network is down");
|
|
}
|
|
const body = bodies.get(request.url);
|
|
if (!body) throw new TypeError(`unknown asset ${request.url}`);
|
|
return new Response(Uint8Array.from(body), {
|
|
headers: {
|
|
"cache-control": "public",
|
|
"content-type": "application/javascript",
|
|
},
|
|
});
|
|
},
|
|
});
|
|
const manifest = await manifestFor(releaseRegistryId, assets, policy);
|
|
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
|
|
ok: true,
|
|
});
|
|
expect(
|
|
await adapter.admin.activateRelease(
|
|
manifest.releaseRegistryId,
|
|
manifest.manifestDigestHex,
|
|
),
|
|
).toMatchObject({ ok: true });
|
|
const cacheName = [...cacheStorage.caches.keys()].find((name) =>
|
|
name.includes(releaseRegistryId),
|
|
);
|
|
if (!cacheName) throw new Error("staged cache missing");
|
|
|
|
return {
|
|
adapter,
|
|
assets,
|
|
cacheName,
|
|
cacheStorage,
|
|
fetchLog,
|
|
manifest,
|
|
setFailure(url: string | null) {
|
|
failFrom = url;
|
|
},
|
|
};
|
|
}
|
|
|
|
it("does not delete an active candidate when the marker read fails transiently", async () => {
|
|
const release = await stagedRelease("transient-marker");
|
|
const cache = release.cacheStorage.caches.get(release.cacheName)!;
|
|
const realMatch = cache.match.bind(cache);
|
|
let markerReads = 0;
|
|
const assetUrls = new Set(release.assets.map((asset) => asset.absoluteUrl));
|
|
cache.match = async (request: RequestInfo | URL) => {
|
|
const url =
|
|
request instanceof Request ? request.url : String(request);
|
|
if (!assetUrls.has(url)) {
|
|
markerReads += 1;
|
|
throw new DOMException("Storage is busy", "InvalidStateError");
|
|
}
|
|
return await realMatch(request);
|
|
};
|
|
|
|
const restaged = await release.adapter.admin.stageRelease(release.manifest);
|
|
|
|
expect(markerReads).toBeGreaterThan(0);
|
|
expect(restaged.ok).toBe(false);
|
|
expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true);
|
|
cache.match = realMatch;
|
|
expect(
|
|
await release.adapter.responses.matchActiveExact({
|
|
absoluteUrl: release.assets[0]!.absoluteUrl,
|
|
}),
|
|
).toMatchObject({ ok: true });
|
|
});
|
|
|
|
it("reports a failed re-verification of a staged candidate as CACHE_STAGE (2026-11-01 02-03)", async () => {
|
|
const observations: Readonly<{ outcome?: string }>[] = [];
|
|
const release = await stagedRelease("reverify-unreadable", (event) =>
|
|
observations.push(event as Readonly<{ outcome?: string }>),
|
|
);
|
|
const cache = release.cacheStorage.caches.get(release.cacheName)!;
|
|
const realMatch = cache.match.bind(cache);
|
|
const assetUrls = new Set(release.assets.map((asset) => asset.absoluteUrl));
|
|
cache.match = async (request: RequestInfo | URL) => {
|
|
const url =
|
|
request instanceof Request ? request.url : String(request);
|
|
if (assetUrls.has(url)) {
|
|
throw new DOMException("Storage is busy", "InvalidStateError");
|
|
}
|
|
return await realMatch(request);
|
|
};
|
|
observations.length = 0;
|
|
|
|
const restaged = await release.adapter.admin.stageRelease(release.manifest);
|
|
|
|
expect(restaged).toMatchObject({
|
|
ok: false,
|
|
error: { code: "UNAVAILABLE", operation: "CACHE_STAGE" },
|
|
});
|
|
expect(
|
|
observations.filter(({ outcome }) => outcome === "FAILED"),
|
|
).toEqual([
|
|
expect.objectContaining({
|
|
operation: "CACHE_STAGE",
|
|
failureCode: "UNAVAILABLE",
|
|
}),
|
|
]);
|
|
});
|
|
|
|
it("keeps every healthy asset when one repair fetch fails", async () => {
|
|
const release = await stagedRelease("partial-repair");
|
|
const cache = release.cacheStorage.caches.get(release.cacheName)!;
|
|
// Corrupt only the first asset's stored bytes.
|
|
const corrupted = cache.responses.findIndex(
|
|
(entry) => entry.request.url === release.assets[0]!.absoluteUrl,
|
|
);
|
|
expect(corrupted).toBeGreaterThanOrEqual(0);
|
|
cache.responses.splice(corrupted, 1);
|
|
|
|
release.setFailure(release.assets[0]!.absoluteUrl);
|
|
const restaged = await release.adapter.admin.stageRelease(release.manifest);
|
|
expect(restaged.ok).toBe(false);
|
|
|
|
// The cache still exists and the healthy asset is still served.
|
|
expect(release.cacheStorage.caches.has(release.cacheName)).toBe(true);
|
|
expect(
|
|
await release.adapter.responses.matchActiveExact({
|
|
absoluteUrl: release.assets[1]!.absoluteUrl,
|
|
}),
|
|
).toMatchObject({ ok: true });
|
|
});
|
|
|
|
it("still removes a candidate this call created when staging fails", async () => {
|
|
const policy = createDefaultPublicCachePolicy(
|
|
"https://assets.example.test",
|
|
);
|
|
const bytes = new Uint8Array([7, 7, 7, 7]);
|
|
const asset: PublicCacheAsset = {
|
|
absoluteUrl: "https://assets.example.test/fresh.js",
|
|
expectedByteLength: bytes.byteLength,
|
|
expectedContentType: "application/javascript",
|
|
integrity: {
|
|
algorithm: "SHA-256",
|
|
digestHex: await digestHex(bytes),
|
|
},
|
|
};
|
|
const cacheStorage = new MemoryCacheStorage();
|
|
const adapter = createPublicResponseCacheAdapter({
|
|
cacheStorage: cacheStorage as unknown as CacheStorage,
|
|
crypto: globalThis.crypto,
|
|
mutationLock: immediateLock,
|
|
policy,
|
|
fetcher: async () => {
|
|
throw new TypeError("network is down");
|
|
},
|
|
});
|
|
const manifest = await manifestFor("fresh-release", [asset], policy);
|
|
|
|
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
|
|
ok: false,
|
|
});
|
|
expect(await cacheStorage.keys()).toEqual([]);
|
|
});
|
|
|
|
it("repairs an evicted asset in place and keeps the release usable", async () => {
|
|
const release = await stagedRelease("in-place-repair");
|
|
const cache = release.cacheStorage.caches.get(release.cacheName)!;
|
|
const evicted = cache.responses.findIndex(
|
|
(entry) => entry.request.url === release.assets[1]!.absoluteUrl,
|
|
);
|
|
cache.responses.splice(evicted, 1);
|
|
|
|
expect(
|
|
await release.adapter.admin.stageRelease(release.manifest),
|
|
).toMatchObject({ ok: true });
|
|
expect(
|
|
await release.adapter.responses.matchActiveExact({
|
|
absoluteUrl: release.assets[1]!.absoluteUrl,
|
|
}),
|
|
).toMatchObject({ ok: true });
|
|
expect(
|
|
await release.adapter.responses.matchActiveExact({
|
|
absoluteUrl: release.assets[0]!.absoluteUrl,
|
|
}),
|
|
).toMatchObject({ ok: true });
|
|
});
|
|
});
|
|
|
|
/**
|
|
* 0929/02-01. The active pointer was checked against the policy of the build
|
|
* reading it, so lowering `retainedPreviousReleaseCount` or a damaged pointer
|
|
* stopped lookup, activation and cleanup for good.
|
|
*/
|
|
describe("public cache pointer after a policy change or damage (0929/02-01)", () => {
|
|
const origin = "https://assets.example.test";
|
|
const policyRetaining = (retainedPreviousReleaseCount: number) =>
|
|
resolvePublicCachePolicy({
|
|
...createDefaultPublicCachePolicy(origin),
|
|
retainedPreviousReleaseCount,
|
|
});
|
|
const assetUrl = (releaseRegistryId: string) =>
|
|
`${origin}/${releaseRegistryId}.js`;
|
|
const body = (releaseRegistryId: string) =>
|
|
new TextEncoder().encode(`release ${releaseRegistryId}`);
|
|
|
|
function adapterFor(
|
|
cacheStorage: MemoryCacheStorage,
|
|
policy: PublicCacheRuntimePolicy,
|
|
) {
|
|
return createPublicResponseCacheAdapter({
|
|
cacheStorage: cacheStorage as unknown as CacheStorage,
|
|
crypto: globalThis.crypto,
|
|
mutationLock: immediateLock,
|
|
policy,
|
|
fetcher: async (request: Request) =>
|
|
new Response(
|
|
Uint8Array.from(
|
|
body(new URL(request.url).pathname.slice(1, -".js".length)),
|
|
),
|
|
{
|
|
headers: {
|
|
"cache-control": "public",
|
|
"content-type": "application/javascript",
|
|
},
|
|
},
|
|
),
|
|
});
|
|
}
|
|
|
|
async function manifestOf(
|
|
releaseRegistryId: string,
|
|
policy: PublicCacheRuntimePolicy,
|
|
) {
|
|
const bytes = body(releaseRegistryId);
|
|
return await manifestFor(
|
|
releaseRegistryId,
|
|
[
|
|
{
|
|
absoluteUrl: assetUrl(releaseRegistryId),
|
|
expectedByteLength: bytes.byteLength,
|
|
expectedContentType: "application/javascript",
|
|
integrity: { algorithm: "SHA-256", digestHex: await digestHex(bytes) },
|
|
},
|
|
],
|
|
policy,
|
|
);
|
|
}
|
|
|
|
async function deploy(
|
|
adapter: ReturnType<typeof adapterFor>,
|
|
releaseRegistryId: string,
|
|
policy: PublicCacheRuntimePolicy,
|
|
) {
|
|
const manifest = await manifestOf(releaseRegistryId, policy);
|
|
expect(await adapter.admin.stageRelease(manifest)).toMatchObject({
|
|
ok: true,
|
|
});
|
|
return await adapter.admin.activateRelease(
|
|
manifest.releaseRegistryId,
|
|
manifest.manifestDigestHex,
|
|
);
|
|
}
|
|
|
|
it("keeps working after retainedPreviousReleaseCount is lowered", async () => {
|
|
const cacheStorage = new MemoryCacheStorage();
|
|
const before = policyRetaining(3);
|
|
const wide = adapterFor(cacheStorage, before);
|
|
for (const id of ["r1", "r2", "r3", "r4"]) {
|
|
expect(await deploy(wide, id, before)).toMatchObject({ ok: true });
|
|
}
|
|
|
|
const after = policyRetaining(1);
|
|
const narrow = adapterFor(cacheStorage, after);
|
|
|
|
expect(
|
|
await narrow.responses.matchActiveExact({ absoluteUrl: assetUrl("r4") }),
|
|
).toMatchObject({ ok: true, value: expect.anything() });
|
|
expect(await deploy(narrow, "r5", after)).toMatchObject({ ok: true });
|
|
expect(await narrow.admin.cleanupOwned()).toMatchObject({ ok: true });
|
|
expect(
|
|
await narrow.responses.matchActiveExact({ absoluteUrl: assetUrl("r5") }),
|
|
).toMatchObject({ ok: true, value: expect.anything() });
|
|
});
|
|
|
|
it("replaces a damaged pointer on the next verified activation", async () => {
|
|
const cacheStorage = new MemoryCacheStorage();
|
|
const policy = policyRetaining(1);
|
|
const adapter = adapterFor(cacheStorage, policy);
|
|
expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true });
|
|
const control = await cacheStorage.open(controlCacheName(policy));
|
|
await control.put(
|
|
activePointerRequest(policy),
|
|
new Response('{"schemaVersion":1,"releaseRegis', {
|
|
headers: { "content-type": "application/json" },
|
|
}),
|
|
);
|
|
|
|
// A release that was never staged is still refused.
|
|
const unstaged = await manifestOf("r9", policy);
|
|
expect(
|
|
await adapter.admin.activateRelease(
|
|
unstaged.releaseRegistryId,
|
|
unstaged.manifestDigestHex,
|
|
),
|
|
).toMatchObject({ ok: false });
|
|
|
|
expect(await deploy(adapter, "r2", policy)).toMatchObject({ ok: true });
|
|
expect(await adapter.admin.cleanupOwned()).toMatchObject({ ok: true });
|
|
expect(
|
|
await adapter.responses.matchActiveExact({ absoluteUrl: assetUrl("r2") }),
|
|
).toMatchObject({ ok: true, value: expect.anything() });
|
|
});
|
|
|
|
it("still stops activation when the pointer read fails transiently", async () => {
|
|
const cacheStorage = new MemoryCacheStorage();
|
|
const policy = policyRetaining(1);
|
|
const adapter = adapterFor(cacheStorage, policy);
|
|
expect(await deploy(adapter, "r1", policy)).toMatchObject({ ok: true });
|
|
const control = cacheStorage.caches.get(controlCacheName(policy))!;
|
|
const realMatch = control.match.bind(control);
|
|
control.match = async () => {
|
|
throw new DOMException("Storage is busy", "InvalidStateError");
|
|
};
|
|
|
|
expect(await deploy(adapter, "r2", policy)).toMatchObject({
|
|
ok: false,
|
|
error: { code: "UNAVAILABLE", operation: "CACHE_ACTIVATE" },
|
|
});
|
|
control.match = realMatch;
|
|
expect(
|
|
await adapter.responses.matchActiveExact({ absoluteUrl: assetUrl("r1") }),
|
|
).toMatchObject({ ok: true, value: expect.anything() });
|
|
});
|
|
});
|