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

extract-vercel-pricing.ts

304 lines10.1 KB

1/**
2 * Daily Vercel route-price extract (issue #451). Rows whose listing says
3 * `pricing.varies_by_provider` have no single billed price. Each route's
4 * price is on `GET /v1/models/{id}/endpoints`. That is one request per
5 * model, so it runs on its own cron, never inside the 15-minute poll.
6 *
7 * An endpoint with `status` other than 0 is not billed right now, so it
8 * is left out of the range. The fact source names every skipped route.
9 * A route with no readable linear price, a tier, or a different currency
10 * refuses the whole range (null, never a partial). A failed fetch keeps
11 * the stored range.
12 */
13import { and, eq, isNull } from 'drizzle-orm'
14import { compileOpenRouterPricing } from '@modelschemas/rate-card'
15import type { RateCard } from '@modelschemas/rate-card'
16​
17import { changes, models } from '#/db/schema.ts'
18import { errorMessage } from '#/server/errors.ts'
19import { VERCEL_MODELS_URL } from '#/server/providers/adapters/vercel.ts'
20import { fetchJson, sha256Text } from '#/server/providers/types.ts'
21import type { ModelFactSources } from '#/server/providers/types.ts'
22import { pricingRange } from '#/server/rate-card.ts'
23import type { PricingRange } from '#/server/rate-card.ts'
24import { changedFactPaths, modelUpdatedPayload } from './change-facts.ts'
25import {
26 captureIngestEvents,
27 ingestFailedEvent,
28 noteIngest,
29 runIngestScope,
30} from './ingest-signals.ts'
31import type { SyncDeps } from './sync.ts'
32​
33/** Once a day, before the 05:00 spec-sync shards. Own invocation budget. */
34export const VERCEL_PRICING_EXTRACT_CRON = '0 4 * * *'
35​
36const JOB = 'vercel-pricing-extract' as const
37​
38export interface VercelPricingExtractOutcome {
39 candidates: number
40 fetched: number
41 ranged: number
42 refused: number
43 unchanged: number
44 fetchFailed: number
45 error?: string
47​
48interface EndpointRoute {
49 provider: string
50 pricing: unknown
51 status: number
53​
54function isRecord(value: unknown): value is Record<string, unknown> {
55 return typeof value === 'object' && value !== null && !Array.isArray(value)
57​
58export function vercelEndpointsUrl(rawId: string): string {
59 return `${VERCEL_MODELS_URL}/${rawId}/endpoints`
61​
62/**
63 * Available routes (`status === 0`) become a range. Anything else is
64 * named in `skipped` and left out. `null` range means the payload was
65 * readable and is not a range: unreadable price, a tier, one route, or
66 * mixed currency. A payload that is not the endpoints document throws.
67 */
68export function compileVercelEndpointRange(
69 rawId: string,
70 payload: unknown,
71 source: RateCard['source'],
72): { range: PricingRange | null; skipped: Array<string> } {
73 const data = isRecord(payload) ? payload.data : undefined
74 const endpoints = isRecord(data) ? data.endpoints : undefined
75 if (!Array.isArray(endpoints)) {
76 throw new Error(`vercel: ${rawId} endpoints payload has no data.endpoints`)
77 }
78 const available: Array<EndpointRoute> = []
79 const skipped: Array<string> = []
80 for (const endpoint of endpoints) {
81 if (!isRecord(endpoint)) {
82 throw new Error(`vercel: ${rawId} endpoint is not an object`)
83 }
84 if (typeof endpoint.status !== 'number') {
85 throw new Error(`vercel: ${rawId} endpoint status is not a number`)
86 }
87 const provider =
88 typeof endpoint.provider_name === 'string' ? endpoint.provider_name : null
89 if (!provider) {
90 throw new Error(`vercel: ${rawId} endpoint has no provider_name`)
91 }
92 if (endpoint.status !== 0) {
93 skipped.push(provider)
94 continue
95 }
96 available.push({ provider, pricing: endpoint.pricing, status: 0 })
97 }
98 const compiled = available.map((route) => ({
99 model: route.provider,
100 provider: route.provider,
101 card: compileOpenRouterPricing(route.pricing, source),
102 }))
103 return { range: pricingRange(compiled), skipped }
105​
106/** Path that states the status filter and every route it dropped. */
107export function vercelRangePath(skipped: Array<string>): string {
108 const kept = 'data.endpoints[status=0].pricing'
109 if (skipped.length === 0) return kept
110 return `${kept}; skipped status!=0: ${skipped.join(', ')}`
112​
113/** Prices only. Uptime and latency on the same document are not a price change. */
114function endpointPrices(payload: unknown): Array<{
115 provider: string
116 status: number
117 pricing: unknown
118}> {
119 const data = isRecord(payload) ? payload.data : undefined
120 const endpoints = isRecord(data) ? data.endpoints : undefined
121 if (!Array.isArray(endpoints)) return []
122 return endpoints.map((endpoint) => {
123 if (!isRecord(endpoint)) return { provider: '', status: -1, pricing: null }
124 return {
125 provider:
126 typeof endpoint.provider_name === 'string'
127 ? endpoint.provider_name
128 : '',
129 status: typeof endpoint.status === 'number' ? endpoint.status : -1,
130 pricing: endpoint.pricing ?? null,
131 }
132 })
134​
135/**
136 * A route whose published per-million rates did not move keeps the stored
137 * card clock, so a daily refetch does not emit `model.updated`.
138 */
139function reuseRouteClocks(
140 range: PricingRange | null,
141 prior: PricingRange | null,
142): PricingRange | null {
143 if (!range || !prior) return range
144 for (const route of range.routes) {
145 if (!route.card) continue
146 const old = prior.routes.find((item) => item.provider === route.provider)
147 if (!old?.card) continue
148 if (JSON.stringify(route.pricing) !== JSON.stringify(old.pricing)) continue
149 route.card = { ...route.card, source: { ...old.card.source } }
150 }
151 return range
153​
154function sourceOf(url: string, hash: string, now: number): RateCard['source'] {
155 return { url, hash, extractedAt: new Date(now * 1000).toISOString() }
157​
158function asFacts(value: unknown): ModelFactSources | null {
159 if (!isRecord(value)) return null
160 return value
162​
163export async function extractVercelPricing(
164 deps: SyncDeps,
165): Promise<VercelPricingExtractOutcome> {
166 return runIngestScope(() => extractVercelPricingScoped(deps))
168​
169async function extractVercelPricingScoped(
170 deps: SyncDeps,
171): Promise<VercelPricingExtractOutcome> {
172 const outcome: VercelPricingExtractOutcome = {
173 candidates: 0,
174 fetched: 0,
175 ranged: 0,
176 refused: 0,
177 unchanged: 0,
178 fetchFailed: 0,
179 }
180 const now = Math.floor(Date.now() / 1000)
181 try {
182 const listing = await fetchJson(VERCEL_MODELS_URL)
183 if (!isRecord(listing) || !Array.isArray(listing.data)) {
184 throw new Error('vercel: models payload has no data array')
185 }
186 const varies = new Set<string>()
187 for (const row of listing.data) {
188 if (!isRecord(row) || typeof row.id !== 'string') continue
189 const pricing = isRecord(row.pricing) ? row.pricing : null
190 if (pricing?.varies_by_provider === true) varies.add(row.id)
191 }
192 const live = await deps.db
193 .select({
194 id: models.id,
195 rawId: models.rawId,
196 pricingRange: models.pricingRange,
197 factSources: models.factSources,
198 })
199 .from(models)
200 .where(and(eq(models.providerId, 'vercel'), isNull(models.deprecatedAt)))
201 const targets = live.filter((row) => varies.has(row.rawId))
202 outcome.candidates = targets.length
203 for (const row of targets) {
204 const url = vercelEndpointsUrl(row.rawId)
205 let payload: unknown
206 try {
207 payload = await fetchJson(url)
208 outcome.fetched++
209 } catch (error) {
210 outcome.fetchFailed++
211 const message = errorMessage(error)
212 console.error(
213 JSON.stringify({
214 job: JOB,
215 providerId: 'vercel',
216 rawId: row.rawId,
217 error: message,
218 }),
219 )
220 noteIngest(ingestFailedEvent(JOB, 'vercel', message, row.rawId))
221 continue
222 }
223 let compiled: { range: PricingRange | null; skipped: Array<string> }
224 try {
225 const priced = endpointPrices(payload)
226 compiled = compileVercelEndpointRange(
227 row.rawId,
228 payload,
229 sourceOf(url, await sha256Text(JSON.stringify(priced)), now),
230 )
231 compiled.range = reuseRouteClocks(compiled.range, row.pricingRange)
232 } catch (error) {
233 outcome.refused++
234 noteIngest(
235 ingestFailedEvent(JOB, 'vercel', errorMessage(error), row.rawId),
236 )
237 continue
238 }
239 const priorFacts = asFacts(row.factSources)
240 const nextFacts: ModelFactSources = { ...priorFacts }
241 if (compiled.range) {
242 nextFacts.pricingRange = {
243 derivation: 'listing',
244 sourceUrl: url,
245 sourceHash: await sha256Text(
246 JSON.stringify({
247 routes: compiled.range.routes.map((route) => ({
248 provider: route.provider,
249 pricing: route.pricing,
250 })),
251 skipped: compiled.skipped,
252 }),
253 ),
254 path: vercelRangePath(compiled.skipped),
255 }
256 } else {
257 delete nextFacts.pricingRange
258 }
259 const before = {
260 pricingRange: row.pricingRange,
261 factSources: priorFacts,
262 }
263 const after = {
264 pricingRange: compiled.range,
265 factSources: Object.keys(nextFacts).length > 0 ? nextFacts : null,
266 }
267 const changed = changedFactPaths(before, after)
268 if (changed.length === 0) {
269 outcome.unchanged++
270 if (compiled.range) outcome.ranged++
271 else outcome.refused++
272 continue
273 }
274 await deps.db
275 .update(models)
276 .set({
277 pricingRange: compiled.range,
278 factSources: after.factSources,
279 lastSeenAt: now,
280 })
281 .where(eq(models.id, row.id))
282 await deps.db.insert(changes).values({
283 id: crypto.randomUUID(),
284 type: 'model.updated',
285 providerId: 'vercel',
286 subjectId: row.id,
287 summary: `Model ${row.rawId} updated`,
288 payload: modelUpdatedPayload(before, after, changed),
289 createdAt: now,
290 })
291 if (compiled.range) outcome.ranged++
292 else outcome.refused++
293 }
294 console.log(JSON.stringify({ job: JOB, ...outcome }))
295 return outcome
296 } catch (error) {
297 outcome.error = errorMessage(error)
298 console.error(JSON.stringify({ job: JOB, error: outcome.error }))
299 noteIngest(ingestFailedEvent(JOB, 'vercel', outcome.error))
300 return outcome
301 } finally {
302 await captureIngestEvents(deps.secrets.POSTHOG_PROJECT_KEY)
303 }