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

fal.test.ts

287 lines9.2 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2​
3import directorAsyncApi from '../ingest/fixtures/fal-minimax-h3-max-director.asyncapi.json'
4import {
5 falAppSlug,
6 falAsyncApiUrl,
7 falLlmsTxtUrl,
8 falProvider,
9 fetchPageWithRetry,
10 parseAsyncApiContractUrl,
11} from './fal.ts'
12​
13const PAGE = { models: [], has_more: false, next_cursor: null }
14​
15function jsonResponse(): Response {
16 return new Response(JSON.stringify(PAGE), {
17 status: 200,
18 headers: { 'Content-Type': 'application/json' },
19 })
21​
22function errorResponse(
23 status: number,
24 headers: Record<string, string> = {},
25): Response {
26 return new Response('nope', { status, headers })
28​
29/** Resolve the retry loop's backoff sleeps as they are scheduled. */
30async function withTimersFlushed<T>(promise: Promise<T>): Promise<T> {
31 // Mark handled before the flush: a rejection landing mid-flush would
32 // otherwise trip the unhandled-rejection detector.
33 void promise.catch(() => undefined)
34 await vi.runAllTimersAsync()
35 return promise
37​
38describe('fetchPageWithRetry', () => {
39 const fetchMock = vi.fn<typeof fetch>()
40​
41 beforeEach(() => {
42 vi.useFakeTimers()
43 vi.stubGlobal('fetch', fetchMock)
44 fetchMock.mockReset()
45 })
46​
47 afterEach(() => {
48 vi.unstubAllGlobals()
49 vi.useRealTimers()
50 })
51​
52 it('returns the parsed page on success', async () => {
53 fetchMock.mockResolvedValueOnce(jsonResponse())
54 await expect(fetchPageWithRetry('https://x', 'key')).resolves.toEqual(PAGE)
55 expect(fetchMock).toHaveBeenCalledTimes(1)
56 })
57​
58 it('retries 429 (with Retry-After) and 5xx before succeeding', async () => {
59 fetchMock
60 .mockResolvedValueOnce(errorResponse(429, { 'Retry-After': '1' }))
61 .mockResolvedValueOnce(errorResponse(503))
62 .mockResolvedValueOnce(jsonResponse())
63 await expect(
64 withTimersFlushed(fetchPageWithRetry('https://x', 'key')),
65 ).resolves.toEqual(PAGE)
66 expect(fetchMock).toHaveBeenCalledTimes(3)
67 })
68​
69 it('retries network-level failures', async () => {
70 fetchMock
71 .mockRejectedValueOnce(new TypeError('connection reset'))
72 .mockResolvedValueOnce(jsonResponse())
73 await expect(
74 withTimersFlushed(fetchPageWithRetry('https://x', 'key')),
75 ).resolves.toEqual(PAGE)
76 expect(fetchMock).toHaveBeenCalledTimes(2)
77 })
78​
79 it('fails fast on non-retryable statuses like 401', async () => {
80 fetchMock.mockResolvedValueOnce(errorResponse(401))
81 await expect(fetchPageWithRetry('https://x', 'key')).rejects.toThrow(
82 'fal models fetch failed: 401',
83 )
84 expect(fetchMock).toHaveBeenCalledTimes(1)
85 })
86​
87 it('gives up after the attempt budget with the last failure in the message', async () => {
88 fetchMock.mockResolvedValue(errorResponse(429))
89 await expect(
90 withTimersFlushed(fetchPageWithRetry('https://x', 'key', 3)),
91 ).rejects.toThrow('fal models fetch failed after 3 attempts: 429')
92 expect(fetchMock).toHaveBeenCalledTimes(3)
93 })
94})
95​
96const DIRECTOR_LLMS = [
97 '# H3 Max Director',
98 '- [OpenAPI Schema](https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=minimax/h3-max/director)',
99 '- [AsyncAPI Contract](https://fal.ai/api/apps/fal-ai/minimax-h3-max-director/asyncapi.json)',
100].join('\n')
101​
102const FLUX_OPENAPI = {
103 openapi: '3.0.0',
104 paths: {
105 '/fal-ai/flux/dev': {
106 post: {
107 requestBody: {
108 content: {
109 'application/json': { schema: { type: 'object' } },
110 },
111 },
112 responses: { '200': { content: {} } },
113 },
114 },
115 },
117​
118function jsonBody(body: unknown, status = 200): Response {
119 return new Response(JSON.stringify(body), {
120 status,
121 headers: { 'Content-Type': 'application/json' },
122 })
124​
125describe('fal AsyncAPI discovery', () => {
126 const fetchMock = vi.fn<typeof fetch>()
127​
128 beforeEach(() => {
129 vi.stubGlobal('fetch', fetchMock)
130 fetchMock.mockReset()
131 })
132​
133 afterEach(() => {
134 vi.unstubAllGlobals()
135 })
136​
137 it('maps raw ids to the apps asyncapi.json URL', () => {
138 expect(falAppSlug('minimax/h3-max/director')).toBe(
139 'fal-ai/minimax-h3-max-director',
140 )
141 expect(falAsyncApiUrl('minimax/h3-max/director')).toBe(
142 'https://fal.ai/api/apps/fal-ai/minimax-h3-max-director/asyncapi.json',
143 )
144 expect(falLlmsTxtUrl('minimax/h3-max/director')).toBe(
145 'https://fal.ai/models/minimax/h3-max/director/llms.txt',
146 )
147 expect(parseAsyncApiContractUrl(DIRECTOR_LLMS)).toBe(
148 'https://fal.ai/api/apps/fal-ai/minimax-h3-max-director/asyncapi.json',
149 )
150 expect(parseAsyncApiContractUrl('# no contract')).toBeNull()
151 })
152​
153 it('probes AsyncAPI only for listed models with no OpenAPI POST', async () => {
154 fetchMock.mockImplementation((input) => {
155 const url = String(input)
156 if (url.startsWith('https://api.fal.ai/v1/models')) {
157 return Promise.resolve(
158 jsonBody({
159 models: [
160 {
161 endpoint_id: 'fal-ai/flux/dev',
162 openapi: FLUX_OPENAPI,
163 metadata: { category: 'text-to-image', display_name: 'Flux' },
164 },
165 {
166 endpoint_id: 'minimax/h3-max/director',
167 metadata: {
168 category: 'text-to-video',
169 display_name: 'H3 Max Director',
170 },
171 },
172 {
173 endpoint_id: 'ghost/no-spec',
174 metadata: { category: 'text-to-image' },
175 },
176 {
177 endpoint_id: 'fal-ai/trainer',
178 metadata: { category: 'training' },
179 },
180 ],
181 has_more: false,
182 next_cursor: null,
183 }),
184 )
185 }
186 if (url === falLlmsTxtUrl('minimax/h3-max/director')) {
187 return Promise.resolve(new Response(DIRECTOR_LLMS))
188 }
189 if (url === falAsyncApiUrl('minimax/h3-max/director')) {
190 return Promise.resolve(jsonBody(directorAsyncApi))
191 }
192 return Promise.resolve(new Response('nope', { status: 404 }))
193 })
194​
195 const fetched = await falProvider.fetchSpec({ FAL_KEY: 'test-key' })
196 expect(fetched.skipped).toBeUndefined()
197 expect(fetched.specs).toHaveLength(1)
198 expect(fetched.specs[0]?.info?.['x-fal-endpoint-id']).toBe(
199 'fal-ai/flux/dev',
200 )
201 expect(fetched.asyncApiRawIds).toEqual(['minimax/h3-max/director'])
202 expect(fetched.bundledEndpoints).toHaveLength(1)
203 expect(fetched.bundledEndpoints?.[0]).toMatchObject({
204 path: '/minimax/h3-max/director',
205 activity: 'video',
206 asyncapi: true,
207 derivation: 'upstream-spec',
208 source: {
209 url: 'https://fal.ai/api/apps/fal-ai/minimax-h3-max-director/asyncapi.json',
210 },
211 })
212 const inputOneOf = fetched.bundledEndpoints?.[0]?.input?.oneOf
213 expect(Array.isArray(inputOneOf)).toBe(true)
214 if (Array.isArray(inputOneOf)) {
215 expect(inputOneOf.length).toBeGreaterThan(0)
216 }
217​
218 const urls = fetchMock.mock.calls.map((call) => String(call[0]))
219 expect(
220 urls.some((u) => u.includes('fal-ai/flux/dev') && u.includes('llms')),
221 ).toBe(false)
222 expect(urls.some((u) => u.includes('fal-ai-flux-dev'))).toBe(false)
223 expect(urls).toContain(falLlmsTxtUrl('minimax/h3-max/director'))
224 expect(urls).toContain(falLlmsTxtUrl('ghost/no-spec'))
225 expect(urls).not.toContain(falLlmsTxtUrl('fal-ai/trainer'))
226 })
227​
228 it('falls back to the constructed asyncapi.json URL when llms.txt has no link', async () => {
229 fetchMock.mockImplementation((input) => {
230 const url = String(input)
231 if (url.startsWith('https://api.fal.ai/v1/models')) {
232 return Promise.resolve(
233 jsonBody({
234 models: [
235 {
236 endpoint_id: 'minimax/h3-max/director',
237 metadata: { category: 'text-to-video' },
238 },
239 ],
240 has_more: false,
241 next_cursor: null,
242 }),
243 )
244 }
245 if (url === falLlmsTxtUrl('minimax/h3-max/director')) {
246 return Promise.resolve(new Response('# no contract here'))
247 }
248 if (url === falAsyncApiUrl('minimax/h3-max/director')) {
249 return Promise.resolve(jsonBody(directorAsyncApi))
250 }
251 return Promise.resolve(new Response('nope', { status: 404 }))
252 })
253​
254 const fetched = await falProvider.fetchSpec({ FAL_KEY: 'test-key' })
255 expect(fetched.asyncApiRawIds).toEqual(['minimax/h3-max/director'])
256 expect(fetched.bundledEndpoints?.[0]?.source.url).toBe(
257 falAsyncApiUrl('minimax/h3-max/director'),
258 )
259 })
260​
261 it('does not fail the fetch when AsyncAPI is missing', async () => {
262 fetchMock.mockImplementation((input) => {
263 const url = String(input)
264 if (url.startsWith('https://api.fal.ai/v1/models')) {
265 return Promise.resolve(
266 jsonBody({
267 models: [
268 {
269 endpoint_id: 'ghost/no-spec',
270 metadata: { category: 'text-to-image' },
271 },
272 ],
273 has_more: false,
274 next_cursor: null,
275 }),
276 )
277 }
278 return Promise.resolve(new Response('nope', { status: 404 }))
279 })
280​
281 const fetched = await falProvider.fetchSpec({ FAL_KEY: 'test-key' })
282 expect(fetched.skipped).toBeUndefined()
283 expect(fetched.specs).toEqual([])
284 expect(fetched.bundledEndpoints).toEqual([])
285 expect(fetched.asyncApiRawIds).toEqual([])
286 })
287})