Open History to see the last commit
1/**
2 * The durable trace of a docs source that keeps failing. A docs failure no
3 * longer fails the poll, so `lastPolledAt` keeps moving and each poll's log
4 * line says nothing of the ones before it. One `cache_meta` row per
5 * provider, `docs-failing:<providerId>`, records when the failures began
6 * and how many polls they have lasted. It is deleted by the first poll
7 * that reports no docs failures, including one that omits `docsFailures`
8 * because the adapter no longer loads docs. A skipped listing leaves it.
9 * Read it with:
10 *
11 * select key, fetched_at, last_error from cache_meta
12 * where key like 'docs-failing:%'
13 *
14 * `fetched_at` is the first failing poll; `last_error` is a `DocsFailing`.
15 *
16 * A refused mass price clear (`refusesPriceClears`) keeps the same kind of
17 * row, `price-clears-refused:<providerId>`, holding a `PriceClearsRefused`.
18 * An update storm (`update-storm:<providerId>`) holds an `UpdateStorm`
19 * when one poll writes `model.updated` for more than half of the live
20 * rows, and at least 20. The updates are still written; the row only
21 * marks them. `GET /v1/status` serves all three (`readIngestRecords`).
22 */
23import { eq, like, or } from 'drizzle-orm'
24
25import type { Db } from '#/db/index.ts'
26import { cacheMeta } from '#/db/schema.ts'
27import type { DocsFailures } from '#/server/providers/types.ts'
28
29export interface DocsFailing {
30 /** Epoch seconds of the first poll in this unbroken run of failures. */
31 since: number
32 /** Consecutive polls with a docs failure, this one included. */
33 polls: number
34 lastAt: number
35 failed: number
36 skipped: number
37 /** The first few failing documents of the latest poll. */
38 sources: Array<string>
39 /** The latest poll's first error. */
40 error: string
41}
42
43export interface PriceClearsRefused {
44 /** Epoch seconds of the first poll in this unbroken run of refusals. */
45 since: number
46 /** Consecutive polls that refused, this one included. */
47 polls: number
48 lastAt: number
49 /** Stored prices the latest poll asked to clear; none was cleared. */
50 refused: number
51 /** Listed rows holding a stored price at that poll. */
52 priced: number
53}
54
55/**
56 * One poll updated more than half of the provider's live rows, and at
57 * least 20. The events are written. The next poll under that line deletes
58 * the row.
59 */
60export interface UpdateStorm {
61 /** Epoch seconds of the first poll in this unbroken run of storms. */
62 since: number
63 /** Consecutive storming polls, this one included. */
64 polls: number
65 lastAt: number
66 /** `model.updated` rows written by the latest poll. */
67 updated: number
68 /** Live rows (not deprecated) at the start of that poll. */
69 live: number
70}
71
72/** The three records of one provider, as `GET /v1/status` serves them. */
73export interface IngestRecords {
74 docsFailing?: DocsFailing
75 priceClearsRefused?: PriceClearsRefused
76 updateStorm?: UpdateStorm
77}
78
79const DOCS = 'docs-failing:'
80const CLEARS = 'price-clears-refused:'
81const STORM = 'update-storm:'
82
83/** More than half of the live rows, and at least this many updates. */
84const STORM_MIN = 20
85
86/**
87 * A poll that rewrites most of a catalog. Null under the line, including
88 * a provider with fewer than 20 live rows.
89 */
90export function updateStormOf(
91 updated: number,
92 live: number,
93): { updated: number; live: number } | null {
94 if (updated < STORM_MIN || updated * 2 <= live) return null
95 return { updated, live }
96}
97
98/** An upstream error can quote a whole HTML page. */
99const ERROR_MAX = 500
100
101function key(providerId: string): string {
102 return `${DOCS}${providerId}`
103}
104
105/**
106 * A row that is not ours to read counts as no record: the next failing
107 * poll overwrites it, the next healthy one deletes it.
108 */
109function parse<T extends { since: number; polls: number }>(
110 text: string | null | undefined,
111 list?: 'sources',
112): T | null {
113 if (!text) return null
114 try {
115 const value = JSON.parse(text) as Partial<Record<string, unknown>> | null
116 if (typeof value?.since !== 'number' || typeof value.polls !== 'number') {
117 return null
118 }
119 if (list && !Array.isArray(value[list])) return null
120 return value as T
121 } catch {
122 return null
123 }
124}
125
126/** Every provider's records in one statement, keyed by provider id. */
127export async function readIngestRecords(
128 db: Db,
129): Promise<Map<string, IngestRecords>> {
130 const rows = await db
131 .select({ key: cacheMeta.key, lastError: cacheMeta.lastError })
132 .from(cacheMeta)
133 .where(
134 or(
135 like(cacheMeta.key, `${DOCS}%`),
136 like(cacheMeta.key, `${CLEARS}%`),
137 like(cacheMeta.key, `${STORM}%`),
138 ),
139 )
140 const byProvider = new Map<string, IngestRecords>()
141 const entry = (providerId: string) => {
142 const records = byProvider.get(providerId) ?? {}
143 byProvider.set(providerId, records)
144 return records
145 }
146 for (const row of rows) {
147 if (row.key.startsWith(DOCS)) {
148 const record = parse<DocsFailing>(row.lastError, 'sources')
149 if (record) entry(row.key.slice(DOCS.length)).docsFailing = record
150 } else if (row.key.startsWith(CLEARS)) {
151 const record = parse<PriceClearsRefused>(row.lastError)
152 if (record) {
153 entry(row.key.slice(CLEARS.length)).priceClearsRefused = record
154 }
155 } else if (row.key.startsWith(STORM)) {
156 const record = parse<UpdateStorm>(row.lastError)
157 if (record && typeof record.updated === 'number') {
158 entry(row.key.slice(STORM.length)).updateStorm = record
159 }
160 }
161 }
162 return byProvider
163}
164
165export async function readDocsFailing(
166 db: Db,
167 providerId: string,
168): Promise<DocsFailing | null> {
169 const row = await db.query.cacheMeta.findFirst({
170 where: eq(cacheMeta.key, key(providerId)),
171 })
172 return parse<DocsFailing>(row?.lastError, 'sources')
173}
174
175/**
176 * Write or extend the provider's refused-clears record, or delete it when
177 * this poll refused nothing. The record describes the poll; it must never
178 * be what fails it, so a failed write is logged and swallowed.
179 */
180export async function recordPriceClearsRefused(
181 db: Db,
182 providerId: string,
183 refused: { clears: number; priced: number } | null,
184 now: number,
185): Promise<void> {
186 const rowKey = `${CLEARS}${providerId}`
187 try {
188 if (!refused) {
189 await db.delete(cacheMeta).where(eq(cacheMeta.key, rowKey))
190 return
191 }
192 const row = await db.query.cacheMeta.findFirst({
193 where: eq(cacheMeta.key, rowKey),
194 })
195 const prior = parse<PriceClearsRefused>(row?.lastError)
196 const record: PriceClearsRefused = {
197 since: prior?.since ?? now,
198 polls: (prior?.polls ?? 0) + 1,
199 lastAt: now,
200 refused: refused.clears,
201 priced: refused.priced,
202 }
203 const lastError = JSON.stringify(record)
204 await db
205 .insert(cacheMeta)
206 .values({
207 key: rowKey,
208 fetchedAt: record.since,
209 staleTime: 0,
210 lastError,
211 })
212 .onConflictDoUpdate({
213 target: cacheMeta.key,
214 set: { fetchedAt: record.since, lastError },
215 })
216 } catch (error) {
217 console.error(
218 JSON.stringify({
219 job: 'models-poll',
220 providerId,
221 error: `price-clears-refused record not written: ${error instanceof Error ? error.message : String(error)}`,
222 }),
223 )
224 }
225}
226
227/** Write, extend, or (when nothing failed) delete the provider's record. */
228export async function recordDocsFailing(
229 db: Db,
230 providerId: string,
231 docs: DocsFailures,
232 now: number,
233): Promise<DocsFailing | null> {
234 if (docs.failed + docs.skipped === 0) {
235 await db.delete(cacheMeta).where(eq(cacheMeta.key, key(providerId)))
236 return null
237 }
238 const prior = await readDocsFailing(db, providerId)
239 const record: DocsFailing = {
240 since: prior?.since ?? now,
241 polls: (prior?.polls ?? 0) + 1,
242 lastAt: now,
243 failed: docs.failed,
244 skipped: docs.skipped,
245 sources: docs.first.map((failure) => failure.source),
246 error: (docs.first[0]?.error ?? '').slice(0, ERROR_MAX),
247 }
248 const lastError = JSON.stringify(record)
249 await db
250 .insert(cacheMeta)
251 .values({
252 key: key(providerId),
253 fetchedAt: record.since,
254 staleTime: 0,
255 lastError,
256 })
257 .onConflictDoUpdate({
258 target: cacheMeta.key,
259 set: { fetchedAt: record.since, lastError },
260 })
261 return record
262}
263
264/**
265 * Write or extend the provider's update-storm record, or delete it when
266 * this poll stayed under the line. The record describes the poll; it must
267 * never be what fails it, so a failed write is logged and swallowed.
268 */
269export async function recordUpdateStorm(
270 db: Db,
271 providerId: string,
272 storm: { updated: number; live: number } | null,
273 now: number,
274): Promise<void> {
275 const rowKey = `${STORM}${providerId}`
276 try {
277 if (!storm) {
278 await db.delete(cacheMeta).where(eq(cacheMeta.key, rowKey))
279 return
280 }
281 const row = await db.query.cacheMeta.findFirst({
282 where: eq(cacheMeta.key, rowKey),
283 })
284 const prior = parse<UpdateStorm>(row?.lastError)
285 const record: UpdateStorm = {
286 since: prior?.since ?? now,
287 polls: (prior?.polls ?? 0) + 1,
288 lastAt: now,
289 updated: storm.updated,
290 live: storm.live,
291 }
292 const lastError = JSON.stringify(record)
293 await db
294 .insert(cacheMeta)
295 .values({
296 key: rowKey,
297 fetchedAt: record.since,
298 staleTime: 0,
299 lastError,
300 })
301 .onConflictDoUpdate({
302 target: cacheMeta.key,
303 set: { fetchedAt: record.since, lastError },
304 })
305 } catch (error) {
306 console.error(
307 JSON.stringify({
308 job: 'models-poll',
309 providerId,
310 error: `update-storm record not written: ${error instanceof Error ? error.message : String(error)}`,
311 }),
312 )
313 }
314}