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

sync.ts

664 lines21.4 KB

1/**
2 * Sync engine (PLAN.md task 2.3): per provider — fetch spec → classify
3 * endpoints → bundle schemas → diff content hashes against
4 * `schema_versions` → insert new versions (reviving superseded rows when
5 * upstream reverts to previously seen content), mark superseded, upsert
6 * `endpoints`, write `changes` rows, warm KV with new blobs. Idempotent.
7 */
8import { and, eq, inArray, isNull, notInArray } from 'drizzle-orm'
9​
10import type { Db } from '#/db/index.ts'
11import {
12 changes,
13 endpoints,
14 models,
15 providers,
16 providerModelNamespaces,
17 schemaVersions,
18} from '#/db/schema.ts'
19import type { Activity } from '#/db/schema.ts'
20import { seedForProvider } from '#/db/seed-providers.ts'
21import { errorMessage } from '#/server/errors.ts'
22import { contentHash, putJson, schemaKey } from '#/server/kv.ts'
23import {
24 isMissingSecretSkip,
25 PROVENANCE_MARKER,
26} from '#/server/providers/types.ts'
27import type {
28 BundledEndpoint,
29 Derivation,
30 EndpointProvenance,
31 OpenApiOperation,
32 ProviderConfig,
33 ProviderEnvironment,
34 SpecFetchResult,
35 SpecSource,
36} from '#/server/providers/types.ts'
37import { hasAsyncApiFlag, withAsyncApiFlag } from './asyncapi.ts'
38import {
39 captureIngestEvents,
40 ingestFailedEvent,
41 noteIngest,
42 runIngestScope,
43} from './ingest-signals.ts'
44import { providerRegistry } from '#/server/providers/index.ts'
45import {
46 EXTRACTOR_VERSION,
47 endpointIdFromPath,
48 extractEndpointSchemas,
49 findDanglingRefs,
50} from './bundle.ts'
51import type { JsonValue } from './bundle.ts'
52import { dropModelsDevSchemaVersions } from './retire-models-dev.ts'
53​
54export interface SyncDeps {
55 db: Db
56 kv: KVNamespace
57 secrets: ProviderEnvironment
58 /** Injectable clock (unix epoch seconds) for deterministic tests. */
59 now?: () => number
61​
62export interface SyncOutcome {
63 providerId: string
64 endpointsSeen: number
65 versionsAdded: number
66 changesWritten: number
67 skipped?: string
68 error?: string
69 warnings: Array<string>
71​
72export interface ClassifiedEndpoint {
73 /** Globally unique db id: `${providerId}/${pathId}`. */
74 dbId: string
75 path: string
76 /** HTTP method. GET is the BytePlus video-task retrieve call. */
77 method: 'POST' | 'GET'
78 activity: Activity
79 description: string | null
80 /** Provenance of the spec document this endpoint came from. */
81 source: SpecSource | null
82 /** How this endpoint's schemas were arrived at (the trust ladder). */
83 derivation: Derivation
84 /** `YYYY-MM-DD` a `probe-verified` claim was last confirmed. */
85 verifiedAt: string | null
86 input?: Record<string, JsonValue>
87 output?: Record<string, JsonValue>
88 /** WMA AsyncAPI — catalog flag; skip HTTP OpenAPI assembly. */
89 asyncapi?: boolean
91​
92function newChangeId(): string {
93 return crypto.randomUUID()
95​
96const DERIVATIONS: ReadonlyArray<Derivation> = [
97 'upstream-spec',
98 'generated',
99 'probe-verified',
100 'docs-derived',
102​
103/**
104 * Per-operation provenance annotation, falling back to the provider's
105 * default. A malformed marker falls back too rather than throwing — a bad
106 * annotation should not sink a sync.
107 */
108function readProvenance(
109 op: OpenApiOperation,
110 provider: ProviderConfig,
111): { derivation: Derivation; verifiedAt: string | null } {
112 const marker = op[PROVENANCE_MARKER]
113 if (marker !== null && typeof marker === 'object') {
114 const { derivation, verifiedAt } = marker as Partial<EndpointProvenance>
115 if (typeof derivation === 'string' && DERIVATIONS.includes(derivation)) {
116 return {
117 derivation: derivation,
118 verifiedAt: typeof verifiedAt === 'string' ? verifiedAt : null,
119 }
120 }
121 }
122 return { derivation: provider.defaultDerivation, verifiedAt: null }
124​
125/**
126 * Classify + bundle every generation endpoint across a provider's fetched
127 * specs. Pure (no storage) — shared by the sync engine and the offline
128 * re-derivation script (`scripts/rederive.ts`), so both always derive
129 * identical content hashes from the same upstream documents.
130 */
131export function classifyAndBundle(
132 provider: ProviderConfig,
133 fetched: SpecFetchResult,
134): { endpoints: Array<ClassifiedEndpoint>; warnings: Array<string> } {
135 const classified: Array<ClassifiedEndpoint> = []
136 const warnings: Array<string> = []
137 for (const [specIndex, spec] of fetched.specs.entries()) {
138 const source = fetched.sources[specIndex] ?? null
139 for (const [pathKey, operations] of Object.entries(spec.paths ?? {})) {
140 const methods = ['post', 'get'] as const
141 for (const method of methods) {
142 const operation = operations[method]
143 if (!operation) continue
144 if (method === 'get' && provider.classifyGets !== true) continue
145 const activity = provider.classify(pathKey, operation)
146 if (activity === null) continue
147​
148 const extracted = extractEndpointSchemas(
149 spec,
150 pathKey,
151 fetched.outputStrategy,
152 method,
153 )
154 warnings.push(...extracted.warnings)
155 for (const [kind, schema] of [
156 ['input', extracted.input],
157 ['output', extracted.output],
158 ] as const) {
159 if (schema && findDanglingRefs(schema).length > 0) {
160 warnings.push(
161 `${provider.id}${pathKey}: bundled ${kind} schema has dangling refs`,
162 )
163 }
164 }
165 if (
166 !extracted.input &&
167 !extracted.output &&
168 operation['x-modelschemas-route-only'] !== true
169 )
170 continue
171​
172 const description =
173 typeof operation.summary === 'string'
174 ? operation.summary
175 : typeof operation.description === 'string'
176 ? operation.description
177 : null
178 const { derivation, verifiedAt } = readProvenance(operation, provider)
179 classified.push({
180 dbId: `${provider.id}/${endpointIdFromPath(pathKey)}`,
181 path: pathKey,
182 method: method === 'get' ? 'GET' : 'POST',
183 activity,
184 description,
185 source,
186 derivation,
187 verifiedAt,
188 input: extracted.input,
189 output: extracted.output,
190 })
191 }
192 }
193 }
194 for (const extra of fetched.bundledEndpoints ?? []) {
195 if (!extra.input && !extra.output) continue
196 classified.push(classifiedFromBundled(provider.id, extra, warnings))
197 }
198 return { endpoints: classified, warnings }
200​
201function asBundledSchema(
202 schema: Record<string, unknown> | undefined,
203): Record<string, JsonValue> | undefined {
204 return schema as Record<string, JsonValue> | undefined
206​
207function classifiedFromBundled(
208 providerId: string,
209 extra: BundledEndpoint,
210 warnings: Array<string>,
211): ClassifiedEndpoint {
212 const input = asBundledSchema(extra.input)
213 const output = asBundledSchema(extra.output)
214 const pathKey = extra.path
215 for (const [kind, schema] of [
216 ['input', input],
217 ['output', output],
218 ] as const) {
219 if (schema && findDanglingRefs(schema).length > 0) {
220 warnings.push(
221 `${providerId}${pathKey}: bundled ${kind} schema has dangling refs`,
222 )
223 }
224 }
225 return {
226 dbId: `${providerId}/${extra.publicId ?? endpointIdFromPath(pathKey)}`,
227 path: pathKey,
228 method: 'POST',
229 activity: extra.activity,
230 description: extra.description,
231 source: extra.source,
232 derivation: extra.derivation,
233 verifiedAt: extra.verifiedAt ?? null,
234 input,
235 output,
236 asyncapi: extra.asyncapi,
237 }
239​
240async function applyAsyncApiCatalogFlags(
241 db: Db,
242 providerId: string,
243 asyncApiRawIds: Array<string>,
244): Promise<void> {
245 const flagged = new Set(asyncApiRawIds)
246 const rows = await db
247 .select()
248 .from(models)
249 .where(eq(models.providerId, providerId))
250 for (const row of rows) {
251 const want = flagged.has(row.rawId)
252 const has = hasAsyncApiFlag(row.capabilities)
253 if (want === has) continue
254 await db
255 .update(models)
256 .set({ capabilities: withAsyncApiFlag(row.capabilities, want) })
257 .where(eq(models.id, row.id))
258 }
260​
261/** Sync one provider. Throws only on programmer error — upstream/storage
262 * failures surface in the outcome's `error` via syncAllProviders. */
263/**
264 * Upsert the provider's row from its registry config: refreshes the seeded
265 * config columns, preserves runtime state (lastPolledAt/lastSyncedAt/status).
266 * Same provider row as `scripts/seed.ts`, plus the provider's namespaces
267 * (which only this writes), run automatically so a newly
268 * registered provider self-heals into the DB on its first sync/poll instead
269 * of waiting on a manual seed against prod.
270 */
271export async function ensureProviderRow(
272 db: Db,
273 provider: ProviderConfig,
274): Promise<void> {
275 const seed = seedForProvider(provider)
276 if (seed === null) return
277 const namespaces = provider.modelNamespaces ?? []
278 // One batch: the namespace table mirrors config (a dropped name stops
279 // resolving) without a second round trip on every poll.
280 await db.batch([
281 db
282 .insert(providers)
283 .values(seed)
284 .onConflictDoUpdate({
285 target: providers.id,
286 set: {
287 displayName: seed.displayName,
288 specSourceUrl: seed.specSourceUrl,
289 modelsEndpoint: seed.modelsEndpoint ?? null,
290 authEnvVar: seed.authEnvVar ?? null,
291 },
292 }),
293 db
294 .delete(providerModelNamespaces)
295 .where(
296 and(
297 eq(providerModelNamespaces.providerId, seed.id),
298 notInArray(providerModelNamespaces.namespace, namespaces),
299 ),
300 ),
301 ...(namespaces.length
302 ? [
303 db
304 .insert(providerModelNamespaces)
305 .values(
306 namespaces.map((namespace) => ({
307 namespace,
308 providerId: seed.id,
309 })),
310 )
311 .onConflictDoNothing(),
312 ]
313 : []),
314 ])
316​
317/** Composite map key for an endpoint's current version of one kind. */
318function versionKey(endpointId: string, kind: 'input' | 'output'): string {
319 return `${endpointId}\u0000${kind}`
321​
322export async function syncProvider(
323 deps: SyncDeps,
324 provider: ProviderConfig,
325): Promise<SyncOutcome> {
326 const { db, kv, secrets } = deps
327 const now = deps.now?.() ?? Math.floor(Date.now() / 1000)
328 const outcome: SyncOutcome = {
329 providerId: provider.id,
330 endpointsSeen: 0,
331 versionsAdded: 0,
332 changesWritten: 0,
333 warnings: [],
334 }
335 await ensureProviderRow(db, provider)
336 await dropModelsDevSchemaVersions(db, provider.id)
337​
338 const fetched = await provider.fetchSpec(secrets)
339 if (fetched.withdrawnSchemaSources?.length) {
340 const withdrawn = await db
341 .select({ id: schemaVersions.id })
342 .from(schemaVersions)
343 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
344 .where(
345 and(
346 eq(endpoints.providerId, provider.id),
347 isNull(schemaVersions.supersededAt),
348 inArray(schemaVersions.sourceUrl, fetched.withdrawnSchemaSources),
349 ),
350 )
351 for (let i = 0; i < withdrawn.length; i += 90) {
352 await db
353 .update(schemaVersions)
354 .set({ supersededAt: now })
355 .where(
356 inArray(
357 schemaVersions.id,
358 withdrawn.slice(i, i + 90).map((row) => row.id),
359 ),
360 )
361 }
362 if (withdrawn.length)
363 outcome.warnings.push(
364 `Withdrew ${withdrawn.length} schema versions from rejected former sources`,
365 )
366 }
367 if (fetched.warnings) outcome.warnings.push(...fetched.warnings)
368 if (fetched.skipped) {
369 outcome.skipped = fetched.skipped
370 outcome.warnings.push(fetched.skipped)
371 // Any skip other than the missing-secret suffix is by design, so the
372 // provider is active again. `lastSyncedAt` is written only on the
373 // non-skip path below.
374 if (!isMissingSecretSkip(fetched.skipped)) {
375 await db
376 .update(providers)
377 .set({ status: 'active' })
378 .where(eq(providers.id, provider.id))
379 }
380 return outcome
381 }
382​
383 const { endpoints: classified, warnings } = classifyAndBundle(
384 provider,
385 fetched,
386 )
387 outcome.warnings.push(...warnings)
388 outcome.endpointsSeen = classified.length
389​
390 const existingEndpoints = await db
391 .select()
392 .from(endpoints)
393 .where(eq(endpoints.providerId, provider.id))
394 const existingById = new Map(existingEndpoints.map((e) => [e.id, e]))
395​
396 // Current (non-superseded) versions for the whole provider in one query.
397 // Per-endpoint lookups here are 2 D1 round trips per endpoint — FAL alone
398 // has ~1,400 endpoints, which blows the invocation's 1,000-subrequest
399 // budget (and its wall clock) before the sync can complete, leaving the
400 // provider stuck degraded. Same batching treatment as poll-models.
401 const currentVersionRows = await db
402 .select({
403 id: schemaVersions.id,
404 endpointId: schemaVersions.endpointId,
405 kind: schemaVersions.kind,
406 contentHash: schemaVersions.contentHash,
407 })
408 .from(schemaVersions)
409 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
410 .where(
411 and(
412 eq(endpoints.providerId, provider.id),
413 isNull(schemaVersions.supersededAt),
414 ),
415 )
416 const currentByEndpointKind = new Map(
417 currentVersionRows.map((v) => [versionKey(v.endpointId, v.kind), v]),
418 )
419​
420 for (const endpoint of classified) {
421 const existing = existingById.get(endpoint.dbId)
422 if (!existing) {
423 // The row and its change in one batch: a run that dies between them
424 // would otherwise leave an endpoint whose `endpoint.added` is never
425 // written, since later runs find the row and skip it.
426 await db.batch([
427 db.insert(endpoints).values({
428 id: endpoint.dbId,
429 providerId: provider.id,
430 activity: endpoint.activity,
431 method: endpoint.method,
432 path: endpoint.path,
433 description: endpoint.description,
434 }),
435 db.insert(changes).values({
436 id: newChangeId(),
437 type: 'endpoint.added',
438 providerId: provider.id,
439 subjectId: endpoint.dbId,
440 summary: `Endpoint ${endpoint.path} added (${endpoint.activity})`,
441 createdAt: now,
442 }),
443 ])
444 outcome.changesWritten++
445 } else if (
446 existing.activity !== endpoint.activity ||
447 existing.description !== endpoint.description
448 ) {
449 await db
450 .update(endpoints)
451 .set({
452 activity: endpoint.activity,
453 description: endpoint.description,
454 })
455 .where(eq(endpoints.id, endpoint.dbId))
456 }
457​
458 for (const [kind, schema] of [
459 ['input', endpoint.input],
460 ['output', endpoint.output],
461 ] as const) {
462 if (!schema) continue
463 const hash = await contentHash(schema)
464 const current = currentByEndpointKind.get(versionKey(endpoint.dbId, kind))
465 if (current?.contentHash === hash) continue
466​
467 // The id is deterministic on content, so when upstream reverts to a
468 // previously served schema (A → B → A) the row already exists as a
469 // superseded version — revive it instead of colliding on the insert.
470 const insert = db
471 .insert(schemaVersions)
472 .values({
473 id: `${endpoint.dbId}:${kind}:${hash.slice(0, 16)}`,
474 endpointId: endpoint.dbId,
475 kind,
476 contentHash: hash,
477 schema: JSON.stringify(schema),
478 specRevision: fetched.specRevision ?? null,
479 sourceUrl: endpoint.source?.url ?? null,
480 sourceHash: endpoint.source?.hash ?? null,
481 extractorVersion: EXTRACTOR_VERSION,
482 derivation: endpoint.derivation,
483 verifiedAt: endpoint.verifiedAt,
484 createdAt: now,
485 })
486 .onConflictDoUpdate({
487 target: schemaVersions.id,
488 set: {
489 supersededAt: null,
490 specRevision: fetched.specRevision ?? null,
491 sourceUrl: endpoint.source?.url ?? null,
492 sourceHash: endpoint.source?.hash ?? null,
493 extractorVersion: EXTRACTOR_VERSION,
494 derivation: endpoint.derivation,
495 verifiedAt: endpoint.verifiedAt,
496 createdAt: now,
497 },
498 })
499 const change = db.insert(changes).values({
500 id: newChangeId(),
501 type: current ? 'schema.updated' : 'schema.added',
502 providerId: provider.id,
503 subjectId: endpoint.dbId,
504 summary: `${current ? 'Updated' : 'Added'} ${kind} schema for ${endpoint.path}`,
505 payload: {
506 kind,
507 contentHash: hash,
508 previousHash: current?.contentHash ?? null,
509 },
510 createdAt: now,
511 })
512 // Content-addressed, so a blob left by a failed batch is unreferenced,
513 // never wrong.
514 await putJson(kv, schemaKey(hash), schema)
515 // One batch, so a run that dies here never leaves two current rows,
516 // nor a current row with no change, which no later run would write:
517 // the next run finds the hash current and skips it.
518 if (current) {
519 await db.batch([
520 db
521 .update(schemaVersions)
522 .set({ supersededAt: now })
523 .where(eq(schemaVersions.id, current.id)),
524 insert,
525 change,
526 ])
527 } else {
528 await db.batch([insert, change])
529 }
530 outcome.versionsAdded++
531 outcome.changesWritten++
532 }
533 }
534​
535 // Endpoints in D1 that vanished from the spec: record the removal but keep
536 // the rows — schema version history stays queryable. The already-recorded
537 // set loads in one query: vanished endpoints accumulate for good (rows are
538 // kept), so per-endpoint lookups would cost one subrequest each, forever.
539 const seenIds = new Set(classified.map((e) => e.dbId))
540 const removalRows = await db
541 .select({ subjectId: changes.subjectId })
542 .from(changes)
543 .where(
544 and(
545 eq(changes.type, 'endpoint.removed'),
546 eq(changes.providerId, provider.id),
547 ),
548 )
549 const alreadyRemovedIds = new Set(removalRows.map((r) => r.subjectId))
550 for (const existing of existingEndpoints) {
551 if (seenIds.has(existing.id)) continue
552 if (alreadyRemovedIds.has(existing.id)) continue
553 await db.insert(changes).values({
554 id: newChangeId(),
555 type: 'endpoint.removed',
556 providerId: provider.id,
557 subjectId: existing.id,
558 summary: `Endpoint ${existing.path} removed from the ${provider.id} spec`,
559 createdAt: now,
560 })
561 outcome.changesWritten++
562 }
563​
564 if (fetched.asyncApiRawIds !== undefined) {
565 await applyAsyncApiCatalogFlags(db, provider.id, fetched.asyncApiRawIds)
566 }
567​
568 await db
569 .update(providers)
570 .set({ lastSyncedAt: now, status: 'active' })
571 .where(eq(providers.id, provider.id))
572​
573 return outcome
575​
576/**
577 * Spec-sync shard schedule: each cron fires its own Worker invocation with
578 * a fresh subrequest/CPU/memory budget, so one provider's blowup can't
579 * starve the providers behind it (production data: FAL's oversized sync
580 * killed the shared 05:00 run mid-flight daily, leaving every provider
581 * after it in the registry permanently unsynced). Shard 0 is FAL alone —
582 * by far the largest (~1,400 per-model specs); the rest of the registry
583 * round-robins across the remaining shards, which also spreads the other
584 * big-spec providers (they're adjacent in the registry). Keep this array
585 * in lockstep with `triggers.crons` in wrangler.jsonc.
586 */
587export const SPEC_SYNC_SHARD_CRONS = [
588 '0 5 * * *',
589 '10 5 * * *',
590 '20 5 * * *',
591 '30 5 * * *',
592] as const
593​
594export function specSyncShard(shardIndex: number): Array<ProviderConfig> {
595 const rest = providerRegistry.filter((p) => p.id !== 'fal')
596 if (shardIndex === 0) return providerRegistry.filter((p) => p.id === 'fal')
597 const restShards = SPEC_SYNC_SHARD_CRONS.length - 1
598 return rest.filter((_, i) => i % restShards === shardIndex - 1)
600​
601/**
602 * Sync the given providers (default: the full registry), sequentially
603 * (subrequest limits), with per-provider isolation: one provider's outage
604 * doesn't sink the run.
605 */
606export async function syncAllProviders(
607 deps: SyncDeps,
608 providersToSync: Array<ProviderConfig> = providerRegistry,
609): Promise<Array<SyncOutcome>> {
610 const outcomes: Array<SyncOutcome> = []
611 for (const provider of providersToSync) {
612 await runIngestScope(async () => {
613 try {
614 outcomes.push(await syncProvider(deps, provider))
615 } catch (error) {
616 const message = errorMessage(error)
617 // Own log line per failure: the aggregate outcomes blob can exceed
618 // what Workers Logs stores, which silently loses these errors.
619 console.error(
620 JSON.stringify({
621 job: 'spec-sync',
622 providerId: provider.id,
623 error: message,
624 }),
625 )
626 noteIngest(ingestFailedEvent('spec-sync', provider.id, message))
627 outcomes.push({
628 providerId: provider.id,
629 endpointsSeen: 0,
630 versionsAdded: 0,
631 changesWritten: 0,
632 error: message,
633 warnings: [],
634 })
635 try {
636 await deps.db
637 .update(providers)
638 .set({ status: 'degraded' })
639 .where(eq(providers.id, provider.id))
640 } catch (statusError) {
641 // Best-effort: if the failure was resource exhaustion (subrequest
642 // budget), this write fails too — don't let it sink the run.
643 console.error(
644 JSON.stringify({
645 job: 'spec-sync',
646 providerId: provider.id,
647 error: `degraded-status write failed: ${errorMessage(statusError)}`,
648 }),
649 )
650 noteIngest(
651 ingestFailedEvent(
652 'spec-sync',
653 provider.id,
654 `degraded-status write failed: ${errorMessage(statusError)}`,
655 ),
656 )
657 }
658 } finally {
659 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
660 }
661 })
662 }
663 return outcomes