Public: anyone can read this; the crew can change it.

/sw.js is revalidated on every load: a new release's service worker is never held for four hours #14036

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

torque/forge:torque/13883-sw-js-is-revalidated-on-every-load-a-new → main 2 commits fork

  • Merged. torque/13883-sw-js-is-revalidated-on-every-load-a-new was merged into main as c04d11d.

Review

Sign in to review this change.
4 files changed +65 −14
docs/FEED.md +1 −1
@@ -97,7 +97,7 @@ The `choose` card comes from `src/feed/choose.ts`, a run card offers Stop
9797
9898 ## Offline (`src/web/sw.ts`, `outbox.ts`)
9999
100 - `/sw.js` (root scope, `no-cache`) keeps `/` network-first and serves the
100 - `/sw.js` (root scope, `private, no-cache` with a 304 on its ETag) keeps `/` network-first and serves the
101101 kept copy when the network fails, with `data-stale="1"` so the note above the
102102 feed says "Offline: this feed is from 12 min ago". The stylesheet, `/assets/*`
103103 and icons are cache-first. Nothing else is touched: the API, `/events`,
src/http/server.ts +1 −1
@@ -918,7 +918,7 @@ export function buildRouter(): Router<Handler> {
918918 ctx.params.name === speculationAsset().name ? fileResponse(ctx.request, speculationAsset()) : notFound(),
919919 );
920920 // The service worker: root scope needs a root path, and it must never be
921 // cached by the browser's HTTP cache or an update would wait a day.
921 // held by the browser or the edge (`private, no-cache`, web/sw.ts, #13883).
922922 router.add("GET", "/sw.js", serviceWorker);
923923 router.add("GET", "/offline", offlinePage);
924924 // The page-view beacon's report (http/measure.ts): numbers only, no IP kept.
src/web/sw.ts +33 −11
@@ -121,15 +121,37 @@ const ETAG = `"${sha256(source).slice(0, 16)}"`;
121121 */
122122 export const SW_CSP = "default-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'";
123123
124 export function serviceWorker(): Response {
125 const kill = !!process.env.FORGE_SW_KILL && process.env.FORGE_SW_KILL !== "0";
126 return new Response(kill ? killSource : source, {
127 headers: {
128 "content-type": "text/javascript; charset=utf-8",
129 "cache-control": "no-cache",
130 ...(kill ? {} : { etag: ETAG }),
131 "service-worker-allowed": "/",
132 "content-security-policy": SW_CSP,
133 },
134 });
124 /**
125 * How the worker's script may be kept (#13883): revalidated on every load,
126 * never held. A bare `no-cache` is rewritten by the edge to its own browser
127 * TTL (`max-age=14400`, seen on production even on a MISS), so a release's
128 * worker waited four hours; `private` is passed through untouched (as
129 * `/audit.csv`'s `private, no-store` is) and keeps the edge from holding a
130 * copy. The ETag still makes each revalidation a body-less 304.
131 */
132 export const SW_CACHE_CONTROL = "private, no-cache";
133
134 /**
135 * Whether `If-None-Match` names `etag`; weak comparison, since the edge weakens a tag it
136 * compresses.
137 */
138 function held(header: string | null, etag: string): boolean {
139 if (header === null) return false;
140 if (header.trim() === "*") return true;
141 const bare = (t: string) => t.trim().replace(/^W\//, "");
142 return header.split(",").some((t) => bare(t) === bare(etag));
143 }
144
145 export function serviceWorker(ctx?: { request: Request }): Response {
146 const kill = !!process.env.FORGE_SW_KILL && process.env.FORGE_SW_KILL !== "0";
147 const headers: Record<string, string> = {
148 "content-type": "text/javascript; charset=utf-8",
149 "cache-control": SW_CACHE_CONTROL,
150 ...(kill ? {} : { etag: ETAG }),
151 "service-worker-allowed": "/",
152 "content-security-policy": SW_CSP,
153 };
154 if (!kill && ctx && held(ctx.request.headers.get("if-none-match"), ETAG))
155 return new Response(null, { status: 304, headers });
156 return new Response(kill ? killSource : source, { headers });
135157 }
test/offline.test.ts +30 −1
@@ -16,6 +16,7 @@ import { serve, type Servers } from "../src/http/server.ts";
1616 import { outboxJs } from "../src/web/outbox.ts";
1717 import { serviceWorker, swSource } from "../src/web/sw.ts";
1818 import { withScripts } from "./helpers/page-script.ts";
19 import { stylesheetAsset } from "../src/web/asset.ts";
1920
2021 type Send = (url: string, init: any) => Promise<{ status: number }>;
2122 const make = new Function(`${outboxJs}; return forgeOutbox;`)() as (
@@ -147,7 +148,10 @@ describe("the service worker and the server", () => {
147148 expect(res.status).toBe(200);
148149 expect(res.headers.get("content-type")).toContain("javascript");
149150 expect(res.headers.get("service-worker-allowed")).toBe("/");
150 expect(res.headers.get("cache-control")).toBe("no-cache");
151 // #13883: revalidated every load; `private` so the edge passes it through
152 // instead of rewriting a bare no-cache to its four-hour browser TTL
153 expect(res.headers.get("cache-control")).toBe("private, no-cache");
154 expect(res.headers.get("cache-control")).not.toContain("max-age");
151155 // the worker's CSP is its own: it must let the worker fetch same-origin
152156 const csp = res.headers.get("content-security-policy") ?? "";
153157 expect(csp).toContain("connect-src 'self'");
@@ -156,6 +160,31 @@ describe("the service worker and the server", () => {
156160 expect(swSource).toContain("stale");
157161 });
158162
163 test("/sw.js answers 304 to its own ETag, strong or weakened by the edge, with the same headers", async () => {
164 const first = await fetch(`${servers.url}/sw.js`);
165 const etag = first.headers.get("etag") ?? "";
166 expect(etag).toMatch(/^"[0-9a-f]{16}"$/);
167 await first.text();
168 for (const tag of [etag, `W/${etag}`, `"other", ${etag}`]) {
169 const again = await fetch(`${servers.url}/sw.js`, { headers: { "if-none-match": tag } });
170 expect(again.status).toBe(304);
171 expect(await again.text()).toBe("");
172 expect(again.headers.get("etag")).toBe(etag);
173 expect(again.headers.get("cache-control")).toBe("private, no-cache");
174 expect(again.headers.get("service-worker-allowed")).toBe("/");
175 }
176 const changed = await fetch(`${servers.url}/sw.js`, { headers: { "if-none-match": '"0000000000000000"' } });
177 expect(changed.status).toBe(200);
178 expect(await changed.text()).toBe(swSource);
179 });
180
181 test("hashed /assets/ files keep their immutable cache beside the revalidated worker", async () => {
182 const res = await fetch(`${servers.url}${stylesheetAsset().path}`);
183 expect(res.status).toBe(200);
184 expect(res.headers.get("cache-control")).toBe("public, max-age=31536000, immutable");
185 await res.arrayBuffer();
186 });
187
159188 test("the home page registers the worker, has the note, and allows workers", async () => {
160189 const res = await fetch(`${servers.url}/feed`, { headers: { cookie } });
161190 const text = await res.text();

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs