Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docs/design/rendering.md
Original file line number Diff line number Diff line change
Expand Up @@ -733,10 +733,14 @@ Freshness belongs to the **data layer** (consumer-wired: TanStack Query + an IDB
- **Activate-time cache sweep.** Runtime buckets are named `<bucket>-<buildTag>`, with the base in
front under a subpath (`/app/static-<tag>`, because Cache Storage is per origin, not per scope); on
`activate`, every cache whose name starts with a bucket adaptv **owns** under this app's base and
whose tag is not the current one is deleted. `cleanupOutdatedCaches()` does **not** do this — it only removes precaches written by *older
whose tag is not the current one is deleted. Precache cleanup does **not** do this — it only removes precaches written by *older
Workbox versions* — so without the sweep every deploy mints buckets that are never freed, ending in a
quota error on a frequently-deployed app. → `docs/decisions/register.md` B2

That precache cleanup is adaptv's own (`sw.precache.ts`), not Workbox's `cleanupOutdatedCaches()`:
Workbox's matches the scope as a substring, so a worker at `/` deleted the precache of an app at
`/docs/` on the same origin. adaptv's requires the precache name to **end** with its own scope.

The owned list is exactly `static`, `pages`, `documents`, and it is an **allowlist on purpose**: a
prefix rule like "delete anything that isn't the current tag" would take caches adaptv did not
create — another app on the same origin, a third-party worker, Workbox's own bookkeeping.
Expand Down
185 changes: 185 additions & 0 deletions src/sw/sw.expiration.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/// <reference lib="webworker" />

import "fake-indexeddb/auto"
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import { executeQuotaErrorCallbacks } from "workbox-core/_private/executeQuotaErrorCallbacks.js"
import { ExpirationPlugin } from "workbox-expiration"
import { createExpirationPlugins } from "#adaptv/sw/sw.expiration"
import { createCacheFirstStrategy } from "#adaptv/sw/sw.strategies"
import type { TestServiceWorkerScope } from "#adaptv/sw/sw.test-helper"
import {
browserRequest,
installServiceWorkerScope,
ORIGIN,
TestFetchEvent,
} from "#adaptv/sw/sw.test-helper"
import type { CacheExpirationOptions } from "#adaptv/sw/sw.types"

/*
* `createExpirationPlugins` — how long a runtime cache keeps what it stored.
*
* Workbox's ExpirationPlugin is the real one, with its IndexedDB timestamp
* store on `fake-indexeddb`; the strategy is adaptv's own cache-first. So a
* test reads the cache the way the worker would, not the options object.
*/

let sw: TestServiceWorkerScope
let now: number

beforeEach(() => {
sw = installServiceWorkerScope()
sw.fetch.mockImplementation(async (input) => {
const url = typeof input === "string" ? input : (input as Request).url
return new Response(`body of ${url}`, {
status: 200,
headers: { date: new Date(now).toUTCString() },
})
})
//one tick per request, so "oldest" is never a tie on the same millisecond
now = Date.UTC(2026, 10, 17, 12)
vi.spyOn(Date, "now").mockImplementation(() => now)
})

afterEach(() => {
vi.restoreAllMocks()
vi.unstubAllGlobals()
})

//each test gets caches the timestamp store has never seen
let caseId = 0
function cacheName(label: string) {
caseId += 1
return `${label}-${caseId}`
}

function strategyFor(name: string, expiration: CacheExpirationOptions) {
return createCacheFirstStrategy({ cacheName: name, expiration })
}

async function request(
strategy: ReturnType<typeof strategyFor>,
path: string,
) {
now += 1000
const event = new TestFetchEvent(browserRequest(path))
const response = await strategy.handle({
request: event.request,
event: event as unknown as FetchEvent,
})
await event.settled()
return response
}

describe("createExpirationPlugins — when it adds a plugin", () => {
it("adds none for a permanent cache", () => {
expect(createExpirationPlugins(undefined)).toEqual([])
})

it("adds exactly one ExpirationPlugin when a window is given", () => {
const plugins = createExpirationPlugins({ maxEntries: 10 })
expect(plugins).toHaveLength(1)
expect(plugins[0]).toBeInstanceOf(ExpirationPlugin)
})
})

describe("createExpirationPlugins — maxEntries", () => {
it("keeps the newest entries and evicts the oldest past the limit", async () => {
const name = cacheName("images")
const strategy = strategyFor(name, { maxEntries: 2 })
await request(strategy, "/img/a.png")
await request(strategy, "/img/b.png")
await request(strategy, "/img/c.png")
expect(sw.caches.urlsIn(name).sort()).toEqual([
`${ORIGIN}/img/b.png`,
`${ORIGIN}/img/c.png`,
])
})

it("counts a cache hit as use, so a re-read entry outlives a newer one", async () => {
const name = cacheName("images")
const strategy = strategyFor(name, { maxEntries: 2 })
await request(strategy, "/img/a.png")
await request(strategy, "/img/b.png")
await request(strategy, "/img/a.png") //served from cache, timestamp bumped
await request(strategy, "/img/c.png")
expect(sw.caches.urlsIn(name).sort()).toEqual([
`${ORIGIN}/img/a.png`,
`${ORIGIN}/img/c.png`,
])
})

it("applies per cache — one cache's limit never evicts from another", async () => {
const small = cacheName("thumbs")
const large = cacheName("photos")
const thumbs = strategyFor(small, { maxEntries: 1 })
const photos = strategyFor(large, { maxEntries: 3 })
for (const path of ["/t/1", "/t/2", "/t/3"]) {
await request(thumbs, path)
}
for (const path of ["/p/1", "/p/2", "/p/3"]) {
await request(photos, path)
}
expect(sw.caches.urlsIn(small)).toEqual([`${ORIGIN}/t/3`])
expect(sw.caches.urlsIn(large).sort()).toEqual([
`${ORIGIN}/p/1`,
`${ORIGIN}/p/2`,
`${ORIGIN}/p/3`,
])
})
})

describe("createExpirationPlugins — maxAgeSeconds", () => {
it("serves a cached entry while it is younger than the limit", async () => {
const name = cacheName("feed")
const strategy = strategyFor(name, { maxAgeSeconds: 60 })
const first = await request(strategy, "/feed.json")
sw.fetch.mockClear()
now += 30_000
const second = await request(strategy, "/feed.json")
expect(sw.fetch).not.toHaveBeenCalled()
expect(await second.text()).toBe(await first.text())
})

it("goes back to the network once the entry is older than the limit", async () => {
const name = cacheName("feed")
const strategy = strategyFor(name, { maxAgeSeconds: 60 })
await request(strategy, "/feed.json")
sw.fetch.mockClear()
now += 120_000
await request(strategy, "/feed.json")
expect(sw.fetch).toHaveBeenCalledTimes(1)
})

it("deletes expired entries from the cache, not only skips them", async () => {
const name = cacheName("feed")
const strategy = strategyFor(name, { maxAgeSeconds: 60 })
await request(strategy, "/old.json")
now += 120_000
await request(strategy, "/new.json")
expect(sw.caches.urlsIn(name)).toEqual([`${ORIGIN}/new.json`])
})
})

describe("createExpirationPlugins — purgeOnQuotaError", () => {
//quota callbacks are process-wide in Workbox, so earlier tests' plugins run
//too; each test only reads its own cache
it("defaults on: a quota error drops the whole cache", async () => {
const name = cacheName("big")
const strategy = strategyFor(name, { maxEntries: 10 })
await request(strategy, "/blob/1")
expect(sw.caches.urlsIn(name)).toHaveLength(1)
await executeQuotaErrorCallbacks()
expect(await sw.caches.has(name)).toBe(false)
})

it("can be turned off, and then the cache survives a quota error", async () => {
const name = cacheName("keep")
const strategy = strategyFor(name, {
maxEntries: 10,
purgeOnQuotaError: false,
})
await request(strategy, "/blob/1")
await executeQuotaErrorCallbacks()
expect(sw.caches.urlsIn(name)).toEqual([`${ORIGIN}/blob/1`])
})
})
157 changes: 157 additions & 0 deletions src/sw/sw.plugins.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,157 @@
/// <reference lib="webworker" />

import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"
import type { WorkboxPlugin } from "workbox-core/types"
import { createCacheOkResponsesPlugin } from "#adaptv/sw/sw.plugins"
import { createCacheFirstStrategy } from "#adaptv/sw/sw.strategies"
import type { TestServiceWorkerScope } from "#adaptv/sw/sw.test-helper"
import {
browserRequest,
installServiceWorkerScope,
ORIGIN,
TestFetchEvent,
} from "#adaptv/sw/sw.test-helper"

/*
* `createCacheOkResponsesPlugin` — the gate every adaptv strategy puts in front
* of the cache. Only a 200 is kept: an opaque response hides its status (it may
* be a 500), a redirect or a 206 is not the resource itself, and an error body
* cached once would be served offline for as long as the entry lives.
*/

function cacheWillUpdate(response: Response | undefined) {
const plugin = createCacheOkResponsesPlugin()
return plugin.cacheWillUpdate?.({
request: new Request(`${ORIGIN}/data/item`),
response: response as Response,
event: new Event("fetch") as ExtendableEvent,
state: {},
})
}

/** What a cross-origin `no-cors` fetch returns: status 0, body unreadable. */
function opaqueResponse(): Response {
const response = new Response(null)
Object.defineProperty(response, "status", { value: 0 })
Object.defineProperty(response, "type", { value: "opaque" })
return response
}

describe("createCacheOkResponsesPlugin — cacheWillUpdate", () => {
it("keeps a 200 as it is", async () => {
const response = new Response("ok", { status: 200 })
expect(await cacheWillUpdate(response)).toBe(response)
})

it("refuses an opaque response — its status could be anything", async () => {
expect(await cacheWillUpdate(opaqueResponse())).toBeNull()
})

it("refuses a network error", async () => {
expect(await cacheWillUpdate(Response.error())).toBeNull()
})

it.each([
[204, "no content"],
[206, "a partial body"],
[301, "a redirect"],
[304, "a revalidation with no body"],
])(
"refuses a %i (%s) — only the full resource is kept",
async (status) => {
const body = status === 204 || status === 304 ? null : "x"
expect(
await cacheWillUpdate(new Response(body, { status })),
).toBeNull()
},
)

it.each([400, 401, 403, 404, 410, 429])(
"refuses a %i client error",
async (status) => {
expect(
await cacheWillUpdate(new Response("nope", { status })),
).toBeNull()
},
)

it.each([500, 502, 503, 504])(
"refuses a %i server error",
async (status) => {
expect(
await cacheWillUpdate(new Response("down", { status })),
).toBeNull()
},
)

it("refuses when there is no response at all", async () => {
expect(await cacheWillUpdate(undefined)).toBeNull()
})
})

describe("createCacheOkResponsesPlugin — inside a real strategy", () => {
let sw: TestServiceWorkerScope

beforeEach(() => {
sw = installServiceWorkerScope()
})

afterEach(() => {
vi.unstubAllGlobals()
})

async function fetchThrough(path: string, plugins?: WorkboxPlugin[]) {
const strategy = createCacheFirstStrategy({
cacheName: "assets",
plugins,
})
const event = new TestFetchEvent(browserRequest(path))
const response = await strategy.handle({
request: event.request,
event: event as unknown as FetchEvent,
})
await event.settled()
return response
}

it("caches a 200 the network returned", async () => {
sw.fetch.mockResolvedValue(new Response("logo", { status: 200 }))
const response = await fetchThrough("/img/logo.png")
expect(response.status).toBe(200)
expect(sw.caches.urlsIn("assets")).toEqual([`${ORIGIN}/img/logo.png`])
})

it("still hands a 500 to the page but does not cache it", async () => {
sw.fetch.mockResolvedValue(new Response("down", { status: 500 }))
const response = await fetchThrough("/img/logo.png")
expect(response.status).toBe(500)
expect(sw.caches.urlsIn("assets")).toEqual([])
})

it("still hands a 404 to the page but does not cache it", async () => {
sw.fetch.mockResolvedValue(new Response("gone", { status: 404 }))
const response = await fetchThrough("/img/missing.png")
expect(response.status).toBe(404)
expect(sw.caches.urlsIn("assets")).toEqual([])
})

it("does not cache an opaque response", async () => {
sw.fetch.mockResolvedValue(opaqueResponse())
await fetchThrough("/img/logo.png")
expect(sw.caches.urlsIn("assets")).toEqual([])
})

it("runs before an app's own plugin, so that plugin never sees a 500", async () => {
//Workbox only applies its own 200-only default when NO plugin defines
//`cacheWillUpdate`; an app plugin that does would otherwise switch it off
const keepEverything = vi.fn(
async ({ response }: { response: Response }) => response,
)
sw.fetch.mockResolvedValue(new Response("down", { status: 500 }))
await fetchThrough("/img/logo.png", [
{ cacheWillUpdate: keepEverything },
])
expect(keepEverything).not.toHaveBeenCalled()
expect(sw.caches.urlsIn("assets")).toEqual([])
})
})
Loading
Loading