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

sync.ts

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