Open History to see the last commit
1import { beforeAll, describe, expect, it } from 'vitest'
2import { env } from 'cloudflare:test'
3
4import { getDb } from '../db/index.ts'
5import type { Db } from '../db/index.ts'
6import { changes, providers } from '../db/schema.ts'
7import { parseWaitSeconds, waitForNewChange } from './wait.ts'
8
9let db: Db
10
11beforeAll(async () => {
12 db = getDb(env)
13 await db.insert(providers).values({
14 id: 'wait-prov',
15 displayName: 'Wait Prov',
16 specSourceUrl: 'https://example.com/spec.json',
17 })
18 await db.insert(changes).values({
19 id: 'wait-baseline',
20 type: 'model.added',
21 providerId: 'wait-prov',
22 subjectId: 'm0',
23 summary: 'baseline',
24 createdAt: 1_000,
25 })
26})
27
28describe('?wait= long-poll (task 11.3)', () => {
29 it('parses wait seconds, accepts the 60s form, caps at 60', () => {
30 const url = (q: string) => new URL(`https://x.test/v1/changes?${q}`)
31 expect(parseWaitSeconds(url('wait=5'))).toBe(5)
32 expect(parseWaitSeconds(url('wait=30s'))).toBe(30)
33 expect(parseWaitSeconds(url('wait=999'))).toBe(60)
34 expect(parseWaitSeconds(url('wait=abc'))).toBe(0)
35 expect(parseWaitSeconds(url(''))).toBe(0)
36 })
37
38 it('returns early when a change lands mid-wait', async () => {
39 const started = Date.now()
40 const insertion = (async () => {
41 await new Promise((resolve) => setTimeout(resolve, 300))
42 await db.insert(changes).values({
43 id: 'wait-mid',
44 type: 'model.added',
45 providerId: 'wait-prov',
46 subjectId: 'm1',
47 summary: 'lands mid-wait',
48 createdAt: 2_000,
49 })
50 })()
51 // wait=2 with a 250ms poll: the change at ~300ms must end the hold
52 // well before the 2s window expires.
53 await waitForNewChange(db, 2, 250)
54 await insertion
55 const elapsed = Date.now() - started
56 expect(elapsed).toBeLessThan(1_500)
57 expect(elapsed).toBeGreaterThanOrEqual(300)
58 })
59
60 it('holds for ~the full window when nothing changes', async () => {
61 const started = Date.now()
62 await waitForNewChange(db, 1, 250)
63 const elapsed = Date.now() - started
64 expect(elapsed).toBeGreaterThanOrEqual(950)
65 expect(elapsed).toBeLessThan(2_000)
66 })
67})