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

wait.ts

88 lines2.7 KB

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, max } from 'drizzle-orm'
10​
11import type { Db } from '#/db/index.ts'
12import { changes, providers } from '#/db/schema.ts'
13​
14export const MAX_WAIT_SECONDS = 60
15export const POLL_INTERVAL_MS = 2_000
16​
17/** Parses `?wait=30` / `?wait=30s`; 0 when absent or invalid; capped. */
18export function parseWaitSeconds(url: URL): number {
19 const raw = url.searchParams.get('wait')
20 if (raw === null) return 0
21 const match = /^(\d+)s?$/.exec(raw.trim())
22 if (!match) return 0
23 return Math.min(Number(match[1]), MAX_WAIT_SECONDS)
25​
26const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms))
27​
28/** Polls `changed` every ~2s until it reports true or `seconds` elapse. */
29export async function waitUntilChanged(
30 changed: () => Promise<boolean>,
31 seconds: number,
32 pollIntervalMs = POLL_INTERVAL_MS,
33): Promise<void> {
34 const deadline = Date.now() + seconds * 1000
35 while (Date.now() < deadline) {
36 await sleep(Math.min(pollIntervalMs, deadline - Date.now()))
37 if (await changed()) return
38 }
40​
41async function latestChangeAt(db: Db): Promise<number> {
42 const row = await db
43 .select({ createdAt: changes.createdAt })
44 .from(changes)
45 .orderBy(desc(changes.createdAt))
46 .limit(1)
47 return row[0]?.createdAt ?? 0
49​
50/** Holds until a change newer than the baseline exists (or expiry). */
51export async function waitForNewChange(
52 db: Db,
53 seconds: number,
54 pollIntervalMs = POLL_INTERVAL_MS,
55): Promise<void> {
56 const baseline = await latestChangeAt(db)
57 await waitUntilChanged(
58 async () => (await latestChangeAt(db)) > baseline,
59 seconds,
60 pollIntervalMs,
61 )
63​
64// Asked every ~2s while a request is held: two columns, not the whole
65// status with its counts and completeness score.
66async function latestStatusAt(db: Db): Promise<number> {
67 const [row] = await db
68 .select({
69 polled: max(providers.lastPolledAt),
70 synced: max(providers.lastSyncedAt),
71 })
72 .from(providers)
73 return Math.max(row?.polled ?? 0, row?.synced ?? 0)
75​
76/** Holds until any provider polls/syncs past the baseline (or expiry). */
77export async function waitForStatusChange(
78 db: Db,
79 seconds: number,
80 pollIntervalMs = POLL_INTERVAL_MS,
81): Promise<void> {
82 const baseline = await latestStatusAt(db)
83 await waitUntilChanged(
84 async () => (await latestStatusAt(db)) > baseline,
85 seconds,
86 pollIntervalMs,
87 )