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

schema.worker.test.ts

221 lines7.4 KB

1import { describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3import { eq } from 'drizzle-orm'
4​
5import { getDb } from './index.ts'
6import {
7 changes,
8 endpoints,
9 models,
10 providers,
11 schemaVersions,
12} from './schema.ts'
13​
14const NOW = 1_781_150_000
15​
16describe('core domain tables (migrated D1)', () => {
17 it('inserts and queries a provider with related rows across all five tables', async () => {
18 const db = getDb(env)
19​
20 await db.insert(providers).values({
21 id: 'anthropic',
22 displayName: 'Anthropic',
23 specSourceUrl: 'https://example.com/spec.yml',
24 modelsEndpoint: 'https://api.anthropic.com/v1/models',
25 authEnvVar: 'ANTHROPIC_API_KEY',
26 })
27​
28 await db.insert(models).values({
29 id: 'anthropic-claude-fable-5',
30 providerId: 'anthropic',
31 rawId: 'claude-fable-5',
32 activity: 'chat',
33 displayName: 'Claude Fable 5',
34 contextWindow: 200_000,
35 modalities: { input: ['text', 'image'], output: ['text'] },
36 firstSeenAt: NOW,
37 lastSeenAt: NOW,
38 })
39​
40 await db.insert(endpoints).values({
41 id: 'anthropic-messages',
42 providerId: 'anthropic',
43 activity: 'chat',
44 method: 'POST',
45 path: '/v1/messages',
46 })
47​
48 await db.insert(schemaVersions).values({
49 id: 'anthropic-messages-input-1',
50 endpointId: 'anthropic-messages',
51 kind: 'input',
52 contentHash: 'a'.repeat(64),
53 schema: JSON.stringify({ type: 'object' }),
54 createdAt: NOW,
55 })
56​
57 await db.insert(changes).values({
58 id: 'change-1',
59 type: 'model.added',
60 providerId: 'anthropic',
61 subjectId: 'anthropic-claude-fable-5',
62 summary: 'Model claude-fable-5 added',
63 createdAt: NOW,
64 })
65​
66 const model = await db.query.models.findFirst({
67 where: eq(models.id, 'anthropic-claude-fable-5'),
68 with: { provider: true },
69 })
70 expect(model?.activity).toBe('chat')
71 expect(model?.provider.displayName).toBe('Anthropic')
72 expect(model?.modalities).toEqual({
73 input: ['text', 'image'],
74 output: ['text'],
75 })
76​
77 const version = await db.query.schemaVersions.findFirst({
78 where: eq(schemaVersions.contentHash, 'a'.repeat(64)),
79 with: { endpoint: true },
80 })
81 expect(version?.kind).toBe('input')
82 expect(version?.endpoint.path).toBe('/v1/messages')
83​
84 const changeRows = await db
85 .select()
86 .from(changes)
87 .where(eq(changes.providerId, 'anthropic'))
88 expect(changeRows).toHaveLength(1)
89 expect(changeRows[0]?.type).toBe('model.added')
90 })
91​
92 it('enforces the providers foreign key', async () => {
93 const db = getDb(env)
94 await expect(
95 db.insert(models).values({
96 id: 'orphan-model',
97 providerId: 'no-such-provider',
98 rawId: 'orphan',
99 firstSeenAt: NOW,
100 lastSeenAt: NOW,
101 }),
102 ).rejects.toThrow()
103 })
104})
105​
106describe('migration 0014: capabilities become flag maps', () => {
107 it('converts every old shape, moves native objects, and is safe to re-run', async () => {
108 const migration = env.TEST_MIGRATIONS.find((m) =>
109 m.name.startsWith('0014_capability_flag_maps'),
110 )
111 if (!migration) throw new Error('migration 0014 not found')
112 await env.DB.prepare(
113 "INSERT INTO providers (id, display_name, spec_source_url) VALUES ('mig', 'Mig', 'https://example.com')",
114 ).run()
115 // Old-shape rows, as stored before the migration. A deprecated row is
116 // included: the poller never revisits those.
117 const old: Record<string, string | null> = {
118 list: '["tools","seed","tools"]',
119 'list-deprecated': '["reasoning"]',
120 empty: '[]',
121 none: null,
122 fal: '{"category":"text-to-image"}',
123 'fal-wma': '{"category":"text-to-video","asyncapi":true}',
124 'flag-only': '{"asyncapi":true}',
125 byteplus:
126 '{"domain":"VLM","taskType":["VisualQuestionAnswering"],"tools":{"function_calling":true},"structured_outputs":{"json_schema":false},"maxReasoningTokens":32768,"structuredOutputProbed":true}',
127 'byteplus-image': '{"maxReferenceImages":14,"sizeTokens":["1K","2K"]}',
128 elevenlabs:
129 '{"canDoTextToSpeech":true,"canDoVoiceConversion":false,"languages":["en","ja"]}',
130 // No `languages`: every value is a boolean, and it is still native.
131 'elevenlabs-bare':
132 '{"canDoTextToSpeech":true,"canDoVoiceConversion":false}',
133 replicate: '{"visibility":"public","official":true}',
134 reactor: '{"pricingName":"fast-h3","upstreamId":"3dc9"}',
135 // Already converted: a map, with a stated no.
136 map: '{"tools":true,"reasoning":false}',
137 }
138 for (const [rawId, capabilities] of Object.entries(old)) {
139 await env.DB.prepare(
140 'INSERT INTO models (id, provider_id, raw_id, capabilities, first_seen_at, last_seen_at, deprecated_at) VALUES (?, ?, ?, ?, 1, 1, ?)',
141 )
142 .bind(
143 `mig-${rawId}`,
144 'mig',
145 rawId,
146 capabilities,
147 rawId === 'list-deprecated' ? 2 : null,
148 )
149 .run()
150 }
151 const run = async () => {
152 for (const query of migration.queries) await env.DB.prepare(query).run()
153 const { results } = await env.DB.prepare(
154 "SELECT raw_id, capabilities, provider_metadata FROM models WHERE provider_id = 'mig'",
155 ).all<{
156 raw_id: string
157 capabilities: string | null
158 provider_metadata: string | null
159 }>()
160 return Object.fromEntries(
161 results.map((row) => [
162 row.raw_id,
163 [row.capabilities, row.provider_metadata].map((json) =>
164 json === null ? null : (JSON.parse(json) as unknown),
165 ),
166 ]),
167 )
168 }
169​
170 const once = await run()
171 expect(once).toEqual({
172 list: [{ tools: true, seed: true }, null],
173 'list-deprecated': [{ reasoning: true }, null],
174 // "Nothing stated": the next poll writes an exact row's noes.
175 empty: [null, null],
176 none: [null, null],
177 fal: [null, { category: 'text-to-image' }],
178 // Split: the flag stays, the listing object moves.
179 'fal-wma': [{ asyncapi: true }, { category: 'text-to-video' }],
180 'flag-only': [{ asyncapi: true }, null],
181 // Native `tools` / `structured_outputs` objects are not flags.
182 byteplus: [
183 null,
184 {
185 domain: 'VLM',
186 taskType: ['VisualQuestionAnswering'],
187 tools: { function_calling: true },
188 structured_outputs: { json_schema: false },
189 maxReasoningTokens: 32768,
190 structuredOutputProbed: true,
191 },
192 ],
193 'byteplus-image': [
194 null,
195 { maxReferenceImages: 14, sizeTokens: ['1K', '2K'] },
196 ],
197 elevenlabs: [
198 null,
199 {
200 canDoTextToSpeech: true,
201 canDoVoiceConversion: false,
202 languages: ['en', 'ja'],
203 },
204 ],
205 'elevenlabs-bare': [
206 null,
207 { canDoTextToSpeech: true, canDoVoiceConversion: false },
208 ],
209 replicate: [null, { visibility: 'public', official: true }],
210 reactor: [null, { pricingName: 'fast-h3', upstreamId: '3dc9' }],
211 map: [{ tools: true, reasoning: false }, null],
212 })
213 // No row holds anything but a boolean map or null.
214 const { results: odd } = await env.DB.prepare(
215 "SELECT m.raw_id FROM models m, json_each(m.capabilities) e WHERE m.provider_id = 'mig' AND (json_type(m.capabilities) <> 'object' OR e.type NOT IN ('true', 'false'))",
216 ).all()
217 expect(odd).toEqual([])
218​
219 expect(await run()).toEqual(once)
220 })
221})