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