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

http-cache.ts

151 lines4.7 KB

1/**
2 * HTTP cache semantics for read endpoints: `ETag` (content hash),
3 * `Last-Modified`, `Cache-Control`, `X-Fetched-At` / `X-Stale-At` (unix
4 * epoch seconds), and `If-None-Match` → 304.
5 *
6 * Workers Cache (the `CachedReads` entrypoint in `src/worker.ts`) stores a
7 * GET before the worker runs when the response is `public` with a
8 * `max-age`. That lifetime matches the 15-minute models poll for catalog
9 * and current schema reads; a `?version=<hash>` schema never changes, so
10 * it is cached for a year. No `s-maxage`: Cloudflare disables
11 * stale-while-revalidate and stale-if-error when it is present, and the
12 * shared and browser lifetimes are the same here anyway.
13 */
14import { contentHash } from '#/server/kv.ts'
15​
16/** Model lists move on the 15-minute poll. Spec sync is daily, so this is the tighter cron. */
17export const CATALOG_CACHE_SECONDS = 15 * 60
18​
19/** Content-addressed schema versions do not change. */
20export const VERSIONED_SCHEMA_CACHE_SECONDS = 365 * 24 * 60 * 60
21​
22export interface CacheHeaderOptions {
23 /** Content hash to use as the ETag; computed from the body when omitted. */
24 etag?: string
25 /** Unix epoch seconds the value was fetched/produced. */
26 fetchedAt: number
27 /** Unix epoch seconds the value goes stale. */
28 staleAt: number
29 /** Cache-Control max-age (seconds), edge and browser. Defaults to the poll cadence. */
30 maxAge?: number
31 /** Cache-Control stale-while-revalidate window (seconds). Omitted when immutable. */
32 staleWhileRevalidate?: number
33 /** Content-addressed body. Caches may keep it for `maxAge` without revalidating. */
34 immutable?: boolean
35 /** Defaults to application/json. */
36 contentType?: string
38​
39/** Cache window for a catalog or current-schema read. */
40export function catalogCache(
41 now = Math.floor(Date.now() / 1000),
42): Pick<CacheHeaderOptions, 'fetchedAt' | 'staleAt' | 'maxAge'> {
43 return {
44 fetchedAt: now,
45 staleAt: now + CATALOG_CACHE_SECONDS,
46 maxAge: CATALOG_CACHE_SECONDS,
47 }
49​
50/** Cache window for a schema read pinned to a content hash. */
51export function versionedSchemaCache(
52 createdAt: number,
53): Pick<CacheHeaderOptions, 'fetchedAt' | 'staleAt' | 'maxAge' | 'immutable'> {
54 return {
55 fetchedAt: createdAt,
56 staleAt: createdAt + VERSIONED_SCHEMA_CACHE_SECONDS,
57 maxAge: VERSIONED_SCHEMA_CACHE_SECONDS,
58 immutable: true,
59 }
61​
62function cacheControl(options: CacheHeaderOptions): string {
63 const parts = [
64 'public',
65 `max-age=${String(options.maxAge ?? CATALOG_CACHE_SECONDS)}`,
66 ]
67 if (options.immutable) {
68 parts.push('immutable')
69 } else {
70 parts.push(
71 `stale-while-revalidate=${String(options.staleWhileRevalidate ?? 600)}`,
72 )
73 }
74 return parts.join(', ')
76​
77function buildHeaders(
78 etag: string,
79 options: CacheHeaderOptions,
80 contentType: string,
81): Headers {
82 return new Headers({
83 'Content-Type': contentType,
84 ETag: `"${etag}"`,
85 'Last-Modified': new Date(options.fetchedAt * 1000).toUTCString(),
86 'Cache-Control': cacheControl(options),
87 'X-Fetched-At': String(options.fetchedAt),
88 'X-Stale-At': String(options.staleAt),
89 })
91​
92/** RFC 9110 If-None-Match: comma-separated entity tags, `W/` prefixes
93 * compare weakly, `*` matches anything. */
94export function ifNoneMatchSatisfied(
95 header: string | null,
96 etag: string,
97): boolean {
98 if (!header) return false
99 if (header.trim() === '*') return true
100 return header
101 .split(',')
102 .map((tag) => tag.trim().replace(/^W\//, ''))
103 .includes(`"${etag}"`)
105​
106/**
107 * JSON response with full cache semantics; returns 304 (no body, same
108 * headers) when the request's If-None-Match matches the ETag.
109 */
110export async function cachedJson(
111 request: Request,
112 value: unknown,
113 options: CacheHeaderOptions,
114): Promise<Response> {
115 const etag = options.etag ?? (await contentHash(value))
116 return respond(
117 request,
118 JSON.stringify(value),
119 etag,
120 options,
121 options.contentType ?? 'application/json',
122 )
124​
125/** Same cache semantics for a non-JSON text body (e.g. `?format=types`). */
126export function cachedText(
127 request: Request,
128 body: string,
129 contentType: string,
130 options: CacheHeaderOptions & { etag: string },
131): Response {
132 return respond(request, body, options.etag, options, contentType)
134​
135function respond(
136 request: Request,
137 body: string,
138 etag: string,
139 options: CacheHeaderOptions,
140 contentType: string,
141): Response {
142 const headers = buildHeaders(etag, options, contentType)
143 if (ifNoneMatchSatisfied(request.headers.get('if-none-match'), etag)) {
144 headers.delete('Content-Type')
145 // A 304 is not the representation. Workers Cache must not store it
146 // under the URL in place of the body.
147 headers.set('Cache-Control', 'private, no-store')
148 return new Response(null, { status: 304, headers })
149 }
150 return new Response(body, { status: 200, headers })