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

row-shape.ts

129 lines4.7 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. On a change: bump
5 * `version`, set `hash` to the value the test prints, rewrite `notes`, and
6 * add a changeset for @modelschemas/client. The models-poll cron then
7 * writes a `catalog.shape_changed` row to /v1/changes.
8 */
9import { and, desc, eq, ne, sql } from 'drizzle-orm'
10​
11import type { Db } from '#/db/index.ts'
12import { changes, providers } from '#/db/schema.ts'
13import { openApiDocument } from '#/server/openapi.ts'
14​
15export const MODEL_ROW_SHAPE = {
16 version: 1,
17 hash: '691a63b1df6de072adbdf78f8261bc7fc6857b61058295be54b319b3d0e7d557',
18 notes:
19 'First versioned row shape. capabilities is a flag map (Record<string, boolean>, a missing key is unknown); provider listing objects, ElevenLabs canDo* flags among them, are in providerMetadata; every row field is typed in openapi.json.',
20} as const
21​
22/** Every component schema a /v1 model row response is built from. */
23const ROW_SCHEMA_ROOTS = [
24 'Model',
25 'ExportModel',
26 'ModelDetail',
27 'ModelList',
28 'ProviderModelList',
30​
31type Json = null | boolean | number | string | Array<Json> | JsonObject
32interface JsonObject {
33 [key: string]: Json
35​
36// Descriptions are prose: rewording one is not a shape change.
37function canonical(value: Json): string {
38 if (Array.isArray(value)) return `[${value.map(canonical).join(',')}]`
39 if (value === null || typeof value !== 'object') return JSON.stringify(value)
40 const entries = Object.entries(value)
41 .filter(([key]) => key !== 'description')
42 .sort(([a], [b]) => (a < b ? -1 : 1))
43 return `{${entries.map(([key, v]) => `${JSON.stringify(key)}:${canonical(v)}`).join(',')}}`
45​
46/** sha256 over the row schemas and every schema they reference. */
47export async function modelRowShapeHash(
48 schemas: Record<string, Json> = openApiDocument.components
49 .schemas as unknown as Record<string, Json>,
50): Promise<string> {
51 const closure = new Map<string, Json>()
52 const visit = (name: string) => {
53 if (closure.has(name)) return
54 const schema = schemas[name]
55 if (schema === undefined) throw new Error(`row shape: no schema ${name}`)
56 closure.set(name, schema)
57 for (const match of canonical(schema).matchAll(
58 /"#\/components\/schemas\/([^"]+)"/g,
59 ))
60 visit(match[1] as string)
61 }
62 ROW_SCHEMA_ROOTS.forEach(visit)
63 const body = canonical(Object.fromEntries(closure))
64 const digest = await crypto.subtle.digest(
65 'SHA-256',
66 new TextEncoder().encode(body),
67 )
68 return [...new Uint8Array(digest)]
69 .map((byte) => byte.toString(16).padStart(2, '0'))
70 .join('')
72​
73/**
74 * Writes a `catalog.shape_changed` row for each provider that has none for
75 * the current hash: every provider when the shape moves, and a provider
76 * added later on its first poll. Returns the rows written. Rows of one
77 * announcement share `payload.contentHash`; dedupe on it when reading
78 * across providers.
79 */
80export async function recordRowShape(
81 db: Db,
82 now = Math.floor(Date.now() / 1000),
83 shape: { version: number; hash: string; notes: string } = MODEL_ROW_SHAPE,
84): Promise<number> {
85 const hashOf = sql`json_extract(${changes.payload}, '$.contentHash')`
86 const isShape = eq(changes.type, 'catalog.shape_changed')
87 const announced = new Set(
88 (
89 await db
90 .selectDistinct({ providerId: changes.providerId })
91 .from(changes)
92 .where(and(isShape, eq(hashOf, shape.hash)))
93 ).map((row) => row.providerId),
94 )
95 const ids = (await db.select({ id: providers.id }).from(providers)).filter(
96 ({ id }) => !announced.has(id),
97 )
98 if (ids.length === 0) return 0
99 const [previous] = await db
100 .select({ hash: hashOf })
101 .from(changes)
102 .where(and(isShape, ne(hashOf, shape.hash)))
103 .orderBy(desc(changes.createdAt))
104 .limit(1)
105 const previousHash = typeof previous?.hash === 'string' ? previous.hash : null
106 const rows = ids.map(({ id }) => ({
107 id: crypto.randomUUID(),
108 type: 'catalog.shape_changed' as const,
109 providerId: id,
110 subjectId: 'model-row',
111 summary: `Model row shape v${String(shape.version)}`,
112 payload: {
113 version: shape.version,
114 contentHash: shape.hash,
115 previousHash,
116 notes: shape.notes,
117 },
118 createdAt: now,
119 }))
120 // Ten rows keep each insert under D1's 100-bound-parameter limit; one
121 // batch commits them all or none, so a failure retries next poll.
122 const inserts = []
123 for (let i = 0; i < rows.length; i += 10) {
124 inserts.push(db.insert(changes).values(rows.slice(i, i + 10)))
125 }
126 const [first, ...rest] = inserts
127 if (first) await db.batch([first, ...rest])
128 return rows.length