/** * Cache headers for dynamic responses (stacksjs/stacks#3566). * * A route declares how a CDN and browsers may keep its responses: * * ```ts * route.get('/v1/suggest', 'Actions/SuggestAction') * .cache({ sMaxAge: 300, staleWhileRevalidate: 60, vary: ['Accept-Language'], tags: ['suggest'] }) * ``` * * or an action decides per request, with `response.cache(policy, body)` / * `withCachePolicy(response, policy)`. Either way the router emits * `Cache-Control`, `CDN-Cache-Control` (and Cloudflare's variant when asked), * `Vary`, `Cache-Tag` and a weak `ETag` over the body, and answers a matching * `If-None-Match` with a bodiless 304. * * **The safety rule.** A shared cache must never keep one visitor's response * for another. So a response that sets a cookie, or answers a request that * carried an `Authorization` header, is downgraded to `private` (no * `s-maxage`, no CDN headers, no tags) unless the policy says * `allowCookies` / `allowAuthorization` - which is a statement that the body * is the same for everyone. */ /** How a response may be cached. Seconds throughout. */ export interface CachePolicy { /** Shared caches (CDNs) may keep it. Implied by `sMaxAge` or `cdnMaxAge`. */ public?: boolean /** Only the visitor's browser may keep it. */ private?: boolean /** Nothing may keep it. Overrides everything else. */ noStore?: boolean /** Caches must revalidate before every reuse (the ETag makes that cheap). */ noCache?: boolean /** How long a browser may reuse it. */ maxAge?: number /** How long a shared cache may reuse it. */ sMaxAge?: number /** How long a stale copy may be served while one revalidation runs. */ staleWhileRevalidate?: number /** How long a stale copy may be served when the origin errors. */ staleIfError?: number /** The body at this URL never changes. */ immutable?: boolean mustRevalidate?: boolean /** Request headers the response varies by, merged with any already set. */ vary?: string[] /** Tags a CDN can purge by (`Cache-Tag`). */ tags?: string[] /** `CDN-Cache-Control: max-age`, when the CDN should keep it longer or shorter than `sMaxAge`. */ cdnMaxAge?: number /** Also emit `Cloudflare-CDN-Cache-Control`, which only Cloudflare reads and passes on to nobody. */ cloudflare?: boolean /** Compute a weak ETag from the body and answer `If-None-Match`. On by default. */ etag?: boolean /** The response sets cookies that are the same for everyone, so it may still be shared. */ allowCookies?: boolean /** The response does not depend on the request's `Authorization`, so it may still be shared. */ allowAuthorization?: boolean /** * Redirect (308) a request whose query string is not in canonical form, so * equivalent URLs share one cache entry. See {@link normalizeCacheQuery}. */ canonicalQuery?: CacheQueryOptions } /** How a query string is put into canonical form for caching. */ export interface CacheQueryOptions { /** Keep only these parameters, dropping the rest (tracking, cache-busters). */ params?: string[] /** Lower-case the parameter names. Values are left alone. */ lowercaseNames?: boolean } const POLICY = Symbol.for('stacks.router.cachePolicy') const CACHEABLE_STATUSES = new Set([200, 203, 204]) /** Attach a cache policy to a response an action returns; the router applies it. */ export function withCachePolicy(response: T, policy: CachePolicy): T { ;(response as unknown as Record)[POLICY] = policy return response } /** The policy an action attached with {@link withCachePolicy}, if any. */ export function cachePolicyOf(response: Response | undefined): CachePolicy | undefined { return response ? (response as unknown as Record)[POLICY] : undefined } function seconds(name: string, value: number | undefined): number | undefined { if (value === undefined) return undefined if (!Number.isFinite(value) || value < 0) throw new RangeError(`[router] Cache policy ${name} must be a non-negative number of seconds, got ${String(value)}`) return Math.floor(value) } /** Check a policy's numbers, so a typo fails where the route is declared. */ export function validateCachePolicy(policy: CachePolicy): CachePolicy { for (const key of ['maxAge', 'sMaxAge', 'staleWhileRevalidate', 'staleIfError', 'cdnMaxAge'] as const) seconds(key, policy[key]) return policy } /** Whether the policy lets a shared cache keep the response. */ export function isSharedCachePolicy(policy: CachePolicy): boolean { if (policy.noStore || policy.private) return false return policy.public === true || policy.sMaxAge !== undefined || policy.cdnMaxAge !== undefined } /** The `Cache-Control` value a policy produces. */ export function cacheControlValue(policy: CachePolicy, shared = isSharedCachePolicy(policy)): string { if (policy.noStore) return 'no-store' const parts: string[] = [shared ? 'public' : 'private'] if (policy.noCache) parts.push('no-cache') const maxAge = seconds('maxAge', policy.maxAge) if (maxAge !== undefined) parts.push(`max-age=${maxAge}`) const sMaxAge = seconds('sMaxAge', policy.sMaxAge) if (shared && sMaxAge !== undefined) parts.push(`s-maxage=${sMaxAge}`) const swr = seconds('staleWhileRevalidate', policy.staleWhileRevalidate) if (swr !== undefined) parts.push(`stale-while-revalidate=${swr}`) const sie = seconds('staleIfError', policy.staleIfError) if (sie !== undefined) parts.push(`stale-if-error=${sie}`) if (policy.mustRevalidate) parts.push('must-revalidate') if (policy.immutable) parts.push('immutable') return parts.join(', ') } /** The `CDN-Cache-Control` value, or undefined when the CDN is told nothing beyond `Cache-Control`. */ export function cdnCacheControlValue(policy: CachePolicy): string | undefined { const maxAge = seconds('cdnMaxAge', policy.cdnMaxAge) ?? seconds('sMaxAge', policy.sMaxAge) if (!isSharedCachePolicy(policy) || maxAge === undefined) return undefined const parts = ['public', `max-age=${maxAge}`] if (policy.staleWhileRevalidate !== undefined) parts.push(`stale-while-revalidate=${Math.floor(policy.staleWhileRevalidate)}`) if (policy.staleIfError !== undefined) parts.push(`stale-if-error=${Math.floor(policy.staleIfError)}`) return parts.join(', ') } /** * A URL's query string in canonical form: parameters sorted, optionally only * the named ones, optionally with lower-cased names. Two requests a cache * should treat as one produce the same string. */ export function normalizeCacheQuery(url: string | URL, options: CacheQueryOptions = {}): string { const parsed = new URL(String(url)) const keep = options.params ? new Set(options.params.map(name => (options.lowercaseNames ? name.toLowerCase() : name))) : undefined const entries: Array<[string, string]> = [] for (const [rawName, value] of parsed.searchParams) { const name = options.lowercaseNames ? rawName.toLowerCase() : rawName if (!keep || keep.has(name)) entries.push([name, value]) } entries.sort(([a, av], [b, bv]) => (a === b ? (av < bv ? -1 : av > bv ? 1 : 0) : a < b ? -1 : 1)) const query = new URLSearchParams(entries).toString() return `${parsed.pathname}${query ? `?${query}` : ''}` } /** * The redirect to the canonical URL when a request's query is not canonical, * or undefined when it is. Only GET and HEAD are redirected. */ export function canonicalQueryRedirect(request: Request, options: CacheQueryOptions): Response | undefined { if (request.method !== 'GET' && request.method !== 'HEAD') return undefined const url = new URL(request.url) const canonical = normalizeCacheQuery(url, options) if (`${url.pathname}${url.search}` === canonical) return undefined return new Response(null, { status: 308, headers: { 'location': canonical, 'cache-control': 'public, max-age=86400' } }) } function mergeVary(headers: Headers, names: readonly string[]): void { if (names.length === 0) return const current = (headers.get('vary') ?? '').split(',').map(name => name.trim()).filter(Boolean) if (current.includes('*')) return const seen = new Set(current.map(name => name.toLowerCase())) for (const name of names) { if (!seen.has(name.toLowerCase())) { current.push(name) seen.add(name.toLowerCase()) } } headers.set('vary', current.join(', ')) } function weakEtag(body: ArrayBuffer): string { return `W/"${Bun.hash(new Uint8Array(body)).toString(36)}-${body.byteLength.toString(36)}"` } /** Whether an `If-None-Match` header matches an ETag (weak comparison, RFC 9110 ยง13.1.2). */ export function ifNoneMatchMatches(header: string | null, etag: string): boolean { if (!header) return false const opaque = (tag: string) => tag.trim().replace(/^W\//, '') const target = opaque(etag) return header.split(',').some(tag => tag.trim() === '*' || opaque(tag) === target) } /** * Apply a policy to a response: the headers, the safety rule, the ETag and * the conditional 304. Responses to methods other than GET and HEAD, and * statuses a cache does not keep, are returned untouched. */ export async function applyCachePolicy(request: Request, response: Response, policy: CachePolicy): Promise { if ((request.method !== 'GET' && request.method !== 'HEAD') || !CACHEABLE_STATUSES.has(response.status)) return response // The safety rule: never share what may be one visitor's. const unsafeCookies = response.headers.has('set-cookie') && !policy.allowCookies const unsafeAuthorization = request.headers.has('authorization') && !policy.allowAuthorization const shared = isSharedCachePolicy(policy) && !unsafeCookies && !unsafeAuthorization const headers = new Headers(response.headers) headers.set('cache-control', cacheControlValue(policy, shared)) const cdn = shared ? cdnCacheControlValue(policy) : undefined if (cdn) { headers.set('cdn-cache-control', cdn) if (policy.cloudflare) headers.set('cloudflare-cdn-cache-control', cdn) } if (shared && policy.tags?.length) headers.set('cache-tag', policy.tags.map(tag => tag.trim()).filter(Boolean).join(',')) mergeVary(headers, [...(policy.vary ?? []), ...(unsafeAuthorization ? ['Authorization'] : [])]) let body: ArrayBuffer | ReadableStream | null = response.body const isStream = (headers.get('content-type') ?? '').includes('text/event-stream') if (policy.etag !== false && !policy.noStore && response.body && !isStream) { const bytes = await response.arrayBuffer() body = bytes if (!headers.has('etag')) headers.set('etag', weakEtag(bytes)) } const etag = headers.get('etag') if (etag && ifNoneMatchMatches(request.headers.get('if-none-match'), etag)) { for (const name of ['content-length', 'content-type', 'content-encoding', 'set-cookie']) headers.delete(name) return new Response(null, { status: 304, headers }) } return new Response(body, { status: response.status, statusText: response.statusText, headers }) }