fix(service-worker): keep an existing candidate cache when install fails (Q-6.6-8)

The static cache name is the asset-set digest, so a worker built with the same
assets (same VITE_BUILD_ID, new worker code) installs into the cache the active
worker serves from. A failed install then deleted that serving cache and its
activation marker. installStaticAssets now checks caches.keys() first and rolls
back (including the deferred post-deadline delete) only a cache this install
created. Rewriting an existing cache only puts identical sha256-verified bytes.
InstallDependencies.caches gains an optional keys(); without it the old
behavior (always roll back) is kept.

Verified: RED first (existing-candidate test saw one delete), then green; a
second test pins that a newly created candidate is still deleted. 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:
DongHyeonka
2026-09-24 13:37:56 +09:00
co-authored by Claude Opus 5.5
parent 88e2b0eece
commit 8990f37cb1
2 changed files with 68 additions and 2 deletions
@@ -101,6 +101,8 @@ export type InstallDependencies = Readonly<{
caches: Readonly<{
open(cacheName: string): Promise<Cache>;
delete(cacheName: string): Promise<boolean>;
/** Q-6.6-8. Without it every failed candidate is treated as new. */
keys?(): Promise<readonly string[]>;
}>;
fetcher: typeof fetch;
digest(bytes: Uint8Array): Promise<string>;
@@ -138,7 +140,8 @@ export function validateStaticAssetManifest(
/**
* §17.9. A partial candidate is never used: any failure deletes the candidate
* cache and rejects install, leaving the previous verified revision in place.
* cache this install created and rejects install, leaving the previous
* verified revision in place.
*/
export async function installStaticAssets(
manifest: StaticAssetManifestV1,
@@ -148,6 +151,12 @@ export async function installStaticAssets(
if (invalid) return invalid;
const cacheName = staticCacheName(manifest.setDigest);
// Q-6.6-8. The name is the asset-set digest, so a worker whose assets did
// not change installs into the cache the active (or retained previous)
// worker serves from. Rewriting it only puts identical verified bytes, but
// deleting it on failure would take the serving cache and its marker away.
// Only a cache this install created is rolled back.
const rollBack = !(await cacheExists(dependencies.caches, cacheName));
const abortController = new AbortController();
let deadlineExceeded = false;
let deadlineTimer: ReturnType<typeof setTimeout> | undefined;
@@ -171,7 +180,7 @@ export async function installStaticAssets(
? rejected("INSTALL_DEADLINE_EXCEEDED")
: raced;
if (outcome.kind === "REJECTED") {
if (outcome.kind === "REJECTED" && rollBack) {
await dependencies.caches.delete(cacheName).catch(() => false);
// SW-09. A non-cooperative fetch, digest or `cache.put` started before the
// deadline cannot be cancelled, so it may recreate the candidate cache
@@ -190,6 +199,17 @@ export async function installStaticAssets(
return outcome;
}
async function cacheExists(
caches: InstallDependencies["caches"],
cacheName: string,
): Promise<boolean> {
try {
return (await caches.keys?.())?.includes(cacheName) ?? false;
} catch {
return false;
}
}
async function installCandidate(
manifest: StaticAssetManifestV1,
cacheName: string,
+46
View File
@@ -1011,6 +1011,52 @@ describe("service worker static asset install", () => {
}
});
/** A failing install through the runtime, with `existing` caches present. */
async function failInstall(existing: readonly string[]) {
const deleteCache = vi.fn(async (_name: string) => true);
const runtime = createServiceWorkerRuntime(
{
caches: {
open: vi.fn(async () => ({ put: vi.fn() }) as unknown as Cache),
keys: vi.fn(async () => existing),
delete: deleteCache,
},
clients: { matchAll: vi.fn(async () => []) },
registrationScope: `${ORIGIN}/`,
skipWaiting: vi.fn(async () => {}),
fetcher: vi.fn(async () => new Response(null, { status: 500 })),
digest: vi.fn(),
} as never,
{
identity,
handlers: ["PWA_STATIC_ASSETS"],
manifest,
runtimeConfigUrl: "/runtime-config.json",
releaseManifestUrl: "/release-manifest.json",
},
);
await expect(runtime.onInstall()).rejects.toThrow(
"STATIC_INSTALL_REJECTED:STATUS_INVALID",
);
return deleteCache;
}
it("keeps a candidate cache that already existed when install fails (Q-6.6-8)", async () => {
// Same asset set as the active worker (same build id, new worker code):
// the candidate name is the cache the active worker is serving from.
const candidate = staticCacheName(manifest.setDigest);
const deleteCache = await failInstall([candidate]);
expect(deleteCache).not.toHaveBeenCalled();
});
it("still deletes a candidate cache that this install created (Q-6.6-8)", async () => {
const candidate = staticCacheName(manifest.setDigest);
const deleteCache = await failInstall([
`${STATIC_CACHE_PREFIX}${"e".repeat(16)}`,
]);
expect(deleteCache.mock.calls.map((call) => call[0])).toEqual([candidate]);
});
it("accepts replies only from the captured waiting or controller source", async () => {
const browser = pageContainer({ waiting: true });
const controller = pageController(browser.container);