You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 12f09f0
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: AGENTS.md
+2-2Lines changed: 2 additions & 2 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -45,7 +45,7 @@ Never touch contents inside `<!-- automd -->` in README.md. They are auto genera
45
45
46
46
### HTTP handler caching (`http/`)
47
47
48
-
Split across the modules listed under Project Structure. The bullets below are about the handler as a whole; each mechanism lives in the module its name suggests — the derived cookie/header/query lists (`HandlerConfig`) in `config.ts`, `shouldBypassCache` + request narrowing in `request.ts`, `resolveKey`/`methodKey`/`cacheableMethods` in `key.ts`, the `filterCookie`/`filteredSearch` allowlists those two share in `filters.ts`, the internal `serialize` hook **and its read-side mirror** `deserializeEntry` (plus the base64 codec, the transport-header strip and the null-body statuses, all private) in `entry.ts`, the `validate` hook + the status allowlist in `validate.ts`, the `Cache-Control` directive parser those decisions read in `cache-control.ts`, `Vary` mechanics in `vary.ts`, and the 304 exchange in `conditional.ts`. `index.ts` holds only the wiring: the `CacheOptions` hooks handed to `cachedFunction`, the resolver, the serve path and the revalidation helpers. Two modules are named for the `CacheOptions` hook they implement (`entry.ts`'s `serialize`, `validate.ts`), and the dependency graph is a DAG — `cache-control.ts`, `vary.ts`, `conditional.ts` and `config.ts` import nothing from the directory.
48
+
Split across the modules listed under Project Structure. The bullets below are about the handler as a whole; each mechanism lives in the module its name suggests — the derived cookie/header/query lists (`HandlerConfig`) in `config.ts`, the composed bypass (`resolveBypass`) + request narrowing in `request.ts`, `resolveKey`/`methodKey`/`cacheableMethods` in `key.ts`, the `filterCookie`/`filteredSearch` allowlists those two share in `filters.ts`, the internal `serialize` hook **and its read-side mirror** `deserializeEntry` (plus the base64 codec, the transport-header strip and the null-body statuses, all private) in `entry.ts`, the `validate` hook + the status allowlist in `validate.ts`, the `Cache-Control` directive parser those decisions read in `cache-control.ts`, `Vary` mechanics in `vary.ts`, and the 304 exchange in `conditional.ts`. `index.ts` holds only the wiring: the `CacheOptions` hooks handed to `cachedFunction`, the resolver, the serve path and the revalidation helpers. Two modules are named for the `CacheOptions` hook they implement (`entry.ts`'s `serialize`, `validate.ts`), and the dependency graph is a DAG — `cache-control.ts`, `vary.ts`, `conditional.ts` and `config.ts` import nothing from the directory.
49
49
50
50
-`defineCachedHandler<E extends HTTPEvent>(handler, opts)` — wraps an `EventHandler` with response caching (generic over event type)
51
51
- Cache key `name`: resolved with `cache.ts`'s shared `resolveName(opts.name, handler)` **before** the `defaultHandlerOptions()` merge (`config.ts`'s own defaults — deliberately not `cache.ts`'s `defaultCacheOptions()`, since only the HTTP layer has a `cacheStatusHeader`, and named apart so neither can be imported for the other), exactly like `defineCachedFunction`. Merging first (the old order) left `opts.name` permanently `"_"` by the time `cachedFunction` re-derived it, so issue #53's fix never reached the HTTP layer and **every** handler keyed as `name: "_"`. Two handlers sharing one `storage` (the configuration `types.ts` recommends) that can see the same path then collided: identical source ⇒ identical integrity ⇒ one served the other's cached response (cross-handler leak); differing source ⇒ every read failed the other's integrity check ⇒ permanent thrash at 0% hit rate. **Breaking key change**, not a behavior change: every existing handler entry goes cold once (the key gains a real name segment). The `HEAD:` method component still sits directly after the name segment, so key shape is otherwise unchanged. Same **documented caveat** as `defineCachedFunction`, and it bites harder here because the shared-`storage` setup turns it into a leak: `hash(handler)` sees only source, so handlers from one factory (`(tenant) => defineCachedHandler(() => render(tenant), { storage })`) share a name _and_ an integrity — pass an explicit `name` per instance. A per-instance discriminator (counter/WeakMap/randomness) is inadmissible: keys must be deterministic across process restarts for persistent/shared backends, which is exactly why a source hash is the right fallback
@@ -71,7 +71,7 @@ Split across the modules listed under Project Structure. The bullets below are a
71
71
- Authorization: **by default `authorization` / `proxy-authorization` do not participate in caching** (secure default, same rigor as cookies) — both are stripped from the handler-visible request on cacheable calls, so a handler cannot render per-user content from a credential that isn't in the cache key. Previously they were forwarded untouched but never keyed, so a token-authenticated route failed **open**: the first caller's private response was stored under the anonymous key, replayed to everyone, and advertised `public, s-maxage=N` for shared CDNs (cookie-authenticated routes already failed safe — that asymmetry was the defect). `allowAuthorization: true` opts both names back in by folding them into both header lists (deduped against `opts.varies`, sorted), which in one step makes them vary the key, appear in the response `Vary`, and stay visible to the handler. Listing either name in `varies` counts as the same opt-in. Callers opting in own the consequence: one entry per distinct credential value, shared by everyone presenting it. A **breaking behavior change** — handlers needing the credential must set `allowAuthorization`, or bypass those requests (`shouldBypassCache`)
72
72
- Transport headers (`content-encoding`, `content-length`, `content-range`, `transfer-encoding`) are stripped in `serialize` before storage (`transportHeaders`): the body is stored fully decoded and re-buffered, so replaying an upstream `content-encoding: gzip` against a decompressed body (or a stale `content-length`/wire `transfer-encoding`) would desync the headers from the served body and yield malformed responses (nitro#2109). The runtime recomputes `content-length` from the served body on read. `content-range` is there for the same reason and **not** because a 206 could reach storage (it can't — `Range` requests bypass and `validate` rejects the status): it describes a _partial_ body, so on an entry we do store — always a complete representation — it is meaningless at best and a lie about the served bytes at worst. Realistic source: a proxying handler copying upstream headers onto a 200
73
73
-`varies` headers are **forwarded to the handler** — their values are part of the cache key, so reading them is safe and is the point of declaring them. **`cookie` is no longer an exception**: it too is forwarded (raw) when listed in `varies` with no `allowCookies`, which is what makes that listing a real opt-in rather than pure key fragmentation. They used to be the only headers filtered out, which meant `varies: ["accept-language"]` produced correct per-language keys and `Vary` while every entry held the _default_ rendering (**breaking behavior change**). Request narrowing is now driven by `keyHeaderNames` alone — a declared header is visible, an undeclared credential header (`authorization`/`proxy-authorization`/`cookie`) is stripped — plus the finer `allowCookies` filter and `allowQuery` on the URL
74
-
- Request narrowing (cookie stripping, authorization stripping, query narrowing) only applies to cacheable calls: non-GET/HEAD requests **and any request carrying a `Range` header** bypass the cache (`shouldBypassCache`, composed with any caller `shouldBypassCache`) and reach the handler with their request untouched — including the body, which the rewritten `Request` would otherwise drop. Narrowing **mutates the caller's event** (`event.req`, plus `event.url` under `allowQuery`) and never restores it, so after a MISS the caller observes the narrowed request while after a HIT or a bypass it does not — downstream middleware and logging see different headers depending on cache state. Not restored in a `finally` on purpose: a handler's body producer can run _after_ the resolver returns (an async `ReadableStream.pull` is drained by `serialize`'s `res.arrayBuffer()`), so a restore would hand the original credentialed request back to a lazy read whose output is then cached and replayed — re-opening exactly what narrowing exists to close. It would also still leave the SWR window, where the background refresh swaps the stale reader's event after its response was already returned. The real fix is to stop mutating the caller's event at all (hand the handler a narrowed copy), which needs a design decision because `E` is an arbitrary framework event — tracked separately
74
+
- Request narrowing (cookie stripping, authorization stripping, query narrowing) only applies to cacheable calls: non-GET/HEAD requests **and any request carrying a `Range` header** bypass the cache (the built-in half of `resolveBypass`, composed with any caller `shouldBypassCache`) and reach the handler with their request untouched — including the body, which the rewritten `Request` would otherwise drop. Gated on the **composed** verdict, never the built-in half alone (finding 09): the built-in check said "cacheable" for a GET the caller had excluded, so `shouldBypassCache` stripped credentials off the very requests it exempted from the cache — and it is the escape hatch the credential defaults document ("set `allowAuthorization`, or bypass those requests"), so following that advice served the anonymous/401 rendering to every authenticated user, on every request. `narrowRequest` gates itself rather than trusting its call site, so the two can't disagree. The verdict is produced **exactly once per call** — the caller's hook may be async, expensive or side-effecting — by `resolveBypass`, which `cache.ts` awaits to decide its short-circuit to the raw resolver and which memoizes the answer on the event in a per-handler-instance `WeakMap` (`config.bypassed`, the `searchCache` pattern) for the resolver to read. Per-call state keyed by the event, deliberately not a module-level "last verdict" slot, which would be a cross-request bug; threaded through `config` rather than through the resolver's arguments because `cache.ts` calls `fn(...args)` with the caller's args and nothing else. `narrowRequest`'s fallback to the built-in check covers only a resolver reached without `resolveBypass`, which `cachedFunction` cannot do. Narrowing **mutates the caller's event** (`event.req`, plus `event.url` under `allowQuery`) and never restores it, so after a MISS the caller observes the narrowed request while after a HIT or a bypass it does not — downstream middleware and logging see different headers depending on cache state. Not restored in a `finally` on purpose: a handler's body producer can run _after_ the resolver returns (an async `ReadableStream.pull` is drained by `serialize`'s `res.arrayBuffer()`), so a restore would hand the original credentialed request back to a lazy read whose output is then cached and replayed — re-opening exactly what narrowing exists to close. It would also still leave the SWR window, where the background refresh swaps the stale reader's event after its response was already returned. The real fix is to stop mutating the caller's event at all (hand the handler a narrowed copy), which needs a design decision because `E` is an arbitrary framework event — tracked separately
75
75
- **`Range` requests bypass the cache** (finding 07), whatever their method — the request-side half of the 206 fix, paired with `206`'s absence from the cacheable-status allowlist. `Range` is forwarded to the handler but is neither in the key nor a `Vary` dimension, so a range-honoring handler (static files, media, `serveStatic`) resolved a **partial** representation under the range-free key: one `curl -r 0-0` stored a one-byte body plus the `Content-Range` describing it, and every later `Range`-less GET was served that truncation for the whole TTL, propagated to shared CDNs by the synthesized `s-maxage` (RFC 9110 §15.3.7 / RFC 9111 §3.3 — a 206 answers only the request that named the range; combining/re-slicing partials is out of scope). Bypassing on the request side is the cheaper half: the handler never runs under a key, so nothing partial is stored, `serialize` never buffers a large partial body, and a ranged request can't thrash the plain entry. **Breaking behavior change**: a ranged request now also skips request narrowing (the standard bypass contract — untouched request in, live `Response` out) and gets no `x-cache`/`etag`/`cache-control` synthesis
76
76
- Bypassed responses pass through untouched: because `serialize` lives outside the resolver, a bypassed call (`cachedFunction` returns the resolver output raw — no `serialize`/`transform`) yields the handler's live `Response`, which the outer wrapper detects (`value instanceof Response`) and returns as-is. No body buffering (streaming/binary bodies survive), no synthesized cache headers, and no bogus `304` for a non-cacheable method — a **breaking behavior change** vs. the old always-serialize path (`fix(http)!`)
77
77
-`validate` rejects a **missing** body (`value.body === undefined`) but accepts `""`: a zero-byte 200 is a legal response and rejecting it would only cost hit rate. The dangerous empty body (a body-less HEAD response replayed to GET clients) is prevented by the method component in the key, not here — an empty entry is only readable by requests of the method that produced it. Documented in-place at the check so it isn't re-litigated
A request you exclude this way gets the same treatment as a `POST`: it reaches the handler **untouched**, with its `Authorization` header, its cookies and its full query string intact. That is what makes `shouldBypassCache` a usable alternative to [`allowAuthorization`](#credential-headers) — the handler can read the credential precisely because the response is never stored or shared.
75
+
74
76
## Cache key name
75
77
76
78
Every key carries a `name` component, resolved exactly like a [cached function's](/guide/functions#cache-keys): `opts.name || handler.name || anon_<hash(handler)>`. It is what keeps two handlers that share one `storage` and can see the same path from colliding.
@@ -185,7 +187,7 @@ Opting in folds both header names into `varies`: they vary the cache key, they a
0 commit comments