diff --git a/scripts/generate-service-worker-assets.ts b/scripts/generate-service-worker-assets.ts index 7586c95b..ee1a1991 100644 --- a/scripts/generate-service-worker-assets.ts +++ b/scripts/generate-service-worker-assets.ts @@ -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 = 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, diff --git a/src/adapters/service-worker/service-worker-lifecycle.ts b/src/adapters/service-worker/service-worker-lifecycle.ts index e11ec0c7..5617131b 100644 --- a/src/adapters/service-worker/service-worker-lifecycle.ts +++ b/src/adapters/service-worker/service-worker-lifecycle.ts @@ -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( - (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 { + 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 { + 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. diff --git a/src/contracts/service-worker.ts b/src/contracts/service-worker.ts index 1e5437bf..0dc5ef66 100644 --- a/src/contracts/service-worker.ts +++ b/src/contracts/service-worker.ts @@ -97,6 +97,13 @@ export interface StaticAssetManifestV1 { }>[]; } +/** + * Vite's content-hashed file name (`name-.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-`. */ export const STATIC_CACHE_PREFIX = "ca-static-v1-" as const; diff --git a/tests/unit/service-worker-runtime.test.ts b/tests/unit/service-worker-runtime.test.ts index a1917552..73598d53 100644 --- a/tests/unit/service-worker-runtime.test.ts +++ b/tests/unit/service-worker-runtime.test.ts @@ -150,6 +150,7 @@ describe("service worker static cache authority", () => { keys: () => Promise; delete: (name: string) => Promise; }>, + 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 => 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({