Skip to content
Myr

edge-cache.test.ts

This file

Path

apps/web/test/edge-cache.test.ts

464 lines · 13.3 KiB · TypeScript

Last changed by

Merge redesign into mainoscabrielbefore adoptioncaedd21

History of this file

Take it

1import { describe, expect, it } from "@effect/vitest";2import { Client, Contracts } from "@repo/protocol/contracts";3import { ProjectName } from "@repo/protocol/ids";4import { asTester, unanswered } from "@repo/protocol/testing";5import { untouchable } from "@repo/testkit/untouchable";6import { Effect, Layer } from "effect";7import { RpcTest } from "effect/rpc";89import { forwarded } from "../src/features/agents/forward.ts";10import { backend } from "../src/server/backend.ts";11import { branchPage, personalPage } from "../src/server/cache-headers.ts";12import {13  edgeEntry,14  forTheEdge,15  KEPT_NOWHERE,16} from "../src/server/edge-cache.ts";17import { frontPageHandler, landingHandler } from "../src/server/front-page.ts";18import { frontLlmsHandler, projectLlmsHandler } from "../src/server/llms.ts";19import { rpcHandler } from "../src/server/rpc.ts";20import { SESSION_COOKIE } from "../src/server/session.ts";2122const WEB_URL = "https://web-test.example.workers.dev";2324const PLATFORM_URL = "https://platform-test.example.workers.dev";2526const SIGNED_IN = `${SESSION_COOKIE}=dev-ada`;2728const get = (path: string, headers: HeadersInit = {}) =>29  new Request(`${WEB_URL}${path}`, { headers });3031const kept = (response: Response) => ({32  cacheControl: response.headers.get("cache-control"),33  vary: response.headers.get("vary"),34});3536const answer = (headers: HeadersInit, status = 200) =>37  new Response("the page", { headers, status });3839const ANSWERS: readonly (readonly [string, HeadersInit])[] = [40  ["a page at main", branchPage],41  ["a page about its reader", personalPage],42  ["an agent's document", { "cache-control": "public, max-age=60" }],43  [44    "a raw file at a commit",45    { "cache-control": "public, max-age=31536000, immutable" },46  ],47  ["a sign-in redirect", { "cache-control": "no-store" }],48  ["an answer with no Cache-Control", {}],49];5051describe("an answer to a request that says who is reading", () => {52  it.each(ANSWERS)(53    "is kept nowhere, given a session cookie: %s",54    (_, headers) => {55      expect(56        kept(57          forTheEdge(58            get("/oscabriel/datekit", { cookie: SIGNED_IN }),59            answer(headers)60          )61        ).cacheControl62      ).toBe(KEPT_NOWHERE);63    }64  );6566  it.each(ANSWERS)("is kept nowhere, given any cookie: %s", (_, headers) => {67    expect(68      kept(69        forTheEdge(70          get("/oscabriel/datekit", { cookie: "theme=dark" }),71          answer(headers)72        )73      ).cacheControl74    ).toBe(KEPT_NOWHERE);75  });7677  it.each(ANSWERS)(78    "is kept nowhere, given an Authorization: %s",79    (_, headers) => {80      expect(81        kept(82          forTheEdge(83            get("/oscabriel/datekit", { authorization: "Bearer dev-ada" }),84            answer(headers)85          )86        ).cacheControl87      ).toBe(KEPT_NOWHERE);88    }89  );90});9192describe("an answer to a request with no cookie", () => {93  it("is kept nowhere when it sets a cookie", () => {94    expect(95      kept(96        forTheEdge(97          get("/auth/whoami"),98          answer({99            ...branchPage,100            "set-cookie": `${SESSION_COOKIE}=; Max-Age=0`,101          })102        )103      ).cacheControl104    ).toBe(KEPT_NOWHERE);105  });106107  it("is kept nowhere when it says nothing of how long it may be kept", () => {108    // Without it, the cache would keep a 200 for two hours by its heuristic.109    expect(kept(forTheEdge(get("/_serverFn/x"), answer({})))).toStrictEqual({110      cacheControl: KEPT_NOWHERE,111      vary: null,112    });113  });114115  it.each([`private="set-cookie"`, `public, no-cache="set-cookie"`])(116    "is kept nowhere when its Cache-Control names a field to strip: %s",117    (cacheControl) => {118      expect(119        kept(forTheEdge(get("/"), answer({ "cache-control": cacheControl })))120          .cacheControl121      ).toBe(KEPT_NOWHERE);122    }123  );124125  it("keeps a page at main as the route says, varied by Cookie", () => {126    expect(127      kept(forTheEdge(get("/oscabriel/datekit/tree/main"), answer(branchPage)))128    ).toStrictEqual({129      cacheControl: branchPage["Cache-Control"],130      vary: "Cookie",131    });132  });133134  it("adds Cookie to what an answer already varies by, once", () => {135    expect(136      [137        { ...branchPage, vary: "Accept" },138        { ...branchPage, vary: "Accept, cookie" },139      ].map((headers) => kept(forTheEdge(get("/"), answer(headers))).vary)140    ).toStrictEqual(["Accept, Cookie", "Accept, cookie"]);141  });142143  it("keeps a page about its reader nowhere, as the route says", () => {144    expect(kept(forTheEdge(get("/inbox"), answer(personalPage)))).toStrictEqual(145      {146        cacheControl: personalPage["Cache-Control"],147        vary: null,148      }149    );150  });151152  it("drops the headers that would outrank Cache-Control at the edge", () => {153    const response = forTheEdge(154      get("/releases/manifest.json"),155      answer({156        ...branchPage,157        "cdn-cache-control": "public, max-age=86400",158        "cloudflare-cdn-cache-control": "public, max-age=86400",159      })160    );161162    expect([163      response.headers.get("cdn-cache-control"),164      response.headers.get("cloudflare-cdn-cache-control"),165    ]).toStrictEqual([null, null]);166  });167168  it.effect("comes back with its status, its other headers and its body", () =>169    Effect.gen(function* () {170      const response = forTheEdge(171        get("/nowhere"),172        answer({ ...branchPage, "content-type": "text/html" }, 404)173      );174175      expect({176        body: yield* Effect.promise(() => response.text()),177        contentType: response.headers.get("content-type"),178        status: response.status,179      }).toStrictEqual({180        body: "the page",181        contentType: "text/html",182        status: 404,183      });184    })185  );186});187188describe("the Worker's entry", () => {189  it.effect(190    "hands the request and the Worker's env and context to Start, and its answer to the edge's rule",191    () =>192      Effect.gen(function* () {193        const handed: unknown[] = [];194195        const entry = edgeEntry({196          fetch: (request: Request, env: string, context: string) => {197            handed.push(request.url, env, context);198199            return Promise.resolve(answer(branchPage));200          },201        });202203        const response = yield* Effect.promise(() =>204          entry.fetch(get("/", { cookie: SIGNED_IN }), "env", "context")205        );206207        expect(handed).toStrictEqual([`${WEB_URL}/`, "env", "context"]);208        expect(kept(response).cacheControl).toBe(KEPT_NOWHERE);209      })210  );211212  it("is Start's server entry behind the address redirects, wrapped by edgeEntry, and nothing else", () => {213    const sources: Readonly<Record<string, string>> = import.meta.glob(214      "../src/server.ts",215      { eager: true, import: "default", query: "?raw" }216    );217218    const code = (sources["../src/server.ts"] ?? "")219      .replaceAll(/\/\*\*[\s\S]*?\*\//gu, "")220      .trim();221222    expect(code.split(/\n+/u)).toStrictEqual([223      'import handler from "@tanstack/react-start/server-entry";',224      'import { addressedEntry } from "./server/addresses.ts";',225      'import { edgeEntry } from "./server/edge-cache.ts";',226      "export default edgeEntry(addressedEntry(handler));",227    ]);228  });229});230231const listingDatekit = () =>232  Layer.effect(Client, RpcTest.makeClient(Contracts)).pipe(233    Layer.provide([234      Layer.mergeAll(235        unanswered,236        Contracts.toLayerHandler("listProjects", () =>237          Effect.succeed({238            projects: [239              {240                openAsks: 0,241                posture: "open" as const,242                project: ProjectName.make("oscabriel/datekit"),243              },244            ],245          })246        ),247        Contracts.toLayerHandler("listAsks", () => Effect.succeed({ asks: [] }))248      ),249      asTester,250    ])251  );252253const platformEnv: Env = {254  PLATFORM: untouchable<Fetcher>("PLATFORM", {255    fetch: () =>256      Promise.resolve(257        answer({ "cache-control": "public, max-age=31536000, immutable" })258      ),259  }),260  PUBLIC_PLATFORM_URL: PLATFORM_URL,261};262263// Each answers a public `Cache-Control` of its own; the entry is what keeps a reader's answer from the edge.264const CREDENTIAL_ROUTES: readonly (readonly [265  string,266  (request: Request) => Promise<Response>,267])[] = [268  [269    "/llms.txt",270    (request) => frontLlmsHandler(listingDatekit, PLATFORM_URL)({ request }),271  ],272  [273    "/oscabriel/datekit/llms.txt",274    (request) =>275      projectLlmsHandler(276        listingDatekit,277        PLATFORM_URL278      )({ params: { project: "datekit" }, request }),279  ],280  [281    "/",282    (request) =>283      Promise.resolve(284        landingHandler(285          listingDatekit,286          PLATFORM_URL287        )({288          next: () => answer(branchPage),289          request,290        })291      ),292  ],293  [294    "/asks",295    (request) =>296      Promise.resolve(297        frontPageHandler(298          listingDatekit,299          PLATFORM_URL300        )({301          next: () => answer(branchPage),302          request,303        })304      ),305  ],306  [307    "/oscabriel/datekit/raw/main/README.md",308    (request) => forwarded(backend, platformEnv).GET({ request }),309  ],310  [311    "/rpc",312    (request) =>313      rpcHandler(314        backend,315        platformEnv316      )({ request: new Request(request, { body: "{}", method: "POST" }) }),317  ],318];319320const signedInAt = (path: string) =>321  get(path, { accept: "text/markdown", cookie: SIGNED_IN });322323describe("a route that hands the reader's cookie on", () => {324  it.effect.each(CREDENTIAL_ROUTES)(325    "%s is kept nowhere when a session cookie comes with it",326    ([path, handle]) =>327      Effect.gen(function* () {328        const own = yield* Effect.promise(() => handle(signedInAt(path)));329330        // The route alone would let a shared cache keep it.331        expect(own.headers.get("cache-control")).toMatch(/^public\b/u);332333        const served = yield* Effect.promise(() =>334          edgeEntry({ fetch: handle }).fetch(signedInAt(path))335        );336337        expect(kept(served).cacheControl).toBe(KEPT_NOWHERE);338      })339  );340341  it.effect.each(CREDENTIAL_ROUTES)(342    "%s, with no cookie, is kept as it says and varied by Cookie",343    ([path, handle]) =>344      Effect.gen(function* () {345        const served = yield* Effect.promise(() =>346          edgeEntry({ fetch: handle }).fetch(347            get(path, { accept: "text/markdown" })348          )349        );350351        expect(kept(served).cacheControl).toMatch(/^public\b/u);352        expect(kept(served).vary).toMatch(/\bCookie$/u);353      })354  );355});356357const landing = (request: Request) =>358  Promise.resolve(359    landingHandler(360      listingDatekit,361      PLATFORM_URL362    )({363      next: () => answer(branchPage),364      request,365    })366  );367368describe("the landing", () => {369  it.effect(370    "sends a reader who carries a session to their inbox, and the edge keeps that nowhere",371    () =>372      Effect.gen(function* () {373        const served = yield* Effect.promise(() =>374          edgeEntry({ fetch: landing }).fetch(375            get("/", { accept: "text/html", cookie: SIGNED_IN })376          )377        );378379        expect({380          location: served.headers.get("location"),381          status: served.status,382          ...kept(served),383        }).toStrictEqual({384          cacheControl: KEPT_NOWHERE,385          location: "/inbox",386          status: 302,387          vary: null,388        });389      })390  );391392  it.effect(393    "is the same page for every reader without a session, which the edge may keep",394    () =>395      Effect.gen(function* () {396        const served = yield* Effect.promise(() =>397          edgeEntry({ fetch: landing }).fetch(get("/", { accept: "text/html" }))398        );399400        expect(served.status).toBe(200);401        expect(kept(served).cacheControl).toMatch(/^public\b/u);402        expect(kept(served).vary).toMatch(/\bCookie$/u);403      })404  );405406  it.effect("lets a cookie that is not a session through to the page", () =>407    Effect.gen(function* () {408      const own = yield* Effect.promise(() =>409        landing(get("/", { accept: "text/html", cookie: "theme=dark" }))410      );411412      expect(own.status).toBe(200);413    })414  );415});416417const routeSources: Readonly<Record<string, string>> = import.meta.glob(418  "../src/routes/**/*.{ts,tsx}",419  { eager: true, import: "default", query: "?raw" }420);421422const allSources: Readonly<Record<string, string>> = import.meta.glob(423  "../src/**/*.{ts,tsx}",424  { eager: true, import: "default", query: "?raw" }425);426427const readsTheRequest = /from "@tanstack\/react-start\/server"/u;428429describe("a page", () => {430  it("reads the reader's request only where it is kept nowhere", () => {431    const reading = Object.entries(allSources).flatMap(([path, source]) =>432      readsTheRequest.test(source) ? [path] : []433    );434435    expect(reading.toSorted()).toStrictEqual([436      "../src/routes/$owner/$project/decisions/$decision.tsx",437      "../src/routes/inbox.tsx",438    ]);439440    for (const path of reading) {441      const source = routeSources[path] ?? "";442443      expect(source, `${path} is kept nowhere`).toContain("personalPage");444      expect(source, `${path} is never kept at main`).not.toContain(445        "branchPage"446      );447    }448  });449450  it("that the edge may keep reads as nobody, so its markup is the same for every reader", () => {451    const keepable = Object.entries(routeSources).filter(([, source]) =>452      source.includes("branchPage")453    );454455    expect(keepable.length).toBeGreaterThan(10);456457    for (const [path, source] of keepable) {458      expect(source, `${path} reaches no request`).not.toMatch(readsTheRequest);459      expect(source, `${path} reads no cookie`).not.toMatch(460        /credentialFrom|SESSION_COOKIE|HANDLE_COOKIE/u461      );462    }463  });464});