Open History to see the last commit
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
66}
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>
76}
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
109}
110
111function newChangeId(): string {
112 return crypto.randomUUID()
113}
114
115const DERIVATIONS: ReadonlyArray<Derivation> = [
116 'upstream-spec',
117 'generated',
118 'probe-verified',
119 'docs-derived',
120]
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}`
139}
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 }
161}
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 }
253}
254
255function asBundledSchema(
256 schema: Record<string, unknown> | undefined,
257): Record<string, JsonValue> | undefined {
258 return schema as Record<string, JsonValue> | undefined
259}
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 }
294}
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
300}
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
308}
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 )
319}
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 }
340}
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 * and maker declaration
349 * (which only this writes), run automatically so a newly
350 * registered provider self-heals into the DB on its first sync/poll instead
351 * of waiting on a manual seed against prod.
352 */
353export async function ensureProviderRow(
354 db: Db,
355 provider: ProviderConfig,
356): Promise<void> {
357 const listed = seedForProvider(provider)
358 if (listed === null) return
359 const seed = { ...listed, makesOwnModels: provider.makesOwnModels === true }
360 const namespaces = provider.modelNamespaces ?? []
361 // One batch: the namespace table mirrors config (a dropped name stops
362 // resolving) without a second round trip on every poll.
363 await db.batch([
364 db
365 .insert(providers)
366 .values(seed)
367 .onConflictDoUpdate({
368 target: providers.id,
369 set: {
370 displayName: seed.displayName,
371 specSourceUrl: seed.specSourceUrl,
372 modelsEndpoint: seed.modelsEndpoint ?? null,
373 authEnvVar: seed.authEnvVar ?? null,
374 makesOwnModels: seed.makesOwnModels,
375 },
376 }),
377 db
378 .delete(providerModelNamespaces)
379 .where(
380 and(
381 eq(providerModelNamespaces.providerId, seed.id),
382 notInArray(providerModelNamespaces.namespace, namespaces),
383 ),
384 ),
385 ...(namespaces.length
386 ? [
387 db
388 .insert(providerModelNamespaces)
389 .values(
390 namespaces.map((namespace) => ({
391 namespace,
392 providerId: seed.id,
393 })),
394 )
395 .onConflictDoNothing(),
396 ]
397 : []),
398 ])
399}
400
401/** Composite map key for an endpoint's current version of one kind. */
402function versionKey(
403 endpointId: string,
404 kind: 'input' | 'output' | 'stream',
405): string {
406 return `${endpointId}\u0000${kind}`
407}
408
409export async function syncProvider(
410 deps: SyncDeps,
411 provider: ProviderConfig,
412): Promise<SyncOutcome> {
413 const { db, secrets } = deps
414 const now = deps.now?.() ?? Math.floor(Date.now() / 1000)
415 const outcome: SyncOutcome = {
416 providerId: provider.id,
417 endpointsSeen: 0,
418 versionsAdded: 0,
419 changesWritten: 0,
420 warnings: [],
421 }
422 await ensureProviderRow(db, provider)
423 await dropModelsDevSchemaVersions(db, provider.id)
424
425 const fetched = await provider.fetchSpec(secrets)
426 if (fetched.withdrawnSchemaSources?.length) {
427 const withdrawn = await db
428 .select({ id: schemaVersions.id })
429 .from(schemaVersions)
430 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
431 .where(
432 and(
433 eq(endpoints.providerId, provider.id),
434 isNull(schemaVersions.supersededAt),
435 inArray(schemaVersions.sourceUrl, fetched.withdrawnSchemaSources),
436 ),
437 )
438 for (let i = 0; i < withdrawn.length; i += 90) {
439 await db
440 .update(schemaVersions)
441 .set({ supersededAt: now })
442 .where(
443 inArray(
444 schemaVersions.id,
445 withdrawn.slice(i, i + 90).map((row) => row.id),
446 ),
447 )
448 }
449 if (withdrawn.length)
450 outcome.warnings.push(
451 `Withdrew ${withdrawn.length} schema versions from rejected former sources`,
452 )
453 }
454 if (fetched.warnings) outcome.warnings.push(...fetched.warnings)
455 if (fetched.skipped) {
456 outcome.skipped = fetched.skipped
457 outcome.warnings.push(fetched.skipped)
458 // Any skip other than the missing-secret suffix is by design, so the
459 // provider is active again. `lastSyncedAt` is written only on the
460 // non-skip path below.
461 if (!isMissingSecretSkip(fetched.skipped)) {
462 await db
463 .update(providers)
464 .set({ status: 'active' })
465 .where(eq(providers.id, provider.id))
466 }
467 return outcome
468 }
469
470 const { endpoints: classified, warnings } = classifyAndBundle(
471 provider,
472 fetched,
473 )
474 outcome.warnings.push(...warnings)
475 outcome.endpointsSeen = classified.length
476
477 const existingEndpoints = await db
478 .select()
479 .from(endpoints)
480 .where(eq(endpoints.providerId, provider.id))
481 const existingById = new Map(existingEndpoints.map((e) => [e.id, e]))
482
483 // Current (non-superseded) versions for the whole provider in one query.
484 // Per-endpoint lookups here are 2 D1 round trips per endpoint — FAL alone
485 // has ~1,400 endpoints, which blows the invocation's 1,000-subrequest
486 // budget (and its wall clock) before the sync can complete, leaving the
487 // provider stuck degraded. Same batching treatment as poll-models.
488 const currentVersionRows = await db
489 .select({
490 id: schemaVersions.id,
491 endpointId: schemaVersions.endpointId,
492 kind: schemaVersions.kind,
493 contentHash: schemaVersions.contentHash,
494 })
495 .from(schemaVersions)
496 .innerJoin(endpoints, eq(schemaVersions.endpointId, endpoints.id))
497 .where(
498 and(
499 eq(endpoints.providerId, provider.id),
500 isNull(schemaVersions.supersededAt),
501 ),
502 )
503 const currentByEndpointKind = new Map(
504 currentVersionRows.map((v) => [versionKey(v.endpointId, v.kind), v]),
505 )
506
507 for (const endpoint of classified) {
508 const existing = existingById.get(endpoint.dbId)
509 if (!existing) {
510 // The row and its change in one batch: a run that dies between them
511 // would otherwise leave an endpoint whose `endpoint.added` is never
512 // written, since later runs find the row and skip it.
513 await db.batch([
514 db.insert(endpoints).values({
515 id: endpoint.dbId,
516 providerId: provider.id,
517 activity: endpoint.activity,
518 method: endpoint.method,
519 path: endpoint.path,
520 description: endpoint.description,
521 requestContentType: endpoint.requestContentType,
522 responseContentTypes: endpoint.responseContentTypes,
523 }),
524 db.insert(changes).values({
525 id: newChangeId(),
526 type: 'endpoint.added',
527 providerId: provider.id,
528 subjectId: endpoint.dbId,
529 summary: `Endpoint ${endpoint.path} added (${endpoint.activity})`,
530 createdAt: now,
531 }),
532 ])
533 outcome.changesWritten++
534 } else if (
535 existing.activity !== endpoint.activity ||
536 existing.method !== endpoint.method ||
537 existing.description !== endpoint.description ||
538 existing.requestContentType !== endpoint.requestContentType ||
539 !sameContentTypes(
540 existing.responseContentTypes,
541 endpoint.responseContentTypes,
542 )
543 ) {
544 await db
545 .update(endpoints)
546 .set({
547 activity: endpoint.activity,
548 method: endpoint.method,
549 description: endpoint.description,
550 requestContentType: endpoint.requestContentType,
551 responseContentTypes: endpoint.responseContentTypes,
552 })
553 .where(eq(endpoints.id, endpoint.dbId))
554 }
555
556 for (const [kind, schema, announce] of [
557 ['input', endpoint.input, true],
558 ['output', endpoint.output, true],
559 ['stream', endpoint.streamOutput, false],
560 ] as const) {
561 if (!schema) continue
562 const hash = await contentHash(schema)
563 const current = currentByEndpointKind.get(versionKey(endpoint.dbId, kind))
564 if (current?.contentHash === hash) continue
565
566 // The id is deterministic on content, so when upstream reverts to a
567 // previously served schema (A → B → A) the row already exists as a
568 // superseded version — revive it instead of colliding on the insert.
569 const insert = db
570 .insert(schemaVersions)
571 .values({
572 id: `${endpoint.dbId}:${kind}:${hash.slice(0, 16)}`,
573 endpointId: endpoint.dbId,
574 kind,
575 contentHash: hash,
576 schema: JSON.stringify(schema),
577 specRevision: fetched.specRevision ?? null,
578 sourceUrl: endpoint.source?.url ?? null,
579 sourceHash: endpoint.source?.hash ?? null,
580 extractorVersion: EXTRACTOR_VERSION,
581 derivation: endpoint.derivation,
582 verifiedAt: endpoint.verifiedAt,
583 createdAt: now,
584 })
585 .onConflictDoUpdate({
586 target: schemaVersions.id,
587 set: {
588 supersededAt: null,
589 specRevision: fetched.specRevision ?? null,
590 sourceUrl: endpoint.source?.url ?? null,
591 sourceHash: endpoint.source?.hash ?? null,
592 extractorVersion: EXTRACTOR_VERSION,
593 derivation: endpoint.derivation,
594 verifiedAt: endpoint.verifiedAt,
595 createdAt: now,
596 },
597 })
598 // One batch, so a run that dies here never leaves two current rows.
599 // `stream` is not a public schema kind: the generation document reads
600 // the row, and the changes feed stays `input` | `output`.
601 const supersede = current
602 ? db
603 .update(schemaVersions)
604 .set({ supersededAt: now })
605 .where(eq(schemaVersions.id, current.id))
606 : null
607 if (announce) {
608 const change = db.insert(changes).values({
609 id: newChangeId(),
610 type: current ? 'schema.updated' : 'schema.added',
611 providerId: provider.id,
612 subjectId: endpoint.dbId,
613 summary: `${current ? 'Updated' : 'Added'} ${kind} schema for ${endpoint.path}`,
614 payload: {
615 kind,
616 contentHash: hash,
617 previousHash: current?.contentHash ?? null,
618 },
619 createdAt: now,
620 })
621 if (supersede) await db.batch([supersede, insert, change])
622 else await db.batch([insert, change])
623 outcome.changesWritten++
624 } else if (supersede) {
625 await db.batch([supersede, insert])
626 } else {
627 await insert
628 }
629 outcome.versionsAdded++
630 }
631 }
632
633 // Endpoints in D1 that vanished from the spec: record the removal but keep
634 // the rows — schema version history stays queryable. The already-recorded
635 // set loads in one query: vanished endpoints accumulate for good (rows are
636 // kept), so per-endpoint lookups would cost one subrequest each, forever.
637 const seenIds = new Set(classified.map((e) => e.dbId))
638 const removalRows = await db
639 .select({ subjectId: changes.subjectId })
640 .from(changes)
641 .where(
642 and(
643 eq(changes.type, 'endpoint.removed'),
644 eq(changes.providerId, provider.id),
645 ),
646 )
647 const alreadyRemovedIds = new Set(removalRows.map((r) => r.subjectId))
648 for (const existing of existingEndpoints) {
649 if (seenIds.has(existing.id)) continue
650 if (alreadyRemovedIds.has(existing.id)) continue
651 await db.insert(changes).values({
652 id: newChangeId(),
653 type: 'endpoint.removed',
654 providerId: provider.id,
655 subjectId: existing.id,
656 summary: `Endpoint ${existing.path} removed from the ${provider.id} spec`,
657 createdAt: now,
658 })
659 outcome.changesWritten++
660 }
661
662 if (fetched.asyncApiRawIds !== undefined) {
663 await applyAsyncApiCatalogFlags(db, provider.id, fetched.asyncApiRawIds)
664 }
665
666 await db
667 .update(providers)
668 .set({ lastSyncedAt: now, status: 'active' })
669 .where(eq(providers.id, provider.id))
670
671 return outcome
672}
673
674/**
675 * Spec-sync shard schedule: each cron fires its own Worker invocation with
676 * a fresh subrequest/CPU/memory budget, so one provider's blowup can't
677 * starve the providers behind it (production data: FAL's oversized sync
678 * killed the shared 05:00 run mid-flight daily, leaving every provider
679 * after it in the registry permanently unsynced). Shard 0 is FAL alone —
680 * by far the largest (~1,400 per-model specs); the rest of the registry
681 * round-robins across the remaining shards, which also spreads the other
682 * big-spec providers (they're adjacent in the registry). Keep this array
683 * in lockstep with `triggers.crons` in wrangler.jsonc.
684 */
685export const SPEC_SYNC_SHARD_CRONS = [
686 '0 5 * * *',
687 '10 5 * * *',
688 '20 5 * * *',
689 '30 5 * * *',
690] as const
691
692export function specSyncShard(shardIndex: number): Array<ProviderConfig> {
693 const rest = providerRegistry.filter((p) => p.id !== 'fal')
694 if (shardIndex === 0) return providerRegistry.filter((p) => p.id === 'fal')
695 const restShards = SPEC_SYNC_SHARD_CRONS.length - 1
696 return rest.filter((_, i) => i % restShards === shardIndex - 1)
697}
698
699/**
700 * Best-effort. A spent D1 window fails this write the same way the sync
701 * failed; the caller waits that window out before calling it. A failure
702 * here must not sink the rest of the shard.
703 */
704async function markProviderDegraded(
705 deps: SyncDeps,
706 providerId: string,
707): Promise<void> {
708 try {
709 await deps.db
710 .update(providers)
711 .set({ status: 'degraded' })
712 .where(eq(providers.id, providerId))
713 } catch (statusError) {
714 const message = `degraded-status write failed: ${errorMessage(statusError)}`
715 console.error(
716 JSON.stringify({ job: 'spec-sync', providerId, error: message }),
717 )
718 noteIngest(ingestFailedEvent('spec-sync', providerId, message))
719 }
720}
721
722/**
723 * Sync the given providers (default: the full registry), sequentially
724 * (subrequest limits), with per-provider isolation: one provider's outage
725 * doesn't sink the run. A spent D1 window is retried once after
726 * `D1_WINDOW_WAIT_MS` (issue #635). A second one still fails, and the
727 * degraded write waits out that window so it is not lost on the same overload.
728 */
729export async function syncAllProviders(
730 deps: SyncDeps,
731 providersToSync: Array<ProviderConfig> = providerRegistry,
732 wait: (ms: number) => Promise<void> = sleep,
733): Promise<Array<SyncOutcome>> {
734 const outcomes: Array<SyncOutcome> = []
735 for (const provider of providersToSync) {
736 const exhausted = await runIngestScope(async () => {
737 try {
738 outcomes.push(
739 await retryOnceAfterD1Window(
740 'spec-sync',
741 provider.id,
742 () => syncProvider(deps, provider),
743 wait,
744 ),
745 )
746 return false
747 } catch (error) {
748 const message = errorMessage(error)
749 // Own log line per failure: the aggregate outcomes blob can exceed
750 // what Workers Logs stores, which silently loses these errors.
751 console.error(
752 JSON.stringify({
753 job: 'spec-sync',
754 providerId: provider.id,
755 error: message,
756 }),
757 )
758 noteIngest(ingestFailedEvent('spec-sync', provider.id, message))
759 outcomes.push({
760 providerId: provider.id,
761 endpointsSeen: 0,
762 versionsAdded: 0,
763 changesWritten: 0,
764 error: message,
765 warnings: [],
766 })
767 const spent = d1WindowExhausted(message)
768 // A non-window failure can write status now. A spent window cannot:
769 // that write failed in production on the same overload (issue #635).
770 if (!spent) await markProviderDegraded(deps, provider.id)
771 return spent
772 } finally {
773 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
774 }
775 })
776 if (exhausted) {
777 await wait(D1_WINDOW_WAIT_MS)
778 await runIngestScope(async () => {
779 try {
780 await markProviderDegraded(deps, provider.id)
781 } finally {
782 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
783 }
784 })
785 }
786 }
787 return outcomes
788}