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

worker.ts

340 lines12.1 KB

1import serverEntry from '@tanstack/react-start/server-entry'
2import { WorkerEntrypoint } from 'cloudflare:workers'
3import type {
4 Request as WorkersRequest,
5 Response as WorkersResponse,
6} from '@cloudflare/workers-types'
7​
8import { getDb } from '#/db/index.ts'
9import type { DbEnv } from '#/db/index.ts'
10import { isAdminRequest } from '#/server/admin.ts'
11import { getAuth } from '#/server/auth.ts'
12import type { KvEnv } from '#/server/kv.ts'
13import type { ProviderEnvironment } from '#/server/providers/types.ts'
14import { withDiscoveryLinks } from '#/server/discovery-links.ts'
15import {
16 markdownForPath,
17 markdownResponse,
18 wantsMarkdown,
19} from '#/server/markdown-pages.ts'
20import { narrativeRoot, wantsJsonRoot } from '#/server/narrative.ts'
21import { enforceRateLimit } from '#/server/rate-limit.ts'
22import { pollAllProviders } from '#/server/ingest/poll-models.ts'
23import {
24 FAL_PRICING_EXTRACT_CRONS,
25 extractFalPricing,
26} from '#/server/ingest/extract-fal-pricing.ts'
27import {
28 VERCEL_PRICING_EXTRACT_CRON,
29 extractVercelPricing,
30} from '#/server/ingest/extract-vercel-pricing.ts'
31import {
32 SPEC_SYNC_SHARD_CRONS,
33 specSyncShard,
34 syncAllProviders,
35} from '#/server/ingest/sync.ts'
36import { PROBE_CRON, runProbeCron } from '#/server/ingest/probe-facts.ts'
37import { recordCompleteness } from '#/server/status.ts'
38import { recordRowShape } from '#/server/row-shape.ts'
39import { runWebhookTick } from '#/server/webhooks.ts'
40import type { SyncDeps } from '#/server/ingest/sync.ts'
41​
42// Durable Object class for the US_EGRESS binding (issue #356).
43export { UsEgress } from '#/server/us-egress-object.ts'
44​
45// Not exported: workerd treats named exports of the entry module as
46// entrypoints and requires them to be functions/ExportedHandlers.
47const MODELS_POLL_CRON = '*/15 * * * *'
48​
49export interface WorkerEnv extends DbEnv, KvEnv, ProviderEnvironment {
50 ADMIN_KEY?: string
51 AI?: Ai
52 AI_GATEWAY_ID?: string
54​
55function syncDeps(env: WorkerEnv): SyncDeps {
56 return { db: getDb(env), kv: env.SCHEMA_CACHE, secrets: env }
58​
59/**
60 * Public reads are keyless JSON meant for any client — including browser
61 * apps (the hosted examples fetch /v1/schemas live). CORS-open GETs on the
62 * read surface; admin and auth routes are excluded.
63 */
64function isCorsReadPath(pathname: string): boolean {
65 return (
66 (pathname.startsWith('/v1/') && !pathname.startsWith('/v1/admin/')) ||
67 pathname === '/openapi.json' ||
68 pathname === '/llms.txt'
69 )
71​
72/**
73 * GETs that Workers Cache may store: catalog, schema and per-provider
74 * OpenAPI reads. The default entrypoint hands these to `CachedReads`, the
75 * one entrypoint with caching on (wrangler.jsonc `exports`). Every other
76 * request skips the cache lookup entirely, which Cloudflare recommends
77 * over answering `no-store` from a cached entrypoint.
78 */
79function isCacheableRead(request: Request, pathname: string): boolean {
80 return (
81 (request.method === 'GET' || request.method === 'HEAD') &&
82 /^\/v1\/(models|providers|schemas|openapi)(\/|$)/.test(pathname)
83 )
85​
86function finalize(response: Response, cors: boolean): Response {
87 // New Response: framework responses can carry immutable headers.
88 const headers = new Headers(response.headers)
89 if (cors) headers.set('Access-Control-Allow-Origin', '*')
90 // Workers Cache applies heuristic freshness to a response with no
91 // Cache-Control (a 404 for three minutes, a 200 for two hours). Catalog
92 // and schema reads opt in with `public, max-age`; anything else that
93 // reaches the cached entrypoint, such as an error body, must not be
94 // stored.
95 const cacheControl = headers.get('cache-control') ?? ''
96 if (
97 !cacheControl.includes('public') &&
98 !cacheControl.includes('no-store') &&
99 !cacheControl.includes('private')
100 ) {
101 headers.set('Cache-Control', 'no-store')
102 }
103 return new Response(response.body, {
104 status: response.status,
105 statusText: response.statusText,
106 headers,
107 })
109​
110async function handle(request: Request, env: WorkerEnv): Promise<Response> {
111 {
112 // Rate limit the public API (admin-keyed requests are exempt; auth
113 // endpoints have agent-auth's own protections).
114 const url = new URL(request.url)
115 const { pathname } = url
116 const corsRead =
117 isCorsReadPath(pathname) &&
118 (request.method === 'GET' || request.method === 'HEAD')
119 if (request.method === 'OPTIONS' && isCorsReadPath(pathname)) {
120 return new Response(null, {
121 status: 204,
122 headers: {
123 'Access-Control-Allow-Origin': '*',
124 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
125 'Access-Control-Allow-Headers': 'Content-Type, If-None-Match',
126 'Access-Control-Max-Age': '86400',
127 },
128 })
129 }
130 if (
131 pathname.startsWith('/v1/') &&
132 !isAdminRequest(request, env.ADMIN_KEY)
133 ) {
134 const limited = await enforceRateLimit(
135 getAuth(),
136 getDb(env),
137 env.SCHEMA_CACHE,
138 request,
139 )
140 if (limited) return finalize(limited, corsRead)
141 }
142 // Narrative API root (task 11.2): JSON-accepting GET / gets the MCP
143 // initialize instructions document instead of the SSR landing page.
144 if (pathname === '/' && wantsJsonRoot(request)) {
145 const body = Response.json(narrativeRoot(url.origin))
146 body.headers.set('Vary', 'Accept')
147 return finalize(body, corsRead)
148 }
149 // Markdown content negotiation (task 10.5): Accept: text/markdown on an
150 // HTML page returns markdown instead of SSR.
151 if (wantsMarkdown(request)) {
152 const md = markdownForPath(pathname, url.origin)
153 if (md !== null) return finalize(markdownResponse(md), false)
154 }
155 // TanStack Start's handler takes (request, opts?) — bindings flow in via
156 // the cloudflare:workers env module, not handler arguments. HTML pages
157 // get RFC 8288 discovery Link headers (task 10.2).
158 const response = withDiscoveryLinks(await serverEntry.fetch(request))
159 return finalize(response, corsRead)
160 }
162​
163/**
164 * The cached entrypoint. Workers Cache sits in front of its `fetch`: a HIT
165 * never runs the worker (so it is outside the rate limit), a MISS runs the
166 * same pipeline as the default entrypoint. A request with `Authorization`
167 * is cached too, because the responses say `public`.
168 */
169export class CachedReads extends WorkerEntrypoint<WorkerEnv> {
170 // The base class is typed with workers-types; the app with lib.dom (see
171 // src/cloudflare-shim.d.ts). Same objects at runtime.
172 override fetch(request: WorkersRequest): Promise<WorkersResponse> {
173 return handle(
174 request as unknown as Request,
175 this.env,
176 ) as unknown as Promise<WorkersResponse>
177 }
178​
179 /**
180 * A purge is scoped to the entrypoint that calls it, so it lives here.
181 * Throws rather than no-ops: a missing `ctx.cache` means caching is off
182 * for this entrypoint (wrangler.jsonc `exports`), and a failed purge
183 * would leave an admin sync invisible for `max-age`.
184 */
185 async purge(): Promise<void> {
186 if (!this.ctx.cache) {
187 throw new Error('CachedReads: ctx.cache is absent; caching is off')
188 }
189 const result = await this.ctx.cache.purge({ purgeEverything: true })
190 if (!result.success) {
191 throw new Error(
192 `CachedReads: purge failed: ${JSON.stringify(result.errors)}`,
193 )
194 }
195 }
197​
198export default {
199 async fetch(
200 request: Request,
201 env: WorkerEnv,
202 ctx: ExecutionContext,
203 ): Promise<Response> {
204 const { pathname } = new URL(request.url)
205 if (isCacheableRead(request, pathname)) {
206 return ctx.exports.CachedReads.fetch(request)
207 }
208 const response = await handle(request, env)
209 // An admin write (sync, extract) changes what the cached reads serve;
210 // the crons do not need this because max-age matches their cadence.
211 if (
212 request.method === 'POST' &&
213 pathname.startsWith('/v1/admin/') &&
214 response.ok
215 ) {
216 ctx.waitUntil(
217 ctx.exports.CachedReads.purge().catch((error: unknown) => {
218 console.error(
219 JSON.stringify({ job: 'cache-purge', error: String(error) }),
220 )
221 }),
222 )
223 }
224 return response
225 },
226​
227 scheduled(
228 controller: ScheduledController,
229 env: WorkerEnv,
230 ctx: ExecutionContext,
231 ): void {
232 // The models poll runs the full registry in one invocation; the spec
233 // sync is sharded across several cron firings so each shard gets its
234 // own subrequest/CPU/memory budgets (see SPEC_SYNC_SHARD_CRONS). FAL
235 // rate-card extract runs hourly 06:00-11:00 UTC, each firing with its
236 // own budget (FAL_PRICING_EXTRACT_CRONS). Work inside each invocation stays
237 // sequential with per-provider isolation.
238 if (controller.cron === MODELS_POLL_CRON) {
239 ctx.waitUntil(
240 pollAllProviders(syncDeps(env))
241 .then(async (outcomes) => {
242 console.log(JSON.stringify({ job: 'models-poll', outcomes }))
243 // Score completeness once per poll; requests only read the
244 // record. It logs and keeps the old record rather than throw.
245 await recordCompleteness(getDb(env))
246 // Announce a new row shape before the drain so webhooks carry
247 // it. A failure is logged and retried next poll; it does not
248 // hold up webhook delivery.
249 await recordRowShape(getDb(env)).then(
250 (written) => {
251 if (written > 0)
252 console.log(JSON.stringify({ job: 'row-shape', written }))
253 },
254 (error: unknown) => {
255 console.error(
256 JSON.stringify({
257 job: 'row-shape',
258 error: String(error),
259 stack: error instanceof Error ? error.stack : undefined,
260 }),
261 )
262 },
263 )
264 // The 15-min cron also drains the webhook queue (task 6.2).
265 return runWebhookTick(getDb(env))
266 })
267 .then(({ enqueued, outcomes }) => {
268 console.log(JSON.stringify({ job: 'webhooks', enqueued, outcomes }))
269 }),
270 )
271 return
272 }
273 const shard = (SPEC_SYNC_SHARD_CRONS as ReadonlyArray<string>).indexOf(
274 controller.cron,
275 )
276 if (shard >= 0) {
277 ctx.waitUntil(
278 syncAllProviders(syncDeps(env), specSyncShard(shard)).then(
279 (outcomes) => {
280 // Summarize warnings to a count: hundreds of dangling-ref lines
281 // push the blob past what Workers Logs stores, losing the log.
282 const summary = outcomes.map(({ warnings, ...rest }) => ({
283 ...rest,
284 warningCount: warnings.length,
285 }))
286 console.log(
287 JSON.stringify({ job: 'spec-sync', shard, outcomes: summary }),
288 )
289 },
290 ),
291 )
292 return
293 }
294 if (
295 (FAL_PRICING_EXTRACT_CRONS as ReadonlyArray<string>).includes(
296 controller.cron,
297 )
298 ) {
299 ctx.waitUntil(
300 extractFalPricing({
301 ...syncDeps(env),
302 ai: env.AI,
303 gatewayId: env.AI_GATEWAY_ID,
304 }).then((outcome) => {
305 console.log(JSON.stringify({ job: 'fal-pricing-extract', outcome }))
306 }),
307 )
308 return
309 }
310 // Live fact probes (issue #717): their own hourly firing, so the
311 // request cap and subrequests never share the 15-minute poll's budget.
312 if (controller.cron === PROBE_CRON) {
313 ctx.waitUntil(
314 // `observed_at` is the firing's scheduled time, so two firings are
315 // exactly PROBE_RUN_GAP_SECONDS apart and an overlap is not.
316 // runProbeCron reports a failure as ingest_failed and rethrows.
317 runProbeCron({
318 db: getDb(env),
319 secrets: env,
320 now: () => Math.floor(controller.scheduledTime / 1000),
321 posthogKey: env.POSTHOG_PROJECT_KEY,
322 }).then((outcome) => {
323 console.log(JSON.stringify({ job: 'probe-run', outcome }))
324 }),
325 )
326 return
327 }
328 if (controller.cron === VERCEL_PRICING_EXTRACT_CRON) {
329 ctx.waitUntil(
330 extractVercelPricing(syncDeps(env)).then((outcome) => {
331 console.log(
332 JSON.stringify({ job: 'vercel-pricing-extract', outcome }),
333 )
334 }),
335 )
336 return
337 }
338 console.log(JSON.stringify({ cron: controller.cron, job: 'unknown-cron' }))
339 },