Open History to see the last commit
1/**
2 * D1's primary rejects further statements for about 10 seconds after
3 * "too many resources" or the internal-error reset (issue #625, #635).
4 */
5import { errorMessage } from '#/server/errors.ts'
6
7/**
8 * How long to wait after D1 says its 10-second resource window is spent,
9 * before retrying that provider once, and before the next provider (or
10 * the same-as reconcile) touches the primary.
11 */
12export const D1_WINDOW_WAIT_MS = 10_000
13
14/**
15 * D1 overload, and the internal-error sibling that resets the same primary.
16 * Either one means the next statement in the next few seconds fails too.
17 */
18export function d1WindowExhausted(message: string): boolean {
19 const text = message.toLowerCase()
20 if (!text.includes('d1')) return false
21 return text.includes('overloaded') || text.includes('internal error')
22}
23
24export const sleep = (ms: number) =>
25 new Promise<void>((resolve) => {
26 setTimeout(resolve, ms)
27 })
28
29/**
30 * Run `work` once. A spent D1 window waits, then runs it once more.
31 * Anything else, including a second spent window, throws to the caller.
32 */
33export async function retryOnceAfterD1Window<T>(
34 job: 'models-poll' | 'spec-sync',
35 providerId: string,
36 work: () => Promise<T>,
37 wait: (ms: number) => Promise<void>,
38): Promise<T> {
39 try {
40 return await work()
41 } catch (error) {
42 const message = errorMessage(error)
43 if (!d1WindowExhausted(message)) throw error
44 console.error(
45 JSON.stringify({ job, providerId, error: message, retry: 'd1-window' }),
46 )
47 await wait(D1_WINDOW_WAIT_MS)
48 return await work()
49 }
50}