Skip to content
Myr

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

8 files+649 added−4 removed

modified:apps/web/src/server/cache-headers.ts+9 added
added: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 */24import { Effect } from "effect";2526/** The `Cache-Control` of an answer kept by nobody: no shared cache, no browser. */27export const KEPT_NOWHERE = "private, no-store";2829/** Headers that would decide what the edge keeps over `Cache-Control`. */30const EDGE_OVERRIDES = ["cdn-cache-control", "cloudflare-cdn-cache-control"];3132/** The directives of a `Cache-Control` value, each as `name` or `name=value`, lower-cased. */33const directivesOf = (cacheControl: string) =>34 cacheControl35 .split(",")36 .map((directive) => directive.trim().toLowerCase())37 .filter((directive) => directive !== "");3839/** Whether the request says who is reading it: any cookie, or an `Authorization`. */40const speaksForSomeone = (request: Request) =>41 request.headers.has("cookie") || request.headers.has("authorization");4243/**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 */48const unsafeFor = (cacheControl: string | null) =>49 cacheControl === null ||50 directivesOf(cacheControl).some(51 (directive) =>52 directive.startsWith("private=") || directive.startsWith("no-cache=")53 );5455/** Whether the cache bypasses an answer under `cacheControl`. */56const keptNowhere = (cacheControl: string) =>57 directivesOf(cacheControl).some(58 (directive) => directive === "private" || directive === "no-store"59 );6061/** `vary` with `Cookie` among its headers. */62const varyingByCookie = (vary: string | null) => {63 const names = (vary ?? "")64 .split(",")65 .map((name) => name.trim())66 .filter((name) => name !== "");6768 return names.some((name) => name.toLowerCase() === "cookie")69 ? names.join(", ")70 : [...names, "Cookie"].join(", ");71};7273/** `response`'s headers as the edge may see them, for `request`. */74const edgeHeaders = (request: Request, response: Response) => {75 const headers = new Headers(response.headers);7677 for (const name of EDGE_OVERRIDES) {78 headers.delete(name);79 }8081 const cacheControl = headers.get("cache-control");8283 if (84 speaksForSomeone(request) ||85 headers.has("set-cookie") ||86 unsafeFor(cacheControl)87 ) {88 headers.set("cache-control", KEPT_NOWHERE);8990 return headers;91 }9293 if (cacheControl !== null && !keptNowhere(cacheControl)) {94 headers.set("vary", varyingByCookie(headers.get("vary")));95 }9697 return headers;98};99100/**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 */104export 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 });110111/** A Worker's `fetch`, as TanStack Start's server entry gives it. */112interface Entry<Rest extends readonly unknown[]> {113 readonly fetch: (114 request: Request,115 ...rest: Rest116 ) => Promise<Response> | Response;117}118119/** The Worker's `fetch` once every answer passes through `forTheEdge`. */120interface EdgeEntry<Rest extends readonly unknown[]> {121 readonly fetch: (request: Request, ...rest: Rest) => Promise<Response>;122}123124/**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 */128export 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
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 */11import { describe, expect, it } from "@effect/vitest";12import { Client, Contracts } from "@repo/protocol/contracts";13import { ProjectName } from "@repo/protocol/ids";14import { asTester, unanswered } from "@repo/protocol/testing";15import { untouchable } from "@repo/testkit/untouchable";16import { Effect, Layer } from "effect";17import { RpcTest } from "effect/rpc";1819import { forwarded } from "../src/features/agents/forward.ts";20import { backend } from "../src/server/backend.ts";21import { branchPage, personalPage } from "../src/server/cache-headers.ts";22import {23 edgeEntry,24 forTheEdge,25 KEPT_NOWHERE,26} from "../src/server/edge-cache.ts";27import { frontPageHandler } from "../src/server/front-page.ts";28import { frontLlmsHandler, projectLlmsHandler } from "../src/server/llms.ts";29import { rpcHandler } from "../src/server/rpc.ts";30import { SESSION_COOKIE } from "../src/server/session.ts";3132const WEB_URL = "https://web-test.example.workers.dev";3334const PLATFORM_URL = "https://platform-test.example.workers.dev";3536/** A signed-in reader's cookie, as the browser sends it. */37const SIGNED_IN = `${SESSION_COOKIE}=dev-ada`;3839/** A GET for `path` on the web host, with `headers`. */40const get = (path: string, headers: HeadersInit = {}) =>41 new Request(`${WEB_URL}${path}`, { headers });4243/** What the edge sees of an answer: how long it may be kept, and what it varies by. */44const kept = (response: Response) => ({45 cacheControl: response.headers.get("cache-control"),46 vary: response.headers.get("vary"),47});4849/** An answer under `headers`, with a body. */50const answer = (headers: HeadersInit, status = 200) =>51 new Response("the page", { headers, status });5253/** Every `Cache-Control` the web gives or passes on, and none. */54const 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];6566describe("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 );7778 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 });8586 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});100101describe("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 });115116 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 });123124 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 );133134 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 });142143 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 });151152 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 });160161 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 );170171 expect([172 response.headers.get("cdn-cache-control"),173 response.headers.get("cloudflare-cdn-cache-control"),174 ]).toStrictEqual([null, null]);175 });176177 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 );183184 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});196197describe("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[] = [];203204 const entry = edgeEntry({205 fetch: (request: Request, env: string, context: string) => {206 handed.push(request.url, env, context);207208 return Promise.resolve(answer(branchPage));209 },210 });211212 const response = yield* Effect.promise(() =>213 entry.fetch(get("/", { cookie: SIGNED_IN }), "env", "context")214 );215216 expect(handed).toStrictEqual([`${WEB_URL}/`, "env", "context"]);217 expect(kept(response).cacheControl).toBe(KEPT_NOWHERE);218 })219 );220221 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 );226227 const code = (sources["../src/server.ts"] ?? "")228 .replaceAll(/\/\*\*[\s\S]*?\*\//gu, "")229 .trim();230231 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});238239// --- The routes that read the reader's credential ----------------------------240241/** A platform that lists datekit and no asks, and answers nothing else. */242const 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 );263264/** An env whose PLATFORM answers every request with a long-lived public answer. */265const 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};274275/**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 */281const 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];323324/** A signed-in agent's request for `path`, as Markdown. */325const signedInAt = (path: string) =>326 get(path, { accept: "text/markdown", cookie: SIGNED_IN });327328describe("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)));334335 // The route alone would let a shared cache keep it.336 expect(own.headers.get("cache-control")).toMatch(/^public\b/u);337338 const served = yield* Effect.promise(() =>339 edgeEntry({ fetch: handle }).fetch(signedInAt(path))340 );341342 expect(kept(served).cacheControl).toBe(KEPT_NOWHERE);343 })344 );345346 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 );355356 expect(kept(served).cacheControl).toMatch(/^public\b/u);357 expect(kept(served).vary).toMatch(/\bCookie$/u);358 })359 );360});361362// --- The pages ---------------------------------------------------------------363364const routeSources: Readonly<Record<string, string>> = import.meta.glob(365 "../src/routes/**/*.{ts,tsx}",366 { eager: true, import: "default", query: "?raw" }367);368369const allSources: Readonly<Record<string, string>> = import.meta.glob(370 "../src/**/*.{ts,tsx}",371 { eager: true, import: "default", query: "?raw" }372);373374/**375 * Where a page's loader or server function reaches the request it answers376 * (its cookie, its headers): TanStack Start's server helpers.377 */378const readsTheRequest = /from "@tanstack\/react-start\/server"/u;379380describe("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 );385386 expect(reading.toSorted()).toStrictEqual([387 "../src/routes/$project/decisions/$decision.tsx",388 "../src/routes/today.tsx",389 ]);390391 for (const path of reading) {392 const source = routeSources[path] ?? "";393394 expect(source, `${path} is kept nowhere`).toContain("personalPage");395 expect(source, `${path} is never kept at main`).not.toContain(396 "branchPage"397 );398 }399 });400401 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 );405406 expect(keepable.length).toBeGreaterThan(10);407408 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
modified:apps/web/wrangler.jsonc+11 added-3 removed
8 unmodified lines
9 //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 lines
36 "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 lines
added:docs/adr/0026-the-edge-keeps-the-webs-anonymous-answers.md+37 added
modified:packages/config/test/web-wiring.test.ts+24 added
158 unmodified lines
159 );160 }161 })162 );163164 // 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);173174 expect(top.main).toBe("src/server.ts");175 expect("cache" in top, "the local stage keeps nothing").toBeFalsy();176177 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});188189describe("the web Worker's generated Env", () => {190 it.effect("has PLATFORM as a Fetcher and nothing named ARTIFACTS…", () =>
91 unmodified lines