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

worker.ts

205 lines7.3 KB

1import serverEntry from '@tanstack/react-start/server-entry'
2​
3import { getDb } from '#/db/index.ts'
4import type { DbEnv } from '#/db/index.ts'
5import { isAdminRequest } from '#/server/admin.ts'
6import { getAuth } from '#/server/auth.ts'
7import type { KvEnv } from '#/server/kv.ts'
8import type { ProviderEnvironment } from '#/server/providers/types.ts'
9import { withDiscoveryLinks } from '#/server/discovery-links.ts'
10import {
11 markdownForPath,
12 markdownResponse,
13 wantsMarkdown,
14} from '#/server/markdown-pages.ts'
15import { narrativeRoot, wantsJsonRoot } from '#/server/narrative.ts'
16import { enforceRateLimit } from '#/server/rate-limit.ts'
17import { pollAllProviders } from '#/server/ingest/poll-models.ts'
18import {
19 FAL_PRICING_EXTRACT_CRONS,
20 extractFalPricing,
21} from '#/server/ingest/extract-fal-pricing.ts'
22import {
23 SPEC_SYNC_SHARD_CRONS,
24 specSyncShard,
25 syncAllProviders,
26} from '#/server/ingest/sync.ts'
27import { recordCompleteness } from '#/server/status.ts'
28import { recordRowShape } from '#/server/row-shape.ts'
29import { runWebhookTick } from '#/server/webhooks.ts'
30import type { SyncDeps } from '#/server/ingest/sync.ts'
31​
32// Durable Object class for the US_EGRESS binding (issue #356).
33export { UsEgress } from '#/server/us-egress-object.ts'
34​
35// Not exported: workerd treats named exports of the entry module as
36// entrypoints and requires them to be functions/ExportedHandlers.
37const MODELS_POLL_CRON = '*/15 * * * *'
38​
39export interface WorkerEnv extends DbEnv, KvEnv, ProviderEnvironment {
40 ADMIN_KEY?: string
42​
43function syncDeps(env: WorkerEnv): SyncDeps {
44 return { db: getDb(env), kv: env.SCHEMA_CACHE, secrets: env }
46​
47/**
48 * Public reads are keyless JSON meant for any client — including browser
49 * apps (the hosted examples fetch /v1/schemas live). CORS-open GETs on the
50 * read surface; admin and auth routes are excluded.
51 */
52function isCorsReadPath(pathname: string): boolean {
53 return (
54 (pathname.startsWith('/v1/') && !pathname.startsWith('/v1/admin/')) ||
55 pathname === '/openapi.json' ||
56 pathname === '/llms.txt'
57 )
59​
60function withCors(response: Response): Response {
61 // New Response: framework responses can carry immutable headers.
62 const wrapped = new Response(response.body, response)
63 wrapped.headers.set('Access-Control-Allow-Origin', '*')
64 return wrapped
66​
67export default {
68 async fetch(
69 request: Request,
70 env: WorkerEnv,
71 ctx: ExecutionContext,
72 ): Promise<Response> {
73 // Rate limit the public API (admin-keyed requests are exempt; auth
74 // endpoints have agent-auth's own protections).
75 const url = new URL(request.url)
76 const { pathname } = url
77 const corsRead =
78 isCorsReadPath(pathname) &&
79 (request.method === 'GET' || request.method === 'HEAD')
80 if (request.method === 'OPTIONS' && isCorsReadPath(pathname)) {
81 return new Response(null, {
82 status: 204,
83 headers: {
84 'Access-Control-Allow-Origin': '*',
85 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
86 'Access-Control-Allow-Headers': 'Content-Type, If-None-Match',
87 'Access-Control-Max-Age': '86400',
88 },
89 })
90 }
91 if (
92 pathname.startsWith('/v1/') &&
93 !isAdminRequest(request, env.ADMIN_KEY)
94 ) {
95 const limited = await enforceRateLimit(
96 getAuth(),
97 getDb(env),
98 env.SCHEMA_CACHE,
99 request,
100 )
101 if (limited) return corsRead ? withCors(limited) : limited
102 }
103 // Narrative API root (task 11.2): JSON-accepting GET / gets the MCP
104 // initialize instructions document instead of the SSR landing page.
105 if (pathname === '/' && wantsJsonRoot(request)) {
106 const body = Response.json(narrativeRoot(url.origin))
107 body.headers.set('Vary', 'Accept')
108 return body
109 }
110 // Markdown content negotiation (task 10.5): Accept: text/markdown on an
111 // HTML page returns markdown instead of SSR.
112 if (wantsMarkdown(request)) {
113 const md = markdownForPath(pathname, url.origin)
114 if (md !== null) return markdownResponse(md)
115 }
116 // TanStack Start's handler takes (request, opts?) — bindings flow in via
117 // the cloudflare:workers env module, not handler arguments. HTML pages
118 // get RFC 8288 discovery Link headers (task 10.2).
119 void ctx
120 const response = withDiscoveryLinks(await serverEntry.fetch(request))
121 return corsRead ? withCors(response) : response
122 },
123​
124 scheduled(
125 controller: ScheduledController,
126 env: WorkerEnv,
127 ctx: ExecutionContext,
128 ): void {
129 // The models poll runs the full registry in one invocation; the spec
130 // sync is sharded across several cron firings so each shard gets its
131 // own subrequest/CPU/memory budgets (see SPEC_SYNC_SHARD_CRONS). FAL
132 // rate-card extract runs hourly 06:00-11:00 UTC, each firing with its
133 // own budget (FAL_PRICING_EXTRACT_CRONS). Work inside each invocation stays
134 // sequential with per-provider isolation.
135 if (controller.cron === MODELS_POLL_CRON) {
136 ctx.waitUntil(
137 pollAllProviders(syncDeps(env))
138 .then(async (outcomes) => {
139 console.log(JSON.stringify({ job: 'models-poll', outcomes }))
140 // Score completeness once per poll; requests only read the
141 // record. It logs and keeps the old record rather than throw.
142 await recordCompleteness(getDb(env))
143 // Announce a new row shape before the drain so webhooks carry
144 // it. A failure is logged and retried next poll; it does not
145 // hold up webhook delivery.
146 await recordRowShape(getDb(env)).then(
147 (written) => {
148 if (written > 0)
149 console.log(JSON.stringify({ job: 'row-shape', written }))
150 },
151 (error: unknown) => {
152 console.error(
153 JSON.stringify({
154 job: 'row-shape',
155 error: String(error),
156 stack: error instanceof Error ? error.stack : undefined,
157 }),
158 )
159 },
160 )
161 // The 15-min cron also drains the webhook queue (task 6.2).
162 return runWebhookTick(getDb(env))
163 })
164 .then(({ enqueued, outcomes }) => {
165 console.log(JSON.stringify({ job: 'webhooks', enqueued, outcomes }))
166 }),
167 )
168 return
169 }
170 const shard = (SPEC_SYNC_SHARD_CRONS as ReadonlyArray<string>).indexOf(
171 controller.cron,
172 )
173 if (shard >= 0) {
174 ctx.waitUntil(
175 syncAllProviders(syncDeps(env), specSyncShard(shard)).then(
176 (outcomes) => {
177 // Summarize warnings to a count: hundreds of dangling-ref lines
178 // push the blob past what Workers Logs stores, losing the log.
179 const summary = outcomes.map(({ warnings, ...rest }) => ({
180 ...rest,
181 warningCount: warnings.length,
182 }))
183 console.log(
184 JSON.stringify({ job: 'spec-sync', shard, outcomes: summary }),
185 )
186 },
187 ),
188 )
189 return
190 }
191 if (
192 (FAL_PRICING_EXTRACT_CRONS as ReadonlyArray<string>).includes(
193 controller.cron,
194 )
195 ) {
196 ctx.waitUntil(
197 extractFalPricing(syncDeps(env)).then((outcome) => {
198 console.log(JSON.stringify({ job: 'fal-pricing-extract', outcome }))
199 }),
200 )
201 return
202 }
203 console.log(JSON.stringify({ cron: controller.cron, job: 'unknown-cron' }))
204 },