Open History to see the last commit
1/**
2 * `?wait=` long-poll support (PLAN.md task 11.3). Agents rarely have a
3 * sleep tool: `?wait=30` (or `30s`) on /v1/changes and /v1/status holds
4 * the request — polling D1 every ~2s inside the request, no cron involved —
5 * until new data lands or the window expires, then returns whatever is
6 * current. Rate limiting happens once per request in the worker fetch
7 * wrapper, so a held request still costs one rate-limit token.
8 */
9import { desc } from 'drizzle-orm'
10
11import type { Db } from '#/db/index.ts'
12import { changes } from '#/db/schema.ts'
13import { getServiceStatus } from '#/server/status.ts'
14
15export const MAX_WAIT_SECONDS = 60
16export const POLL_INTERVAL_MS = 2_000
17
18/** Parses `?wait=30` / `?wait=30s`; 0 when absent or invalid; capped. */
19export function parseWaitSeconds(url: URL): number {
20 const raw = url.searchParams.get('wait')
21 if (raw === null) return 0
22 const match = /^(\d+)s?$/.exec(raw.trim())
23 if (!match) return 0
24 return Math.min(Number(match[1]), MAX_WAIT_SECONDS)
25}
26
27const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
28
29/** Polls `changed` every ~2s until it reports true or `seconds` elapse. */
30export async function waitUntilChanged(
31 changed: () => Promise<boolean>,
32 seconds: number,
33 pollIntervalMs = POLL_INTERVAL_MS,
34): Promise<void> {
35 const deadline = Date.now() + seconds * 1000
36 while (Date.now() < deadline) {
37 await sleep(Math.min(pollIntervalMs, deadline - Date.now()))
38 if (await changed()) return
39 }
40}
41
42async function latestChangeAt(db: Db): Promise<number> {
43 const row = await db
44 .select({ createdAt: changes.createdAt })
45 .from(changes)
46 .orderBy(desc(changes.createdAt))
47 .limit(1)
48 return row[0]?.createdAt ?? 0
49}
50
51/** Holds until a change newer than the baseline exists (or expiry). */
52export async function waitForNewChange(
53 db: Db,
54 seconds: number,
55 pollIntervalMs = POLL_INTERVAL_MS,
56): Promise<void> {
57 const baseline = await latestChangeAt(db)
58 await waitUntilChanged(
59 async () => (await latestChangeAt(db)) > baseline,
60 seconds,
61 pollIntervalMs,
62 )
63}
64
65async function latestStatusAt(db: Db): Promise<number> {
66 const status = await getServiceStatus(db)
67 return status.providers.reduce(
68 (max, p) => Math.max(max, p.lastPolledAt ?? 0, p.lastSyncedAt ?? 0),
69 0,
70 )
71}
72
73/** Holds until any provider polls/syncs past the baseline (or expiry). */
74export async function waitForStatusChange(
75 db: Db,
76 seconds: number,
77 pollIntervalMs = POLL_INTERVAL_MS,
78): Promise<void> {
79 const baseline = await latestStatusAt(db)
80 await waitUntilChanged(
81 async () => (await latestStatusAt(db)) > baseline,
82 seconds,
83 pollIntervalMs,
84 )
85}