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

ingest-signals.ts

244 lines6.6 KB

1/**
2 * Failure signals for docs parses and ingest jobs (issue #104).
3 * Builders are pure. `captureIngestEvents` posts them to PostHog US and
4 * never throws — a dead analytics host must not fail a cron.
5 */
6import { AsyncLocalStorage } from 'node:async_hooks'
7​
8import { errorMessage } from '#/server/errors.ts'
9import type { FactAbsence } from '#/server/providers/types.ts'
10​
11export const POSTHOG_CAPTURE_URL = 'https://us.i.posthog.com/batch/'
12export const CF_TRACE_URL = 'https://www.cloudflare.com/cdn-cgi/trace'
13const DISTINCT_ID = 'modelschemas'
14​
15export type IngestJob =
16 | 'models-poll'
17 | 'spec-sync'
18 | 'fal-pricing-extract'
19 | 'vercel-pricing-extract'
20 | 'same-as-reconcile'
21​
22export type IngestEvent =
23 | {
24 event: 'ingest_failed'
25 properties: {
26 job: IngestJob
27 providerId: string
28 error: string
29 /** The docs source that failed; absent when the whole job failed. */
30 source?: string
31 /** The Cloudflare colo the job ran in; added at capture. */
32 colo?: string
33 }
34 }
35 | {
36 event: 'pricing_lost'
37 properties: { providerId: string; rawId: string; reason: string }
38 }
39 | {
40 event: 'rate_card_refused'
41 properties: { providerId: string; rawId: string; reason: string }
42 }
43 | {
44 event: 'parse_rows'
45 properties: { source: string; rows: number }
46 }
47 | {
48 event: 'update_storm'
49 properties: { providerId: string; updated: number; live: number }
50 }
51​
52export interface PostHogBatch {
53 api_key: string
54 batch: Array<{
55 event: IngestEvent['event']
56 distinct_id: string
57 properties: IngestEvent['properties']
58 }>
60​
61const pending: Array<IngestEvent> = []
62const scopes = new AsyncLocalStorage<Array<IngestEvent>>()
63​
64/** One buffer per poll, sync, or extract call so overlapping crons do not mix events. */
65export function runIngestScope<T>(fn: () => Promise<T>): Promise<T> {
66 return scopes.run([], fn)
68​
69export function noteIngest(event: IngestEvent): void {
70 const scope = scopes.getStore()
71 ;(scope ?? pending).push(event)
73​
74export function takeIngestEvents(): Array<IngestEvent> {
75 const scope = scopes.getStore()
76 return (scope ?? pending).splice(0)
78​
79export function ingestFailedEvent(
80 job: IngestJob,
81 providerId: string,
82 error: string,
83 source?: string,
84): IngestEvent {
85 return {
86 event: 'ingest_failed',
87 properties: { job, providerId, error, ...(source ? { source } : {}) },
88 }
90​
91export function parseRowsEvent(source: string, rows: number): IngestEvent {
92 return { event: 'parse_rows', properties: { source, rows } }
94​
95export interface PricingWriteInput {
96 providerId: string
97 rawId: string
98 /** Fresh listing/docs pricing was null or omitted. */
99 incomingNull: boolean
100 hadStoredCard: boolean
101 /** FAL keeps a `docs-extracted` card the listing never carries. */
102 keepExtracted: boolean
103 /** The adapter's stated reason for no price (`ModelInfo.absent.pricing`). */
104 absent?: FactAbsence
105 refused?: string
107​
108export interface PricingWriteDecision {
109 /** Keep the stored card instead of writing null. */
110 keepPrior: boolean
111 events: Array<IngestEvent>
112 /** Counted on the poll outcome. 0 or 1. */
113 failure: number
115​
116/**
117 * A docs parser that yields nothing for one model used to null its stored
118 * card with no signal. Keep the card (same as FAL's docs-extracted rows)
119 * and emit `pricing_lost`. A write-gate refusal still nulls the card and
120 * emits `rate_card_refused`. Uncompilable listings with no stored card
121 * stay quiet — that is the normal OpenRouter zero-price case.
122 *
123 * A stated reason wins and is quiet: `cleared` nulls the card (the source
124 * says there is no price), `unavailable` keeps it (the docs failure is
125 * reported once for the provider, not per row).
126 */
127export function observePricingWrite(
128 input: PricingWriteInput,
129): PricingWriteDecision {
130 if (input.absent) {
131 return {
132 keepPrior: input.absent === 'unavailable',
133 events: [],
134 failure: 0,
135 }
136 }
137 if (input.keepExtracted) {
138 return { keepPrior: true, events: [], failure: 0 }
139 }
140 if (input.refused) {
141 if (input.refused === 'uncompilable' && !input.hadStoredCard) {
142 return { keepPrior: false, events: [], failure: 0 }
143 }
144 return {
145 keepPrior: false,
146 events: [
147 {
148 event: 'rate_card_refused',
149 properties: {
150 providerId: input.providerId,
151 rawId: input.rawId,
152 reason: input.refused,
153 },
154 },
155 ],
156 failure: 1,
157 }
158 }
159 if (input.incomingNull && input.hadStoredCard) {
160 return {
161 keepPrior: true,
162 events: [
163 {
164 event: 'pricing_lost',
165 properties: {
166 providerId: input.providerId,
167 rawId: input.rawId,
168 reason: 'parser_miss',
169 },
170 },
171 ],
172 failure: 1,
173 }
174 }
175 return { keepPrior: false, events: [], failure: 0 }
177​
178export function posthogBatch(
179 events: Array<IngestEvent>,
180 apiKey: string,
181): PostHogBatch {
182 return {
183 api_key: apiKey,
184 batch: events.map((event) => ({
185 event: event.event,
186 distinct_id: DISTINCT_ID,
187 properties: event.properties,
188 })),
189 }
191​
192/**
193 * The colo this invocation runs in, or null when the trace cannot be read
194 * (issue #356). Cron Triggers run wherever Cloudflare has capacity, and
195 * some providers refuse requests from some regions.
196 */
197async function traceColo(
198 fetchImpl: typeof fetch = fetch,
199): Promise<string | null> {
200 try {
201 const response = await fetchImpl(CF_TRACE_URL, {
202 signal: AbortSignal.timeout(2_000),
203 })
204 if (!response.ok) return null
205 return /^colo=([A-Z]+)$/m.exec(await response.text())?.[1] ?? null
206 } catch {
207 return null
208 }
210​
211export async function captureIngestEvents(
212 apiKey: string | undefined,
213 fetchImpl: typeof fetch = fetch,
214): Promise<void> {
215 const events = takeIngestEvents()
216 if (!apiKey || events.length === 0) return
217 const colo = events.some((event) => event.event === 'ingest_failed')
218 ? await traceColo(fetchImpl)
219 : null
220 const stamped = colo
221 ? events.map((event) =>
222 event.event === 'ingest_failed'
223 ? { ...event, properties: { ...event.properties, colo } }
224 : event,
225 )
226 : events
227 try {
228 const response = await fetchImpl(POSTHOG_CAPTURE_URL, {
229 method: 'POST',
230 headers: { 'Content-Type': 'application/json' },
231 body: JSON.stringify(posthogBatch(stamped, apiKey)),
232 signal: AbortSignal.timeout(5_000),
233 })
234 if (!response.ok) {
235 console.error(
236 JSON.stringify({ job: 'posthog', error: `capture ${response.status}` }),
237 )
238 }
239 } catch (error) {
240 console.error(
241 JSON.stringify({ job: 'posthog', error: errorMessage(error) }),
242 )
243 }