@baukit/api-runtime 0.18.2 → 0.19.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/retry.ts ADDED
@@ -0,0 +1,154 @@
1
+ import { fullJitterBackoffMs } from './backoff.js';
2
+ import { NetworkError } from './errors.js';
3
+ import { IDEMPOTENCY_KEY_HEADER } from './headers.js';
4
+ import type { RetryableMethod, RetryOptions } from './index.js';
5
+
6
+ export interface NormalizedRetryOptions {
7
+ readonly maxRetries: number;
8
+ readonly baseDelayMs: number;
9
+ readonly maxDelayMs: number;
10
+ readonly methods: ReadonlySet<RetryableMethod>;
11
+ readonly random: () => number;
12
+ readonly sleep: (delayMs: number, signal: AbortSignal | null) => Promise<void>;
13
+ }
14
+
15
+ const KEYED_RETRY_ONLY = new Set(['POST', 'PATCH']);
16
+ const RETRYABLE_METHODS = new Set<string>([
17
+ 'GET',
18
+ 'HEAD',
19
+ 'OPTIONS',
20
+ 'PUT',
21
+ 'DELETE',
22
+ 'POST',
23
+ 'PATCH',
24
+ ]);
25
+ const RETRYABLE_STATUSES = new Set([502, 503, 504]);
26
+
27
+ const DEFAULT_MAX_RETRIES = 2;
28
+ const DEFAULT_BASE_DELAY_MS = 100;
29
+ const DEFAULT_MAX_DELAY_MS = 2_000;
30
+ const DISABLED_RETRY: RetryOptions = { maxRetries: 0, methods: [] };
31
+
32
+ export function normalizeRetryOptions(
33
+ options: RetryOptions | false | undefined,
34
+ ): NormalizedRetryOptions {
35
+ const configured = options === false ? DISABLED_RETRY : (options ?? {});
36
+ const maxRetries = configured.maxRetries ?? DEFAULT_MAX_RETRIES;
37
+ const baseDelayMs = configured.baseDelayMs ?? DEFAULT_BASE_DELAY_MS;
38
+ const maxDelayMs = configured.maxDelayMs ?? DEFAULT_MAX_DELAY_MS;
39
+ assertFiniteNonNegativeInteger(maxRetries, 'maxRetries');
40
+ assertFiniteNonNegative(baseDelayMs, 'baseDelayMs');
41
+ assertFiniteNonNegative(maxDelayMs, 'maxDelayMs');
42
+ const requestedMethods = configured.methods ?? ['GET', 'HEAD'];
43
+ const methods = new Set(
44
+ requestedMethods.filter((method): method is RetryableMethod => RETRYABLE_METHODS.has(method)),
45
+ );
46
+ return {
47
+ maxRetries,
48
+ baseDelayMs,
49
+ maxDelayMs,
50
+ methods,
51
+ random: configured.random ?? Math.random,
52
+ sleep: configured.sleep ?? abortableSleep,
53
+ };
54
+ }
55
+
56
+ function assertFiniteNonNegative(value: number, name: string): void {
57
+ if (!Number.isFinite(value) || value < 0) {
58
+ throw new Error(`${name} must be a finite non-negative number`);
59
+ }
60
+ }
61
+
62
+ function assertFiniteNonNegativeInteger(value: number, name: string): void {
63
+ assertFiniteNonNegative(value, name);
64
+ if (!Number.isInteger(value)) {
65
+ throw new Error(`${name} must be an integer`);
66
+ }
67
+ }
68
+
69
+ export function shouldRetryMethod(request: Request, retry: NormalizedRetryOptions): boolean {
70
+ const method = request.method;
71
+ if (!retry.methods.has(method as RetryableMethod)) {
72
+ return false;
73
+ }
74
+ return !KEYED_RETRY_ONLY.has(method) || request.headers.has(IDEMPOTENCY_KEY_HEADER);
75
+ }
76
+
77
+ export function shouldRetryResponse(
78
+ request: Request,
79
+ status: number,
80
+ retries: number,
81
+ retry: NormalizedRetryOptions,
82
+ ): boolean {
83
+ return (
84
+ retries < retry.maxRetries &&
85
+ shouldRetryMethod(request, retry) &&
86
+ RETRYABLE_STATUSES.has(status)
87
+ );
88
+ }
89
+
90
+ export async function retryDelay(
91
+ retryIndex: number,
92
+ retry: NormalizedRetryOptions,
93
+ signal: AbortSignal,
94
+ requestId: string,
95
+ ): Promise<void> {
96
+ try {
97
+ await retry.sleep(fullJitterBackoffMs(retryIndex, retry), signal);
98
+ } catch (cause) {
99
+ throw new NetworkError('API request was aborted', requestId, cause, true);
100
+ }
101
+ throwIfAborted(signal, requestId);
102
+ }
103
+
104
+ function abortableSleep(delayMs: number, signal: AbortSignal | null): Promise<void> {
105
+ if (signal === null) {
106
+ return new Promise((resolve) => {
107
+ globalThis.setTimeout(resolve, delayMs);
108
+ });
109
+ }
110
+ if (signal.aborted) {
111
+ return Promise.reject(abortReason(signal));
112
+ }
113
+ return new Promise((resolve, reject) => {
114
+ const onAbort = (): void => {
115
+ globalThis.clearTimeout(timer);
116
+ reject(abortReason(signal));
117
+ };
118
+ const timer = globalThis.setTimeout(() => {
119
+ signal.removeEventListener('abort', onAbort);
120
+ resolve();
121
+ }, delayMs);
122
+ signal.addEventListener('abort', onAbort, { once: true });
123
+ });
124
+ }
125
+
126
+ function abortReason(signal: AbortSignal): Error {
127
+ return signal.reason instanceof Error
128
+ ? signal.reason
129
+ : new Error('API request was aborted', { cause: signal.reason });
130
+ }
131
+
132
+ export function throwIfAborted(signal: AbortSignal, requestId: string): void {
133
+ if (signal.aborted) {
134
+ throw new NetworkError('API request was aborted', requestId, signal.reason, true);
135
+ }
136
+ }
137
+
138
+ export function networkError(
139
+ cause: unknown,
140
+ requestId: string,
141
+ signal: AbortSignal | null,
142
+ ): NetworkError {
143
+ const aborted = signal?.aborted === true || isAbortError(cause);
144
+ return new NetworkError(
145
+ aborted ? 'API request was aborted' : 'API network request failed',
146
+ requestId,
147
+ cause,
148
+ aborted,
149
+ );
150
+ }
151
+
152
+ export function isAbortError(value: unknown): boolean {
153
+ return value instanceof Error && value.name === 'AbortError';
154
+ }