fix(service-worker): serve an old build's hashed chunk from the previous cache (Q-6.6-6b)
The fetch listener only called respondWith for URLs in the current manifest, so the previous-cache fallback (T29) never ran for the one case it exists for: a tab of the previous build lazy-loading a chunk the new release no longer lists. classifyFetch now returns PREVIOUS_RELEASE_FALLBACK for a same-origin, non-navigate GET whose path is a content-hashed name (HASHED_STATIC_ASSET_NAME) and that is not in the manifest; the runtime answers it only from the marked previous release cache, otherwise the entry falls back to the network. The decision is a synchronous runtime.intercepts() so respondWith is still called only for requests the worker may answer. Runtime config and release manifest stay network-only even though `-manifest.json` matches the hash pattern. Verified: RED first (3 new tests failed: runtime onFetch returned null, entry did not call respondWith), then green. New entry tests cover old chunk from previous cache, previous miss -> network, and no interception for navigate, POST, API, cross-origin, unhashed same-origin and release-manifest.json. Gates: check:architecture, types app/test/service-worker, lint, test:unit (only pre-existing removal-fixture failure), test:component. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
7797461105
commit
88e2b0eece
@@ -94,24 +94,18 @@ self.addEventListener("activate", (event) => {
|
||||
if (handlers.includes("PWA_STATIC_ASSETS")) {
|
||||
self.addEventListener("fetch", (event) => {
|
||||
const request = event.request;
|
||||
// R-6.6. Decided synchronously: only a GET for a verified static asset of
|
||||
// this release is answered. Navigations, API calls and cross-origin
|
||||
// requests are left to the browser untouched.
|
||||
if (
|
||||
request.method !== "GET" ||
|
||||
request.mode === "navigate" ||
|
||||
!runtime.manifestUrls.has(request.url)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const described = {
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
};
|
||||
// R-6.6 / Q-6.6-6b. Decided synchronously: only a same-origin GET for a
|
||||
// verified asset of this release or a content-hashed old-build chunk is
|
||||
// answered. Navigations, API calls, cross-origin and unhashed requests are
|
||||
// left to the browser untouched. Every cache miss goes to the network.
|
||||
if (!runtime.intercepts(described)) return;
|
||||
event.respondWith(
|
||||
runtime
|
||||
.onFetch({
|
||||
method: request.method,
|
||||
url: request.url,
|
||||
mode: request.mode,
|
||||
})
|
||||
.then((cached) => cached ?? fetch(request)),
|
||||
runtime.onFetch(described).then((cached) => cached ?? fetch(request)),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -238,30 +238,54 @@ export function createServiceWorkerRuntime(
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* §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.
|
||||
*/
|
||||
async function onFetch(
|
||||
request: Readonly<{ method: string; url: string; mode?: string }>,
|
||||
): Promise<Response | null> {
|
||||
const classification = classifyFetch({
|
||||
type FetchRequest = Readonly<{ method: string; url: string; mode?: string }>;
|
||||
|
||||
function classify(request: FetchRequest) {
|
||||
if (!staticEnabled) return "NETWORK_PASSTHROUGH";
|
||||
return classifyFetch({
|
||||
method: request.method,
|
||||
requestUrl: request.url,
|
||||
isNavigation: request.mode === "navigate",
|
||||
runtimeConfigUrl: config.runtimeConfigUrl,
|
||||
releaseManifestUrl: config.releaseManifestUrl,
|
||||
manifestUrls,
|
||||
scopeUrl: scope.registrationScope,
|
||||
});
|
||||
if (classification !== "VERIFIED_CACHE_FIRST") return null;
|
||||
}
|
||||
|
||||
// SW-01. Only the current release cache may answer. A CacheStorage-wide
|
||||
// match could return a previous release's response for the same URL, and
|
||||
// the subsequent delete would then target a cache that was never read.
|
||||
/**
|
||||
* R-6.6 / Q-6.6-6b. Synchronous, so the fetch listener decides before it
|
||||
* calls `respondWith`. Only a manifest asset of this release or a
|
||||
* same-origin content-hashed URL (an old build's chunk) is answered;
|
||||
* navigations, API calls, cross-origin and unhashed URLs are left alone.
|
||||
*/
|
||||
function intercepts(request: FetchRequest): boolean {
|
||||
const classification = classify(request);
|
||||
return (
|
||||
classification === "VERIFIED_CACHE_FIRST" ||
|
||||
classification === "PREVIOUS_RELEASE_FALLBACK"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* §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.
|
||||
*/
|
||||
async function onFetch(request: FetchRequest): Promise<Response | null> {
|
||||
const classification = classify(request);
|
||||
// SW-01. Only the current release cache may answer a manifest URL. A
|
||||
// CacheStorage-wide match could return a previous release's response for
|
||||
// the same URL, and the subsequent delete would then target a cache that
|
||||
// was never read.
|
||||
const currentCacheName = config.manifest
|
||||
? staticCacheName(config.manifest.setDigest)
|
||||
: null;
|
||||
if (!currentCacheName) return null;
|
||||
if (classification === "PREVIOUS_RELEASE_FALLBACK") {
|
||||
// Q-6.6-6b. Not listed by this release, so not in the current cache.
|
||||
return matchPreviousRelease(request.url, currentCacheName);
|
||||
}
|
||||
if (classification !== "VERIFIED_CACHE_FIRST") return null;
|
||||
// SW-RR-04. Both `open` and `match` are storage calls that can throw
|
||||
// synchronously or reject. Either one escaping here rejects `respondWith`
|
||||
// itself, so the entry never reaches its network fallback and the page
|
||||
@@ -475,6 +499,7 @@ export function createServiceWorkerRuntime(
|
||||
onInstall,
|
||||
onActivate,
|
||||
onFetch,
|
||||
intercepts,
|
||||
onActivateRequest,
|
||||
onClientMessage,
|
||||
onCacheResetRequest,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
HASHED_STATIC_ASSET_NAME,
|
||||
isOwnedStaticCacheName,
|
||||
SERVICE_WORKER_BOUNDS,
|
||||
staticCacheName,
|
||||
@@ -17,7 +18,13 @@ import {
|
||||
export type FetchClassification =
|
||||
| "NETWORK_PASSTHROUGH"
|
||||
| "NETWORK_ONLY"
|
||||
| "VERIFIED_CACHE_FIRST";
|
||||
| "VERIFIED_CACHE_FIRST"
|
||||
/**
|
||||
* Q-6.6-6b. A same-origin content-hashed URL this release does not list,
|
||||
* typically a lazy chunk of the build a tab still runs. Only the previous
|
||||
* release cache may answer it; otherwise it goes to the network.
|
||||
*/
|
||||
| "PREVIOUS_RELEASE_FALLBACK";
|
||||
|
||||
export type ClassificationInput = Readonly<{
|
||||
method: string;
|
||||
@@ -26,6 +33,8 @@ export type ClassificationInput = Readonly<{
|
||||
runtimeConfigUrl: string;
|
||||
releaseManifestUrl: string;
|
||||
manifestUrls: ReadonlySet<string>;
|
||||
/** The registration scope; a hashed URL outside its origin is never cached. */
|
||||
scopeUrl: string;
|
||||
}>;
|
||||
|
||||
/**
|
||||
@@ -42,9 +51,24 @@ export function classifyFetch(input: ClassificationInput): FetchClassification {
|
||||
return "NETWORK_ONLY";
|
||||
}
|
||||
if (input.manifestUrls.has(input.requestUrl)) return "VERIFIED_CACHE_FIRST";
|
||||
if (isSameOriginHashedAsset(input.requestUrl, input.scopeUrl)) {
|
||||
return "PREVIOUS_RELEASE_FALLBACK";
|
||||
}
|
||||
return "NETWORK_PASSTHROUGH";
|
||||
}
|
||||
|
||||
function isSameOriginHashedAsset(requestUrl: string, scopeUrl: string): boolean {
|
||||
try {
|
||||
const request = new URL(requestUrl);
|
||||
return (
|
||||
request.origin === new URL(scopeUrl).origin &&
|
||||
HASHED_STATIC_ASSET_NAME.test(request.pathname)
|
||||
);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function sameResource(left: string, right: string): boolean {
|
||||
try {
|
||||
const a = new URL(left);
|
||||
|
||||
@@ -289,6 +289,21 @@ describe("service worker static cache authority", () => {
|
||||
await expect(served?.text()).resolves.toBe("previous");
|
||||
});
|
||||
|
||||
it("serves an old build's hashed chunk that the current manifest does not list from the previous release cache (Q-6.6-6b)", async () => {
|
||||
// The page still runs the previous build and lazy-loads a chunk the new
|
||||
// manifest (and so the current cache) no longer has.
|
||||
const oldChunk = "/assets/settings-page-Zz9Yy8Xx.js";
|
||||
const fixture = previousReleaseCaches(oldChunk);
|
||||
const runtime = staticRuntime(fixture.caches, "/assets/app-Dq3x8Yk2.js");
|
||||
|
||||
const served = await runtime.onFetch({
|
||||
method: "GET",
|
||||
url: `${ORIGIN}${oldChunk}`,
|
||||
mode: "cors",
|
||||
});
|
||||
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);
|
||||
@@ -1334,7 +1349,14 @@ describe("page ↔ worker activation seam", () => {
|
||||
* Loads the real worker entry against stubbed worker globals and build-time
|
||||
* constants, and returns the listeners it registered on `self`.
|
||||
*/
|
||||
async function loadWorkerEntry(handlers: readonly string[]) {
|
||||
async function loadWorkerEntry(
|
||||
handlers: readonly string[],
|
||||
cacheStorage: unknown = {
|
||||
open: async () => ({ match: async () => new Response("cached") }),
|
||||
keys: async () => [],
|
||||
delete: async () => true,
|
||||
},
|
||||
) {
|
||||
const listeners = new Map<string, (event: unknown) => void>();
|
||||
vi.stubGlobal("self", {
|
||||
addEventListener: (type: string, listener: (event: unknown) => void) => {
|
||||
@@ -1362,11 +1384,7 @@ async function loadWorkerEntry(handlers: readonly string[]) {
|
||||
vi.stubGlobal("__CA_SERVICE_WORKER_HANDLERS__", handlers);
|
||||
vi.stubGlobal("__CA_RUNTIME_CONFIG_URL__", "/runtime-config.json");
|
||||
vi.stubGlobal("__CA_RELEASE_MANIFEST_URL__", "/release-manifest.json");
|
||||
vi.stubGlobal("caches", {
|
||||
open: async () => ({ match: async () => new Response("cached") }),
|
||||
keys: async () => [],
|
||||
delete: async () => true,
|
||||
});
|
||||
vi.stubGlobal("caches", cacheStorage);
|
||||
vi.stubGlobal("fetch", async () => new Response("network"));
|
||||
vi.resetModules();
|
||||
// A computed specifier keeps the WebWorker-lib entry out of the DOM-lib
|
||||
@@ -1376,12 +1394,12 @@ async function loadWorkerEntry(handlers: readonly string[]) {
|
||||
return listeners;
|
||||
}
|
||||
|
||||
describe("service worker entry fetch interception (R-6.6)", () => {
|
||||
describe("service worker entry fetch interception (R-6.6, Q-6.6-6b)", () => {
|
||||
function fetchEvent(request: { method: string; url: string; mode: string }) {
|
||||
return { request, respondWith: vi.fn() };
|
||||
}
|
||||
|
||||
it("answers only same-origin GETs for manifest assets", async () => {
|
||||
it("answers manifest assets and leaves navigations, API, cross-origin and unhashed requests alone", async () => {
|
||||
try {
|
||||
const listeners = await loadWorkerEntry(["PWA_STATIC_ASSETS"]);
|
||||
const onFetch = listeners.get("fetch")!;
|
||||
@@ -1392,7 +1410,15 @@ describe("service worker entry fetch interception (R-6.6)", () => {
|
||||
{ method: "POST", url: asset, mode: "cors" },
|
||||
{ method: "GET", url: `${ORIGIN}/api/users`, mode: "cors" },
|
||||
{ method: "GET", url: `${ORIGIN}/runtime-config.json`, mode: "cors" },
|
||||
// `-manifest.json` looks like a content hash; it is still network-only.
|
||||
{ method: "GET", url: `${ORIGIN}/release-manifest.json`, mode: "cors" },
|
||||
{ method: "GET", url: "https://cdn.example/assets/app-Dq3x8Yk2.js", mode: "cors" },
|
||||
{ method: "GET", url: "https://cdn.example/assets/old-Zz9Yy8Xx.js", mode: "cors" },
|
||||
// Q-6.6-6b. Same-origin but not a content-hashed name.
|
||||
{ method: "GET", url: `${ORIGIN}/assets/app.js`, mode: "cors" },
|
||||
{ method: "GET", url: `${ORIGIN}/favicon.ico`, mode: "no-cors" },
|
||||
{ method: "POST", url: `${ORIGIN}/assets/old-Zz9Yy8Xx.js`, mode: "cors" },
|
||||
{ method: "GET", url: `${ORIGIN}/assets/old-Zz9Yy8Xx.js`, mode: "navigate" },
|
||||
];
|
||||
for (const request of passthrough) {
|
||||
const event = fetchEvent(request);
|
||||
@@ -1410,6 +1436,72 @@ describe("service worker entry fetch interception (R-6.6)", () => {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Q-6.6-6b. The current cache is empty; the previous release cache (found by
|
||||
* its activation marker) still holds the old build's lazy chunk.
|
||||
*/
|
||||
function previousReleaseStorage(oldChunk: string) {
|
||||
const current = staticCacheName(identity.staticAssetSetDigest);
|
||||
const previous = `${STATIC_CACHE_PREFIX}${"e".repeat(16)}`;
|
||||
const marker = JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
cacheName: previous,
|
||||
activationSequence: 1,
|
||||
});
|
||||
return {
|
||||
open: async (name: string) => ({
|
||||
match: async (url: string) => {
|
||||
if (name !== previous) return undefined;
|
||||
if (url === oldChunk) return new Response("previous");
|
||||
return url.startsWith("https://clean-architecture.invalid/")
|
||||
? new Response(marker)
|
||||
: undefined;
|
||||
},
|
||||
}),
|
||||
keys: async () => [current, previous],
|
||||
delete: async () => true,
|
||||
};
|
||||
}
|
||||
|
||||
it("serves an old build's hashed chunk from the previous release cache (Q-6.6-6b)", async () => {
|
||||
try {
|
||||
const oldChunk = `${ORIGIN}/assets/settings-Zz9Yy8Xx.js`;
|
||||
const listeners = await loadWorkerEntry(
|
||||
["PWA_STATIC_ASSETS"],
|
||||
previousReleaseStorage(oldChunk),
|
||||
);
|
||||
const event = fetchEvent({ method: "GET", url: oldChunk, mode: "cors" });
|
||||
listeners.get("fetch")!(event);
|
||||
|
||||
expect(event.respondWith).toHaveBeenCalledOnce();
|
||||
const response = (await event.respondWith.mock.calls[0]![0]) as Response;
|
||||
await expect(response.text()).resolves.toBe("previous");
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("falls back to the network when the previous release cache misses too (Q-6.6-6b)", async () => {
|
||||
try {
|
||||
const listeners = await loadWorkerEntry(
|
||||
["PWA_STATIC_ASSETS"],
|
||||
previousReleaseStorage(`${ORIGIN}/assets/settings-Zz9Yy8Xx.js`),
|
||||
);
|
||||
const event = fetchEvent({
|
||||
method: "GET",
|
||||
url: `${ORIGIN}/assets/unknown-Qq1Ww2Ee.js`,
|
||||
mode: "cors",
|
||||
});
|
||||
listeners.get("fetch")!(event);
|
||||
|
||||
expect(event.respondWith).toHaveBeenCalledOnce();
|
||||
const response = (await event.respondWith.mock.calls[0]![0]) as Response;
|
||||
await expect(response.text()).resolves.toBe("network");
|
||||
} finally {
|
||||
vi.unstubAllGlobals();
|
||||
}
|
||||
});
|
||||
|
||||
it("registers no fetch listener without the static asset handler", async () => {
|
||||
try {
|
||||
const listeners = await loadWorkerEntry(["WEB_PUSH"]);
|
||||
|
||||
Reference in New Issue
Block a user