@backendkit-labs/retry 0.1.2 → 0.2.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/README.md CHANGED
@@ -67,23 +67,24 @@ npm install @nestjs/common @nestjs/core rxjs
67
67
 
68
68
  ## Quick Start
69
69
 
70
- `Retry()` is a standalone function backed by a global registry. It covers 90% of use cases in two lines:
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 { Retry } from '@backendkit-labs/retry';
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
- result.match(
81
- (user) => res.json(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
- `Retry()` returns `Result<T, RetryError>` — it **never throws**. Use `.match()`, `.ok`, or `.error` to handle both paths.
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
 
@@ -92,6 +93,8 @@ result.match(
92
93
  const result = await retry(() => callExternalApi());
93
94
  ```
94
95
 
96
+ Only **transient** errors are retried: network codes (`ECONNRESET`, `ETIMEDOUT`, ...), timeouts, HTTP 429 and 5xx, `circuit-open` and `bulkhead-rejected`. A plain `new Error('...')` has no status or code, so it is `type: 'unknown'` and **permanent**: one attempt, no retry. Attach a `status` or `code` to the error, or use `retryIf` / `classifiers`, to retry it.
97
+
95
98
  ### Handle specific error types
96
99
 
97
100
  ```typescript
@@ -117,8 +120,8 @@ if (!result.ok) {
117
120
 
118
121
  ```typescript
119
122
  import { RetryEngine } from '@backendkit-labs/retry';
120
- import { circuitBreaker } from '@backendkit-labs/circuit-breaker';
121
- import { bulkhead } from '@backendkit-labs/bulkhead';
123
+ import { CircuitBreaker } from '@backendkit-labs/circuit-breaker';
124
+ import { Bulkhead } from '@backendkit-labs/bulkhead';
122
125
 
123
126
  const engine = new RetryEngine({
124
127
  name: 'payment-gateway',
@@ -128,10 +131,10 @@ const engine = new RetryEngine({
128
131
  timeout: { attemptTimeoutMs: 5_000, globalTimeoutMs: 20_000 },
129
132
  },
130
133
  integrations: {
131
- circuitBreaker: circuitBreaker({ failureThreshold: 5, cooldownMs: 10_000 }),
132
- bulkhead: bulkhead({ maxConcurrent: 10, maxQueue: 20 }),
134
+ circuitBreaker: new CircuitBreaker({ name: 'payment-gateway', failureThreshold: 50, openTimeoutMs: 10_000 }),
135
+ bulkhead: new Bulkhead({ name: 'payment-gateway', maxConcurrentCalls: 10, maxQueueSize: 20, queueTimeoutMs: 5_000, rejectWhenFull: true }),
133
136
  observability: {
134
- logger: myLogger,
137
+ logger: console,
135
138
  metrics: myMetricsEmitter,
136
139
  },
137
140
  },
@@ -168,7 +171,7 @@ interface RetryConfig {
168
171
  budget?: Partial<RetryBudgetConfig>;
169
172
  idempotency?: Partial<IdempotencyConfig>;
170
173
  classifiers?: ClassifierRule[];
171
- dynamicDelay?: (error: RetryErrorPayload, attempt: number) => number;
174
+ dynamicDelay?: (error: RetryErrorPayload, attempt: number) => number | undefined;
172
175
  hooks?: RetryHooks;
173
176
  fallback?: (error: RetryErrorPayload) => unknown | Promise<unknown>;
174
177
  correlationId?: string;
@@ -211,7 +214,9 @@ await retry(task, {
211
214
  });
212
215
  ```
213
216
 
214
- Both accept a plain function `(error: RetryErrorPayload) => boolean | Promise<boolean>` or an object implementing `RetryCondition` / `AbortCondition`. Default behavior: retry on 5xx, network, and timeout errors; abort on 4xx (except 429).
217
+ Both accept a plain function `(error: RetryErrorPayload) => boolean | Promise<boolean>` or an object implementing `RetryCondition` / `AbortCondition`.
218
+
219
+ **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
220
 
216
221
  ### timeout
217
222
 
@@ -230,6 +235,17 @@ await retry(task, {
230
235
  - `globalTimeoutMs` expiration → operation aborted immediately regardless of attempt count
231
236
  - `0` means unlimited (default)
232
237
 
238
+ 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:
239
+
240
+ ```typescript
241
+ await retry(
242
+ (signal) => fetch('https://api.example.com/data', { signal }).then(r => r.json()),
243
+ { timeout: { attemptTimeoutMs: 5_000 } },
244
+ );
245
+ ```
246
+
247
+ 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.
248
+
233
249
  ### budget
234
250
 
235
251
  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.
@@ -244,7 +260,7 @@ await retry(task, {
244
260
  });
245
261
  ```
246
262
 
247
- Budget exhaustion produces `type: 'unknown'` with `metadata.budgetExhausted: true`. Share a budget across calls by reusing the same `RetryEngine` instance.
263
+ Budget exhaustion returns the last attempt's error (its `type` is that error's type, e.g. `'network'`) with `metadata.budgetExhausted: true`. The budget only starts refusing retries once the window has seen `minRequestCount` calls. Share a budget across calls by reusing the same `RetryEngine` instance.
248
264
 
249
265
  ### hooks
250
266
 
@@ -285,6 +301,8 @@ const result = await retry(() => fetchConfig(), {
285
301
  // result.ok === true, result.value === DEFAULT_CONFIG
286
302
  ```
287
303
 
304
+ `fallback` runs when transient errors exhaust `maxAttempts`, when the budget refuses a retry, or when `retryIf` returns `false`. It does **not** run when the call is aborted — by `abortIf`, or by default for a permanent error (e.g. a 4xx, or a plain `Error` with no status/code): those return `fail(...)` after one attempt.
305
+
288
306
  ### dynamicDelay
289
307
 
290
308
  Override backoff with a delay computed from the error — useful for respecting `Retry-After` headers:
@@ -297,14 +315,14 @@ await retry(task, {
297
315
  const retryAfterMs = (error.cause as any)?.retryAfterMs ?? 5_000;
298
316
  return retryAfterMs;
299
317
  }
300
- return 0; // 0 = fall back to backoff strategy
318
+ return undefined; // undefined = use the backoff strategy (0 means retry with no delay)
301
319
  },
302
320
  });
303
321
  ```
304
322
 
305
323
  ### classifiers
306
324
 
307
- Add custom rules that classify errors as `'transient'` (retryable) or `'permanent'` (abort):
325
+ 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
326
 
309
327
  ```typescript
310
328
  await retry(task, {
@@ -362,7 +380,7 @@ Delay grows linearly:
362
380
  import { LinearBackoff } from '@backendkit-labs/retry';
363
381
 
364
382
  new LinearBackoff({ baseDelay: 200, multiplier: 1.5, maxDelay: 5_000 });
365
- // attempt 1→2: 200ms, 2→3: 300ms, 3→4: 450ms, ...
383
+ // delay = baseDelay × attempt × multiplier → 1→2: 300ms, 2→3: 600ms, 3→4: 900ms, ...
366
384
  ```
367
385
 
368
386
  Shorthand: `{ type: 'linear', baseDelay: 200, multiplier: 1.5, maxDelay: 5_000 }`
@@ -418,7 +436,6 @@ interface RetryMetadata {
418
436
  totalElapsedMs: number; // total operation duration
419
437
  lastError?: RetryErrorPayload;
420
438
  budgetExhausted?: boolean; // true if stopped by budget
421
- circuitOpen?: boolean; // true if stopped by circuit breaker
422
439
  }
423
440
  ```
424
441
 
@@ -438,7 +455,7 @@ if (!result.ok) {
438
455
  console.log(`Timed out after ${error.metadata.totalElapsedMs}ms`);
439
456
  break;
440
457
  case 'circuit-open':
441
- console.log('Circuit breaker is OPEN — fast-failed without retrying');
458
+ console.log('Circuit breaker stayed OPEN on every attempt — the task was never called');
442
459
  break;
443
460
  case 'network':
444
461
  console.log('Network error:', error.cause);
@@ -463,7 +480,7 @@ The circuit breaker controls whether to attempt a call. `Retry` checks it before
463
480
  import { CircuitBreaker } from '@backendkit-labs/circuit-breaker';
464
481
  import { RetryEngine } from '@backendkit-labs/retry';
465
482
 
466
- const cb = new CircuitBreaker({ name: 'payments', threshold: 5 });
483
+ const cb = new CircuitBreaker({ name: 'payments', failureThreshold: 50, minimumCalls: 5 });
467
484
 
468
485
  const engine = new RetryEngine({
469
486
  name: 'payments',
@@ -475,12 +492,12 @@ const engine = new RetryEngine({
475
492
  const result = await engine.execute(() => chargePayment(order));
476
493
 
477
494
  if (!result.ok && result.error.type === 'circuit-open') {
478
- // Breaker was OPEN — Retry returned immediately without calling the task
495
+ // Breaker stayed OPEN on every attempt — the task was never called
479
496
  }
480
497
  ```
481
498
 
482
499
  **Execution flow:**
483
- 1. `Retry` calls `cb.canAttempt()` before every attempt. If `false` → returns `{ type: 'circuit-open' }` immediately.
500
+ 1. `Retry` calls `cb.canAttempt()` before every attempt. If `false`, that attempt is skipped (the task is not called) and counted as `circuit-open`, which is transient: Retry backs off and checks again, so the breaker can move to half-open in the meantime. After `maxAttempts` it returns `{ type: 'circuit-open' }`. Use `maxAttempts: 1` to fail fast.
484
501
  2. On success → `cb.onSuccess(durationMs)` — registers the healthy call.
485
502
  3. On transient failure → `cb.onError(err)` — updates the breaker's failure counter.
486
503
  4. On permanent/business failure (e.g. 422) → CB is **not** notified — this is not an infrastructure problem.
@@ -497,38 +514,46 @@ Limits the concurrency of attempts. Every attempt — including retries — pass
497
514
  import { Bulkhead } from '@backendkit-labs/bulkhead';
498
515
  import { RetryEngine } from '@backendkit-labs/retry';
499
516
 
500
- const bulkhead = new Bulkhead({ maxConcurrent: 10, maxQueue: 20 });
517
+ const bulkhead = new Bulkhead({
518
+ name: 'orders',
519
+ maxConcurrentCalls: 10,
520
+ maxQueueSize: 20,
521
+ queueTimeoutMs: 5_000,
522
+ rejectWhenFull: true,
523
+ });
501
524
 
502
525
  const engine = new RetryEngine({
503
526
  name: 'orders',
504
527
  integrations: {
505
- bulkhead, // duck-typed: execute(fn) / isFull()
528
+ bulkhead, // duck-typed: execute(fn)
506
529
  },
507
530
  });
508
531
  ```
509
532
 
510
533
  **Execution flow:**
511
534
  - Each attempt (including retries) is wrapped in `bulkhead.execute(fn)`.
512
- - If the bulkhead is full → it rejects → `Retry` classifies as `type: 'bulkhead-rejected'` (transient by default) → waits with backoff and re-queues.
535
+ - If the bulkhead is full → it rejects (`BulkheadRejectedError` / `BulkheadTimeoutError`) → `Retry` classifies it as `type: 'bulkhead-rejected'` (transient by default) → waits with backoff and tries again.
536
+ - A bulkhead rejection is **not** reported to the circuit breaker: the call never reached the dependency.
513
537
 
514
538
  ---
515
539
 
516
540
  ### `@backendkit-labs/result`
517
541
 
518
- `Retry()` already returns `Result<T, RetryError>` — direct integration, no adapter needed:
542
+ `retry()` already returns `Result<T, RetryError>` — direct integration, no adapter needed:
519
543
 
520
544
  ```typescript
521
- import { Retry } from '@backendkit-labs/retry';
545
+ import { retry } from '@backendkit-labs/retry';
546
+ import { match } from '@backendkit-labs/result';
522
547
 
523
548
  const result = await retry(() => fetchOrder(id), {
524
549
  maxAttempts: 3,
525
550
  backoff: { type: 'exponential', baseDelay: 200 },
526
551
  });
527
552
 
528
- result.match(
529
- (order) => res.json(order),
530
- (err) => res.status(502).json({ message: err.message, attempts: err.metadata.attempts }),
531
- );
553
+ match(result, {
554
+ ok: (order) => res.json(order),
555
+ fail: (err) => res.status(502).json({ message: err.message, attempts: err.metadata.attempts }),
556
+ });
532
557
  ```
533
558
 
534
559
  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`:
@@ -550,18 +575,21 @@ The thrown error with a `.status` property is detected as `type: 'http'` and cla
550
575
 
551
576
  ### `@backendkit-labs/observability`
552
577
 
553
- Plug in any logger and metrics emitter that satisfy the minimal duck-typed interfaces:
578
+ Plug in any logger and metrics emitter that satisfy the minimal duck-typed interfaces: the logger needs `warn(msg, meta)` (`console` works as is), the metrics emitter needs `emit({ name, value, tags })`.
554
579
 
555
- ```typescript
556
- import { Logger } from '@backendkit-labs/observability';
580
+ `LoggerService` from `@backendkit-labs/observability` takes a context *string* as its second argument, so pass it through a one-line adapter or the meta is lost:
557
581
 
558
- const logger = new Logger({ service: 'payments' });
582
+ ```typescript
583
+ const logger = { warn: (msg: string, meta?: unknown) => loggerService.warn(`${msg} ${JSON.stringify(meta)}`, 'Retry') };
584
+ // [warn] [Retry] Retry: attempt failed {"attempt":1,"message":"reset","type":"network","classification":"transient"}
585
+ ```
559
586
 
587
+ ```typescript
560
588
  const engine = new RetryEngine({
561
589
  name: 'payments',
562
590
  integrations: {
563
591
  observability: {
564
- logger, // info / warn / error
592
+ logger: console, // warn(msg, meta)
565
593
  metrics: metricsRegistry, // emit(event)
566
594
  },
567
595
  },
@@ -572,7 +600,6 @@ const engine = new RetryEngine({
572
600
 
573
601
  ```
574
602
  WARN "Retry: attempt failed" { attempt: 2, type: 'http', classification: 'transient' }
575
- ERROR "Retry: exhausted" { attempts: 3, type: 'http', totalElapsedMs: 1842 }
576
603
  ```
577
604
 
578
605
  **Metrics emitted automatically:**
@@ -581,7 +608,6 @@ ERROR "Retry: exhausted" { attempts: 3, type: 'http', totalElapsedMs: 1842
581
608
  |---|---|---|
582
609
  | `Retry.attempt_failed` | After each failed attempt | `attempt`, `type`, `classification` |
583
610
  | `Retry.success` | On eventual success | `attempt` (attempt number that succeeded) |
584
- | `Retry.exhausted` | All retries exhausted | `type` |
585
611
  | `Retry.budget_exhausted` | Budget refused a retry | — |
586
612
 
587
613
  ---
@@ -593,12 +619,11 @@ The most complete pattern for a production service — circuit breaker, bulkhead
593
619
  ```typescript
594
620
  import { CircuitBreaker } from '@backendkit-labs/circuit-breaker';
595
621
  import { Bulkhead } from '@backendkit-labs/bulkhead';
596
- import { Logger } from '@backendkit-labs/observability';
597
622
  import { RetryEngine } from '@backendkit-labs/retry';
598
623
 
599
- const cb = new CircuitBreaker({ name: 'payments', threshold: 5 });
600
- const bulkhead = new Bulkhead({ maxConcurrent: 10, maxQueue: 20 });
601
- const logger = new Logger({ service: 'payments-client' });
624
+ const cb = new CircuitBreaker({ name: 'payments', failureThreshold: 50, minimumCalls: 5 });
625
+ const bulkhead = new Bulkhead({ name: 'payments-client', maxConcurrentCalls: 10, maxQueueSize: 20, queueTimeoutMs: 5_000, rejectWhenFull: true });
626
+ const logger = console; // or the LoggerService adapter shown above
602
627
 
603
628
  const engine = new RetryEngine({
604
629
  name: 'payments-client',
@@ -635,7 +660,7 @@ budget.recordCall()
635
660
 
636
661
  ## NestJS Integration
637
662
 
638
- Import `RetryModule` once at the application root. It registers `RetryService` and an optional global `RetryInterceptor`.
663
+ Import `RetryModule` once at the application root. It registers `RetryService` and, only if `globalInterceptor: true` is set (default: `false`), a global `RetryInterceptor`.
639
664
 
640
665
  ### Module setup
641
666
 
@@ -683,7 +708,7 @@ export class PaymentsService {
683
708
 
684
709
  ### @Retry decorator
685
710
 
686
- Mark a method for retry without changing its signature. Pairs with `RetryInterceptor`:
711
+ Wraps the method directly -- works on any `@Injectable()` (or plain) class, with or without NestJS DI, no `RetryModule` import required:
687
712
 
688
713
  ```typescript
689
714
  import { Retry } from '@backendkit-labs/retry/nestjs';
@@ -700,6 +725,22 @@ export class InventoryService {
700
725
  }
701
726
  ```
702
727
 
728
+ 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):
729
+
730
+ ```typescript
731
+ import { RetryRegistry } from '@backendkit-labs/retry';
732
+
733
+ @Injectable()
734
+ export class InventoryService {
735
+ constructor(public readonly retryRegistry: RetryRegistry) {}
736
+
737
+ @Retry({ maxAttempts: 3 })
738
+ async reserveStock(productId: string, quantity: number) { ... }
739
+ }
740
+ ```
741
+
742
+ `@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.
743
+
703
744
  ### DI tokens
704
745
 
705
746
  Inject the underlying engine or registry directly:
@@ -751,13 +792,13 @@ registry.reset('payments');
751
792
 
752
793
  ## API Reference
753
794
 
754
- ### `Retry(task, options?)`
795
+ ### `retry(task, options?)`
755
796
 
756
797
  Standalone function using a global default registry.
757
798
 
758
799
  | Param | Type | Description |
759
800
  |---|---|---|
760
- | `task` | `() => Promise<T>` | The async operation to retry |
801
+ | `task` | `(signal: AbortSignal) => Promise<T>` | The async operation to retry; pass `signal` to `fetch`/axios so a timeout cancels it |
761
802
  | `options` | `Partial<RetryConfig>` | Optional config overrides |
762
803
  | Returns | `Promise<Result<T, RetryError>>` | Never throws |
763
804
 
@@ -789,8 +830,8 @@ Standalone function using a global default registry.
789
830
  | `RetryService` | `Injectable` | `.execute(task, options?)` |
790
831
  | `Retry` | `MethodDecorator` | `@Retry(config)` |
791
832
  | `RetryInterceptor` | `NestInterceptor` | Intercepts methods decorated with `@Retry` |
792
- | `RETRY_ENGINE_TOKEN` | `string` | DI token for `RetryEngine` |
793
- | `RETRY_REGISTRY_TOKEN` | `string` | DI token for `RetryRegistry` |
833
+ | `RETRY_ENGINE_TOKEN` | `symbol` | DI token for `RetryEngine` |
834
+ | `RETRY_REGISTRY_TOKEN` | `symbol` | DI token for `RetryRegistry` |
794
835
 
795
836
  ---
796
837