feat(http): ETag and 304 for static files and buffered responses (CARD-15, #114)
CI / dco (pull_request) Successful in 4s
CI / runtimes (bun) (pull_request) Successful in 16s
CI / build (pull_request) Successful in 27s
CI / runtimes (deno) (pull_request) Successful in 21s
CI / runtimes (edge) (pull_request) Successful in 13s

Conditional GETs were never answered: every revalidation re-downloaded
the file or response.

- Static (D12, always on): a hit carries W/"<size>-<mtimeMs base36>",
  Last-Modified and Cache-Control from the stat the resolver already did.
  A matching If-None-Match, or If-Modified-Since when If-None-Match is
  absent, answers 304 before the file is read. StaticHit now carries the
  stat and a read() for the bytes, and HEAD no longer reads either.
- static: { dir?, cacheControl? } (rule 1a): Cache-Control defaults to
  no-cache so browsers revalidate rather than reuse a file for a lifetime
  guessed from Last-Modified. An unknown key or CR/LF throws at boot.
- createApp({ etag: true }) (off by default, boolean only): a buffered 200
  to GET/HEAD gets a weak tag from a 32-bit FNV-1a hash of its UTF-8 bytes
  plus its length, computed before HEAD blanks the body. A handler-set
  etag is kept and only compared. Weak comparison, lists split outside
  quotes, and * are supported.
- Every buffered 304 leaves dispatch bodiless, with its content-* headers
  dropped, so NotModified matches the ETag path on every adapter.

Signed-off-by: Diego Resendez <diego.resendez@zero-oneit.com>
This commit is contained in:
chrnx committed 2026-10-23 01:09:54 -05:00
1 parent 50010da88d
commit d32fc9f8d7
14 files changed
+706 -37

No files matched your search

+121
View File
@@ -0,0 +1,121 @@
// src/http/conditional.ts — ETags and conditional GET (RFC 9110 §8.8.3, §13.1.2, §13.1.3, §15.4.5).
type HeaderBag = Record<string, string | string[] | undefined>;
/** The first value of a request header, or `undefined`. */
function single(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value.join(', ') : value;
}
/**
* Splits an `If-None-Match` list on the commas that sit outside quotes. An entity-tag may legally
* contain a comma inside its quotes (`"a,b"`), so a plain `split(',')` would cut one tag in two.
*/
function splitTags(header: string): string[] {
const tags: string[] = [];
let start = 0;
let quoted = false;
for (let i = 0; i < header.length; i++) {
const ch = header[i];
if (ch === '"') quoted = !quoted;
else if (ch === ',' && !quoted) {
tags.push(header.slice(start, i).trim());
start = i + 1;
}
}
tags.push(header.slice(start).trim());
return tags.filter(Boolean);
}
/** The opaque part of an entity-tag: `W/"x"` and `"x"` both become `"x"` (weak comparison). */
const opaque = (tag: string): string => (tag.startsWith('W/') ? tag.slice(2) : tag);
/**
* Whether `If-None-Match` matches `etag` under the weak comparison GET and HEAD use
* (RFC 9110 §13.1.2): `W/"x"` matches `"x"`, and `*` matches any current representation.
*/
export function ifNoneMatchMatches(header: string, etag: string): boolean {
const own = opaque(etag.trim());
for (const tag of splitTags(header)) if (tag === '*' || opaque(tag) === own) return true;
return false;
}
/**
* Whether a resource last modified at `mtimeMs` is unchanged since an `If-Modified-Since` date.
* HTTP dates have one-second resolution, so the modification time is truncated to the second first;
* otherwise a file written at 12:00:00.400 would never match the `Last-Modified` it was served with.
* An unparseable date is ignored, as RFC 9110 §13.1.3 requires.
*/
export function notModifiedSince(header: string, mtimeMs: number): boolean {
const since = Date.parse(header);
if (Number.isNaN(since)) return false;
return Math.floor(mtimeMs / 1000) * 1000 <= since;
}
/**
* Decides a conditional GET/HEAD: `If-None-Match` when present, else `If-Modified-Since` when the
* caller has a modification time to compare (static files only — handler responses have none).
*/
export function isNotModified(headers: HeaderBag, etag: string, mtimeMs?: number): boolean {
const inm = single(headers['if-none-match']);
if (inm !== undefined) return ifNoneMatchMatches(inm, etag);
const ims = single(headers['if-modified-since']);
return ims !== undefined && mtimeMs !== undefined && notModifiedSince(ims, mtimeMs);
}
/** Weak validator for a static file, from the `stat` the resolver already does: `W/"<size>-<mtimeMs base36>"`. */
export function staticEtag(size: number, mtimeMs: number): string {
return `W/"${size}-${Math.floor(mtimeMs).toString(36)}"`;
}
/**
* Weak validator for a buffered body: its byte length plus a 32-bit FNV-1a hash of its bytes, in
* base 36. FNV rather than `crypto.subtle.digest`: it is synchronous and dependency-free, where
* `subtle` costs a promise per response. It is not collision-resistant and need not be — an ETag
* detects change, it does not authenticate. The length narrows a collision to equal-length bodies.
*
* Weak, so one tag can describe every content-coding of the same body (CARD-16 hashes before it
* encodes). Strings are hashed as UTF-8, so the tag matches what goes on the wire.
*/
export function bodyEtag(body: string | Uint8Array): string {
const bytes = typeof body === 'string' ? Buffer.from(body, 'utf8') : body;
let hash = 0x811c9dc5;
for (let i = 0; i < bytes.length; i++) {
hash ^= bytes[i];
hash = Math.imul(hash, 0x01000193);
}
return `W/"${bytes.length.toString(36)}-${(hash >>> 0).toString(36)}"`;
}
/** The key under which `headers` holds `name`, case-insensitively, or `undefined`. */
export function findHeader(headers: Record<string, unknown>, name: string): string | undefined {
for (const key of Object.keys(headers)) if (key.toLowerCase() === name) return key;
return undefined;
}
/**
* The headers of a `304` built from the `200` it stands for: everything but the `content-*`
* headers that describe a body (`content-type`, `content-length`, `content-encoding`, …), plus
* `transfer-encoding`. `content-location` is kept: §15.4.5 lists it among the fields a 304 sends. `ETag`, `Vary`, `Cache-Control`, `Last-Modified` and anything else a cache
* would update stay (RFC 9110 §15.4.5). Injected security headers are merged later by the adapter,
* exactly as on a `200`.
*/
export function notModifiedHeaders(headers: Record<string, string | string[]>): Record<string, string | string[]> {
const out: Record<string, string | string[]> = {};
for (const key of Object.keys(headers)) {
const lower = key.toLowerCase();
if ((lower.startsWith('content-') && lower !== 'content-location') || lower === 'transfer-encoding') continue;
out[key] = headers[key];
}
return out;
}
+64 -16
View File
@@ -6,6 +6,8 @@ import { buildSecurityHeaders, resolveCors, corsPreflightHeaders } from '../secu
import { resolveRoute, allowedMethods, normalizeRequestPath, parseQuery } from './router';
import { pickEncoder } from './stream';
import { acquireBody, type BodyReader } from './body';
import { bodyEtag, findHeader, isNotModified, notModifiedHeaders, staticEtag } from './conditional';
import type { StaticHit } from '../views';
import type { RouteDef, HttpOptions } from './types';
import type { StreamEncoder } from '../encoders';
import type { Bus } from '../bus';
@@ -131,15 +133,69 @@ function errorOutcome(
const rendered = renderError(error, req, opts?.onError, opts?.logger);
return {
injected,
outcome: {
outcome: bodyless({
kind: 'buffered',
status: rendered.status,
headers: { ...rendered.headers, ...headers },
body: req.method === 'HEAD' ? '' : rendered.body,
},
}),
};
}
type Buffered = Extract<NeutralOutcome, { kind: 'buffered' }>;
/**
* A `304` has no body on any adapter, and none of the headers that describe one. This is the one
* place every buffered outcome passes through on its way out, so a handler that throws
* `NotModified` — rendered by the default renderer as a JSON envelope — answers the same bodiless
* `304` the ETag path does. Node would drop the body of a 304 by itself; the fetch adapters already
* null it; the `content-type` would still have gone out on both.
*/
function bodyless(outcome: Buffered): Buffered {
if (outcome.status !== 304) return outcome;
return { kind: 'buffered', status: 304, headers: notModifiedHeaders(outcome.headers), body: '' };
}
/**
* Answers a static hit: `ETag` + `Last-Modified` from the resolver's `stat`, `Cache-Control` from the
* `static` option, and a `304` — decided before the file is read, so a revalidation costs a `stat`
* and nothing more. HEAD never reads either.
*/
async function staticOutcome(hit: StaticHit, req: NeutralRequest): Promise<Buffered> {
const etag = staticEtag(hit.size, hit.mtimeMs);
const headers: Record<string, string> = {
'content-type': hit.contentType,
etag,
'last-modified': new Date(hit.mtimeMs).toUTCString(),
'cache-control': hit.cacheControl,
};
if (isNotModified(req.headers, etag, hit.mtimeMs))
return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : await hit.read() };
}
/**
* `createApp({ etag: true })` for a handler response: a buffered `200` to GET/HEAD gets a weak ETag
* from its body — computed before HEAD blanks the body, so HEAD and GET carry the same tag — unless
* the handler set one, which is kept and only compared. A match becomes a bodiless `304`. The
* handler has already run: this saves bandwidth, not work.
*/
function tagged(
result: { status: number; headers: Record<string, string | string[]>; body: string },
req: NeutralRequest,
): Buffered {
const key = findHeader(result.headers, 'etag');
const existing = key === undefined ? undefined : result.headers[key];
const etag = typeof existing === 'string' ? existing : bodyEtag(result.body);
const headers = key === undefined ? { ...result.headers, etag } : result.headers;
if (isNotModified(req.headers, etag)) return bodyless({ kind: 'buffered', status: 304, headers, body: '' });
return { kind: 'buffered', status: 200, headers, body: req.method === 'HEAD' ? '' : result.body };
}
async function unmatchedOutcome(
routes: RouteDef[],
opts: HttpOptions | undefined,
@@ -149,18 +205,7 @@ async function unmatchedOutcome(
): Promise<HandleResult> {
if ((req.method === 'GET' || req.method === 'HEAD') && opts?.static) {
const hit = await opts.static(path);
if (hit) {
return {
injected,
outcome: {
kind: 'buffered',
status: 200,
headers: { 'content-type': hit.contentType },
body: req.method === 'HEAD' ? '' : hit.body,
},
};
}
if (hit) return { injected, outcome: await staticOutcome(hit, req) };
}
const allow = allowedMethods(routes, path);
@@ -411,13 +456,16 @@ async function dispatch(
};
}
if (opts?.etag && result.status === 200 && (req.method === 'GET' || req.method === 'HEAD'))
return { injected, outcome: tagged(result, req) };
return {
injected,
outcome: {
outcome: bodyless({
kind: 'buffered',
status: result.status,
headers: result.headers,
body: req.method === 'HEAD' ? '' : result.body,
},
}),
};
}
+2
View File
@@ -68,6 +68,8 @@ export interface HttpOptions {
* Absent when health is off, so no path is intercepted.
*/
health?: HealthProbe;
/** Weak ETags + `304` for buffered `200` GET/HEAD handler responses (`createApp({ etag })`). */
etag?: boolean;
}
/** Handler for a matched HTTP route; receives a normalized request and resolves to a pipeline result. */