Merge perf/workers-cache into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by oscabriel · committed by oscabriel · parents 923d465, a3720ac · Browse files · 8 files·+649 added−4 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+649 added−4 removed
- tests:+439 added−0 removed
- other:+210 added−4 removed
Provenance
- Commit
ccd5da2- Tree
4c13426- Author
oscabriel <oscarhernandeziv@gmail.com>- Committer
oscabriel <oscarhernandeziv@gmail.com>- Parent 1
923d465- Parent 2
a3720ac
8 files changed+649 added−4 removed
modified:apps/web/src/server/cache-headers.ts+9 added
11 unmodified lines12131415161718192021222324252627285 unmodified lines11 unmodified lines * finds none), and times reckoned from when it was read. What does not * change is kept below the page, by object id (ADR 0019, ADR 0020). * - A page about the person reading it (Today, a decision, a proposal) is * kept nowhere. * * Workers Cache keeps these at the edge too, shared by every reader, keyed * by path and query and never by cookie (ADR 0026). So a page that gives * `branchPage` reads as nobody: its loader never reaches the reader's * request, and its markup is the same for everyone. The Worker's entry * (`edge-cache.ts`) has the last word on every answer: one to a request * that carries a cookie is kept nowhere whatever its route says, and one * the edge may keep varies by `Cookie`, so it reaches only a reader with * none (`test/edge-cache.test.ts`). */
export const branchPage = { "Cache-Control": "public, max-age=30, stale-while-revalidate=300",5 unmodified linesadded:apps/web/src/server/edge-cache.ts+138 added
1+/**2+ * What the edge may keep of the web's answers (ADR 0026). Workers Cache3+ * stands in front of the deployed web Worker and keys an answer by its path4+ * and query string alone: not by the host, and not by the `Cookie` or the5+ * `Authorization` a request carries. A request with a cookie is served what6+ * the cache holds for its path, unless the stored answer varies by7+ * `Cookie`; an answer without `Cache-Control` is kept by a heuristic (two8+ * hours for a 200). Every answer the Worker gives passes through9+ * `forTheEdge` (`src/server.ts`), which holds two rules:10+ *11+ * - An answer to a request that carries any cookie or an `Authorization`,12+ * an answer that sets a cookie, and an answer that says nothing of how13+ * long it may be kept, is kept nowhere: `private, no-store`, which the14+ * cache bypasses. So nothing read with a reader's credential is ever15+ * stored, and a route that forgets its headers keeps nothing.16+ * - Any other answer the cache may store varies by `Cookie`: it was made for17+ * a request with no cookie, and is served only to one, so a signed-in18+ * reader is never handed a page kept from a signed-out one.19+ *20+ * `CDN-Cache-Control` and `Cloudflare-CDN-Cache-Control` would outrank21+ * `Cache-Control` at the edge; the web sets neither, and drops any an22+ * answer it passes on carries.23+ */24+import { Effect } from "effect";25+26+/** The `Cache-Control` of an answer kept by nobody: no shared cache, no browser. */27+export const KEPT_NOWHERE = "private, no-store";28+29+/** Headers that would decide what the edge keeps over `Cache-Control`. */30+const EDGE_OVERRIDES = ["cdn-cache-control", "cloudflare-cdn-cache-control"];31+32+/** The directives of a `Cache-Control` value, each as `name` or `name=value`, lower-cased. */33+const directivesOf = (cacheControl: string) =>34+ cacheControl35+ .split(",")36+ .map((directive) => directive.trim().toLowerCase())37+ .filter((directive) => directive !== "");38+39+/** Whether the request says who is reading it: any cookie, or an `Authorization`. */40+const speaksForSomeone = (request: Request) =>41+ request.headers.has("cookie") || request.headers.has("authorization");42+43+/**44+ * Whether `cacheControl` must be replaced by `KEPT_NOWHERE`: it is missing,45+ * or it names a field (`private="set-cookie"`, `no-cache="…"`), the form46+ * that lets the cache store the answer with that field stripped.47+ */48+const unsafeFor = (cacheControl: string | null) =>49+ cacheControl === null ||50+ directivesOf(cacheControl).some(51+ (directive) =>52+ directive.startsWith("private=") || directive.startsWith("no-cache=")53+ );54+55+/** Whether the cache bypasses an answer under `cacheControl`. */56+const keptNowhere = (cacheControl: string) =>57+ directivesOf(cacheControl).some(58+ (directive) => directive === "private" || directive === "no-store"59+ );60+61+/** `vary` with `Cookie` among its headers. */62+const varyingByCookie = (vary: string | null) => {63+ const names = (vary ?? "")64+ .split(",")65+ .map((name) => name.trim())66+ .filter((name) => name !== "");67+68+ return names.some((name) => name.toLowerCase() === "cookie")69+ ? names.join(", ")70+ : [...names, "Cookie"].join(", ");71+};72+73+/** `response`'s headers as the edge may see them, for `request`. */74+const edgeHeaders = (request: Request, response: Response) => {75+ const headers = new Headers(response.headers);76+77+ for (const name of EDGE_OVERRIDES) {78+ headers.delete(name);79+ }80+81+ const cacheControl = headers.get("cache-control");82+83+ if (84+ speaksForSomeone(request) ||85+ headers.has("set-cookie") ||86+ unsafeFor(cacheControl)87+ ) {88+ headers.set("cache-control", KEPT_NOWHERE);89+90+ return headers;91+ }92+93+ if (cacheControl !== null && !keptNowhere(cacheControl)) {94+ headers.set("vary", varyingByCookie(headers.get("vary")));95+ }96+97+ return headers;98+};99+100+/**101+ * `response` as the edge may keep it, for `request`: the same status and102+ * body (a stream stays a stream), under the two rules above.103+ */104+export const forTheEdge = (request: Request, response: Response): Response =>105+ new Response(response.body, {106+ headers: edgeHeaders(request, response),107+ status: response.status,108+ statusText: response.statusText,109+ });110+111+/** A Worker's `fetch`, as TanStack Start's server entry gives it. */112+interface Entry<Rest extends readonly unknown[]> {113+ readonly fetch: (114+ request: Request,115+ ...rest: Rest116+ ) => Promise<Response> | Response;117+}118+119+/** The Worker's `fetch` once every answer passes through `forTheEdge`. */120+interface EdgeEntry<Rest extends readonly unknown[]> {121+ readonly fetch: (request: Request, ...rest: Rest) => Promise<Response>;122+}123+124+/**125+ * `entry` with every answer it gives passed through `forTheEdge`; its other126+ * arguments (the Worker's env and context) go on to it untouched.127+ */128+export const edgeEntry = <Rest extends readonly unknown[]>(129+ entry: Entry<Rest>130+): EdgeEntry<Rest> => ({131+ fetch: (request, ...rest) =>132+ Effect.runPromise(133+ Effect.map(134+ Effect.promise(() => Promise.resolve(entry.fetch(request, ...rest))),135+ (response) => forTheEdge(request, response)136+ )137+ ),138+});added:apps/web/src/server.ts+11 added
1234567891011/** * The web Worker's entry (`wrangler.jsonc`'s `main`): TanStack Start's own * server entry, with every answer it gives passed through `forTheEdge`, so * what the edge's cache may keep is decided in one place for pages, server * functions, server routes, redirects and errors alike (ADR 0026). */import handler from "@tanstack/react-start/server-entry";
import { edgeEntry } from "./server/edge-cache.ts";
export default edgeEntry(handler);added:apps/web/test/edge-cache.test.ts+415 added
1+/**2+ * What the edge's cache may keep of the web's answers (ADR 0026). Workers3+ * Cache keys an answer by its path and query alone, never by the cookie a4+ * request carries, so the Worker's entry decides for every answer: one to a5+ * request that carries a cookie or an `Authorization`, one that sets a6+ * cookie, and one that says nothing of how long it may be kept, is kept7+ * nowhere; any other the cache may store varies by `Cookie`, so it is served8+ * only to a request with none. And no page the cache may keep reads who is9+ * reading it: only a page kept nowhere reaches the reader's request.10+ */11+import { describe, expect, it } from "@effect/vitest";12+import { Client, Contracts } from "@repo/protocol/contracts";13+import { ProjectName } from "@repo/protocol/ids";14+import { asTester, unanswered } from "@repo/protocol/testing";15+import { untouchable } from "@repo/testkit/untouchable";16+import { Effect, Layer } from "effect";17+import { RpcTest } from "effect/rpc";18+19+import { forwarded } from "../src/features/agents/forward.ts";20+import { backend } from "../src/server/backend.ts";21+import { branchPage, personalPage } from "../src/server/cache-headers.ts";22+import {23+ edgeEntry,24+ forTheEdge,25+ KEPT_NOWHERE,26+} from "../src/server/edge-cache.ts";27+import { frontPageHandler } from "../src/server/front-page.ts";28+import { frontLlmsHandler, projectLlmsHandler } from "../src/server/llms.ts";29+import { rpcHandler } from "../src/server/rpc.ts";30+import { SESSION_COOKIE } from "../src/server/session.ts";31+32+const WEB_URL = "https://web-test.example.workers.dev";33+34+const PLATFORM_URL = "https://platform-test.example.workers.dev";35+36+/** A signed-in reader's cookie, as the browser sends it. */37+const SIGNED_IN = `${SESSION_COOKIE}=dev-ada`;38+39+/** A GET for `path` on the web host, with `headers`. */40+const get = (path: string, headers: HeadersInit = {}) =>41+ new Request(`${WEB_URL}${path}`, { headers });42+43+/** What the edge sees of an answer: how long it may be kept, and what it varies by. */44+const kept = (response: Response) => ({45+ cacheControl: response.headers.get("cache-control"),46+ vary: response.headers.get("vary"),47+});48+49+/** An answer under `headers`, with a body. */50+const answer = (headers: HeadersInit, status = 200) =>51+ new Response("the page", { headers, status });52+53+/** Every `Cache-Control` the web gives or passes on, and none. */54+const ANSWERS: readonly (readonly [string, HeadersInit])[] = [55+ ["a page at main", branchPage],56+ ["a page about its reader", personalPage],57+ ["an agent's document", { "cache-control": "public, max-age=60" }],58+ [59+ "a raw file at a commit",60+ { "cache-control": "public, max-age=31536000, immutable" },61+ ],62+ ["a sign-in redirect", { "cache-control": "no-store" }],63+ ["an answer with no Cache-Control", {}],64+];65+66+describe("an answer to a request that says who is reading", () => {67+ it.each(ANSWERS)(68+ "is kept nowhere, given a session cookie: %s",69+ (_, headers) => {70+ expect(71+ kept(72+ forTheEdge(get("/datekit", { cookie: SIGNED_IN }), answer(headers))73+ ).cacheControl74+ ).toBe(KEPT_NOWHERE);75+ }76+ );77+78+ it.each(ANSWERS)("is kept nowhere, given any cookie: %s", (_, headers) => {79+ expect(80+ kept(81+ forTheEdge(get("/datekit", { cookie: "theme=dark" }), answer(headers))82+ ).cacheControl83+ ).toBe(KEPT_NOWHERE);84+ });85+86+ it.each(ANSWERS)(87+ "is kept nowhere, given an Authorization: %s",88+ (_, headers) => {89+ expect(90+ kept(91+ forTheEdge(92+ get("/datekit", { authorization: "Bearer dev-ada" }),93+ answer(headers)94+ )95+ ).cacheControl96+ ).toBe(KEPT_NOWHERE);97+ }98+ );99+});100+101+describe("an answer to a request with no cookie", () => {102+ it("is kept nowhere when it sets a cookie", () => {103+ expect(104+ kept(105+ forTheEdge(106+ get("/auth/whoami"),107+ answer({108+ ...branchPage,109+ "set-cookie": `${SESSION_COOKIE}=; Max-Age=0`,110+ })111+ )112+ ).cacheControl113+ ).toBe(KEPT_NOWHERE);114+ });115+116+ it("is kept nowhere when it says nothing of how long it may be kept", () => {117+ // Without it, the cache would keep a 200 for two hours by its heuristic.118+ expect(kept(forTheEdge(get("/_serverFn/x"), answer({})))).toStrictEqual({119+ cacheControl: KEPT_NOWHERE,120+ vary: null,121+ });122+ });123+124+ it.each([`private="set-cookie"`, `public, no-cache="set-cookie"`])(125+ "is kept nowhere when its Cache-Control names a field to strip: %s",126+ (cacheControl) => {127+ expect(128+ kept(forTheEdge(get("/"), answer({ "cache-control": cacheControl })))129+ .cacheControl130+ ).toBe(KEPT_NOWHERE);131+ }132+ );133+134+ it("keeps a page at main as the route says, varied by Cookie", () => {135+ expect(136+ kept(forTheEdge(get("/datekit/tree/main"), answer(branchPage)))137+ ).toStrictEqual({138+ cacheControl: branchPage["Cache-Control"],139+ vary: "Cookie",140+ });141+ });142+143+ it("adds Cookie to what an answer already varies by, once", () => {144+ expect(145+ [146+ { ...branchPage, vary: "Accept" },147+ { ...branchPage, vary: "Accept, cookie" },148+ ].map((headers) => kept(forTheEdge(get("/"), answer(headers))).vary)149+ ).toStrictEqual(["Accept, Cookie", "Accept, cookie"]);150+ });151+152+ it("keeps a page about its reader nowhere, as the route says", () => {153+ expect(kept(forTheEdge(get("/today"), answer(personalPage)))).toStrictEqual(154+ {155+ cacheControl: personalPage["Cache-Control"],156+ vary: null,157+ }158+ );159+ });160+161+ it("drops the headers that would outrank Cache-Control at the edge", () => {162+ const response = forTheEdge(163+ get("/releases/manifest.json"),164+ answer({165+ ...branchPage,166+ "cdn-cache-control": "public, max-age=86400",167+ "cloudflare-cdn-cache-control": "public, max-age=86400",168+ })169+ );170+171+ expect([172+ response.headers.get("cdn-cache-control"),173+ response.headers.get("cloudflare-cdn-cache-control"),174+ ]).toStrictEqual([null, null]);175+ });176+177+ it.effect("comes back with its status, its other headers and its body", () =>178+ Effect.gen(function* () {179+ const response = forTheEdge(180+ get("/nowhere"),181+ answer({ ...branchPage, "content-type": "text/html" }, 404)182+ );183+184+ expect({185+ body: yield* Effect.promise(() => response.text()),186+ contentType: response.headers.get("content-type"),187+ status: response.status,188+ }).toStrictEqual({189+ body: "the page",190+ contentType: "text/html",191+ status: 404,192+ });193+ })194+ );195+});196+197+describe("the Worker's entry", () => {198+ it.effect(199+ "hands the request and the Worker's env and context to Start, and its answer to the edge's rule",200+ () =>201+ Effect.gen(function* () {202+ const handed: unknown[] = [];203+204+ const entry = edgeEntry({205+ fetch: (request: Request, env: string, context: string) => {206+ handed.push(request.url, env, context);207+208+ return Promise.resolve(answer(branchPage));209+ },210+ });211+212+ const response = yield* Effect.promise(() =>213+ entry.fetch(get("/", { cookie: SIGNED_IN }), "env", "context")214+ );215+216+ expect(handed).toStrictEqual([`${WEB_URL}/`, "env", "context"]);217+ expect(kept(response).cacheControl).toBe(KEPT_NOWHERE);218+ })219+ );220+221+ it("is Start's server entry wrapped by edgeEntry, and nothing else", () => {222+ const sources: Readonly<Record<string, string>> = import.meta.glob(223+ "../src/server.ts",224+ { eager: true, import: "default", query: "?raw" }225+ );226+227+ const code = (sources["../src/server.ts"] ?? "")228+ .replaceAll(/\/\*\*[\s\S]*?\*\//gu, "")229+ .trim();230+231+ expect(code.split(/\n+/u)).toStrictEqual([232+ 'import handler from "@tanstack/react-start/server-entry";',233+ 'import { edgeEntry } from "./server/edge-cache.ts";',234+ "export default edgeEntry(handler);",235+ ]);236+ });237+});238+239+// --- The routes that read the reader's credential ----------------------------240+241+/** A platform that lists datekit and no asks, and answers nothing else. */242+const listingDatekit = () =>243+ Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(244+ Layer.provide([245+ Layer.mergeAll(246+ unanswered,247+ Contracts.toLayerHandler("listProjects", () =>248+ Effect.succeed({249+ projects: [250+ {251+ openAsks: 0,252+ posture: "open" as const,253+ project: ProjectName.make("datekit"),254+ },255+ ],256+ })257+ ),258+ Contracts.toLayerHandler("listAsks", () => Effect.succeed({ asks: [] }))259+ ),260+ asTester,261+ ])262+ );263+264+/** An env whose PLATFORM answers every request with a long-lived public answer. */265+const platformEnv: Env = {266+ PLATFORM: untouchable<Fetcher>("PLATFORM", {267+ fetch: () =>268+ Promise.resolve(269+ answer({ "cache-control": "public, max-age=31536000, immutable" })270+ ),271+ }),272+ PUBLIC_PLATFORM_URL: PLATFORM_URL,273+};274+275+/**276+ * Each server route that hands the reader's cookie on (to the platform, as277+ * its credential), by the request it answers. Each answers a public278+ * `Cache-Control` of its own; the entry is what keeps a reader's answer279+ * from the edge.280+ */281+const CREDENTIAL_ROUTES: readonly (readonly [282+ string,283+ (request: Request) => Promise<Response>,284+])[] = [285+ [286+ "/llms.txt",287+ (request) => frontLlmsHandler(listingDatekit, PLATFORM_URL)({ request }),288+ ],289+ [290+ "/datekit/llms.txt",291+ (request) =>292+ projectLlmsHandler(293+ listingDatekit,294+ PLATFORM_URL295+ )({ params: { project: "datekit" }, request }),296+ ],297+ [298+ "/",299+ (request) =>300+ Promise.resolve(301+ frontPageHandler(302+ listingDatekit,303+ PLATFORM_URL304+ )({305+ next: () => answer(branchPage),306+ request,307+ })308+ ),309+ ],310+ [311+ "/datekit/raw/main/README.md",312+ (request) => forwarded(backend, platformEnv).GET({ request }),313+ ],314+ [315+ "/rpc",316+ (request) =>317+ rpcHandler(318+ backend,319+ platformEnv320+ )({ request: new Request(request, { body: "{}", method: "POST" }) }),321+ ],322+];323+324+/** A signed-in agent's request for `path`, as Markdown. */325+const signedInAt = (path: string) =>326+ get(path, { accept: "text/markdown", cookie: SIGNED_IN });327+328+describe("a route that hands the reader's cookie on", () => {329+ it.effect.each(CREDENTIAL_ROUTES)(330+ "%s is kept nowhere when a session cookie comes with it",331+ ([path, handle]) =>332+ Effect.gen(function* () {333+ const own = yield* Effect.promise(() => handle(signedInAt(path)));334+335+ // The route alone would let a shared cache keep it.336+ expect(own.headers.get("cache-control")).toMatch(/^public\b/u);337+338+ const served = yield* Effect.promise(() =>339+ edgeEntry({ fetch: handle }).fetch(signedInAt(path))340+ );341+342+ expect(kept(served).cacheControl).toBe(KEPT_NOWHERE);343+ })344+ );345+346+ it.effect.each(CREDENTIAL_ROUTES)(347+ "%s, with no cookie, is kept as it says and varied by Cookie",348+ ([path, handle]) =>349+ Effect.gen(function* () {350+ const served = yield* Effect.promise(() =>351+ edgeEntry({ fetch: handle }).fetch(352+ get(path, { accept: "text/markdown" })353+ )354+ );355+356+ expect(kept(served).cacheControl).toMatch(/^public\b/u);357+ expect(kept(served).vary).toMatch(/\bCookie$/u);358+ })359+ );360+});361+362+// --- The pages ---------------------------------------------------------------363+364+const routeSources: Readonly<Record<string, string>> = import.meta.glob(365+ "../src/routes/**/*.{ts,tsx}",366+ { eager: true, import: "default", query: "?raw" }367+);368+369+const allSources: Readonly<Record<string, string>> = import.meta.glob(370+ "../src/**/*.{ts,tsx}",371+ { eager: true, import: "default", query: "?raw" }372+);373+374+/**375+ * Where a page's loader or server function reaches the request it answers376+ * (its cookie, its headers): TanStack Start's server helpers.377+ */378+const readsTheRequest = /from "@tanstack\/react-start\/server"/u;379+380+describe("a page", () => {381+ it("reads the reader's request only where it is kept nowhere", () => {382+ const reading = Object.entries(allSources).flatMap(([path, source]) =>383+ readsTheRequest.test(source) ? [path] : []384+ );385+386+ expect(reading.toSorted()).toStrictEqual([387+ "../src/routes/$project/decisions/$decision.tsx",388+ "../src/routes/today.tsx",389+ ]);390+391+ for (const path of reading) {392+ const source = routeSources[path] ?? "";393+394+ expect(source, `${path} is kept nowhere`).toContain("personalPage");395+ expect(source, `${path} is never kept at main`).not.toContain(396+ "branchPage"397+ );398+ }399+ });400+401+ it("that the edge may keep reads as nobody, so its markup is the same for every reader", () => {402+ const keepable = Object.entries(routeSources).filter(([, source]) =>403+ source.includes("branchPage")404+ );405+406+ expect(keepable.length).toBeGreaterThan(10);407+408+ for (const [path, source] of keepable) {409+ expect(source, `${path} reaches no request`).not.toMatch(readsTheRequest);410+ expect(source, `${path} reads no cookie`).not.toMatch(411+ /credentialFrom|SESSION_COOKIE|HANDLE_COOKIE/u412+ );413+ }414+ });415+});modified:apps/web/worker-configuration.d.ts+4 added-1 removed
1223456789101112131413 unmodified lines/* eslint-disable */// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: da1857314b335dfd1203e75276309d10)// Generated by Wrangler by running `wrangler types --include-runtime=false --strict-vars=false` (hash: aa7c6db610447e5e6e68b0fe0dbbcb47)interface __BaseEnv_Env { PUBLIC_PLATFORM_URL: string; PLATFORM: Fetcher /* platform-dev-oscabriel */ | Fetcher /* platform-demo */ | Fetcher /* platform */;}declare namespace Cloudflare { interface GlobalProps { mainModule: typeof import("./src/server"); } interface DevOscabrielEnv { PUBLIC_PLATFORM_URL: string; PLATFORM: Fetcher /* platform-dev-oscabriel */; }13 unmodified linesmodified:apps/web/wrangler.jsonc+11 added-3 removed
8 unmodified lines9 //10 // The top level is stage `local`: `vite dev` and the type generation read11 // it, and it is never deployed. Each stage under `env` repeats the binding12 // and the vars, since wrangler does not inherit them into an environment.13+ //14+ // Workers Cache is on in each deployed stage, and off at the top, so `vite15+ // dev` keeps nothing (ADR 0026). It keys by the Worker's version, so each16+ // deploy starts cold and a kept page never names another version's hashed17+ // assets: `cross_version_cache` stays off.18 "$schema": "node_modules/wrangler/config-schema.json",19 "name": "web",15- // TanStack Start's own server entry (the Cloudflare framework guide); the16- // Cloudflare Vite plugin builds it.17- "main": "@tanstack/react-start/server-entry",20+ // TanStack Start's own server entry, wrapped so every answer passes21+ // through what the edge may keep (src/server/edge-cache.ts; the Cloudflare22+ // framework guide's custom entrypoint). The Cloudflare Vite plugin builds it.23+ "main": "src/server.ts",24 "compatibility_date": "2026-10-05",25 "compatibility_flags": ["nodejs_compat"],26 "workers_dev": true,27 "preview_urls": false,8 unmodified lines36 "PUBLIC_PLATFORM_URL": "http://localhost:8787",37 },38 "env": {39 "dev-oscabriel": {40+ "cache": { "enabled": true },41 "services": [42 { "binding": "PLATFORM", "service": "platform-dev-oscabriel" },43 ],44 "vars": {45 "PUBLIC_PLATFORM_URL": "https://platform-dev-oscabriel.oscargabriel.workers.dev",46 },47 },48 "demo": {49+ "cache": { "enabled": true },50 "services": [{ "binding": "PLATFORM", "service": "platform-demo" }],51 "vars": {52 "PUBLIC_PLATFORM_URL": "https://platform-demo.oscargabriel.workers.dev",53 },3 unmodified linesadded:docs/adr/0026-the-edge-keeps-the-webs-anonymous-answers.md+37 added
12345678910111213141516171819202122232425262728293031323334353637---status: accepted---
# The edge keeps the web's anonymous answers, and nothing read for a reader
The web Worker runs behind Workers Cache in each deployed stage (`"cache": { "enabled": true }` in `apps/web/wrangler.jsonc`'s `dev-oscabriel` and `demo` blocks; the top-level `local` stage, which `vite dev` reads, has none). A page the cache holds comes back from the edge without running the Worker, at the `Cache-Control` the page already gives: `branchPage` (`public, max-age=30, stale-while-revalidate=300`) for the pages at `main`, a tag or a commit, `public, max-age=60` for the agents' documents, and the platform's own headers on what the web passes on (raw files, releases, the install script).
Workers Cache keys an answer by the Worker's entrypoint, path, query string and version, and by none of the host, the `Cookie` or the `Authorization` (<https://developers.cloudflare.com/workers/cache/cache-keys/>). It bypasses a request with an `Authorization`, an answer with `Set-Cookie`, and an answer marked `private` or `no-store`. It does not bypass a request that carries a cookie, it honours `Vary` by storing one variant per verbatim value of each named request header, and an answer with no `Cache-Control` is kept by a heuristic: two hours for a 200, three minutes for a 404 (<https://developers.cloudflare.com/workers/cache/configuration/>). So a page whose markup depended on its reader would be handed to everyone, and a route that forgot its headers would be kept for hours.
The web holds that off in one place. `wrangler.jsonc`'s `main` is `apps/web/src/server.ts`: TanStack Start's own server entry, with every answer it gives (pages, server functions, server routes, redirects and errors) passed through `forTheEdge` (`apps/web/src/server/edge-cache.ts`):
- An answer to a request that carries any cookie or an `Authorization`, an answer that sets a cookie, an answer with no `Cache-Control`, and one whose `private` or `no-cache` names a field to strip, is `private, no-store`, which the cache bypasses. Nothing read with a reader's credential is stored.- Any other answer the cache may store varies by `Cookie`. It was made for a request with no cookie, and the cache serves it only to a request with none, so a signed-in reader never receives a page kept from a signed-out one, and the browser's own cache drops it when a session begins or ends.- `CDN-Cache-Control` and `Cloudflare-CDN-Cache-Control`, which outrank `Cache-Control` at the edge, are dropped.
The pages keep a rule their loaders already followed (`apps/web/src/server/front-page.ts` reads "as the anonymous viewer reads it"): a page the edge may keep reads as nobody. Its loader calls `serverClient(env)` without the request, and only the pages kept nowhere (Today and a decision, `personalPage`) reach the reader's request through Start's server helpers. The rail's signed-in state and Today's count are read in the browser after hydration. So the markup of a `branchPage` page is the same for every reader, and the `Vary` above is a second wall, not the only one.
`apps/web/test/edge-cache.test.ts` holds it: the rule for every kind of answer the web gives, the entry as Start's handler wrapped and nothing else, each server route that hands the reader's cookie on (`/llms.txt`, a project's `llms.txt`, `/` as Markdown, a raw file, `/rpc`) kept nowhere when a session cookie comes with it, and the pages that read the request being exactly the `personalPage` ones. `packages/config/test/web-wiring.test.ts` holds the config: the entry, the cache on in each stage and off at the top, and no `cross_version_cache`.
## Considered Options
- **No Workers Cache.** Nothing to hold, but every page view runs the Worker and its platform reads; a page at a commit, which never changes, costs as much as one at `main`.- **A cookie-reading gateway entrypoint with the cache off, forwarding cookie-less requests to a cached inner entrypoint over `ctx.exports`** (Cloudflare's own pattern for authenticated traffic, <https://developers.cloudflare.com/workers/cache/examples/>). Every request would run the gateway, and it needs a second entrypoint in a Worker that TanStack Start's build owns. The `Vary: Cookie` rule gives the same separation inside one entrypoint.- **Bypassing only on the session cookie.** More hits for a reader who carries some other cookie, but every cookie the web sets would have to be weighed; the web's readers carry none until they sign in.- **`private` with the page's own `max-age` for a signed-in reader**, so their browser could still keep a page. Kept simple instead: `private, no-store` is what the cookie fence checks.- **`cross_version_cache`.** Pages would survive a deploy, but a kept page names the hashed assets of the version that drew it.
## Consequences
- Cost: with caching on, every request to the web Worker is billed at the standard request rate, including the static asset requests (`/assets/*`, icons, fonts) and the service-binding calls that are free without it (<https://developers.cloudflare.com/workers/cache/>). A hit runs no CPU.- Cost: an answer is held to the Free plan's cacheable size, whatever the account's plan, while that launch limit lasts, and purges run at the Free tier's rate (<https://developers.cloudflare.com/workers/cache/limitations/>).- A signed-in reader, and anyone who carries a cookie, always runs the Worker and keeps nothing in the browser; the edge serves signed-out readers and agents.- A page at `main` may be served by the edge up to 30 seconds old, and up to five minutes more while one request refreshes it in the background, now to every reader rather than one browser. Purging on a landing would have to run inside the web Worker (`ctx.cache.purge`), since a purge belongs to the entrypoint that owns the answer; nothing purges yet.- Each deploy starts the cache cold, since the version is in the key.- The host is not in the key: an answer that names its own origin (the agents' documents' `webUrl`) is kept for whichever host asked first. Each stage's web answers on one `workers.dev` host today; a custom domain beside it would share one cache.- After a deploy, `curl -sI <web>/<project>/tree/main` twice shows `cf-cache-status: MISS` then `HIT` and `vary: Cookie`; the same request with `-H 'cookie: a=b'` shows `cache-control: private, no-store` and no `HIT`.modified:packages/config/test/web-wiring.test.ts+24 added
158 unmodified lines159 );160 }161 })162 );163+164+ // ADR 0026: the edge keeps the web's answers only behind its entry, which165+ // decides what may be kept; `vite dev` keeps nothing; and a kept page166+ // never outlives its Worker version, whose hashed assets it names.167+ it.effect(168+ "enters through src/server.ts, and turns Workers Cache on in each stage alone, per version",169+ () =>170+ Effect.gen(function* () {171+ const config = yield* presentJson("apps/web/wrangler.jsonc", Wrangler);172+ const top = yield* presentJson("apps/web/wrangler.jsonc", Block);173+174+ expect(top.main).toBe("src/server.ts");175+ expect("cache" in top, "the local stage keeps nothing").toBeFalsy();176+177+ for (const stage of stages) {178+ expect(179+ config.env[stage]?.cache,180+ `${stage} keeps answers`181+ ).toStrictEqual({182+ enabled: true,183+ });184+ }185+ })186+ );187 });188 189 describe("the web Worker's generated Env", () => {190 it.effect("has PLATFORM as a Fetcher and nothing named ARTIFACTS…", () =>91 unmodified lines