-
-
Notifications
You must be signed in to change notification settings - Fork 80.8k
Expand file tree
/
Copy pathretry.ts
More file actions
211 lines (194 loc) · 8.27 KB
/
Copy pathretry.ts
File metadata and controls
211 lines (194 loc) · 8.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Provides generic retry timing and sleep helpers.
import { asFiniteNumber } from "@openclaw/normalization-core/number-coercion";
import { MAX_TIMER_TIMEOUT_MS, resolveTimerTimeoutMs } from "../shared/number-coercion.js";
import { sleep } from "../utils.js";
import { toErrorObject } from "./errors.js";
import { generateSecureFraction } from "./secure-random.js";
/** Retry timing knobs shared by generic retry runners and channel retry policies. */
export type RetryConfig = {
attempts?: number;
minDelayMs?: number;
maxDelayMs?: number;
jitter?: number;
};
/** Metadata emitted before a retry attempt sleeps and reruns the operation. */
export type RetryInfo = {
attempt: number;
maxAttempts: number;
delayMs: number;
err: unknown;
label?: string;
};
/** Retry execution options, including predicates, Retry-After hooks, and retry callbacks. */
export type RetryOptions = RetryConfig & {
label?: string;
shouldRetry?: (err: unknown, attempt: number) => boolean;
retryAfterMs?: (err: unknown) => number | undefined;
retryAfterMaxDelayMs?: number;
onRetry?: (info: RetryInfo) => void;
};
const DEFAULT_RETRY_CONFIG = {
attempts: 3,
minDelayMs: 300,
maxDelayMs: 30_000,
jitter: 0,
};
const clampNumber = (value: unknown, fallback: number, min?: number, max?: number) => {
const next = asFiniteNumber(value);
if (next === undefined) {
return fallback;
}
const floor = typeof min === "number" ? min : Number.NEGATIVE_INFINITY;
const ceiling = typeof max === "number" ? max : Number.POSITIVE_INFINITY;
return Math.min(Math.max(next, floor), ceiling);
};
function resolveAttemptCount(value: unknown, fallback: number): number {
const candidate = typeof value === "number" && Number.isFinite(value) ? value : fallback;
return Math.max(1, Math.round(candidate));
}
function resolveRetryDelayMs(value: number): number {
if (value === Number.POSITIVE_INFINITY) {
return MAX_TIMER_TIMEOUT_MS;
}
return resolveTimerTimeoutMs(value, 0, 0);
}
/** Resolves retry config overrides into clamped timer-safe settings. */
export function resolveRetryConfig(
defaults: Required<RetryConfig> = DEFAULT_RETRY_CONFIG,
overrides?: RetryConfig,
): Required<RetryConfig> {
const attempts = resolveAttemptCount(
clampNumber(overrides?.attempts, defaults.attempts, 1),
defaults.attempts,
);
const minDelayMs = resolveRetryDelayMs(
Math.round(clampNumber(overrides?.minDelayMs, defaults.minDelayMs, 0)),
);
const maxDelayMs = Math.max(
minDelayMs,
resolveRetryDelayMs(Math.round(clampNumber(overrides?.maxDelayMs, defaults.maxDelayMs, 0))),
);
const jitter = clampNumber(overrides?.jitter, defaults.jitter, 0, 1);
return { attempts, minDelayMs, maxDelayMs, jitter };
}
type JitterMode = "symmetric" | "positive";
function applyJitter(delayMs: number, jitter: number, mode: JitterMode = "symmetric"): number {
if (jitter <= 0) {
return delayMs;
}
// `symmetric` spreads within ±jitter around the base delay; correct for pure
// exponential backoff where going slightly early is harmless. `positive`
// only adds to the base delay; use it when the base delay is already a
// lower bound the caller must respect (for example a server-supplied
// Retry-After) so concurrent clients still spread without ever dipping
// below the caller's floor.
const fraction = generateSecureFraction();
const offset = mode === "positive" ? fraction * jitter : (fraction * 2 - 1) * jitter;
const raw = delayMs * (1 + offset);
// Rounding choice preserves the mode's contract. `positive` guarantees
// `delay >= delayMs`, so a non-integer `delayMs` (e.g. retryAfterMs=1.4)
// must round *up* — plain `Math.round(1.4)=1` would drop the delay below
// the caller's lower bound and violate the Retry-After invariant the
// positive branch exists to enforce. Symmetric has no floor contract so
// it stays on `Math.round`.
return Math.max(0, mode === "positive" ? Math.ceil(raw) : Math.round(raw));
}
/** Runs an async operation until it succeeds, retry policy stops, or attempts are exhausted. */
export async function retryAsync<T>(
fn: () => Promise<T>,
attemptsOrOptions: number | RetryOptions = 3,
initialDelayMs = 300,
): Promise<T> {
if (typeof attemptsOrOptions === "number") {
const attempts = resolveAttemptCount(attemptsOrOptions, DEFAULT_RETRY_CONFIG.attempts);
let lastErr: unknown;
for (let i = 0; i < attempts; i += 1) {
try {
return await fn();
} catch (err) {
lastErr = err;
if (i === attempts - 1) {
break;
}
const delay = resolveRetryDelayMs(initialDelayMs * 2 ** i);
await sleep(delay);
}
}
throw toErrorObject(lastErr ?? new Error("Retry failed"), "Non-Error thrown");
}
const options = attemptsOrOptions;
const resolved = resolveRetryConfig(DEFAULT_RETRY_CONFIG, options);
const maxAttempts = resolved.attempts;
const minDelayMs = resolved.minDelayMs;
const maxDelayMs =
Number.isFinite(resolved.maxDelayMs) && resolved.maxDelayMs > 0
? resolved.maxDelayMs
: Number.POSITIVE_INFINITY;
const retryAfterMaxDelayMs =
options.retryAfterMaxDelayMs === undefined
? maxDelayMs
: Math.max(
minDelayMs,
resolveRetryDelayMs(Math.round(clampNumber(options.retryAfterMaxDelayMs, maxDelayMs, 0))),
);
const jitter = resolved.jitter;
const shouldRetry = options.shouldRetry ?? (() => true);
let lastErr: unknown;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
return await fn();
} catch (err) {
lastErr = err;
if (attempt >= maxAttempts || !shouldRetry(err, attempt)) {
break;
}
const retryAfterMs = options.retryAfterMs?.(err);
const hasRetryAfter = typeof retryAfterMs === "number" && Number.isFinite(retryAfterMs);
const baseDelay = hasRetryAfter
? Math.max(retryAfterMs, minDelayMs)
: minDelayMs * 2 ** (attempt - 1);
const delayCap = hasRetryAfter ? retryAfterMaxDelayMs : maxDelayMs;
let delay = Math.min(baseDelay, delayCap);
// Server-supplied Retry-After is a lower-bound contract with the
// upstream rate limiter; symmetric jitter would let roughly half the
// retries land before the requested time and invite escalation. Use
// positive-only jitter in that case so clients still spread but never
// dip below the server's hint.
//
// Exception: when retryAfterMs > maxDelayMs the base is already capped
// to maxDelayMs, so positive jitter would be erased by the final clamp
// below and every retry would land at exactly maxDelayMs — reintroducing
// the thundering herd we are trying to avoid. In that case the server
// contract is already unsatisfiable, so fall back to symmetric jitter
// to preserve spread.
// Use `<=` so the `retryAfterMs === maxDelayMs` boundary keeps the
// positive-jitter contract. At the boundary, positive jitter followed by
// the final clamp collapses every retry to exactly maxDelayMs — clients
// do land in lockstep at that instant, which is thundering-herd-shaped
// locally. The trade-off is deliberate: symmetric jitter at the boundary
// would schedule roughly half the retries below maxDelayMs (=
// retryAfterMs), which is a *Retry-After contract violation* and invites
// upstream escalation (429 → extended cooldown / bans on Telegram,
// Discord, etc.). A synchronized retry at the exact server-cleared
// instant is strictly preferable to a spread that undercuts the server's
// hint. Only switch to symmetric when the hint exceeds our local cap
// (`retryAfterMs > maxDelayMs`), where the contract is already
// unsatisfiable and we gain spread without adding a violation.
const canHonorRetryAfter =
hasRetryAfter && typeof retryAfterMs === "number" && retryAfterMs <= delayCap;
delay = applyJitter(delay, jitter, canHonorRetryAfter ? "positive" : "symmetric");
delay = Math.min(Math.max(delay, minDelayMs), delayCap);
options.onRetry?.({
attempt,
maxAttempts,
delayMs: delay,
err,
label: options.label,
});
if (delay > 0) {
await sleep(delay);
}
}
}
throw toErrorObject(lastErr ?? new Error("Retry failed"), "Non-Error thrown");
}