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

ingest-signals.ts

207 lines5.5 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/'
12const DISTINCT_ID = 'modelschemas'
13​
14export type IngestJob =
15 | 'models-poll'
16 | 'spec-sync'
17 | 'fal-pricing-extract'
18 | 'same-as-reconcile'
19​
20export type IngestEvent =
21 | {
22 event: 'ingest_failed'
23 properties: {
24 job: IngestJob
25 providerId: string
26 error: string
27 /** The docs source that failed; absent when the whole job failed. */
28 source?: string
29 }
30 }
31 | {
32 event: 'pricing_lost'
33 properties: { providerId: string; rawId: string; reason: string }
34 }
35 | {
36 event: 'rate_card_refused'
37 properties: { providerId: string; rawId: string; reason: string }
38 }
39 | {
40 event: 'parse_rows'
41 properties: { source: string; rows: number }
42 }
43​
44export interface PostHogBatch {
45 api_key: string
46 batch: Array<{
47 event: IngestEvent['event']
48 distinct_id: string
49 properties: IngestEvent['properties']
50 }>
52​
53const pending: Array<IngestEvent> = []
54const scopes = new AsyncLocalStorage<Array<IngestEvent>>()
55​
56/** One buffer per poll, sync, or extract call so overlapping crons do not mix events. */
57export function runIngestScope<T>(fn: () => Promise<T>): Promise<T> {
58 return scopes.run([], fn)
60​
61export function noteIngest(event: IngestEvent): void {
62 const scope = scopes.getStore()
63 ;(scope ?? pending).push(event)
65​
66export function takeIngestEvents(): Array<IngestEvent> {
67 const scope = scopes.getStore()
68 return (scope ?? pending).splice(0)
70​
71export function ingestFailedEvent(
72 job: IngestJob,
73 providerId: string,
74 error: string,
75 source?: string,
76): IngestEvent {
77 return {
78 event: 'ingest_failed',
79 properties: { job, providerId, error, ...(source ? { source } : {}) },
80 }
82​
83export function parseRowsEvent(source: string, rows: number): IngestEvent {
84 return { event: 'parse_rows', properties: { source, rows } }
86​
87export interface PricingWriteInput {
88 providerId: string
89 rawId: string
90 /** Fresh listing/docs pricing was null or omitted. */
91 incomingNull: boolean
92 hadStoredCard: boolean
93 /** FAL keeps a `docs-extracted` card the listing never carries. */
94 keepExtracted: boolean
95 /** The adapter's stated reason for no price (`ModelInfo.absent.pricing`). */
96 absent?: FactAbsence
97 refused?: string
99​
100export interface PricingWriteDecision {
101 /** Keep the stored card instead of writing null. */
102 keepPrior: boolean
103 events: Array<IngestEvent>
104 /** Counted on the poll outcome. 0 or 1. */
105 failure: number
107​
108/**
109 * A docs parser that yields nothing for one model used to null its stored
110 * card with no signal. Keep the card (same as FAL's docs-extracted rows)
111 * and emit `pricing_lost`. A write-gate refusal still nulls the card and
112 * emits `rate_card_refused`. Uncompilable listings with no stored card
113 * stay quiet — that is the normal OpenRouter zero-price case.
114 *
115 * A stated reason wins and is quiet: `cleared` nulls the card (the source
116 * says there is no price), `unavailable` keeps it (the docs failure is
117 * reported once for the provider, not per row).
118 */
119export function observePricingWrite(
120 input: PricingWriteInput,
121): PricingWriteDecision {
122 if (input.absent) {
123 return {
124 keepPrior: input.absent === 'unavailable',
125 events: [],
126 failure: 0,
127 }
128 }
129 if (input.keepExtracted) {
130 return { keepPrior: true, events: [], failure: 0 }
131 }
132 if (input.refused) {
133 if (input.refused === 'uncompilable' && !input.hadStoredCard) {
134 return { keepPrior: false, events: [], failure: 0 }
135 }
136 return {
137 keepPrior: false,
138 events: [
139 {
140 event: 'rate_card_refused',
141 properties: {
142 providerId: input.providerId,
143 rawId: input.rawId,
144 reason: input.refused,
145 },
146 },
147 ],
148 failure: 1,
149 }
150 }
151 if (input.incomingNull && input.hadStoredCard) {
152 return {
153 keepPrior: true,
154 events: [
155 {
156 event: 'pricing_lost',
157 properties: {
158 providerId: input.providerId,
159 rawId: input.rawId,
160 reason: 'parser_miss',
161 },
162 },
163 ],
164 failure: 1,
165 }
166 }
167 return { keepPrior: false, events: [], failure: 0 }
169​
170export function posthogBatch(
171 events: Array<IngestEvent>,
172 apiKey: string,
173): PostHogBatch {
174 return {
175 api_key: apiKey,
176 batch: events.map((event) => ({
177 event: event.event,
178 distinct_id: DISTINCT_ID,
179 properties: event.properties,
180 })),
181 }
183​
184export async function captureIngestEvents(
185 apiKey: string | undefined,
186 fetchImpl: typeof fetch = fetch,
187): Promise<void> {
188 const events = takeIngestEvents()
189 if (!apiKey || events.length === 0) return
190 try {
191 const response = await fetchImpl(POSTHOG_CAPTURE_URL, {
192 method: 'POST',
193 headers: { 'Content-Type': 'application/json' },
194 body: JSON.stringify(posthogBatch(events, apiKey)),
195 signal: AbortSignal.timeout(5_000),
196 })
197 if (!response.ok) {
198 console.error(
199 JSON.stringify({ job: 'posthog', error: `capture ${response.status}` }),
200 )
201 }
202 } catch (error) {
203 console.error(
204 JSON.stringify({ job: 'posthog', error: errorMessage(error) }),
205 )
206 }