|
| 1 | +import { BudgetExceeded } from "./errors.js"; |
| 2 | +import { type BudgetAdvisory, BudgetGuard } from "./guard.js"; |
| 3 | + |
| 4 | +export interface RetryPlan<T> { |
| 5 | + /** Operation to run for this retry attempt. */ |
| 6 | + call: () => T | Promise<T>; |
| 7 | + /** |
| 8 | + * Estimated retry cost passed to `guard.check()` before the retry runs. |
| 9 | + * Leave undefined to use the guard's default last-call estimate. |
| 10 | + */ |
| 11 | + estimatedCost?: number; |
| 12 | +} |
| 13 | + |
| 14 | +export interface BudgetRetryOptions<T> { |
| 15 | + /** Estimated cost for retrying the original call. */ |
| 16 | + estimatedCost?: number; |
| 17 | + /** Total attempts, including the first call. Default: 2. */ |
| 18 | + maxAttempts?: number; |
| 19 | + /** Choose a cheaper retry plan when `guard.advisory().nearLimit` is true. */ |
| 20 | + onDegrade?: ( |
| 21 | + error: unknown, |
| 22 | + advisory: BudgetAdvisory, |
| 23 | + ) => RetryPlan<T> | Promise<RetryPlan<T> | undefined> | undefined; |
| 24 | + /** Decide whether an error is retryable. Defaults to all non-budget errors. */ |
| 25 | + retryIf?: (error: unknown) => boolean; |
| 26 | +} |
| 27 | + |
| 28 | +function defaultRetryIf(error: unknown): boolean { |
| 29 | + return !(error instanceof BudgetExceeded); |
| 30 | +} |
| 31 | + |
| 32 | +/** |
| 33 | + * Run `call` with budget-aware retries. |
| 34 | + * |
| 35 | + * The first attempt runs unchanged. If it fails with a retryable error, the |
| 36 | + * helper retries as-is with ample budget, asks `onDegrade` for a cheaper plan |
| 37 | + * when near the limit, and always calls `guard.check(estimatedCost)` before a |
| 38 | + * retry so an over-budget retry is blocked before it runs. |
| 39 | + */ |
| 40 | +export async function withBudgetRetry<T>( |
| 41 | + guard: BudgetGuard, |
| 42 | + call: () => T | Promise<T>, |
| 43 | + options: BudgetRetryOptions<T> = {}, |
| 44 | +): Promise<T> { |
| 45 | + const maxAttempts = options.maxAttempts ?? 2; |
| 46 | + if (!Number.isInteger(maxAttempts) || maxAttempts < 1) { |
| 47 | + throw new RangeError(`maxAttempts must be an integer >= 1, got ${maxAttempts}`); |
| 48 | + } |
| 49 | + const retryIf = options.retryIf ?? defaultRetryIf; |
| 50 | + let plan: RetryPlan<T> = { call, estimatedCost: options.estimatedCost }; |
| 51 | + |
| 52 | + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { |
| 53 | + try { |
| 54 | + return await plan.call(); |
| 55 | + } catch (error) { |
| 56 | + if (attempt >= maxAttempts || !retryIf(error)) { |
| 57 | + throw error; |
| 58 | + } |
| 59 | + plan = await nextPlan(guard, error, plan, options.onDegrade); |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + throw new Error("unreachable"); |
| 64 | +} |
| 65 | + |
| 66 | +async function nextPlan<T>( |
| 67 | + guard: BudgetGuard, |
| 68 | + error: unknown, |
| 69 | + current: RetryPlan<T>, |
| 70 | + onDegrade: BudgetRetryOptions<T>["onDegrade"], |
| 71 | +): Promise<RetryPlan<T>> { |
| 72 | + const advisory = guard.advisory(); |
| 73 | + if (advisory.nearLimit && onDegrade !== undefined) { |
| 74 | + const degraded = await onDegrade(error, advisory); |
| 75 | + if (degraded !== undefined) { |
| 76 | + guard.check(degraded.estimatedCost); |
| 77 | + return degraded; |
| 78 | + } |
| 79 | + } |
| 80 | + guard.check(current.estimatedCost); |
| 81 | + return current; |
| 82 | +} |
0 commit comments