@backendkit-labs/retry 0.1.2 → 0.2.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/README.md +51 -20
- package/dist/{chunk-MTBUSC7V.cjs → chunk-BX4TTYBY.cjs} +122 -79
- package/dist/chunk-BX4TTYBY.cjs.map +1 -0
- package/dist/{chunk-6UD5URCQ.js → chunk-NV6QXLUR.js} +122 -78
- package/dist/chunk-NV6QXLUR.js.map +1 -0
- package/dist/index.cjs +52 -24
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -8
- package/dist/index.d.ts +17 -8
- package/dist/index.js +37 -3
- package/dist/index.js.map +1 -1
- package/dist/nestjs/index.cjs +25 -8
- package/dist/nestjs/index.cjs.map +1 -1
- package/dist/nestjs/index.d.cts +23 -2
- package/dist/nestjs/index.d.ts +23 -2
- package/dist/nestjs/index.js +23 -6
- package/dist/nestjs/index.js.map +1 -1
- package/dist/{retry.engine-ETXna-Ud.d.cts → retry.engine-DZPAMpkR.d.cts} +15 -2
- package/dist/{retry.engine-ETXna-Ud.d.ts → retry.engine-DZPAMpkR.d.ts} +15 -2
- package/package.json +2 -1
- package/dist/chunk-6UD5URCQ.js.map +0 -1
- package/dist/chunk-MTBUSC7V.cjs.map +0 -1
package/README.md
CHANGED
|
@@ -67,23 +67,24 @@ npm install @nestjs/common @nestjs/core rxjs
|
|
|
67
67
|
|
|
68
68
|
## Quick Start
|
|
69
69
|
|
|
70
|
-
`
|
|
70
|
+
`retry()` is a standalone function backed by a global registry. It covers 90% of use cases in two lines:
|
|
71
71
|
|
|
72
72
|
```typescript
|
|
73
|
-
import {
|
|
73
|
+
import { retry } from '@backendkit-labs/retry';
|
|
74
|
+
import { match } from '@backendkit-labs/result';
|
|
74
75
|
|
|
75
76
|
const result = await retry(() => fetchUser(userId), {
|
|
76
77
|
maxAttempts: 3,
|
|
77
78
|
backoff: { type: 'exponential', baseDelay: 200 },
|
|
78
79
|
});
|
|
79
80
|
|
|
80
|
-
|
|
81
|
-
(user)
|
|
82
|
-
(error) => res.status(502).json({ error: error.message }),
|
|
83
|
-
);
|
|
81
|
+
match(result, {
|
|
82
|
+
ok: (user) => res.json(user),
|
|
83
|
+
fail: (error) => res.status(502).json({ error: error.message }),
|
|
84
|
+
});
|
|
84
85
|
```
|
|
85
86
|
|
|
86
|
-
`
|
|
87
|
+
`retry()` returns `Result<T, RetryError>` — a plain `{ ok, value } | { ok, error }` object — and **never throws**. Check `result.ok`, or use `match()` from `@backendkit-labs/result` to handle both paths.
|
|
87
88
|
|
|
88
89
|
### Minimal retry with default config
|
|
89
90
|
|
|
@@ -211,7 +212,9 @@ await retry(task, {
|
|
|
211
212
|
});
|
|
212
213
|
```
|
|
213
214
|
|
|
214
|
-
Both accept a plain function `(error: RetryErrorPayload) => boolean | Promise<boolean>` or an object implementing `RetryCondition` / `AbortCondition`.
|
|
215
|
+
Both accept a plain function `(error: RetryErrorPayload) => boolean | Promise<boolean>` or an object implementing `RetryCondition` / `AbortCondition`.
|
|
216
|
+
|
|
217
|
+
**Default behavior is driven by the [classifier](#classifiers):** an error classified `'transient'` retries, `'permanent'` aborts (5xx/network/timeout → transient; 4xx except 429 → permanent, by default). Supplying custom `classifiers` changes this default without needing to also set `retryIf`/`abortIf`. `retryIf`/`abortIf` are independent overrides on top of that -- `abortIf` is checked first, so if you only override `retryIf` to force a retry, also set `abortIf: () => false` or the classifier-driven default abort will still win.
|
|
215
218
|
|
|
216
219
|
### timeout
|
|
217
220
|
|
|
@@ -230,6 +233,17 @@ await retry(task, {
|
|
|
230
233
|
- `globalTimeoutMs` expiration → operation aborted immediately regardless of attempt count
|
|
231
234
|
- `0` means unlimited (default)
|
|
232
235
|
|
|
236
|
+
Your task receives an `AbortSignal` that fires on either timeout -- pass it through to anything that supports cancellation (`fetch`, database drivers, etc.) so a timed-out attempt actually stops instead of just being abandoned:
|
|
237
|
+
|
|
238
|
+
```typescript
|
|
239
|
+
await retry(
|
|
240
|
+
(signal) => fetch('https://api.example.com/data', { signal }).then(r => r.json()),
|
|
241
|
+
{ timeout: { attemptTimeoutMs: 5_000 } },
|
|
242
|
+
);
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
A task that ignores the signal (most existing code) keeps running in the background after the timeout fires -- `retry()` stops waiting on it and moves to the next attempt, but the abandoned call isn't force-killed. The signal is optional to use; omitting the parameter is fine and behaves exactly as before.
|
|
246
|
+
|
|
233
247
|
### budget
|
|
234
248
|
|
|
235
249
|
Sliding-window budget prevents retry storms. If the ratio of retries to total calls exceeds `maxRetryRatio` in the last `windowMs` milliseconds, further retries are rejected.
|
|
@@ -304,7 +318,7 @@ await retry(task, {
|
|
|
304
318
|
|
|
305
319
|
### classifiers
|
|
306
320
|
|
|
307
|
-
Add custom rules that classify errors as `'transient'` (retryable) or `'permanent'` (abort):
|
|
321
|
+
Add custom rules that classify errors as `'transient'` (retryable) or `'permanent'` (abort). This classification **is** the default retry/abort decision (see [retryIf / abortIf](#retryif--abortif)) -- adding a rule here changes what actually gets retried, not just how it's logged:
|
|
308
322
|
|
|
309
323
|
```typescript
|
|
310
324
|
await retry(task, {
|
|
@@ -463,7 +477,7 @@ The circuit breaker controls whether to attempt a call. `Retry` checks it before
|
|
|
463
477
|
import { CircuitBreaker } from '@backendkit-labs/circuit-breaker';
|
|
464
478
|
import { RetryEngine } from '@backendkit-labs/retry';
|
|
465
479
|
|
|
466
|
-
const cb = new CircuitBreaker({ name: 'payments',
|
|
480
|
+
const cb = new CircuitBreaker({ name: 'payments', failureThreshold: 50, minimumCalls: 5 });
|
|
467
481
|
|
|
468
482
|
const engine = new RetryEngine({
|
|
469
483
|
name: 'payments',
|
|
@@ -515,20 +529,21 @@ const engine = new RetryEngine({
|
|
|
515
529
|
|
|
516
530
|
### `@backendkit-labs/result`
|
|
517
531
|
|
|
518
|
-
`
|
|
532
|
+
`retry()` already returns `Result<T, RetryError>` — direct integration, no adapter needed:
|
|
519
533
|
|
|
520
534
|
```typescript
|
|
521
|
-
import {
|
|
535
|
+
import { retry } from '@backendkit-labs/retry';
|
|
536
|
+
import { match } from '@backendkit-labs/result';
|
|
522
537
|
|
|
523
538
|
const result = await retry(() => fetchOrder(id), {
|
|
524
539
|
maxAttempts: 3,
|
|
525
540
|
backoff: { type: 'exponential', baseDelay: 200 },
|
|
526
541
|
});
|
|
527
542
|
|
|
528
|
-
|
|
529
|
-
(order) => res.json(order),
|
|
530
|
-
(err) => res.status(502).json({ message: err.message, attempts: err.metadata.attempts }),
|
|
531
|
-
);
|
|
543
|
+
match(result, {
|
|
544
|
+
ok: (order) => res.json(order),
|
|
545
|
+
fail: (err) => res.status(502).json({ message: err.message, attempts: err.metadata.attempts }),
|
|
546
|
+
});
|
|
532
547
|
```
|
|
533
548
|
|
|
534
549
|
When combining with `@backendkit-labs/http-client` (which also returns `Result`), unwrap between layers so `Retry` sees a thrown error instead of a nested `Result`:
|
|
@@ -596,7 +611,7 @@ import { Bulkhead } from '@backendkit-labs/bulkhead';
|
|
|
596
611
|
import { Logger } from '@backendkit-labs/observability';
|
|
597
612
|
import { RetryEngine } from '@backendkit-labs/retry';
|
|
598
613
|
|
|
599
|
-
const cb = new CircuitBreaker({ name: 'payments',
|
|
614
|
+
const cb = new CircuitBreaker({ name: 'payments', failureThreshold: 50, minimumCalls: 5 });
|
|
600
615
|
const bulkhead = new Bulkhead({ maxConcurrent: 10, maxQueue: 20 });
|
|
601
616
|
const logger = new Logger({ service: 'payments-client' });
|
|
602
617
|
|
|
@@ -635,7 +650,7 @@ budget.recordCall()
|
|
|
635
650
|
|
|
636
651
|
## NestJS Integration
|
|
637
652
|
|
|
638
|
-
Import `RetryModule` once at the application root. It registers `RetryService` and
|
|
653
|
+
Import `RetryModule` once at the application root. It registers `RetryService` and, only if `globalInterceptor: true` is set (default: `false`), a global `RetryInterceptor`.
|
|
639
654
|
|
|
640
655
|
### Module setup
|
|
641
656
|
|
|
@@ -683,7 +698,7 @@ export class PaymentsService {
|
|
|
683
698
|
|
|
684
699
|
### @Retry decorator
|
|
685
700
|
|
|
686
|
-
|
|
701
|
+
Wraps the method directly -- works on any `@Injectable()` (or plain) class, with or without NestJS DI, no `RetryModule` import required:
|
|
687
702
|
|
|
688
703
|
```typescript
|
|
689
704
|
import { Retry } from '@backendkit-labs/retry/nestjs';
|
|
@@ -700,6 +715,22 @@ export class InventoryService {
|
|
|
700
715
|
}
|
|
701
716
|
```
|
|
702
717
|
|
|
718
|
+
Each `@Retry`-decorated method gets its own named `RetryEngine`, so `budget`/`idempotency` config actually accumulates across calls. By default that engine lives in an internal registry private to `@Retry`; inject `public readonly retryRegistry: RetryRegistry` on the class to use your own instead (so you can read its metrics, or share it with other code):
|
|
719
|
+
|
|
720
|
+
```typescript
|
|
721
|
+
import { RetryRegistry } from '@backendkit-labs/retry';
|
|
722
|
+
|
|
723
|
+
@Injectable()
|
|
724
|
+
export class InventoryService {
|
|
725
|
+
constructor(public readonly retryRegistry: RetryRegistry) {}
|
|
726
|
+
|
|
727
|
+
@Retry({ maxAttempts: 3 })
|
|
728
|
+
async reserveStock(productId: string, quantity: number) { ... }
|
|
729
|
+
}
|
|
730
|
+
```
|
|
731
|
+
|
|
732
|
+
`@Retry` also sets metadata for `RetryInterceptor` to read, but you don't need the interceptor for this to work -- the decorator retries the method itself. Only turn on `RetryModule`'s `globalInterceptor` if you specifically want pipeline-level retry (re-running `next.handle()`, including other interceptors) instead of method-level retry; enabling both for the same method retries it twice.
|
|
733
|
+
|
|
703
734
|
### DI tokens
|
|
704
735
|
|
|
705
736
|
Inject the underlying engine or registry directly:
|
|
@@ -751,7 +782,7 @@ registry.reset('payments');
|
|
|
751
782
|
|
|
752
783
|
## API Reference
|
|
753
784
|
|
|
754
|
-
### `
|
|
785
|
+
### `retry(task, options?)`
|
|
755
786
|
|
|
756
787
|
Standalone function using a global default registry.
|
|
757
788
|
|
|
@@ -10,6 +10,7 @@ var __decorateClass = (decorators, target, key, kind) => {
|
|
|
10
10
|
if (kind && result) __defProp(target, key, result);
|
|
11
11
|
return result;
|
|
12
12
|
};
|
|
13
|
+
var __decorateParam = (index, decorator) => (target, key) => decorator(target, key, index);
|
|
13
14
|
|
|
14
15
|
// src/timeout/timeout.errors.ts
|
|
15
16
|
var AttemptTimeoutError = class extends Error {
|
|
@@ -118,43 +119,74 @@ var DefaultErrorClassifier = class {
|
|
|
118
119
|
};
|
|
119
120
|
|
|
120
121
|
// src/timeout/timeout.manager.ts
|
|
122
|
+
var NEVER_ABORTS = new AbortController().signal;
|
|
123
|
+
function abortReason(signal) {
|
|
124
|
+
const reason = signal.reason;
|
|
125
|
+
return reason instanceof Error ? reason : new Error(String(reason));
|
|
126
|
+
}
|
|
121
127
|
var TimeoutManager = class {
|
|
122
128
|
constructor(config) {
|
|
123
129
|
this.config = config;
|
|
124
130
|
this.startTime = Date.now();
|
|
131
|
+
if (this.config.globalTimeoutMs && this.config.globalTimeoutMs > 0) {
|
|
132
|
+
this.globalController = new AbortController();
|
|
133
|
+
this.globalTimer = setTimeout(() => {
|
|
134
|
+
this.globalController.abort(
|
|
135
|
+
new GlobalTimeoutError(this.config.globalTimeoutMs, this.config.globalTimeoutMs)
|
|
136
|
+
);
|
|
137
|
+
}, this.config.globalTimeoutMs);
|
|
138
|
+
this.globalTimer.unref?.();
|
|
139
|
+
}
|
|
125
140
|
}
|
|
126
141
|
config;
|
|
127
142
|
startTime;
|
|
143
|
+
globalController;
|
|
144
|
+
globalTimer;
|
|
128
145
|
/**
|
|
129
|
-
* Execute a task with per-attempt timeout
|
|
130
|
-
*
|
|
146
|
+
* Execute a task with a per-attempt timeout, passing it an `AbortSignal`
|
|
147
|
+
* that fires when the attempt (or the overall global timeout) expires.
|
|
148
|
+
*
|
|
149
|
+
* A task that doesn't check the signal (e.g. doesn't pass it to `fetch`)
|
|
150
|
+
* keeps running in the background after we give up waiting on it -- we
|
|
151
|
+
* can only abandon the wait, not force JS execution to stop.
|
|
131
152
|
*/
|
|
132
153
|
async executeWithAttemptTimeout(task) {
|
|
133
|
-
if (
|
|
134
|
-
|
|
154
|
+
if (this.globalController?.signal.aborted) {
|
|
155
|
+
throw abortReason(this.globalController.signal);
|
|
135
156
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
157
|
+
if (!this.globalController && (!this.config.attemptTimeoutMs || this.config.attemptTimeoutMs <= 0)) {
|
|
158
|
+
return task(NEVER_ABORTS);
|
|
159
|
+
}
|
|
160
|
+
const attemptController = new AbortController();
|
|
161
|
+
const forwardGlobalAbort = () => {
|
|
162
|
+
attemptController.abort(this.globalController.signal.reason);
|
|
163
|
+
};
|
|
164
|
+
this.globalController?.signal.addEventListener("abort", forwardGlobalAbort, { once: true });
|
|
165
|
+
const attemptTimeoutMs = this.config.attemptTimeoutMs;
|
|
166
|
+
const timer = attemptTimeoutMs && attemptTimeoutMs > 0 ? setTimeout(() => attemptController.abort(new AttemptTimeoutError(attemptTimeoutMs)), attemptTimeoutMs) : void 0;
|
|
167
|
+
timer?.unref?.();
|
|
168
|
+
try {
|
|
169
|
+
return await new Promise((resolve, reject) => {
|
|
170
|
+
attemptController.signal.addEventListener(
|
|
171
|
+
"abort",
|
|
172
|
+
() => reject(abortReason(attemptController.signal)),
|
|
173
|
+
{ once: true }
|
|
174
|
+
);
|
|
175
|
+
task(attemptController.signal).then(resolve, reject);
|
|
146
176
|
});
|
|
147
|
-
}
|
|
177
|
+
} finally {
|
|
178
|
+
if (timer) clearTimeout(timer);
|
|
179
|
+
this.globalController?.signal.removeEventListener("abort", forwardGlobalAbort);
|
|
180
|
+
}
|
|
148
181
|
}
|
|
149
182
|
/**
|
|
150
|
-
* Check if the global timeout has
|
|
151
|
-
*
|
|
183
|
+
* Check if the global timeout has already fired. Called at the start of
|
|
184
|
+
* each attempt loop iteration -- the AbortSignal handles cutting off an
|
|
185
|
+
* attempt that's already in flight when the deadline hits.
|
|
152
186
|
*/
|
|
153
187
|
checkGlobalTimeout() {
|
|
154
|
-
if (
|
|
155
|
-
|
|
156
|
-
if (elapsed >= this.config.globalTimeoutMs) {
|
|
157
|
-
throw new GlobalTimeoutError(this.config.globalTimeoutMs, elapsed);
|
|
188
|
+
if (this.globalController?.signal.aborted) {
|
|
189
|
+
throw abortReason(this.globalController.signal);
|
|
158
190
|
}
|
|
159
191
|
}
|
|
160
192
|
/**
|
|
@@ -170,6 +202,10 @@ var TimeoutManager = class {
|
|
|
170
202
|
reset() {
|
|
171
203
|
this.startTime = Date.now();
|
|
172
204
|
}
|
|
205
|
+
/** Release the global timeout timer. Call once the retry loop is done. */
|
|
206
|
+
dispose() {
|
|
207
|
+
if (this.globalTimer) clearTimeout(this.globalTimer);
|
|
208
|
+
}
|
|
173
209
|
};
|
|
174
210
|
|
|
175
211
|
// src/idempotency/memory.store.ts
|
|
@@ -325,7 +361,7 @@ var ExponentialBackoff = class _ExponentialBackoff {
|
|
|
325
361
|
const delay = this.config.baseDelay * Math.pow(this.config.multiplier ?? 2, attempt - 1);
|
|
326
362
|
const capped = Math.min(delay, this.config.maxDelay ?? Infinity);
|
|
327
363
|
if (this.config.jitter) {
|
|
328
|
-
return applyJitter(capped, this.config.jitter);
|
|
364
|
+
return Math.min(applyJitter(capped, this.config.jitter), this.config.maxDelay ?? Infinity);
|
|
329
365
|
}
|
|
330
366
|
return capped;
|
|
331
367
|
}
|
|
@@ -341,40 +377,6 @@ var ExponentialBackoff = class _ExponentialBackoff {
|
|
|
341
377
|
}
|
|
342
378
|
};
|
|
343
379
|
|
|
344
|
-
// src/conditions/http.conditions.ts
|
|
345
|
-
var defaultRetryCondition = {
|
|
346
|
-
shouldRetry(error) {
|
|
347
|
-
switch (error.type) {
|
|
348
|
-
case "http":
|
|
349
|
-
return error.status === 429 || error.status != null && error.status >= 500;
|
|
350
|
-
case "network":
|
|
351
|
-
case "timeout":
|
|
352
|
-
case "circuit-open":
|
|
353
|
-
case "bulkhead-rejected":
|
|
354
|
-
return true;
|
|
355
|
-
case "business":
|
|
356
|
-
case "unknown":
|
|
357
|
-
return false;
|
|
358
|
-
}
|
|
359
|
-
}
|
|
360
|
-
};
|
|
361
|
-
var defaultAbortCondition = {
|
|
362
|
-
shouldAbort(error) {
|
|
363
|
-
switch (error.type) {
|
|
364
|
-
case "http":
|
|
365
|
-
return error.status != null && error.status < 500 && error.status !== 429;
|
|
366
|
-
case "business":
|
|
367
|
-
return true;
|
|
368
|
-
case "network":
|
|
369
|
-
case "timeout":
|
|
370
|
-
case "circuit-open":
|
|
371
|
-
case "bulkhead-rejected":
|
|
372
|
-
case "unknown":
|
|
373
|
-
return false;
|
|
374
|
-
}
|
|
375
|
-
}
|
|
376
|
-
};
|
|
377
|
-
|
|
378
380
|
// ../result/dist/chunk-XLOUAMAH.js
|
|
379
381
|
var ok = (value) => ({ ok: true, value });
|
|
380
382
|
var fail = (error) => ({ ok: false, error });
|
|
@@ -390,13 +392,19 @@ var NETWORK_CODES = /* @__PURE__ */ new Set([
|
|
|
390
392
|
"ETIMEDOUT",
|
|
391
393
|
"EAI_AGAIN",
|
|
392
394
|
"ECONNABORTED",
|
|
393
|
-
"EPIPE"
|
|
395
|
+
"EPIPE",
|
|
396
|
+
"ERR_NETWORK"
|
|
397
|
+
// axios, no response received
|
|
394
398
|
]);
|
|
395
399
|
function getHttpStatus(err) {
|
|
396
400
|
if (err == null || typeof err !== "object") return void 0;
|
|
397
401
|
const e = err;
|
|
398
402
|
if (typeof e["status"] === "number") return e["status"];
|
|
399
403
|
if (typeof e["statusCode"] === "number") return e["statusCode"];
|
|
404
|
+
if (typeof e["getStatus"] === "function") {
|
|
405
|
+
const status = e["getStatus"]();
|
|
406
|
+
if (typeof status === "number") return status;
|
|
407
|
+
}
|
|
400
408
|
const response = e["response"];
|
|
401
409
|
if (response != null && typeof response === "object") {
|
|
402
410
|
const r = response;
|
|
@@ -404,6 +412,17 @@ function getHttpStatus(err) {
|
|
|
404
412
|
}
|
|
405
413
|
return void 0;
|
|
406
414
|
}
|
|
415
|
+
function getErrorCode(err) {
|
|
416
|
+
if (err == null || typeof err !== "object") return void 0;
|
|
417
|
+
const e = err;
|
|
418
|
+
if (typeof e["code"] === "string") return e["code"];
|
|
419
|
+
const cause = e["cause"];
|
|
420
|
+
if (cause != null && typeof cause === "object") {
|
|
421
|
+
const causeCode = cause["code"];
|
|
422
|
+
if (typeof causeCode === "string") return causeCode;
|
|
423
|
+
}
|
|
424
|
+
return void 0;
|
|
425
|
+
}
|
|
407
426
|
function normalizeError(err, attempt, startTime) {
|
|
408
427
|
const elapsedMs = Date.now() - startTime;
|
|
409
428
|
if (err instanceof AttemptTimeoutError || err instanceof GlobalTimeoutError) {
|
|
@@ -414,12 +433,10 @@ function normalizeError(err, attempt, startTime) {
|
|
|
414
433
|
const message2 = err instanceof Error ? err.message : `HTTP ${status}`;
|
|
415
434
|
return { type: "http", message: message2, status, attempt, elapsedMs, cause: err };
|
|
416
435
|
}
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
return { type: "network", message: message2, attempt, elapsedMs, cause: err };
|
|
422
|
-
}
|
|
436
|
+
const code = getErrorCode(err);
|
|
437
|
+
if (code !== void 0 && NETWORK_CODES.has(code)) {
|
|
438
|
+
const message2 = err instanceof Error ? err.message : "Network error";
|
|
439
|
+
return { type: "network", message: message2, attempt, elapsedMs, cause: err };
|
|
423
440
|
}
|
|
424
441
|
const message = err instanceof Error ? err.message : String(err);
|
|
425
442
|
return { type: "unknown", message, attempt, elapsedMs, cause: err };
|
|
@@ -438,6 +455,13 @@ var RetryExecutor = class {
|
|
|
438
455
|
deps;
|
|
439
456
|
config;
|
|
440
457
|
async run(task) {
|
|
458
|
+
try {
|
|
459
|
+
return await this.attempt(task);
|
|
460
|
+
} finally {
|
|
461
|
+
this.deps.timeoutManager.dispose();
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
async attempt(task) {
|
|
441
465
|
const {
|
|
442
466
|
backoff,
|
|
443
467
|
budget,
|
|
@@ -460,7 +484,7 @@ var RetryExecutor = class {
|
|
|
460
484
|
if (idempotency && idempotencyKey) {
|
|
461
485
|
const cached = await idempotency.getResult(idempotencyKey);
|
|
462
486
|
if (cached !== null) {
|
|
463
|
-
return ok(JSON.parse(cached));
|
|
487
|
+
return ok(JSON.parse(cached).value);
|
|
464
488
|
}
|
|
465
489
|
}
|
|
466
490
|
budget?.recordCall();
|
|
@@ -490,24 +514,27 @@ var RetryExecutor = class {
|
|
|
490
514
|
await hooks.afterRetry({ attempt, error: payload2, delayMs: delay });
|
|
491
515
|
continue;
|
|
492
516
|
}
|
|
517
|
+
const attemptStart = Date.now();
|
|
493
518
|
try {
|
|
494
519
|
const executeTask = () => timeoutManager.executeWithAttemptTimeout(task);
|
|
495
520
|
const value = await (bulkhead ? bulkhead.execute(executeTask) : executeTask());
|
|
496
|
-
circuitBreaker?.onSuccess(Date.now() -
|
|
521
|
+
circuitBreaker?.onSuccess(Date.now() - attemptStart);
|
|
497
522
|
budget?.recordSuccess();
|
|
498
523
|
if (attempt > 1) {
|
|
499
524
|
await hooks.onRetrySuccess({ attempt, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });
|
|
500
525
|
}
|
|
501
526
|
metrics?.emit({ name: "Retry.success", value: 1, tags: { attempt: String(attempt) } });
|
|
502
527
|
if (idempotency && idempotencyKey) {
|
|
503
|
-
await idempotency.storeResult(idempotencyKey, JSON.stringify(value));
|
|
528
|
+
await idempotency.storeResult(idempotencyKey, JSON.stringify({ value }));
|
|
504
529
|
}
|
|
505
530
|
return ok(value);
|
|
506
531
|
} catch (err) {
|
|
507
532
|
const payload2 = normalizeError(err, attempt, startTime);
|
|
508
533
|
lastError = payload2;
|
|
509
534
|
const classification = classifier.classify(payload2);
|
|
510
|
-
|
|
535
|
+
if (classification === "transient") {
|
|
536
|
+
circuitBreaker?.onError(err);
|
|
537
|
+
}
|
|
511
538
|
budget?.recordFailure();
|
|
512
539
|
logger?.warn("Retry: attempt failed", { attempt, message: payload2.message, type: payload2.type, classification, correlationId });
|
|
513
540
|
metrics?.emit({ name: "Retry.attempt_failed", value: 1, tags: { attempt: String(attempt), type: payload2.type, classification } });
|
|
@@ -607,13 +634,13 @@ function createBackoff(config) {
|
|
|
607
634
|
return new ExponentialBackoff({ baseDelay: config.baseDelay, multiplier: config.multiplier, maxDelay: config.maxDelay, jitter: config.jitter });
|
|
608
635
|
}
|
|
609
636
|
}
|
|
610
|
-
function wrapRetryCondition(condition) {
|
|
611
|
-
if (!condition) return
|
|
637
|
+
function wrapRetryCondition(condition, classifier) {
|
|
638
|
+
if (!condition) return { shouldRetry: (error) => classifier.classify(error) === "transient" };
|
|
612
639
|
if (typeof condition === "function") return { shouldRetry: condition };
|
|
613
640
|
return condition;
|
|
614
641
|
}
|
|
615
|
-
function wrapAbortCondition(condition) {
|
|
616
|
-
if (!condition) return
|
|
642
|
+
function wrapAbortCondition(condition, classifier) {
|
|
643
|
+
if (!condition) return { shouldAbort: (error) => classifier.classify(error) === "permanent" };
|
|
617
644
|
if (typeof condition === "function") return { shouldAbort: condition };
|
|
618
645
|
return condition;
|
|
619
646
|
}
|
|
@@ -630,6 +657,19 @@ var RetryEngine = class {
|
|
|
630
657
|
totalBudgetExhausted: 0,
|
|
631
658
|
totalTimeouts: 0
|
|
632
659
|
};
|
|
660
|
+
/**
|
|
661
|
+
* A budget is a *shared* sliding window -- recreating it on every execute()
|
|
662
|
+
* call means it never accumulates enough history to reject anything. Built
|
|
663
|
+
* lazily from whichever call first enables it, then reused for the life of
|
|
664
|
+
* this engine.
|
|
665
|
+
*/
|
|
666
|
+
budget;
|
|
667
|
+
/**
|
|
668
|
+
* Same problem for idempotency: the cache has to outlive a single
|
|
669
|
+
* execute() call to do anything. Only the default in-memory store needs
|
|
670
|
+
* this -- a caller-supplied store (e.g. Redis) is already persistent.
|
|
671
|
+
*/
|
|
672
|
+
defaultIdempotencyStore;
|
|
633
673
|
async execute(task, options) {
|
|
634
674
|
const merged = { ...this.config.defaultConfig, ...options };
|
|
635
675
|
const backoffConfig = !merged.backoff || isBackoffStrategy(merged.backoff) ? { type: "fixed", baseDelay: 200 } : merged.backoff;
|
|
@@ -640,17 +680,21 @@ var RetryEngine = class {
|
|
|
640
680
|
attemptTimeoutMs: 0,
|
|
641
681
|
...merged.timeout
|
|
642
682
|
});
|
|
643
|
-
|
|
683
|
+
if (merged.budget && !this.budget) {
|
|
684
|
+
this.budget = new SlidingWindowBudgetImpl({ windowMs: 6e4, maxRetryRatio: 0.1, minRequestCount: 10, ...merged.budget });
|
|
685
|
+
}
|
|
686
|
+
const budget = merged.budget ? this.budget : void 0;
|
|
644
687
|
const idempotency = merged.idempotency?.enabled ? new IdempotencyManager({
|
|
645
688
|
enabled: true,
|
|
646
689
|
idempotentMethods: ["POST", "PUT", "PATCH"],
|
|
647
690
|
headerName: "Idempotency-Key",
|
|
648
691
|
ttlMs: 24 * 60 * 60 * 1e3,
|
|
649
|
-
...merged.idempotency
|
|
692
|
+
...merged.idempotency,
|
|
693
|
+
store: merged.idempotency.store ?? (this.defaultIdempotencyStore ??= new InMemoryIdempotencyStore())
|
|
650
694
|
}) : void 0;
|
|
651
695
|
const hookRunner = new HookRunner(merged.hooks ?? {}, merged.correlationId);
|
|
652
|
-
const RetryCondition = wrapRetryCondition(merged.retryIf);
|
|
653
|
-
const abortCondition = wrapAbortCondition(merged.abortIf);
|
|
696
|
+
const RetryCondition = wrapRetryCondition(merged.retryIf, classifier);
|
|
697
|
+
const abortCondition = wrapAbortCondition(merged.abortIf, classifier);
|
|
654
698
|
const fullConfig = {
|
|
655
699
|
maxAttempts: 3,
|
|
656
700
|
backoff: backoffConfig,
|
|
@@ -756,8 +800,7 @@ exports.RetryRegistry = RetryRegistry;
|
|
|
756
800
|
exports.SlidingWindowBudgetImpl = SlidingWindowBudgetImpl;
|
|
757
801
|
exports.TimeoutManager = TimeoutManager;
|
|
758
802
|
exports.__decorateClass = __decorateClass;
|
|
803
|
+
exports.__decorateParam = __decorateParam;
|
|
759
804
|
exports.applyJitter = applyJitter;
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
//# sourceMappingURL=chunk-MTBUSC7V.cjs.map
|
|
763
|
-
//# sourceMappingURL=chunk-MTBUSC7V.cjs.map
|
|
805
|
+
//# sourceMappingURL=chunk-BX4TTYBY.cjs.map
|
|
806
|
+
//# sourceMappingURL=chunk-BX4TTYBY.cjs.map
|