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

docs-failing.ts

214 lines6.4 KB

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 * `GET /v1/status` serves both (`readIngestRecords`).
17 */
18import { eq, like, or } from 'drizzle-orm'
19​
20import type { Db } from '#/db/index.ts'
21import { cacheMeta } from '#/db/schema.ts'
22import type { DocsFailures } from '#/server/providers/types.ts'
23​
24export interface DocsFailing {
25 /** Epoch seconds of the first poll in this unbroken run of failures. */
26 since: number
27 /** Consecutive polls with a docs failure, this one included. */
28 polls: number
29 lastAt: number
30 failed: number
31 skipped: number
32 /** The first few failing documents of the latest poll. */
33 sources: Array<string>
34 /** The latest poll's first error. */
35 error: string
37​
38export interface PriceClearsRefused {
39 /** Epoch seconds of the first poll in this unbroken run of refusals. */
40 since: number
41 /** Consecutive polls that refused, this one included. */
42 polls: number
43 lastAt: number
44 /** Stored prices the latest poll asked to clear; none was cleared. */
45 refused: number
46 /** Listed rows holding a stored price at that poll. */
47 priced: number
49​
50/** Both records of one provider, as `GET /v1/status` serves them. */
51export interface IngestRecords {
52 docsFailing?: DocsFailing
53 priceClearsRefused?: PriceClearsRefused
55​
56const DOCS = 'docs-failing:'
57const CLEARS = 'price-clears-refused:'
58​
59/** An upstream error can quote a whole HTML page. */
60const ERROR_MAX = 500
61​
62function key(providerId: string): string {
63 return `${DOCS}${providerId}`
65​
66/**
67 * A row that is not ours to read counts as no record: the next failing
68 * poll overwrites it, the next healthy one deletes it.
69 */
70function parse<T extends { since: number; polls: number }>(
71 text: string | null | undefined,
72 list?: 'sources',
73): T | null {
74 if (!text) return null
75 try {
76 const value = JSON.parse(text) as Partial<Record<string, unknown>> | null
77 if (typeof value?.since !== 'number' || typeof value.polls !== 'number') {
78 return null
79 }
80 if (list && !Array.isArray(value[list])) return null
81 return value as T
82 } catch {
83 return null
84 }
86​
87/** Every provider's records in one statement, keyed by provider id. */
88export async function readIngestRecords(
89 db: Db,
90): Promise<Map<string, IngestRecords>> {
91 const rows = await db
92 .select({ key: cacheMeta.key, lastError: cacheMeta.lastError })
93 .from(cacheMeta)
94 .where(
95 or(like(cacheMeta.key, `${DOCS}%`), like(cacheMeta.key, `${CLEARS}%`)),
96 )
97 const byProvider = new Map<string, IngestRecords>()
98 const entry = (providerId: string) => {
99 const records = byProvider.get(providerId) ?? {}
100 byProvider.set(providerId, records)
101 return records
102 }
103 for (const row of rows) {
104 if (row.key.startsWith(DOCS)) {
105 const record = parse<DocsFailing>(row.lastError, 'sources')
106 if (record) entry(row.key.slice(DOCS.length)).docsFailing = record
107 } else {
108 const record = parse<PriceClearsRefused>(row.lastError)
109 if (record) {
110 entry(row.key.slice(CLEARS.length)).priceClearsRefused = record
111 }
112 }
113 }
114 return byProvider
116​
117export async function readDocsFailing(
118 db: Db,
119 providerId: string,
120): Promise<DocsFailing | null> {
121 const row = await db.query.cacheMeta.findFirst({
122 where: eq(cacheMeta.key, key(providerId)),
123 })
124 return parse<DocsFailing>(row?.lastError, 'sources')
126​
127/**
128 * Write or extend the provider's refused-clears record, or delete it when
129 * this poll refused nothing. The record describes the poll; it must never
130 * be what fails it, so a failed write is logged and swallowed.
131 */
132export async function recordPriceClearsRefused(
133 db: Db,
134 providerId: string,
135 refused: { clears: number; priced: number } | null,
136 now: number,
137): Promise<void> {
138 const rowKey = `${CLEARS}${providerId}`
139 try {
140 if (!refused) {
141 await db.delete(cacheMeta).where(eq(cacheMeta.key, rowKey))
142 return
143 }
144 const row = await db.query.cacheMeta.findFirst({
145 where: eq(cacheMeta.key, rowKey),
146 })
147 const prior = parse<PriceClearsRefused>(row?.lastError)
148 const record: PriceClearsRefused = {
149 since: prior?.since ?? now,
150 polls: (prior?.polls ?? 0) + 1,
151 lastAt: now,
152 refused: refused.clears,
153 priced: refused.priced,
154 }
155 const lastError = JSON.stringify(record)
156 await db
157 .insert(cacheMeta)
158 .values({
159 key: rowKey,
160 fetchedAt: record.since,
161 staleTime: 0,
162 lastError,
163 })
164 .onConflictDoUpdate({
165 target: cacheMeta.key,
166 set: { fetchedAt: record.since, lastError },
167 })
168 } catch (error) {
169 console.error(
170 JSON.stringify({
171 job: 'models-poll',
172 providerId,
173 error: `price-clears-refused record not written: ${error instanceof Error ? error.message : String(error)}`,
174 }),
175 )
176 }
178​
179/** Write, extend, or (when nothing failed) delete the provider's record. */
180export async function recordDocsFailing(
181 db: Db,
182 providerId: string,
183 docs: DocsFailures,
184 now: number,
185): Promise<DocsFailing | null> {
186 if (docs.failed + docs.skipped === 0) {
187 await db.delete(cacheMeta).where(eq(cacheMeta.key, key(providerId)))
188 return null
189 }
190 const prior = await readDocsFailing(db, providerId)
191 const record: DocsFailing = {
192 since: prior?.since ?? now,
193 polls: (prior?.polls ?? 0) + 1,
194 lastAt: now,
195 failed: docs.failed,
196 skipped: docs.skipped,
197 sources: docs.first.map((failure) => failure.source),
198 error: (docs.first[0]?.error ?? '').slice(0, ERROR_MAX),
199 }
200 const lastError = JSON.stringify(record)
201 await db
202 .insert(cacheMeta)
203 .values({
204 key: key(providerId),
205 fetchedAt: record.since,
206 staleTime: 0,
207 lastError,
208 })
209 .onConflictDoUpdate({
210 target: cacheMeta.key,
211 set: { fetchedAt: record.since, lastError },
212 })
213 return record