Open History to see the last commit
1import { requestUrl } from '#/lib/text.ts'
2import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
3
4import directorAsyncApi from '../ingest/fixtures/fal-minimax-h3-max-director.asyncapi.json'
5import {
6 FAL_ACTIVITY_MARKER,
7 falAppSlug,
8 falAsyncApiUrl,
9 falLlmsTxtUrl,
10 falProvider,
11 fetchPageWithRetry,
12 parseAsyncApiContractUrl,
13} from './fal.ts'
14
15const PAGE = { models: [], has_more: false, next_cursor: null }
16
17function jsonResponse(): Response {
18 return new Response(JSON.stringify(PAGE), {
19 status: 200,
20 headers: { 'Content-Type': 'application/json' },
21 })
22}
23
24function errorResponse(
25 status: number,
26 headers: Record<string, string> = {},
27): Response {
28 return new Response('nope', { status, headers })
29}
30
31/** Resolve the retry loop's backoff sleeps as they are scheduled. */
32async function withTimersFlushed<T>(promise: Promise<T>): Promise<T> {
33 // Mark handled before the flush: a rejection landing mid-flush would
34 // otherwise trip the unhandled-rejection detector.
35 void promise.catch(() => undefined)
36 await vi.runAllTimersAsync()
37 return promise
38}
39
40describe('fetchPageWithRetry', () => {
41 const fetchMock = vi.fn<typeof fetch>()
42
43 beforeEach(() => {
44 vi.useFakeTimers()
45 vi.stubGlobal('fetch', fetchMock)
46 fetchMock.mockReset()
47 })
48
49 afterEach(() => {
50 vi.unstubAllGlobals()
51 vi.useRealTimers()
52 })
53
54 it('returns the parsed page on success', async () => {
55 fetchMock.mockResolvedValueOnce(jsonResponse())
56 await expect(fetchPageWithRetry('https://x', 'key')).resolves.toEqual(PAGE)
57 expect(fetchMock).toHaveBeenCalledTimes(1)
58 })
59
60 it('retries 429 (with Retry-After) and 5xx before succeeding', async () => {
61 fetchMock
62 .mockResolvedValueOnce(errorResponse(429, { 'Retry-After': '1' }))
63 .mockResolvedValueOnce(errorResponse(503))
64 .mockResolvedValueOnce(jsonResponse())
65 await expect(
66 withTimersFlushed(fetchPageWithRetry('https://x', 'key')),
67 ).resolves.toEqual(PAGE)
68 expect(fetchMock).toHaveBeenCalledTimes(3)
69 })
70
71 it('retries network-level failures', async () => {
72 fetchMock
73 .mockRejectedValueOnce(new TypeError('connection reset'))
74 .mockResolvedValueOnce(jsonResponse())
75 await expect(
76 withTimersFlushed(fetchPageWithRetry('https://x', 'key')),
77 ).resolves.toEqual(PAGE)
78 expect(fetchMock).toHaveBeenCalledTimes(2)
79 })
80
81 it('fails fast on non-retryable statuses like 401', async () => {
82 fetchMock.mockResolvedValueOnce(errorResponse(401))
83 await expect(fetchPageWithRetry('https://x', 'key')).rejects.toThrow(
84 'fal models fetch failed: 401',
85 )
86 expect(fetchMock).toHaveBeenCalledTimes(1)
87 })
88
89 it('gives up after the attempt budget with the last failure in the message', async () => {
90 fetchMock.mockImplementation(() => Promise.resolve(errorResponse(429)))
91 await expect(
92 withTimersFlushed(fetchPageWithRetry('https://x', 'key', 3)),
93 ).rejects.toThrow('fetch failed after 3 attempts: https://x → 429')
94 expect(fetchMock).toHaveBeenCalledTimes(3)
95 })
96})
97
98const DIRECTOR_LLMS = [
99 '# H3 Max Director',
100 '- [OpenAPI Schema](https://fal.ai/api/openapi/queue/openapi.json?endpoint_id=minimax/h3-max/director)',
101 '- [AsyncAPI Contract](https://fal.ai/api/apps/fal-ai/minimax-h3-max-director/asyncapi.json)',
102].join('\n')
103
104const FLUX_OPENAPI = {
105 openapi: '3.0.0',
106 paths: {
107 '/fal-ai/flux/dev': {
108 post: {
109 requestBody: {
110 content: {
111 'application/json': { schema: { type: 'object' } },
112 },
113 },
114 responses: { '200': { content: {} } },
115 },
116 },
117 },
118}
119
120function jsonBody(body: unknown, status = 200): Response {
121 return new Response(JSON.stringify(body), {
122 status,
123 headers: { 'Content-Type': 'application/json' },
124 })
125}
126
127describe('fal AsyncAPI discovery', () => {
128 const fetchMock = vi.fn<typeof fetch>()
129
130 beforeEach(() => {
131 vi.stubGlobal('fetch', fetchMock)
132 fetchMock.mockReset()
133 })
134
135 afterEach(() => {
136 vi.unstubAllGlobals()
137 })
138
139 it('maps raw ids to the apps asyncapi.json URL', () => {
140 expect(falAppSlug('minimax/h3-max/director')).toBe(
141 'fal-ai/minimax-h3-max-director',
142 )
143 expect(falAsyncApiUrl('minimax/h3-max/director')).toBe(
144 'https://fal.ai/api/apps/fal-ai/minimax-h3-max-director/asyncapi.json',
145 )
146 expect(falLlmsTxtUrl('minimax/h3-max/director')).toBe(
147 'https://fal.ai/models/minimax/h3-max/director/llms.txt',
148 )
149 expect(parseAsyncApiContractUrl(DIRECTOR_LLMS)).toBe(
150 'https://fal.ai/api/apps/fal-ai/minimax-h3-max-director/asyncapi.json',
151 )
152 expect(parseAsyncApiContractUrl('# no contract')).toBeNull()
153 })
154
155 it('probes AsyncAPI only for listed models with no OpenAPI POST', async () => {
156 fetchMock.mockImplementation((input) => {
157 const url = requestUrl(input)
158 if (url.startsWith('https://api.fal.ai/v1/models')) {
159 return Promise.resolve(
160 jsonBody({
161 models: [
162 {
163 endpoint_id: 'fal-ai/flux/dev',
164 openapi: FLUX_OPENAPI,
165 metadata: { category: 'text-to-image', display_name: 'Flux' },
166 },
167 {
168 endpoint_id: 'minimax/h3-max/director',
169 metadata: {
170 category: 'text-to-video',
171 display_name: 'H3 Max Director',
172 },
173 },
174 {
175 endpoint_id: 'ghost/no-spec',
176 metadata: { category: 'text-to-image' },
177 },
178 {
179 endpoint_id: 'fal-ai/trainer',
180 metadata: { category: 'training' },
181 },
182 ],
183 has_more: false,
184 next_cursor: null,
185 }),
186 )
187 }
188 if (url === falLlmsTxtUrl('minimax/h3-max/director')) {
189 return Promise.resolve(new Response(DIRECTOR_LLMS))
190 }
191 if (url === falAsyncApiUrl('minimax/h3-max/director')) {
192 return Promise.resolve(jsonBody(directorAsyncApi))
193 }
194 return Promise.resolve(new Response('nope', { status: 404 }))
195 })
196
197 const fetched = await falProvider.fetchSpec({ FAL_KEY: 'test-key' })
198 expect(fetched.skipped).toBeUndefined()
199 expect(fetched.specs).toHaveLength(1)
200 expect(fetched.specs[0]?.info?.['x-fal-endpoint-id']).toBe(
201 'fal-ai/flux/dev',
202 )
203 expect(fetched.asyncApiRawIds).toEqual(['minimax/h3-max/director'])
204 expect(fetched.bundledEndpoints).toHaveLength(1)
205 expect(fetched.bundledEndpoints?.[0]).toMatchObject({
206 path: '/minimax/h3-max/director',
207 activity: 'video',
208 asyncapi: true,
209 derivation: 'upstream-spec',
210 source: {
211 url: 'https://fal.ai/api/apps/fal-ai/minimax-h3-max-director/asyncapi.json',
212 },
213 })
214 const inputOneOf = fetched.bundledEndpoints?.[0]?.input?.oneOf
215 expect(Array.isArray(inputOneOf)).toBe(true)
216 if (Array.isArray(inputOneOf)) {
217 expect(inputOneOf.length).toBeGreaterThan(0)
218 }
219
220 const urls = fetchMock.mock.calls.map((call) => requestUrl(call[0]))
221 expect(
222 urls.some((u) => u.includes('fal-ai/flux/dev') && u.includes('llms')),
223 ).toBe(false)
224 expect(urls.some((u) => u.includes('fal-ai-flux-dev'))).toBe(false)
225 expect(urls).toContain(falLlmsTxtUrl('minimax/h3-max/director'))
226 expect(urls).toContain(falLlmsTxtUrl('ghost/no-spec'))
227 expect(urls).not.toContain(falLlmsTxtUrl('fal-ai/trainer'))
228 })
229
230 it('falls back to the constructed asyncapi.json URL when llms.txt has no link', async () => {
231 fetchMock.mockImplementation((input) => {
232 const url = requestUrl(input)
233 if (url.startsWith('https://api.fal.ai/v1/models')) {
234 return Promise.resolve(
235 jsonBody({
236 models: [
237 {
238 endpoint_id: 'minimax/h3-max/director',
239 metadata: { category: 'text-to-video' },
240 },
241 ],
242 has_more: false,
243 next_cursor: null,
244 }),
245 )
246 }
247 if (url === falLlmsTxtUrl('minimax/h3-max/director')) {
248 return Promise.resolve(new Response('# no contract here'))
249 }
250 if (url === falAsyncApiUrl('minimax/h3-max/director')) {
251 return Promise.resolve(jsonBody(directorAsyncApi))
252 }
253 return Promise.resolve(new Response('nope', { status: 404 }))
254 })
255
256 const fetched = await falProvider.fetchSpec({ FAL_KEY: 'test-key' })
257 expect(fetched.asyncApiRawIds).toEqual(['minimax/h3-max/director'])
258 expect(fetched.bundledEndpoints?.[0]?.source.url).toBe(
259 falAsyncApiUrl('minimax/h3-max/director'),
260 )
261 })
262
263 it('does not fail the fetch when AsyncAPI is missing', async () => {
264 fetchMock.mockImplementation((input) => {
265 const url = requestUrl(input)
266 if (url.startsWith('https://api.fal.ai/v1/models')) {
267 return Promise.resolve(
268 jsonBody({
269 models: [
270 {
271 endpoint_id: 'ghost/no-spec',
272 metadata: { category: 'text-to-image' },
273 },
274 ],
275 has_more: false,
276 next_cursor: null,
277 }),
278 )
279 }
280 return Promise.resolve(new Response('nope', { status: 404 }))
281 })
282
283 const fetched = await falProvider.fetchSpec({ FAL_KEY: 'test-key' })
284 expect(fetched.skipped).toBeUndefined()
285 expect(fetched.specs).toEqual([])
286 expect(fetched.bundledEndpoints).toEqual([])
287 expect(fetched.asyncApiRawIds).toEqual([])
288 })
289
290 it('ingests fal-ai/whisper from a direct lookup when metadata is null', async () => {
291 const whisperOpenApi = {
292 openapi: '3.0.4',
293 info: {
294 title: 'Whisper',
295 'x-fal-metadata': {
296 category: 'speech-to-text',
297 endpointId: 'fal-ai/whisper',
298 },
299 },
300 paths: {
301 '/': {
302 post: {
303 operationId: 'whisper',
304 responses: { '200': { description: 'ok' } },
305 },
306 },
307 },
308 }
309 fetchMock.mockImplementation((input) => {
310 const url = requestUrl(input)
311 if (url.startsWith('https://api.fal.ai/v1/models')) {
312 const parsed = new URL(url)
313 if (parsed.searchParams.get('endpoint_id') === 'fal-ai/whisper') {
314 return Promise.resolve(
315 jsonBody({
316 models: [
317 {
318 endpoint_id: 'fal-ai/whisper',
319 metadata: null,
320 openapi: whisperOpenApi,
321 },
322 ],
323 has_more: false,
324 next_cursor: null,
325 }),
326 )
327 }
328 return Promise.resolve(
329 jsonBody({
330 models: [
331 {
332 endpoint_id: 'fal-ai/flux/dev',
333 openapi: FLUX_OPENAPI,
334 metadata: { category: 'text-to-image' },
335 },
336 ],
337 has_more: false,
338 next_cursor: null,
339 }),
340 )
341 }
342 return Promise.resolve(new Response('nope', { status: 404 }))
343 })
344
345 const fetched = await falProvider.fetchSpec({ FAL_KEY: 'test-key' })
346 const whisper = fetched.specs.find(
347 (spec) => spec.info?.['x-fal-endpoint-id'] === 'fal-ai/whisper',
348 )
349 expect(whisper).toBeDefined()
350 const post = whisper?.paths?.['/']?.post
351 expect(post?.[FAL_ACTIVITY_MARKER]).toBe('audio')
352 expect(fetched.specs).toHaveLength(2)
353 expect(fetched.asyncApiRawIds).toEqual([])
354 })
355
356 it('throws when the unlisted lookup 404s without Endpoint(s) not found', async () => {
357 fetchMock.mockImplementation((input) => {
358 const url = requestUrl(input)
359 if (url.startsWith('https://api.fal.ai/v1/models')) {
360 if (new URL(url).searchParams.get('endpoint_id') === 'fal-ai/whisper') {
361 return Promise.resolve(new Response('missing', { status: 404 }))
362 }
363 return Promise.resolve(
364 jsonBody({
365 models: [
366 {
367 endpoint_id: 'fal-ai/flux/dev',
368 openapi: FLUX_OPENAPI,
369 metadata: { category: 'text-to-image' },
370 },
371 ],
372 has_more: false,
373 next_cursor: null,
374 }),
375 )
376 }
377 return Promise.resolve(new Response('nope', { status: 404 }))
378 })
379 await expect(
380 falProvider.fetchSpec({ FAL_KEY: 'test-key' }),
381 ).rejects.toThrow('404')
382 })
383
384 it('throws when the unlisted lookup fails with anything but 404', async () => {
385 fetchMock.mockImplementation((input) => {
386 const url = requestUrl(input)
387 if (url.startsWith('https://api.fal.ai/v1/models')) {
388 if (new URL(url).searchParams.get('endpoint_id') === 'fal-ai/whisper') {
389 return Promise.resolve(new Response('forbidden', { status: 403 }))
390 }
391 return Promise.resolve(
392 jsonBody({
393 models: [
394 {
395 endpoint_id: 'fal-ai/flux/dev',
396 openapi: FLUX_OPENAPI,
397 metadata: { category: 'text-to-image' },
398 },
399 ],
400 has_more: false,
401 next_cursor: null,
402 }),
403 )
404 }
405 return Promise.resolve(new Response('nope', { status: 404 }))
406 })
407 await expect(
408 falProvider.fetchSpec({ FAL_KEY: 'test-key' }),
409 ).rejects.toThrow('403')
410 })
411})