fix(service-worker): fall back to the previous release cache for hashed assets (R-6.3)

onActivate keeps one previous release cache, but onFetch only ever read
the current one, so the retained cache was never used.

On a current-cache miss, onFetch now looks up the owned non-current cache
with the highest activation marker (same rule onActivate uses; extracted
as highestMarkedCache) and serves a valid 200 hit from it. Per D-7 this
only applies to content-hashed file names; any other URL goes to the
network as before. The hashed-name rule moves to
HASHED_STATIC_ASSET_NAME in src/contracts/service-worker.ts and the
build generator imports it, so the generator and the worker share one
definition.

Scope note: the fallback runs inside onFetch's VERIFIED_CACHE_FIRST
branch, i.e. for URLs in the current manifest. Old-build chunks that are
not in the current manifest stay network-only (R-6.6 limits interception
to manifest URLs).

RED before fix: "serves a hashed asset missing from the current cache
from the previous release cache (R-6.3)" got null. Guard test "never
answers a non-hashed URL from the previous release cache (D-7)" added.
Gates: check:architecture, check:types:{app,node,test,service-worker},
lint, test:component pass. test:unit passes except the pre-existing
removal-fixture.test.ts case that needs generated release evidence
under artifacts/ (absent in a fresh worktree; unrelated to this diff).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DongHyeonka
2026-09-24 12:28:38 +09:00
co-authored by Claude Opus 5.5
parent fb8a3b5e1d
commit 39aa573746
4 changed files with 122 additions and 15 deletions
+2 -1
View File
@@ -10,6 +10,7 @@ import { mkdir, readFile, readdir, stat, writeFile } from "node:fs/promises";
import path from "node:path";
import {
HASHED_STATIC_ASSET_NAME,
SERVICE_WORKER_BOUNDS,
SERVICE_WORKER_SCRIPT_PATH,
type StaticAssetManifestV1,
@@ -38,7 +39,7 @@ const EXCLUDED_FILES: ReadonlySet<string> = new Set([
]);
/** Vite emits content-hashed names; only those may be treated as immutable. */
const HASHED_NAME = /-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/;
const HASHED_NAME = HASHED_STATIC_ASSET_NAME;
export async function collectStaticAssets(
distDirectory: string,
@@ -1,4 +1,5 @@
import {
HASHED_STATIC_ASSET_NAME,
SERVICE_WORKER_BOUNDS,
isOwnedStaticCacheName,
staticCacheName,
@@ -153,19 +154,8 @@ export function createServiceWorkerRuntime(
const owned = names.filter(isOwnedStaticCacheName);
const currentCache = await scope.caches.open(current);
const oldCaches = owned.filter((name) => name !== current);
const markers: ActivationMarker[] = [];
for (const name of oldCaches) {
const marker = await readActivationMarker(await scope.caches.open(name), name);
if (marker) markers.push(marker);
}
const highestOld = await highestMarkedCache(names, current);
const currentMarker = await readActivationMarker(currentCache, current);
const highestOld = markers.reduce<ActivationMarker | null>(
(highest, marker) =>
!highest || marker.activationSequence >= highest.activationSequence
? marker
: highest,
null,
);
const previous = highestOld?.cacheName ?? oldCaches.at(-1) ?? null;
if (
!currentMarker ||
@@ -199,6 +189,55 @@ export function createServiceWorkerRuntime(
return deleted;
}
/** The owned non-current cache with the highest activation marker. */
async function highestMarkedCache(
names: readonly string[],
current: string,
): Promise<ActivationMarker | null> {
let highest: ActivationMarker | null = null;
for (const name of names) {
if (!isOwnedStaticCacheName(name) || name === current) continue;
const marker = await readActivationMarker(
await scope.caches.open(name),
name,
);
if (
marker &&
(!highest || marker.activationSequence >= highest.activationSequence)
) {
highest = marker;
}
}
return highest;
}
/**
* R-6.3 / D-7. A hashed URL names immutable bytes, so the copy kept in the
* previous release cache (found by its activation marker) is the same
* response. Any other URL is never answered from a previous release.
*/
async function matchPreviousRelease(
url: string,
current: string,
): Promise<Response | null> {
try {
if (!HASHED_STATIC_ASSET_NAME.test(new URL(url).pathname)) return null;
const previous = await highestMarkedCache(
await scope.caches.keys(),
current,
);
if (!previous) return null;
const cached = await (
await scope.caches.open(previous.cacheName)
).match(url);
return cached?.status === 200 && cached.type !== "opaque"
? cached
: null;
} catch {
return null;
}
}
/**
* §18.5–§18.7. A verified cache hit is returned; anything else goes to the
* network and is never written back into the active cache at runtime.
@@ -235,7 +274,7 @@ export function createServiceWorkerRuntime(
} catch {
return null;
}
if (!cached) return null;
if (!cached) return matchPreviousRelease(request.url, currentCacheName);
if (cached.status !== 200 || cached.type === "opaque") {
// §18.6. An invalid hit is deleted from the cache it was read from and
// treated as a release mismatch.
+7
View File
@@ -97,6 +97,13 @@ export interface StaticAssetManifestV1 {
}>[];
}
/**
* Vite's content-hashed file name (`name-<hash>.ext`). Only these are
* immutable: the build generator lists nothing else, and the worker answers
* from a previous release cache only for these (D-7).
*/
export const HASHED_STATIC_ASSET_NAME = /-[A-Za-z0-9_-]{8,}\.[a-z0-9]+$/;
/** §18.2. `ca-static-v1-<first 16 lower-hex of staticAssetSetDigest>`. */
export const STATIC_CACHE_PREFIX = "ca-static-v1-" as const;
+61 -1
View File
@@ -150,6 +150,7 @@ describe("service worker static cache authority", () => {
keys: () => Promise<readonly string[]>;
delete: (name: string) => Promise<boolean>;
}>,
assetUrl = "/assets/app.0123456789abcdef.js",
) {
return createServiceWorkerRuntime(
{
@@ -171,7 +172,7 @@ describe("service worker static cache authority", () => {
// SW-URL-01. Generator output is root-relative.
assets: [
{
url: "/assets/app.0123456789abcdef.js",
url: assetUrl,
sha256: `sha256:${"d".repeat(64)}`,
bytes: 10,
contentType: "text/javascript",
@@ -235,6 +236,65 @@ describe("service worker static cache authority", () => {
expect(previousMatch).not.toHaveBeenCalled();
});
/** Current cache is empty; the marked previous release cache holds `url`. */
function previousReleaseCaches(assetUrl: string) {
const previousCacheName = `${STATIC_CACHE_PREFIX}${"e".repeat(16)}`;
const previousAsset = vi.fn(
async () => new Response("previous", { status: 200 }),
);
const previousCache = {
match: async (url: string) =>
url === `${ORIGIN}${assetUrl}`
? previousAsset()
: new Response(
JSON.stringify({
schemaVersion: 1,
cacheName: previousCacheName,
activationSequence: 1,
}),
{ status: 200 },
),
delete: async () => true,
};
const emptyCache = {
match: async (): Promise<Response | undefined> => undefined,
delete: async () => true,
};
return {
previousAsset,
caches: {
open: vi.fn(async (name: string) =>
name === previousCacheName ? previousCache : emptyCache,
),
keys: vi.fn(async () => [currentCacheName, previousCacheName]),
delete: vi.fn(async () => true),
},
};
}
it("serves a hashed asset missing from the current cache from the previous release cache (R-6.3)", async () => {
const assetUrl = "/assets/app-Dq3x8Yk2.js";
const fixture = previousReleaseCaches(assetUrl);
const runtime = staticRuntime(fixture.caches, assetUrl);
const served = await runtime.onFetch({
method: "GET",
url: `${ORIGIN}${assetUrl}`,
});
await expect(served?.text()).resolves.toBe("previous");
});
it("never answers a non-hashed URL from the previous release cache (D-7)", async () => {
const assetUrl = "/assets/app.js";
const fixture = previousReleaseCaches(assetUrl);
const runtime = staticRuntime(fixture.caches, assetUrl);
await expect(
runtime.onFetch({ method: "GET", url: `${ORIGIN}${assetUrl}` }),
).resolves.toBeNull();
expect(fixture.previousAsset).not.toHaveBeenCalled();
});
it("deletes an invalid hit only from the current release cache", async () => {
const deletes: string[] = [];
const runtime = staticRuntime({