@zap-studio/retry 0.2.0 → 0.3.1
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/CHANGELOG.md +24 -0
- package/README.md +23 -12
- package/dist/abort.d.mts +29 -0
- package/dist/abort.d.mts.map +1 -0
- package/dist/abort.mjs +61 -0
- package/dist/abort.mjs.map +1 -0
- package/dist/errors-BVZjP1Q5.d.mts +76 -0
- package/dist/errors-BVZjP1Q5.d.mts.map +1 -0
- package/dist/errors.d.mts +2 -0
- package/dist/{error.mjs → errors.mjs} +21 -3
- package/dist/errors.mjs.map +1 -0
- package/dist/exponential-backoff.d.mts +33 -16
- package/dist/exponential-backoff.d.mts.map +1 -1
- package/dist/exponential-backoff.mjs +13 -4
- package/dist/exponential-backoff.mjs.map +1 -1
- package/dist/fixed-delay.d.mts +26 -15
- package/dist/fixed-delay.d.mts.map +1 -1
- package/dist/fixed-delay.mjs +10 -4
- package/dist/fixed-delay.mjs.map +1 -1
- package/dist/index.d.mts +40 -70
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +14 -177
- package/dist/index.mjs.map +1 -1
- package/dist/result-mode.d.mts +19 -0
- package/dist/result-mode.d.mts.map +1 -0
- package/dist/result-mode.mjs +145 -0
- package/dist/result-mode.mjs.map +1 -0
- package/dist/sleep.d.mts +17 -0
- package/dist/sleep.d.mts.map +1 -0
- package/dist/sleep.mjs +23 -0
- package/dist/sleep.mjs.map +1 -0
- package/dist/throw-mode.d.mts +21 -0
- package/dist/throw-mode.d.mts.map +1 -0
- package/dist/throw-mode.mjs +49 -0
- package/dist/throw-mode.mjs.map +1 -0
- package/dist/types.d.mts +99 -46
- package/dist/types.d.mts.map +1 -1
- package/package.json +10 -7
- package/dist/error-CVW4I654.d.mts +0 -44
- package/dist/error-CVW4I654.d.mts.map +0 -1
- package/dist/error.d.mts +0 -2
- package/dist/error.mjs.map +0 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,89 +1,59 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { r as RetryError } from "./errors-BVZjP1Q5.mjs";
|
|
2
2
|
import { RetryDecision, RetryDecisionInput, RetryExhaustedInput, RetryPolicy, RetryRunOptions, RetryRunResult } from "./types.mjs";
|
|
3
|
-
|
|
4
3
|
//#region src/index.d.ts
|
|
5
4
|
/**
|
|
6
|
-
* Base class for implementing retry policies and running retry orchestration.
|
|
7
|
-
*
|
|
8
|
-
* Extend this class and implement {@link BaseRetryPolicy.next} to define retry
|
|
9
|
-
* behavior, then call {@link BaseRetryPolicy.run} to execute operations with that
|
|
10
|
-
* policy.
|
|
11
|
-
*/
|
|
5
|
+
* Base class for implementing retry policies and running retry orchestration.
|
|
6
|
+
*
|
|
7
|
+
* Extend this class and implement {@link BaseRetryPolicy.next} to define retry
|
|
8
|
+
* behavior, then call {@link BaseRetryPolicy.run} to execute operations with that
|
|
9
|
+
* policy.
|
|
10
|
+
*/
|
|
12
11
|
declare abstract class BaseRetryPolicy<TError = unknown, TData = unknown> implements RetryPolicy<TError, TData> {
|
|
13
12
|
/**
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
13
|
+
* Returns the retry decision for a failed attempt.
|
|
14
|
+
*
|
|
15
|
+
* @param input - Attempt context used to compute retry behavior.
|
|
16
|
+
* @throws {Error} Any error thrown by a concrete retry policy implementation.
|
|
17
|
+
*/
|
|
19
18
|
abstract next(input: RetryDecisionInput<TError, TData>): RetryDecision;
|
|
20
19
|
/**
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
20
|
+
* Builds the terminal error thrown or returned when retries are exhausted.
|
|
21
|
+
*
|
|
22
|
+
* Override this when you need custom terminal error types.
|
|
23
|
+
*
|
|
24
|
+
* @param input - Exhaustion context.
|
|
25
|
+
* @returns `RetryError` by default.
|
|
26
|
+
* @throws {Error} Any error thrown by an overriding policy implementation.
|
|
27
|
+
*/
|
|
29
28
|
onExhausted(input: RetryExhaustedInput<TError, TData>): RetryError;
|
|
30
29
|
/**
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
30
|
+
* Runs retry orchestration in non-throw mode.
|
|
31
|
+
*
|
|
32
|
+
* @param execute - Async function to execute per attempt.
|
|
33
|
+
* @param options - Runner settings with `throwOnExhausted: false`.
|
|
34
|
+
* @returns A discriminated result union containing success value or terminal error.
|
|
35
|
+
* @throws {Error} Any error thrown by `next`, `onExhausted`, or a custom `sleep`.
|
|
36
|
+
*/
|
|
38
37
|
run<T>(execute: (attempt: number) => Promise<T>, options: RetryRunOptions & {
|
|
39
38
|
throwOnExhausted: false;
|
|
40
39
|
}): Promise<RetryRunResult<T>>;
|
|
41
40
|
/**
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
41
|
+
* Runs retry orchestration and throws terminal error on exhaustion.
|
|
42
|
+
*
|
|
43
|
+
* @param execute - Async function to execute per attempt.
|
|
44
|
+
* @param options - Optional runner settings.
|
|
45
|
+
* @returns The successful execution value.
|
|
46
|
+
* @throws {RetryError} When retries are exhausted and `onExhausted` returns the
|
|
47
|
+
* terminal retry error. The default implementation returns `RetryError` with the last
|
|
48
|
+
* execution failure available on `RetryError.lastError`.
|
|
49
|
+
* @throws {AbortError} When `options.signal` is already aborted or aborts while retrying.
|
|
50
|
+
* @throws {Error} Any error thrown by `next`, by `onExhausted`, or by a custom `sleep`
|
|
51
|
+
* function.
|
|
52
|
+
*/
|
|
54
53
|
run<T>(execute: (attempt: number) => Promise<T>, options?: RetryRunOptions & {
|
|
55
54
|
throwOnExhausted?: true;
|
|
56
55
|
}): Promise<T>;
|
|
57
|
-
/**
|
|
58
|
-
* Runs retry orchestration in throwing mode.
|
|
59
|
-
*
|
|
60
|
-
* This path is selected when `throwOnExhausted` is not `false`.
|
|
61
|
-
*
|
|
62
|
-
* @param execute - Async function to execute per attempt.
|
|
63
|
-
* @param sleep - Delay function used between retry attempts.
|
|
64
|
-
* @returns The successful execution value.
|
|
65
|
-
* @throws {RetryError} Terminal error returned by `onExhausted(...)`.
|
|
66
|
-
* @throws Any error thrown by `next`, by `onExhausted`, or by `sleep`.
|
|
67
|
-
*/
|
|
68
|
-
private runThrowMode;
|
|
69
|
-
/**
|
|
70
|
-
* Runs retry orchestration in non-throw mode.
|
|
71
|
-
*
|
|
72
|
-
* This path is selected when `throwOnExhausted` is `false`.
|
|
73
|
-
*
|
|
74
|
-
* @param execute - Async function to execute per attempt.
|
|
75
|
-
* @param sleep - Delay function used between retry attempts.
|
|
76
|
-
* @returns A discriminated result union containing success value or terminal error.
|
|
77
|
-
* @throws Any error thrown by `next`, by `onExhausted`, or by `sleep`.
|
|
78
|
-
*/
|
|
79
|
-
private runResultMode;
|
|
80
56
|
}
|
|
81
|
-
/**
|
|
82
|
-
* Default delay implementation used by `run(...)` when no custom sleep function is provided.
|
|
83
|
-
*
|
|
84
|
-
* Returns immediately when `delayMs` is non-positive.
|
|
85
|
-
*/
|
|
86
|
-
declare function defaultSleep(delayMs: number): Promise<void>;
|
|
87
57
|
//#endregion
|
|
88
|
-
export { BaseRetryPolicy
|
|
58
|
+
export { BaseRetryPolicy };
|
|
89
59
|
//# sourceMappingURL=index.d.mts.map
|
package/dist/index.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../src/index.ts"],"mappings":";;;;;;;;;;uBA0BsB,gBACpB,kBACA,4BACW,YAAY,QAAQ;;;;;;;WAOf,KAAK,OAAO,mBAAmB,QAAQ,SAAS;;;;;;;;;;EAYhE,YAAmB,OAAO,oBAAoB,QAAQ,SAAS;;;;;;;;;EAgB/D,IAAiB,GACf,UAAU,oBAAoB,QAAQ,IACtC,SAAS;IAAoB;MAC5B,QAAQ,eAAe;;;;;;;;;;;;;;EAe1B,IAAiB,GACf,UAAU,oBAAoB,QAAQ,IACtC,UAAU;IAAoB;MAC7B,QAAQ"}
|
package/dist/index.mjs
CHANGED
|
@@ -1,4 +1,7 @@
|
|
|
1
|
-
import { RetryError } from "./
|
|
1
|
+
import { RetryError } from "./errors.mjs";
|
|
2
|
+
import { runResultMode } from "./result-mode.mjs";
|
|
3
|
+
import { defaultSleep } from "./sleep.mjs";
|
|
4
|
+
import { runThrowMode } from "./throw-mode.mjs";
|
|
2
5
|
//#region src/index.ts
|
|
3
6
|
/**
|
|
4
7
|
* Retry runner base class and shared orchestration implementation.
|
|
@@ -20,13 +23,13 @@ var BaseRetryPolicy = class {
|
|
|
20
23
|
*
|
|
21
24
|
* @param input - Exhaustion context.
|
|
22
25
|
* @returns `RetryError` by default.
|
|
23
|
-
* @throws Any error thrown by an overriding policy implementation.
|
|
26
|
+
* @throws {Error} Any error thrown by an overriding policy implementation.
|
|
24
27
|
*/
|
|
25
28
|
onExhausted(input) {
|
|
26
29
|
return new RetryError("Retry policy exhausted all attempts.", {
|
|
27
30
|
attempts: input.attempts,
|
|
28
|
-
|
|
29
|
-
|
|
31
|
+
lastData: input.data,
|
|
32
|
+
lastError: input.error
|
|
30
33
|
});
|
|
31
34
|
}
|
|
32
35
|
/**
|
|
@@ -37,10 +40,11 @@ var BaseRetryPolicy = class {
|
|
|
37
40
|
* @param execute - Async function to execute per attempt.
|
|
38
41
|
* @param options - Runner settings.
|
|
39
42
|
* @returns Success value or terminal result object based on option mode.
|
|
40
|
-
* @throws Any error thrown by `next`, by `onExhausted`, or by a custom `sleep`
|
|
43
|
+
* @throws {Error} Any error thrown by `next`, by `onExhausted`, or by a custom `sleep`
|
|
41
44
|
* function. When `throwOnExhausted` is `false`, exhaustion itself is returned
|
|
42
45
|
* as `{ ok: false }` instead of thrown.
|
|
43
|
-
*
|
|
46
|
+
* Cancellation is returned as `{ ok: false, error: AbortError }` in non-throw
|
|
47
|
+
* mode.
|
|
44
48
|
*
|
|
45
49
|
* @example
|
|
46
50
|
* const result = await policy.run(doWork, { throwOnExhausted: false });
|
|
@@ -48,179 +52,12 @@ var BaseRetryPolicy = class {
|
|
|
48
52
|
*/
|
|
49
53
|
async run(execute, options = {}) {
|
|
50
54
|
const sleep = options.sleep ?? defaultSleep;
|
|
51
|
-
const signal = options
|
|
52
|
-
if (options.throwOnExhausted === false) return
|
|
53
|
-
return
|
|
54
|
-
}
|
|
55
|
-
/**
|
|
56
|
-
* Runs retry orchestration in throwing mode.
|
|
57
|
-
*
|
|
58
|
-
* This path is selected when `throwOnExhausted` is not `false`.
|
|
59
|
-
*
|
|
60
|
-
* @param execute - Async function to execute per attempt.
|
|
61
|
-
* @param sleep - Delay function used between retry attempts.
|
|
62
|
-
* @returns The successful execution value.
|
|
63
|
-
* @throws {RetryError} Terminal error returned by `onExhausted(...)`.
|
|
64
|
-
* @throws Any error thrown by `next`, by `onExhausted`, or by `sleep`.
|
|
65
|
-
*/
|
|
66
|
-
async runThrowMode(execute, sleep, signal) {
|
|
67
|
-
let attempt = 1;
|
|
68
|
-
while (true) {
|
|
69
|
-
throwIfAborted(signal);
|
|
70
|
-
try {
|
|
71
|
-
return await execute(attempt);
|
|
72
|
-
} catch (error) {
|
|
73
|
-
throwIfAborted(signal);
|
|
74
|
-
const typedError = error;
|
|
75
|
-
const decision = this.next({
|
|
76
|
-
attempt,
|
|
77
|
-
error: typedError
|
|
78
|
-
});
|
|
79
|
-
if (!decision.shouldRetry) throw this.onExhausted({
|
|
80
|
-
attempts: attempt,
|
|
81
|
-
error: typedError
|
|
82
|
-
});
|
|
83
|
-
if (decision.delayMs > 0) if (signal) await sleepWithAbortSignal(sleep, decision.delayMs, signal);
|
|
84
|
-
else await sleep(decision.delayMs);
|
|
85
|
-
attempt += 1;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
/**
|
|
90
|
-
* Runs retry orchestration in non-throw mode.
|
|
91
|
-
*
|
|
92
|
-
* This path is selected when `throwOnExhausted` is `false`.
|
|
93
|
-
*
|
|
94
|
-
* @param execute - Async function to execute per attempt.
|
|
95
|
-
* @param sleep - Delay function used between retry attempts.
|
|
96
|
-
* @returns A discriminated result union containing success value or terminal error.
|
|
97
|
-
* @throws Any error thrown by `next`, by `onExhausted`, or by `sleep`.
|
|
98
|
-
*/
|
|
99
|
-
async runResultMode(execute, sleep, signal) {
|
|
100
|
-
let attempt = 1;
|
|
101
|
-
while (true) {
|
|
102
|
-
if (signal?.aborted) {
|
|
103
|
-
const attempts = Math.max(0, attempt - 1);
|
|
104
|
-
return {
|
|
105
|
-
ok: false,
|
|
106
|
-
error: toRetryError(signal.reason, attempts),
|
|
107
|
-
attempts
|
|
108
|
-
};
|
|
109
|
-
}
|
|
110
|
-
try {
|
|
111
|
-
return {
|
|
112
|
-
ok: true,
|
|
113
|
-
value: await execute(attempt)
|
|
114
|
-
};
|
|
115
|
-
} catch (error) {
|
|
116
|
-
if (signal?.aborted) {
|
|
117
|
-
const attempts = Math.max(0, attempt - 1);
|
|
118
|
-
return {
|
|
119
|
-
ok: false,
|
|
120
|
-
error: toRetryError(signal.reason, attempts),
|
|
121
|
-
attempts
|
|
122
|
-
};
|
|
123
|
-
}
|
|
124
|
-
const typedError = error;
|
|
125
|
-
const decision = this.next({
|
|
126
|
-
attempt,
|
|
127
|
-
error: typedError
|
|
128
|
-
});
|
|
129
|
-
if (!decision.shouldRetry) return {
|
|
130
|
-
ok: false,
|
|
131
|
-
error: this.onExhausted({
|
|
132
|
-
attempts: attempt,
|
|
133
|
-
error: typedError
|
|
134
|
-
}),
|
|
135
|
-
attempts: attempt
|
|
136
|
-
};
|
|
137
|
-
if (decision.delayMs > 0) if (signal) try {
|
|
138
|
-
await sleepWithAbortSignal(sleep, decision.delayMs, signal);
|
|
139
|
-
} catch (error) {
|
|
140
|
-
if (signal.aborted) return {
|
|
141
|
-
ok: false,
|
|
142
|
-
error: toRetryError(signal.reason, attempt),
|
|
143
|
-
attempts: attempt
|
|
144
|
-
};
|
|
145
|
-
throw error;
|
|
146
|
-
}
|
|
147
|
-
else await sleep(decision.delayMs);
|
|
148
|
-
attempt += 1;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
55
|
+
const { signal } = options;
|
|
56
|
+
if (options.throwOnExhausted === false) return await runResultMode(this, execute, sleep, signal);
|
|
57
|
+
return await runThrowMode(this, execute, sleep, signal);
|
|
151
58
|
}
|
|
152
59
|
};
|
|
153
|
-
/**
|
|
154
|
-
* Default delay implementation used by `run(...)` when no custom sleep function is provided.
|
|
155
|
-
*
|
|
156
|
-
* Returns immediately when `delayMs` is non-positive.
|
|
157
|
-
*/
|
|
158
|
-
async function defaultSleep(delayMs) {
|
|
159
|
-
if (delayMs <= 0) return;
|
|
160
|
-
await new Promise((resolve) => setTimeout(resolve, delayMs));
|
|
161
|
-
}
|
|
162
|
-
/**
|
|
163
|
-
* Throws an abort error when the provided signal is already aborted.
|
|
164
|
-
*
|
|
165
|
-
* @param signal - Optional cancellation signal.
|
|
166
|
-
* @throws {Error} Abort reason converted to an `Error`.
|
|
167
|
-
*/
|
|
168
|
-
function throwIfAborted(signal) {
|
|
169
|
-
if (!signal?.aborted) return;
|
|
170
|
-
throw toAbortError(signal.reason);
|
|
171
|
-
}
|
|
172
|
-
/**
|
|
173
|
-
* Normalizes an abort reason value into an `Error` instance.
|
|
174
|
-
*
|
|
175
|
-
* @param reason - Abort reason from `AbortSignal.reason`.
|
|
176
|
-
* @returns Normalized error instance.
|
|
177
|
-
*/
|
|
178
|
-
function toAbortError(reason) {
|
|
179
|
-
if (reason instanceof Error) return reason;
|
|
180
|
-
if (typeof reason === "string" && reason.length > 0) return new Error(reason);
|
|
181
|
-
if (reason === void 0) return /* @__PURE__ */ new Error("Retry aborted.");
|
|
182
|
-
try {
|
|
183
|
-
return /* @__PURE__ */ new Error(`Retry aborted: ${JSON.stringify(reason)}`);
|
|
184
|
-
} catch {
|
|
185
|
-
return /* @__PURE__ */ new Error("Retry aborted.");
|
|
186
|
-
}
|
|
187
|
-
}
|
|
188
|
-
/**
|
|
189
|
-
* Converts an abort reason into a `RetryError` for non-throw runner mode.
|
|
190
|
-
*
|
|
191
|
-
* @param reason - Abort reason from `AbortSignal.reason`.
|
|
192
|
-
* @returns Retry terminal error value.
|
|
193
|
-
*/
|
|
194
|
-
function toRetryError(reason, attempts) {
|
|
195
|
-
const abortError = toAbortError(reason);
|
|
196
|
-
return new RetryError(abortError.message, {
|
|
197
|
-
attempts,
|
|
198
|
-
lastError: abortError
|
|
199
|
-
});
|
|
200
|
-
}
|
|
201
|
-
/**
|
|
202
|
-
* Awaits delay sleep while also observing cancellation via `AbortSignal`.
|
|
203
|
-
*
|
|
204
|
-
* @param sleep - Delay function.
|
|
205
|
-
* @param delayMs - Delay duration in milliseconds.
|
|
206
|
-
* @param signal - Cancellation signal.
|
|
207
|
-
* @throws {Error} Abort reason converted to an `Error` when canceled.
|
|
208
|
-
*/
|
|
209
|
-
async function sleepWithAbortSignal(sleep, delayMs, signal) {
|
|
210
|
-
if (signal.aborted) throw toAbortError(signal.reason);
|
|
211
|
-
let onAbort;
|
|
212
|
-
try {
|
|
213
|
-
await Promise.race([sleep(delayMs), new Promise((_, reject) => {
|
|
214
|
-
onAbort = () => {
|
|
215
|
-
reject(toAbortError(signal.reason));
|
|
216
|
-
};
|
|
217
|
-
signal.addEventListener("abort", onAbort, { once: true });
|
|
218
|
-
})]);
|
|
219
|
-
} finally {
|
|
220
|
-
if (onAbort) signal.removeEventListener("abort", onAbort);
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
60
|
//#endregion
|
|
224
|
-
export { BaseRetryPolicy
|
|
61
|
+
export { BaseRetryPolicy };
|
|
225
62
|
|
|
226
63
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Retry runner base class and shared orchestration implementation.\n *\n * @module @zap-studio/retry\n */\n\nimport { RetryError } from \"./error.js\";\nimport type {\n RetryDecision,\n RetryDecisionInput,\n RetryExhaustedInput,\n RetryPolicy,\n RetryRunOptions,\n RetryRunResult,\n} from \"./types.js\";\n\n/**\n * Base class for implementing retry policies and running retry orchestration.\n *\n * Extend this class and implement {@link BaseRetryPolicy.next} to define retry\n * behavior, then call {@link BaseRetryPolicy.run} to execute operations with that\n * policy.\n */\nexport abstract class BaseRetryPolicy<TError = unknown, TData = unknown> implements RetryPolicy<\n TError,\n TData\n> {\n /**\n * Returns the retry decision for a failed attempt.\n *\n * @param input - Attempt context used to compute retry behavior.\n * @throws Any error thrown by a concrete retry policy implementation.\n */\n public abstract next(input: RetryDecisionInput<TError, TData>): RetryDecision;\n\n /**\n * Builds the terminal error thrown or returned when retries are exhausted.\n *\n * Override this when you need custom terminal error types.\n *\n * @param input - Exhaustion context.\n * @returns `RetryError` by default.\n * @throws Any error thrown by an overriding policy implementation.\n */\n public onExhausted(input: RetryExhaustedInput<TError, TData>): RetryError {\n return new RetryError(\"Retry policy exhausted all attempts.\", {\n attempts: input.attempts,\n lastError: input.error,\n lastData: input.data,\n });\n }\n\n /**\n * Runs retry orchestration in non-throw mode.\n *\n * @param execute - Async function to execute per attempt.\n * @param options - Runner settings with `throwOnExhausted: false`.\n * @returns A discriminated result union containing success value or terminal error.\n * @throws Any error thrown by `next`, `onExhausted`, or a custom `sleep`.\n */\n public async run<T>(\n execute: (attempt: number) => Promise<T>,\n options: RetryRunOptions & { throwOnExhausted: false },\n ): Promise<RetryRunResult<T>>;\n\n /**\n * Runs retry orchestration and throws terminal error on exhaustion.\n *\n * @param execute - Async function to execute per attempt.\n * @param options - Optional runner settings.\n * @returns The successful execution value.\n * @throws {RetryError} When retries are exhausted and `onExhausted` returns the\n * terminal retry error. The default implementation returns `RetryError` with the last\n * execution failure available on `RetryError.lastError`.\n * @throws {Error} When `options.signal` is already aborted or aborts while retrying.\n * @throws Any error thrown by `next`, by `onExhausted`, or by a custom `sleep`\n * function.\n */\n public async run<T>(\n execute: (attempt: number) => Promise<T>,\n options?: RetryRunOptions & { throwOnExhausted?: true },\n ): Promise<T>;\n\n /**\n * Runs retry orchestration in non-throw mode.\n *\n * When `throwOnExhausted` is `false`, returns a discriminated result union.\n *\n * @param execute - Async function to execute per attempt.\n * @param options - Runner settings.\n * @returns Success value or terminal result object based on option mode.\n * @throws Any error thrown by `next`, by `onExhausted`, or by a custom `sleep`\n * function. When `throwOnExhausted` is `false`, exhaustion itself is returned\n * as `{ ok: false }` instead of thrown.\n * Abort errors are also returned as `{ ok: false }` in non-throw mode.\n *\n * @example\n * const result = await policy.run(doWork, { throwOnExhausted: false });\n * if (!result.ok) console.error(result.error);\n */\n public async run<T>(\n execute: (attempt: number) => Promise<T>,\n options: RetryRunOptions = {},\n ): Promise<T | RetryRunResult<T>> {\n const sleep = options.sleep ?? defaultSleep;\n const signal = options.signal;\n if (options.throwOnExhausted === false) {\n return this.runResultMode(execute, sleep, signal);\n }\n\n return this.runThrowMode(execute, sleep, signal);\n }\n\n /**\n * Runs retry orchestration in throwing mode.\n *\n * This path is selected when `throwOnExhausted` is not `false`.\n *\n * @param execute - Async function to execute per attempt.\n * @param sleep - Delay function used between retry attempts.\n * @returns The successful execution value.\n * @throws {RetryError} Terminal error returned by `onExhausted(...)`.\n * @throws Any error thrown by `next`, by `onExhausted`, or by `sleep`.\n */\n private async runThrowMode<T>(\n execute: (attempt: number) => Promise<T>,\n sleep: (delayMs: number) => Promise<void>,\n signal?: AbortSignal,\n ): Promise<T> {\n let attempt = 1;\n\n while (true) {\n throwIfAborted(signal);\n\n try {\n return await execute(attempt);\n } catch (error) {\n throwIfAborted(signal);\n\n const typedError = error as TError;\n const decision = this.next({\n attempt,\n error: typedError,\n });\n\n if (!decision.shouldRetry) {\n throw this.onExhausted({\n attempts: attempt,\n error: typedError,\n });\n }\n\n if (decision.delayMs > 0) {\n if (signal) {\n await sleepWithAbortSignal(sleep, decision.delayMs, signal);\n } else {\n await sleep(decision.delayMs);\n }\n }\n\n attempt += 1;\n }\n }\n }\n\n /**\n * Runs retry orchestration in non-throw mode.\n *\n * This path is selected when `throwOnExhausted` is `false`.\n *\n * @param execute - Async function to execute per attempt.\n * @param sleep - Delay function used between retry attempts.\n * @returns A discriminated result union containing success value or terminal error.\n * @throws Any error thrown by `next`, by `onExhausted`, or by `sleep`.\n */\n private async runResultMode<T>(\n execute: (attempt: number) => Promise<T>,\n sleep: (delayMs: number) => Promise<void>,\n signal?: AbortSignal,\n ): Promise<RetryRunResult<T>> {\n let attempt = 1;\n\n while (true) {\n if (signal?.aborted) {\n const attempts = Math.max(0, attempt - 1);\n return {\n ok: false,\n error: toRetryError(signal.reason, attempts),\n attempts,\n };\n }\n\n try {\n const value = await execute(attempt);\n return { ok: true, value };\n } catch (error) {\n if (signal?.aborted) {\n const attempts = Math.max(0, attempt - 1);\n return {\n ok: false,\n error: toRetryError(signal.reason, attempts),\n attempts,\n };\n }\n\n const typedError = error as TError;\n const decision = this.next({\n attempt,\n error: typedError,\n });\n\n if (!decision.shouldRetry) {\n const terminalError = this.onExhausted({\n attempts: attempt,\n error: typedError,\n });\n\n return {\n ok: false,\n error: terminalError,\n attempts: attempt,\n };\n }\n\n if (decision.delayMs > 0) {\n if (signal) {\n try {\n await sleepWithAbortSignal(sleep, decision.delayMs, signal);\n } catch (error) {\n if (signal.aborted) {\n return {\n ok: false,\n error: toRetryError(signal.reason, attempt),\n attempts: attempt,\n };\n }\n throw error;\n }\n } else {\n await sleep(decision.delayMs);\n }\n }\n\n attempt += 1;\n }\n }\n }\n}\n\n/**\n * Default delay implementation used by `run(...)` when no custom sleep function is provided.\n *\n * Returns immediately when `delayMs` is non-positive.\n */\nexport async function defaultSleep(delayMs: number): Promise<void> {\n if (delayMs <= 0) {\n return;\n }\n\n await new Promise((resolve) => setTimeout(resolve, delayMs));\n}\n\n/**\n * Throws an abort error when the provided signal is already aborted.\n *\n * @param signal - Optional cancellation signal.\n * @throws {Error} Abort reason converted to an `Error`.\n */\nfunction throwIfAborted(signal?: AbortSignal): void {\n if (!signal?.aborted) {\n return;\n }\n\n throw toAbortError(signal.reason);\n}\n\n/**\n * Normalizes an abort reason value into an `Error` instance.\n *\n * @param reason - Abort reason from `AbortSignal.reason`.\n * @returns Normalized error instance.\n */\nfunction toAbortError(reason: unknown): Error {\n if (reason instanceof Error) {\n return reason;\n }\n\n if (typeof reason === \"string\" && reason.length > 0) {\n return new Error(reason);\n }\n\n if (reason === undefined) {\n return new Error(\"Retry aborted.\");\n }\n\n try {\n return new Error(`Retry aborted: ${JSON.stringify(reason)}`);\n } catch {\n return new Error(\"Retry aborted.\");\n }\n}\n\n/**\n * Converts an abort reason into a `RetryError` for non-throw runner mode.\n *\n * @param reason - Abort reason from `AbortSignal.reason`.\n * @returns Retry terminal error value.\n */\nfunction toRetryError(reason: unknown, attempts: number): RetryError {\n const abortError = toAbortError(reason);\n return new RetryError(abortError.message, {\n attempts,\n lastError: abortError,\n });\n}\n\n/**\n * Awaits delay sleep while also observing cancellation via `AbortSignal`.\n *\n * @param sleep - Delay function.\n * @param delayMs - Delay duration in milliseconds.\n * @param signal - Cancellation signal.\n * @throws {Error} Abort reason converted to an `Error` when canceled.\n */\nasync function sleepWithAbortSignal(\n sleep: (delayMs: number) => Promise<void>,\n delayMs: number,\n signal: AbortSignal,\n): Promise<void> {\n if (signal.aborted) {\n throw toAbortError(signal.reason);\n }\n\n let onAbort: (() => void) | undefined;\n\n try {\n await Promise.race([\n sleep(delayMs),\n new Promise<never>((_, reject) => {\n onAbort = (): void => {\n reject(toAbortError(signal.reason));\n };\n\n signal.addEventListener(\"abort\", onAbort, { once: true });\n }),\n ]);\n } finally {\n if (onAbort) {\n signal.removeEventListener(\"abort\", onAbort);\n }\n }\n}\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;;;;;AAWJ,eAAe,qBACb,OACA,SACA,QACe;AACf,KAAI,OAAO,QACT,OAAM,aAAa,OAAO,OAAO;CAGnC,IAAI;AAEJ,KAAI;AACF,QAAM,QAAQ,KAAK,CACjB,MAAM,QAAQ,EACd,IAAI,SAAgB,GAAG,WAAW;AAChC,mBAAsB;AACpB,WAAO,aAAa,OAAO,OAAO,CAAC;;AAGrC,UAAO,iBAAiB,SAAS,SAAS,EAAE,MAAM,MAAM,CAAC;IACzD,CACH,CAAC;WACM;AACR,MAAI,QACF,QAAO,oBAAoB,SAAS,QAAQ"}
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Retry runner base class and shared orchestration implementation.\n *\n * @module @zap-studio/retry\n */\n\nimport { RetryError } from \"./errors.js\";\nimport { runResultMode } from \"./result-mode.js\";\nimport { defaultSleep } from \"./sleep.js\";\nimport { runThrowMode } from \"./throw-mode.js\";\nimport type {\n RetryDecision,\n RetryDecisionInput,\n RetryExhaustedInput,\n RetryPolicy,\n RetryRunOptions,\n RetryRunResult,\n} from \"./types.js\";\n\n/**\n * Base class for implementing retry policies and running retry orchestration.\n *\n * Extend this class and implement {@link BaseRetryPolicy.next} to define retry\n * behavior, then call {@link BaseRetryPolicy.run} to execute operations with that\n * policy.\n */\nexport abstract class BaseRetryPolicy<\n TError = unknown,\n TData = unknown,\n> implements RetryPolicy<TError, TData> {\n /**\n * Returns the retry decision for a failed attempt.\n *\n * @param input - Attempt context used to compute retry behavior.\n * @throws {Error} Any error thrown by a concrete retry policy implementation.\n */\n public abstract next(input: RetryDecisionInput<TError, TData>): RetryDecision;\n\n /**\n * Builds the terminal error thrown or returned when retries are exhausted.\n *\n * Override this when you need custom terminal error types.\n *\n * @param input - Exhaustion context.\n * @returns `RetryError` by default.\n * @throws {Error} Any error thrown by an overriding policy implementation.\n */\n // oxlint-disable-next-line class-methods-use-this -- RetryPolicy requires an instance hook that subclasses may override.\n public onExhausted(input: RetryExhaustedInput<TError, TData>): RetryError {\n return new RetryError(\"Retry policy exhausted all attempts.\", {\n attempts: input.attempts,\n lastData: input.data,\n lastError: input.error,\n });\n }\n\n /**\n * Runs retry orchestration in non-throw mode.\n *\n * @param execute - Async function to execute per attempt.\n * @param options - Runner settings with `throwOnExhausted: false`.\n * @returns A discriminated result union containing success value or terminal error.\n * @throws {Error} Any error thrown by `next`, `onExhausted`, or a custom `sleep`.\n */\n public async run<T>(\n execute: (attempt: number) => Promise<T>,\n options: RetryRunOptions & { throwOnExhausted: false }\n ): Promise<RetryRunResult<T>>;\n\n /**\n * Runs retry orchestration and throws terminal error on exhaustion.\n *\n * @param execute - Async function to execute per attempt.\n * @param options - Optional runner settings.\n * @returns The successful execution value.\n * @throws {RetryError} When retries are exhausted and `onExhausted` returns the\n * terminal retry error. The default implementation returns `RetryError` with the last\n * execution failure available on `RetryError.lastError`.\n * @throws {AbortError} When `options.signal` is already aborted or aborts while retrying.\n * @throws {Error} Any error thrown by `next`, by `onExhausted`, or by a custom `sleep`\n * function.\n */\n public async run<T>(\n execute: (attempt: number) => Promise<T>,\n options?: RetryRunOptions & { throwOnExhausted?: true }\n ): Promise<T>;\n\n /**\n * Runs retry orchestration in non-throw mode.\n *\n * When `throwOnExhausted` is `false`, returns a discriminated result union.\n *\n * @param execute - Async function to execute per attempt.\n * @param options - Runner settings.\n * @returns Success value or terminal result object based on option mode.\n * @throws {Error} Any error thrown by `next`, by `onExhausted`, or by a custom `sleep`\n * function. When `throwOnExhausted` is `false`, exhaustion itself is returned\n * as `{ ok: false }` instead of thrown.\n * Cancellation is returned as `{ ok: false, error: AbortError }` in non-throw\n * mode.\n *\n * @example\n * const result = await policy.run(doWork, { throwOnExhausted: false });\n * if (!result.ok) console.error(result.error);\n */\n public async run<T>(\n execute: (attempt: number) => Promise<T>,\n options: RetryRunOptions = {}\n ): Promise<T | RetryRunResult<T>> {\n const sleep = options.sleep ?? defaultSleep;\n const { signal } = options;\n if (options.throwOnExhausted === false) {\n return await runResultMode(this, execute, sleep, signal);\n }\n\n return await runThrowMode(this, execute, sleep, signal);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AA0BA,IAAsB,kBAAtB,MAGwC;;;;;;;;;;CAmBtC,YAAmB,OAAuD;EACxE,OAAO,IAAI,WAAW,wCAAwC;GAC5D,UAAU,MAAM;GAChB,UAAU,MAAM;GAChB,WAAW,MAAM;EACnB,CAAC;CACH;;;;;;;;;;;;;;;;;;;CAmDA,MAAa,IACX,SACA,UAA2B,CAAC,GACI;EAChC,MAAM,QAAQ,QAAQ,SAAS;EAC/B,MAAM,EAAE,WAAW;EACnB,IAAI,QAAQ,qBAAqB,OAC/B,OAAO,MAAM,cAAc,MAAM,SAAS,OAAO,MAAM;EAGzD,OAAO,MAAM,aAAa,MAAM,SAAS,OAAO,MAAM;CACxD;AACF"}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { RetryPolicy, RetryRunResult } from "./types.mjs";
|
|
2
|
+
//#region src/result-mode.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Runs the non-throw retry loop, returning
|
|
5
|
+
* `RetryRunResult`.
|
|
6
|
+
*
|
|
7
|
+
* @param policy - Object providing `next` and `onExhausted` (same contract as
|
|
8
|
+
* `BaseRetryPolicy`).
|
|
9
|
+
* @param execute - Async work callback per attempt.
|
|
10
|
+
* @param sleep - Delay function between retries.
|
|
11
|
+
* @param signal - Optional cancel signal.
|
|
12
|
+
* @returns Terminal success or failure object.
|
|
13
|
+
* @throws {Error} Any error thrown by `next`, `onExhausted`, or a non-abort `sleep`
|
|
14
|
+
* failure.
|
|
15
|
+
*/
|
|
16
|
+
declare const runResultMode: <T, TError, TData>(policy: RetryPolicy<TError, TData>, execute: (attempt: number) => Promise<T>, sleep: (delayMs: number) => Promise<void>, signal?: AbortSignal) => Promise<RetryRunResult<T>>;
|
|
17
|
+
//#endregion
|
|
18
|
+
export { runResultMode };
|
|
19
|
+
//# sourceMappingURL=result-mode.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"result-mode.d.mts","names":[],"sources":["../src/result-mode.ts"],"mappings":";;;;;;;;;;;;;;;cA0Ka,gBAAuB,GAAG,QAAQ,OAC7C,QAAQ,YAAY,QAAQ,QAC5B,UAAU,oBAAoB,QAAQ,IACtC,QAAQ,oBAAoB,eAC5B,SAAS,gBACR,QAAQ,eAAe"}
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
import { sleepWithAbortSignal, toAbortError } from "./abort.mjs";
|
|
2
|
+
//#region src/result-mode.ts
|
|
3
|
+
/**
|
|
4
|
+
* Result-mode execution path for `BaseRetryPolicy.run` when
|
|
5
|
+
* `throwOnExhausted: false` is set.
|
|
6
|
+
*
|
|
7
|
+
* @module @zap-studio/retry/result-mode
|
|
8
|
+
*/
|
|
9
|
+
/**
|
|
10
|
+
* When `signal` is already aborted, builds the terminal `{ ok: false }` object
|
|
11
|
+
* with a normalized `AbortError` on `error`.
|
|
12
|
+
*
|
|
13
|
+
* @param signal - Optional abort signal; only acts when `aborted` is set.
|
|
14
|
+
* @param attempts - Number of finished attempts to report in the result.
|
|
15
|
+
* @returns Failure result or `undefined` if not aborted.
|
|
16
|
+
*/
|
|
17
|
+
const buildAbortResult = (signal, attempts) => {
|
|
18
|
+
if (signal?.aborted !== true) return;
|
|
19
|
+
return {
|
|
20
|
+
attempts,
|
|
21
|
+
error: toAbortError(signal.reason),
|
|
22
|
+
ok: false
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* Runs one `execute(attempt)` call and returns either a success value or a
|
|
27
|
+
* captured error without rethrowing.
|
|
28
|
+
*
|
|
29
|
+
* @param execute - User work callback.
|
|
30
|
+
* @param attempt - One-based attempt number passed to `execute`.
|
|
31
|
+
* @returns A tagged success with `value` or a tagged failure with `error`.
|
|
32
|
+
*/
|
|
33
|
+
const runAttempt = async (execute, attempt) => {
|
|
34
|
+
try {
|
|
35
|
+
return {
|
|
36
|
+
ok: true,
|
|
37
|
+
value: await execute(attempt)
|
|
38
|
+
};
|
|
39
|
+
} catch (error) {
|
|
40
|
+
return {
|
|
41
|
+
error,
|
|
42
|
+
ok: false
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Awaits inter-attempt delay in result mode, mapping an abort during wait to
|
|
48
|
+
* a terminal result instead of throwing when `throwOnExhausted` is false.
|
|
49
|
+
*
|
|
50
|
+
* @param sleep - Custom or default sleep implementation.
|
|
51
|
+
* @param delayMs - Milliseconds to wait.
|
|
52
|
+
* @param signal - If set, `sleep` is raced with the abort signal.
|
|
53
|
+
* @param attempts - Attempt count to attach if the wait ends in abort.
|
|
54
|
+
* @returns A terminal result when canceled during the wait, otherwise
|
|
55
|
+
* `undefined`.
|
|
56
|
+
* @throws {Error} The underlying `sleep` rejection when it is not an abort.
|
|
57
|
+
*/
|
|
58
|
+
const waitForDelay = async (sleep, delayMs, signal, attempts) => {
|
|
59
|
+
if (signal === void 0) {
|
|
60
|
+
await sleep(delayMs);
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
await sleepWithAbortSignal(sleep, delayMs, signal);
|
|
65
|
+
return;
|
|
66
|
+
} catch (error) {
|
|
67
|
+
const aborted = buildAbortResult(signal, attempts);
|
|
68
|
+
if (aborted !== void 0) return aborted;
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
};
|
|
72
|
+
/**
|
|
73
|
+
* After a failed attempt, applies abort rules, `next`, optional delay, and
|
|
74
|
+
* either returns a terminal `RetryRunResult` or `undefined` to continue.
|
|
75
|
+
*
|
|
76
|
+
* @param policy - Retry policy hooks (`next`, `onExhausted`) matching
|
|
77
|
+
* `BaseRetryPolicy`.
|
|
78
|
+
* @param params - Failure context for the current attempt.
|
|
79
|
+
* @param params.attempt - Current attempt number.
|
|
80
|
+
* @param params.error - Error thrown by the attempt.
|
|
81
|
+
* @param params.sleep - Delay function between retries.
|
|
82
|
+
* @param params.signal - Optional abort signal.
|
|
83
|
+
* @returns Terminal non-throw result if the loop should stop, otherwise
|
|
84
|
+
* `undefined` to schedule another attempt.
|
|
85
|
+
* @throws {Error} Any error thrown by `next`, `onExhausted`, or a custom `sleep` when
|
|
86
|
+
* the error is not an abort.
|
|
87
|
+
*/
|
|
88
|
+
const handleFailure = async (policy, params) => {
|
|
89
|
+
const { attempt, error, sleep, signal } = params;
|
|
90
|
+
const abortResult = buildAbortResult(signal, attempt);
|
|
91
|
+
if (abortResult !== void 0) return abortResult;
|
|
92
|
+
const decision = policy.next({
|
|
93
|
+
attempt,
|
|
94
|
+
error
|
|
95
|
+
});
|
|
96
|
+
if (!decision.shouldRetry) return {
|
|
97
|
+
attempts: attempt,
|
|
98
|
+
error: policy.onExhausted({
|
|
99
|
+
attempts: attempt,
|
|
100
|
+
error
|
|
101
|
+
}),
|
|
102
|
+
ok: false
|
|
103
|
+
};
|
|
104
|
+
if (decision.delayMs > 0) {
|
|
105
|
+
const delayAbortResult = await waitForDelay(sleep, decision.delayMs, signal, attempt);
|
|
106
|
+
if (delayAbortResult !== void 0) return delayAbortResult;
|
|
107
|
+
}
|
|
108
|
+
};
|
|
109
|
+
/**
|
|
110
|
+
* Runs the non-throw retry loop, returning
|
|
111
|
+
* `RetryRunResult`.
|
|
112
|
+
*
|
|
113
|
+
* @param policy - Object providing `next` and `onExhausted` (same contract as
|
|
114
|
+
* `BaseRetryPolicy`).
|
|
115
|
+
* @param execute - Async work callback per attempt.
|
|
116
|
+
* @param sleep - Delay function between retries.
|
|
117
|
+
* @param signal - Optional cancel signal.
|
|
118
|
+
* @returns Terminal success or failure object.
|
|
119
|
+
* @throws {Error} Any error thrown by `next`, `onExhausted`, or a non-abort `sleep`
|
|
120
|
+
* failure.
|
|
121
|
+
*/
|
|
122
|
+
const runResultMode = async (policy, execute, sleep, signal) => {
|
|
123
|
+
let attempt = 1;
|
|
124
|
+
while (true) {
|
|
125
|
+
const abortResult = buildAbortResult(signal, Math.max(0, attempt - 1));
|
|
126
|
+
if (abortResult !== void 0) return abortResult;
|
|
127
|
+
const execution = await runAttempt(execute, attempt);
|
|
128
|
+
if (execution.ok) return {
|
|
129
|
+
ok: true,
|
|
130
|
+
value: execution.value
|
|
131
|
+
};
|
|
132
|
+
const failure = await handleFailure(policy, {
|
|
133
|
+
attempt,
|
|
134
|
+
error: execution.error,
|
|
135
|
+
signal,
|
|
136
|
+
sleep
|
|
137
|
+
});
|
|
138
|
+
if (failure !== void 0) return failure;
|
|
139
|
+
attempt += 1;
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
//#endregion
|
|
143
|
+
export { runResultMode };
|
|
144
|
+
|
|
145
|
+
//# sourceMappingURL=result-mode.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"result-mode.mjs","names":[],"sources":["../src/result-mode.ts"],"sourcesContent":["/**\n * Result-mode execution path for `BaseRetryPolicy.run` when\n * `throwOnExhausted: false` is set.\n *\n * @module @zap-studio/retry/result-mode\n */\n\nimport { sleepWithAbortSignal, toAbortError } from \"./abort.js\";\nimport type { RetryPolicy, RetryRunResult } from \"./types.js\";\n\n/**\n * When `signal` is already aborted, builds the terminal `{ ok: false }` object\n * with a normalized `AbortError` on `error`.\n *\n * @param signal - Optional abort signal; only acts when `aborted` is set.\n * @param attempts - Number of finished attempts to report in the result.\n * @returns Failure result or `undefined` if not aborted.\n */\nconst buildAbortResult = (\n signal: AbortSignal | undefined,\n attempts: number\n): RetryRunResult<never> | undefined => {\n if (signal?.aborted !== true) {\n return undefined;\n }\n\n return {\n attempts,\n error: toAbortError(signal.reason),\n ok: false,\n };\n};\n\n/**\n * Runs one `execute(attempt)` call and returns either a success value or a\n * captured error without rethrowing.\n *\n * @param execute - User work callback.\n * @param attempt - One-based attempt number passed to `execute`.\n * @returns A tagged success with `value` or a tagged failure with `error`.\n */\nconst runAttempt = async <T>(\n execute: (attempt: number) => Promise<T>,\n attempt: number\n): Promise<{ ok: true; value: T } | { ok: false; error: unknown }> => {\n try {\n return {\n ok: true,\n value: await execute(attempt),\n };\n } catch (error) {\n return {\n error,\n ok: false,\n };\n }\n};\n\n/**\n * Awaits inter-attempt delay in result mode, mapping an abort during wait to\n * a terminal result instead of throwing when `throwOnExhausted` is false.\n *\n * @param sleep - Custom or default sleep implementation.\n * @param delayMs - Milliseconds to wait.\n * @param signal - If set, `sleep` is raced with the abort signal.\n * @param attempts - Attempt count to attach if the wait ends in abort.\n * @returns A terminal result when canceled during the wait, otherwise\n * `undefined`.\n * @throws {Error} The underlying `sleep` rejection when it is not an abort.\n */\nconst waitForDelay = async (\n sleep: (delayMs: number) => Promise<void>,\n delayMs: number,\n signal: AbortSignal | undefined,\n attempts: number\n): Promise<RetryRunResult<never> | undefined> => {\n if (signal === undefined) {\n await sleep(delayMs);\n return undefined;\n }\n\n try {\n await sleepWithAbortSignal(sleep, delayMs, signal);\n return undefined;\n } catch (error) {\n const aborted = buildAbortResult(signal, attempts);\n if (aborted !== undefined) {\n return aborted;\n }\n throw error;\n }\n};\n\n/**\n * After a failed attempt, applies abort rules, `next`, optional delay, and\n * either returns a terminal `RetryRunResult` or `undefined` to continue.\n *\n * @param policy - Retry policy hooks (`next`, `onExhausted`) matching\n * `BaseRetryPolicy`.\n * @param params - Failure context for the current attempt.\n * @param params.attempt - Current attempt number.\n * @param params.error - Error thrown by the attempt.\n * @param params.sleep - Delay function between retries.\n * @param params.signal - Optional abort signal.\n * @returns Terminal non-throw result if the loop should stop, otherwise\n * `undefined` to schedule another attempt.\n * @throws {Error} Any error thrown by `next`, `onExhausted`, or a custom `sleep` when\n * the error is not an abort.\n */\nconst handleFailure = async <TError, TData>(\n policy: RetryPolicy<TError, TData>,\n params: {\n attempt: number;\n error: TError;\n sleep: (delayMs: number) => Promise<void>;\n signal: AbortSignal | undefined;\n }\n): Promise<RetryRunResult<never> | undefined> => {\n const { attempt, error, sleep, signal } = params;\n const abortResult = buildAbortResult(signal, attempt);\n if (abortResult !== undefined) {\n return abortResult;\n }\n\n const decision = policy.next({\n attempt,\n error,\n });\n\n if (!decision.shouldRetry) {\n const terminalError = policy.onExhausted({\n attempts: attempt,\n error,\n });\n\n return {\n attempts: attempt,\n error: terminalError,\n ok: false,\n };\n }\n\n if (decision.delayMs > 0) {\n const delayAbortResult = await waitForDelay(\n sleep,\n decision.delayMs,\n signal,\n attempt\n );\n if (delayAbortResult !== undefined) {\n return delayAbortResult;\n }\n }\n\n return undefined;\n};\n\n/**\n * Runs the non-throw retry loop, returning\n * `RetryRunResult`.\n *\n * @param policy - Object providing `next` and `onExhausted` (same contract as\n * `BaseRetryPolicy`).\n * @param execute - Async work callback per attempt.\n * @param sleep - Delay function between retries.\n * @param signal - Optional cancel signal.\n * @returns Terminal success or failure object.\n * @throws {Error} Any error thrown by `next`, `onExhausted`, or a non-abort `sleep`\n * failure.\n */\nexport const runResultMode = async <T, TError, TData>(\n policy: RetryPolicy<TError, TData>,\n execute: (attempt: number) => Promise<T>,\n sleep: (delayMs: number) => Promise<void>,\n signal?: AbortSignal\n): Promise<RetryRunResult<T>> => {\n let attempt = 1;\n\n while (true) {\n const abortResult = buildAbortResult(signal, Math.max(0, attempt - 1));\n if (abortResult !== undefined) {\n return abortResult;\n }\n\n // oxlint-disable-next-line no-await-in-loop -- Retry attempts must run sequentially.\n const execution = await runAttempt(execute, attempt);\n if (execution.ok) {\n return { ok: true, value: execution.value };\n }\n\n // oxlint-disable-next-line no-await-in-loop -- Failure handling belongs to the current sequential attempt.\n const failure = await handleFailure(policy, {\n attempt,\n // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- Policy error generic represents the caller's thrown error domain.\n error: execution.error as TError,\n signal,\n sleep,\n });\n if (failure !== undefined) {\n return failure;\n }\n\n attempt += 1;\n }\n};\n"],"mappings":";;;;;;;;;;;;;;;;AAkBA,MAAM,oBACJ,QACA,aACsC;CACtC,IAAI,QAAQ,YAAY,MACtB;CAGF,OAAO;EACL;EACA,OAAO,aA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W,SAAS,OAAO;EACnD,IAAI,UAAU,IACZ,OAAO;GAAE,IAAI;GAAM,OAAO,UAAU;EAAM;EAI5C,MAAM,UAAU,MAAM,cAAc,QAAQ;GAC1C;GAEA,OAAO,UAAU;GACjB;GACA;EACF,CAAC;EACD,IAAI,YAAY,KAAA,GACd,OAAO;EAGT,WAAW;CACb;AACF"}
|
package/dist/sleep.d.mts
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
//#region src/sleep.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Default delay implementation used by `BaseRetryPolicy.run` when no custom
|
|
4
|
+
* `sleep` is provided.
|
|
5
|
+
*
|
|
6
|
+
* @module @zap-studio/retry/sleep
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Awaits a timer-based delay, unless `delayMs` is non-positive.
|
|
10
|
+
*
|
|
11
|
+
* @param delayMs - Milliseconds to wait before resolving.
|
|
12
|
+
* @returns Promise that resolves when the delay completes.
|
|
13
|
+
*/
|
|
14
|
+
declare const defaultSleep: (delayMs: number) => Promise<void>;
|
|
15
|
+
//#endregion
|
|
16
|
+
export { defaultSleep };
|
|
17
|
+
//# sourceMappingURL=sleep.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sleep.d.mts","names":[],"sources":["../src/sleep.ts"],"mappings":";;;;;;;;;;;;;cAaa,eAAsB,oBAAkB"}
|
package/dist/sleep.mjs
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
//#region src/sleep.ts
|
|
2
|
+
/**
|
|
3
|
+
* Default delay implementation used by `BaseRetryPolicy.run` when no custom
|
|
4
|
+
* `sleep` is provided.
|
|
5
|
+
*
|
|
6
|
+
* @module @zap-studio/retry/sleep
|
|
7
|
+
*/
|
|
8
|
+
/**
|
|
9
|
+
* Awaits a timer-based delay, unless `delayMs` is non-positive.
|
|
10
|
+
*
|
|
11
|
+
* @param delayMs - Milliseconds to wait before resolving.
|
|
12
|
+
* @returns Promise that resolves when the delay completes.
|
|
13
|
+
*/
|
|
14
|
+
const defaultSleep = async (delayMs) => {
|
|
15
|
+
if (delayMs <= 0) return;
|
|
16
|
+
await new Promise((resolve) => {
|
|
17
|
+
setTimeout(resolve, delayMs);
|
|
18
|
+
});
|
|
19
|
+
};
|
|
20
|
+
//#endregion
|
|
21
|
+
export { defaultSleep };
|
|
22
|
+
|
|
23
|
+
//# sourceMappingURL=sleep.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sleep.mjs","names":[],"sources":["../src/sleep.ts"],"sourcesContent":["/**\n * Default delay implementation used by `BaseRetryPolicy.run` when no custom\n * `sleep` is provided.\n *\n * @module @zap-studio/retry/sleep\n */\n\n/**\n * Awaits a timer-based delay, unless `delayMs` is non-positive.\n *\n * @param delayMs - Milliseconds to wait before resolving.\n * @returns Promise that resolves when the delay completes.\n */\nexport const defaultSleep = async (delayMs: number): Promise<void> => {\n if (delayMs <= 0) {\n return;\n }\n\n // oxlint-disable-next-line promise/avoid-new -- Timer sleep requires adapting callback API to a promise.\n await new Promise<void>((resolve) => {\n setTimeout(resolve, delayMs);\n });\n};\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,eAAe,OAAO,YAAmC;CACpE,IAAI,WAAW,GACb;CAIF,MAAM,IAAI,SAAe,YAAY;EACnC,WAAW,SAAS,OAAO;CAC7B,CAAC;AACH"}
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { RetryPolicy } from "./types.mjs";
|
|
2
|
+
//#region src/throw-mode.d.ts
|
|
3
|
+
/**
|
|
4
|
+
* Runs the throw-mode retry loop: throws `RetryError` on exhaustion and
|
|
5
|
+
* `AbortError` when `signal` aborts.
|
|
6
|
+
*
|
|
7
|
+
* @param policy - Object providing `next` and `onExhausted` (same contract as
|
|
8
|
+
* `BaseRetryPolicy`).
|
|
9
|
+
* @param execute - Async work callback per attempt.
|
|
10
|
+
* @param sleep - Delay function between retries.
|
|
11
|
+
* @param signal - Optional cancel signal.
|
|
12
|
+
* @returns Resolves to the first successful return value.
|
|
13
|
+
* @throws {RetryError} When retries are exhausted and `onExhausted` returns
|
|
14
|
+
* the terminal error.
|
|
15
|
+
* @throws {AbortError} When `signal` is already aborted or aborts while waiting.
|
|
16
|
+
* @throws {Error} Any error thrown by `next`, `onExhausted`, or `sleep`.
|
|
17
|
+
*/
|
|
18
|
+
declare const runThrowMode: <T, TError, TData>(policy: RetryPolicy<TError, TData>, execute: (attempt: number) => Promise<T>, sleep: (delayMs: number) => Promise<void>, signal?: AbortSignal) => Promise<T>;
|
|
19
|
+
//#endregion
|
|
20
|
+
export { runThrowMode };
|
|
21
|
+
//# sourceMappingURL=throw-mode.d.mts.map
|