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

worker.ts

161 lines5.7 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 { ProviderSecrets } 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 SPEC_SYNC_SHARD_CRONS,
20 specSyncShard,
21 syncAllProviders,
22} from '#/server/ingest/sync.ts'
23import { runWebhookTick } from '#/server/webhooks.ts'
24import type { SyncDeps } from '#/server/ingest/sync.ts'
25​
26// Not exported: workerd treats named exports of the entry module as
27// entrypoints and requires them to be functions/ExportedHandlers.
28const MODELS_POLL_CRON = '*/15 * * * *'
29​
30export interface WorkerEnv extends DbEnv, KvEnv, ProviderSecrets {
31 ADMIN_KEY?: string
33​
34function syncDeps(env: WorkerEnv): SyncDeps {
35 return { db: getDb(env), kv: env.SCHEMA_CACHE, secrets: env }
37​
38/**
39 * Public reads are keyless JSON meant for any client — including browser
40 * apps (the hosted examples fetch /v1/schemas live). CORS-open GETs on the
41 * read surface; admin and auth routes are excluded.
42 */
43function isCorsReadPath(pathname: string): boolean {
44 return (
45 (pathname.startsWith('/v1/') && !pathname.startsWith('/v1/admin/')) ||
46 pathname === '/openapi.json' ||
47 pathname === '/llms.txt'
48 )
50​
51function withCors(response: Response): Response {
52 // New Response: framework responses can carry immutable headers.
53 const wrapped = new Response(response.body, response)
54 wrapped.headers.set('Access-Control-Allow-Origin', '*')
55 return wrapped
57​
58export default {
59 async fetch(
60 request: Request,
61 env: WorkerEnv,
62 ctx: ExecutionContext,
63 ): Promise<Response> {
64 // Rate limit the public API (admin-keyed requests are exempt; auth
65 // endpoints have agent-auth's own protections).
66 const url = new URL(request.url)
67 const { pathname } = url
68 const corsRead =
69 isCorsReadPath(pathname) &&
70 (request.method === 'GET' || request.method === 'HEAD')
71 if (request.method === 'OPTIONS' && isCorsReadPath(pathname)) {
72 return new Response(null, {
73 status: 204,
74 headers: {
75 'Access-Control-Allow-Origin': '*',
76 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
77 'Access-Control-Allow-Headers': 'Content-Type, If-None-Match',
78 'Access-Control-Max-Age': '86400',
79 },
80 })
81 }
82 if (
83 pathname.startsWith('/v1/') &&
84 !isAdminRequest(request, env.ADMIN_KEY)
85 ) {
86 const limited = await enforceRateLimit(
87 getAuth(),
88 getDb(env),
89 env.SCHEMA_CACHE,
90 request,
91 )
92 if (limited) return corsRead ? withCors(limited) : limited
93 }
94 // Narrative API root (task 11.2): JSON-accepting GET / gets the MCP
95 // initialize instructions document instead of the SSR landing page.
96 if (pathname === '/' && wantsJsonRoot(request)) {
97 const body = Response.json(narrativeRoot(url.origin))
98 body.headers.set('Vary', 'Accept')
99 return body
100 }
101 // Markdown content negotiation (task 10.5): Accept: text/markdown on an
102 // HTML page returns markdown instead of SSR.
103 if (wantsMarkdown(request)) {
104 const md = markdownForPath(pathname, url.origin)
105 if (md !== null) return markdownResponse(md)
106 }
107 // TanStack Start's handler takes (request, opts?) — bindings flow in via
108 // the cloudflare:workers env module, not handler arguments. HTML pages
109 // get RFC 8288 discovery Link headers (task 10.2).
110 void ctx
111 const response = withDiscoveryLinks(await serverEntry.fetch(request))
112 return corsRead ? withCors(response) : response
113 },
114​
115 scheduled(
116 controller: ScheduledController,
117 env: WorkerEnv,
118 ctx: ExecutionContext,
119 ): void {
120 // The models poll runs the full registry in one invocation; the spec
121 // sync is sharded across several cron firings so each shard gets its
122 // own subrequest/CPU/memory budgets (see SPEC_SYNC_SHARD_CRONS). Work
123 // inside each invocation stays sequential with per-provider isolation.
124 if (controller.cron === MODELS_POLL_CRON) {
125 ctx.waitUntil(
126 pollAllProviders(syncDeps(env))
127 .then((outcomes) => {
128 console.log(JSON.stringify({ job: 'models-poll', outcomes }))
129 // The 15-min cron also drains the webhook queue (task 6.2).
130 return runWebhookTick(getDb(env))
131 })
132 .then(({ enqueued, outcomes }) => {
133 console.log(JSON.stringify({ job: 'webhooks', enqueued, outcomes }))
134 }),
135 )
136 return
137 }
138 const shard = (SPEC_SYNC_SHARD_CRONS as ReadonlyArray<string>).indexOf(
139 controller.cron,
140 )
141 if (shard >= 0) {
142 ctx.waitUntil(
143 syncAllProviders(syncDeps(env), specSyncShard(shard)).then(
144 (outcomes) => {
145 // Summarize warnings to a count: hundreds of dangling-ref lines
146 // push the blob past what Workers Logs stores, losing the log.
147 const summary = outcomes.map(({ warnings, ...rest }) => ({
148 ...rest,
149 warningCount: warnings.length,
150 }))
151 console.log(
152 JSON.stringify({ job: 'spec-sync', shard, outcomes: summary }),
153 )
154 },
155 ),
156 )
157 return
158 }
159 console.log(JSON.stringify({ cron: controller.cron, job: 'unknown-cron' }))
160 },