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

row-shape.ts

147 lines5.5 KB

1/**
2 * The served model row's shape version (issue #412). `hash` is the
3 * description-free hash of the row schemas in openapi.ts; row-shape.test.ts
4 * fails when they change and this record does not. When a served field
5 * changed: bump `version`, set `hash` to the value the test prints, rewrite
6 * `notes`, and add a changeset for @modelschemas/client; the models-poll
7 * cron then writes a `catalog.shape_changed` row per provider to
8 * /v1/changes. When only the emitter respelled the same shape (a zod bump
9 * that canonical() does not yet absorb): set `hash` alone — announcements
10 * key on `version`, so nothing is written.
11 */
12import { and, desc, eq, ne, sql } from 'drizzle-orm'
13​
14import type { Db } from '#/db/index.ts'
15import { changes, providers } from '#/db/schema.ts'
16import { openApiDocument } from '#/server/openapi.ts'
17​
18export const MODEL_ROW_SHAPE = {
19 version: 9,
20 hash: '5591ebc85597cefbd738785bfecac8d330f942a908d2d4437f311dbac8fa7ec5',
21 notes:
22 'Activity gained search for web search endpoints that take no model (Perplexity POST /search, issue #660).',
23} as const
24​
25/** Every component schema a /v1 model row response is built from. */
26const ROW_SCHEMA_ROOTS = [
27 'Model',
28 'ExportModel',
29 'ModelDetail',
30 'ModelList',
31 'ProviderModelList',
33​
34type Json = null | boolean | number | string | Array<Json> | JsonObject
35interface JsonObject {
36 [key: string]: Json
38​
39// zod 4.6 respelled three things 4.3 wrote; the hash reads both the same
40// so the emitter alone never moves the hash again: a `type` array is an
41// `anyOf` of bare types, a tuple carries no `items: false` +
42// `minItems`/`maxItems`, and a `format` says what its `pattern` spells.
43// Descriptions are prose: rewording one is not a shape change.
44function canonical(value: Json): string {
45 if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
46 if (value === null || typeof value !== 'object') return JSON.stringify(value)
47 if (Array.isArray(value.type) && value.anyOf === undefined) {
48 const { type, ...rest } = value
49 return canonical({ ...rest, anyOf: type.map((t) => ({ type: t })) })
50 }
51 const tuple = value.prefixItems !== undefined
52 const formatted = typeof value.format === 'string'
53 const entries = Object.entries(value)
54 .filter(([key]) => key !== 'description')
55 .filter(
56 ([key]) => !tuple || !['items', 'minItems', 'maxItems'].includes(key),
57 )
58 .filter(([key]) => !formatted || key !== 'pattern')
59 .sort(([a], [b]) => (a < b ? -1 : 1))
60 return `{${entries.map(([key, v]) => `${JSON.stringify(key)}:${canonical(v)}`).join(',')}}`
62​
63/** sha256 over the row schemas and every schema they reference. */
64export async function modelRowShapeHash(
65 schemas: Record<string, Json> = openApiDocument.components
66 .schemas as unknown as Record<string, Json>,
67): Promise<string> {
68 const closure = new Map<string, Json>()
69 const visit = (name: string) => {
70 if (closure.has(name)) return
71 const schema = schemas[name]
72 if (schema === undefined) throw new Error(`row shape: no schema ${name}`)
73 closure.set(name, schema)
74 for (const match of canonical(schema).matchAll(
75 /"#\/components\/schemas\/([^"]+)"/g,
76 ))
77 visit(match[1] as string)
78 }
79 ROW_SCHEMA_ROOTS.forEach(visit)
80 const body = canonical(Object.fromEntries(closure))
81 const digest = await crypto.subtle.digest(
82 'SHA-256',
83 new TextEncoder().encode(body),
84 )
85 return [...new Uint8Array(digest)]
86 .map((byte) => byte.toString(16).padStart(2, '0'))
87 .join('')
89​
90/**
91 * Writes a `catalog.shape_changed` row for each provider that has none for
92 * the current version: every provider when the version moves, and a provider
93 * added later on its first poll. Returns the rows written. Rows of one
94 * announcement share `payload.contentHash`; dedupe on it when reading
95 * across providers.
96 */
97export async function recordRowShape(
98 db: Db,
99 now = Math.floor(Date.now() / 1000),
100 shape: { version: number; hash: string; notes: string } = MODEL_ROW_SHAPE,
101): Promise<number> {
102 const versionOf = sql`json_extract(${changes.payload}, '$.version')`
103 const hashOf = sql`json_extract(${changes.payload}, '$.contentHash')`
104 const isShape = eq(changes.type, 'catalog.shape_changed')
105 const announced = new Set(
106 (
107 await db
108 .selectDistinct({ providerId: changes.providerId })
109 .from(changes)
110 .where(and(isShape, eq(versionOf, shape.version)))
111 ).map((row) => row.providerId),
112 )
113 const ids = (await db.select({ id: providers.id }).from(providers)).filter(
114 ({ id }) => !announced.has(id),
115 )
116 if (ids.length === 0) return 0
117 const [previous] = await db
118 .select({ hash: hashOf })
119 .from(changes)
120 .where(and(isShape, ne(versionOf, shape.version)))
121 .orderBy(desc(changes.createdAt))
122 .limit(1)
123 const previousHash = typeof previous?.hash === 'string' ? previous.hash : null
124 const rows = ids.map(({ id }) => ({
125 id: crypto.randomUUID(),
126 type: 'catalog.shape_changed' as const,
127 providerId: id,
128 subjectId: 'model-row',
129 summary: `Model row shape v${String(shape.version)}`,
130 payload: {
131 version: shape.version,
132 contentHash: shape.hash,
133 previousHash,
134 notes: shape.notes,
135 },
136 createdAt: now,
137 }))
138 // Ten rows keep each insert under D1's 100-bound-parameter limit; one
139 // batch commits them all or none, so a failure retries next poll.
140 const inserts = []
141 for (let i = 0; i < rows.length; i += 10) {
142 inserts.push(db.insert(changes).values(rows.slice(i, i + 10)))
143 }
144 const [first, ...rest] = inserts
145 if (first) await db.batch([first, ...rest])
146 return rows.length