Skip to content
Source
Sign inSign up
TanStack/schemas
Open History to see the last commit

http-cache.ts

96 lines2.9 KB

1/**
2 * HTTP cache semantics for read endpoints (PLAN.md task 3.2): `ETag`
3 * (content hash), `Last-Modified`, `Cache-Control` with
4 * stale-while-revalidate, `X-Fetched-At` / `X-Stale-At` (unix epoch
5 * seconds), and `If-None-Match` → 304. Applied to every schema/model read
6 * endpoint in Phase 4.
7 */
8import { contentHash } from '#/server/kv.ts'
9​
10export interface CacheHeaderOptions {
11 /** Content hash to use as the ETag; computed from the body when omitted. */
12 etag?: string
13 /** Unix epoch seconds the value was fetched/produced. */
14 fetchedAt: number
15 /** Unix epoch seconds the value goes stale. */
16 staleAt: number
17 /** Cache-Control max-age (seconds). */
18 maxAge?: number
19 /** Cache-Control stale-while-revalidate window (seconds). */
20 staleWhileRevalidate?: number
21 /** Defaults to application/json. */
22 contentType?: string
24​
25function buildHeaders(
26 etag: string,
27 options: CacheHeaderOptions,
28 contentType: string,
29): Headers {
30 return new Headers({
31 'Content-Type': contentType,
32 ETag: `"${etag}"`,
33 'Last-Modified': new Date(options.fetchedAt * 1000).toUTCString(),
34 'Cache-Control': `public, max-age=${String(options.maxAge ?? 60)}, stale-while-revalidate=${String(options.staleWhileRevalidate ?? 600)}`,
35 'X-Fetched-At': String(options.fetchedAt),
36 'X-Stale-At': String(options.staleAt),
37 })
39​
40/** RFC 9110 If-None-Match: comma-separated entity tags, `W/` prefixes
41 * compare weakly, `*` matches anything. */
42export function ifNoneMatchSatisfied(
43 header: string | null,
44 etag: string,
45): boolean {
46 if (!header) return false
47 if (header.trim() === '*') return true
48 return header
49 .split(',')
50 .map((tag) => tag.trim().replace(/^W\//, ''))
51 .includes(`"${etag}"`)
53​
54/**
55 * JSON response with full cache semantics; returns 304 (no body, same
56 * headers) when the request's If-None-Match matches the ETag.
57 */
58export async function cachedJson(
59 request: Request,
60 value: unknown,
61 options: CacheHeaderOptions,
62): Promise<Response> {
63 const etag = options.etag ?? (await contentHash(value))
64 return respond(
65 request,
66 JSON.stringify(value),
67 etag,
68 options,
69 options.contentType ?? 'application/json',
70 )
72​
73/** Same cache semantics for a non-JSON text body (e.g. `?format=types`). */
74export function cachedText(
75 request: Request,
76 body: string,
77 contentType: string,
78 options: CacheHeaderOptions & { etag: string },
79): Response {
80 return respond(request, body, options.etag, options, contentType)
82​
83function respond(
84 request: Request,
85 body: string,
86 etag: string,
87 options: CacheHeaderOptions,
88 contentType: string,
89): Response {
90 const headers = buildHeaders(etag, options, contentType)
91 if (ifNoneMatchSatisfied(request.headers.get('if-none-match'), etag)) {
92 headers.delete('Content-Type')
93 return new Response(null, { status: 304, headers })
94 }
95 return new Response(body, { status: 200, headers })