@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/dist/index.cjs CHANGED
@@ -1,14 +1,48 @@
1
1
  'use strict';
2
2
 
3
- var chunkMTBUSC7V_cjs = require('./chunk-MTBUSC7V.cjs');
3
+ var chunkVHMSEPWD_cjs = require('./chunk-VHMSEPWD.cjs');
4
4
 
5
5
  // src/retry/retry.fn.ts
6
- var defaultRegistry = new chunkMTBUSC7V_cjs.RetryRegistry();
6
+ var defaultRegistry = new chunkVHMSEPWD_cjs.RetryRegistry();
7
7
  async function retry(task, options) {
8
8
  const engine = defaultRegistry.getOrCreate("__default__");
9
9
  return engine.execute(task, options);
10
10
  }
11
11
 
12
+ // src/conditions/http.conditions.ts
13
+ var defaultRetryCondition = {
14
+ shouldRetry(error) {
15
+ switch (error.type) {
16
+ case "http":
17
+ return error.status === 429 || error.status != null && error.status >= 500;
18
+ case "network":
19
+ case "timeout":
20
+ case "circuit-open":
21
+ case "bulkhead-rejected":
22
+ return true;
23
+ case "business":
24
+ case "unknown":
25
+ return false;
26
+ }
27
+ }
28
+ };
29
+ var defaultAbortCondition = {
30
+ shouldAbort(error) {
31
+ switch (error.type) {
32
+ case "http":
33
+ return error.status != null && error.status < 500 && error.status !== 429;
34
+ case "business":
35
+ return true;
36
+ case "network":
37
+ case "timeout":
38
+ case "circuit-open":
39
+ case "bulkhead-rejected":
40
+ case "unknown":
41
+ return false;
42
+ }
43
+ }
44
+ };
45
+
12
46
  // src/retry/retry.errors.ts
13
47
  var RetryExhaustedError = class extends Error {
14
48
  constructor(message, attempts, totalElapsedMs) {
@@ -29,70 +63,64 @@ var BudgetExhaustedError = class extends Error {
29
63
 
30
64
  Object.defineProperty(exports, "AttemptTimeoutError", {
31
65
  enumerable: true,
32
- get: function () { return chunkMTBUSC7V_cjs.AttemptTimeoutError; }
66
+ get: function () { return chunkVHMSEPWD_cjs.AttemptTimeoutError; }
33
67
  });
34
68
  Object.defineProperty(exports, "DefaultErrorClassifier", {
35
69
  enumerable: true,
36
- get: function () { return chunkMTBUSC7V_cjs.DefaultErrorClassifier; }
70
+ get: function () { return chunkVHMSEPWD_cjs.DefaultErrorClassifier; }
37
71
  });
38
72
  Object.defineProperty(exports, "ExponentialBackoff", {
39
73
  enumerable: true,
40
- get: function () { return chunkMTBUSC7V_cjs.ExponentialBackoff; }
74
+ get: function () { return chunkVHMSEPWD_cjs.ExponentialBackoff; }
41
75
  });
42
76
  Object.defineProperty(exports, "FixedBackoff", {
43
77
  enumerable: true,
44
- get: function () { return chunkMTBUSC7V_cjs.FixedBackoff; }
78
+ get: function () { return chunkVHMSEPWD_cjs.FixedBackoff; }
45
79
  });
46
80
  Object.defineProperty(exports, "GlobalTimeoutError", {
47
81
  enumerable: true,
48
- get: function () { return chunkMTBUSC7V_cjs.GlobalTimeoutError; }
82
+ get: function () { return chunkVHMSEPWD_cjs.GlobalTimeoutError; }
49
83
  });
50
84
  Object.defineProperty(exports, "IdempotencyManager", {
51
85
  enumerable: true,
52
- get: function () { return chunkMTBUSC7V_cjs.IdempotencyManager; }
86
+ get: function () { return chunkVHMSEPWD_cjs.IdempotencyManager; }
53
87
  });
54
88
  Object.defineProperty(exports, "InMemoryIdempotencyStore", {
55
89
  enumerable: true,
56
- get: function () { return chunkMTBUSC7V_cjs.InMemoryIdempotencyStore; }
90
+ get: function () { return chunkVHMSEPWD_cjs.InMemoryIdempotencyStore; }
57
91
  });
58
92
  Object.defineProperty(exports, "JitterDecorator", {
59
93
  enumerable: true,
60
- get: function () { return chunkMTBUSC7V_cjs.JitterDecorator; }
94
+ get: function () { return chunkVHMSEPWD_cjs.JitterDecorator; }
61
95
  });
62
96
  Object.defineProperty(exports, "LinearBackoff", {
63
97
  enumerable: true,
64
- get: function () { return chunkMTBUSC7V_cjs.LinearBackoff; }
98
+ get: function () { return chunkVHMSEPWD_cjs.LinearBackoff; }
65
99
  });
66
100
  Object.defineProperty(exports, "RetryEngine", {
67
101
  enumerable: true,
68
- get: function () { return chunkMTBUSC7V_cjs.RetryEngine; }
102
+ get: function () { return chunkVHMSEPWD_cjs.RetryEngine; }
69
103
  });
70
104
  Object.defineProperty(exports, "RetryRegistry", {
71
105
  enumerable: true,
72
- get: function () { return chunkMTBUSC7V_cjs.RetryRegistry; }
106
+ get: function () { return chunkVHMSEPWD_cjs.RetryRegistry; }
73
107
  });
74
108
  Object.defineProperty(exports, "SlidingWindowBudgetImpl", {
75
109
  enumerable: true,
76
- get: function () { return chunkMTBUSC7V_cjs.SlidingWindowBudgetImpl; }
110
+ get: function () { return chunkVHMSEPWD_cjs.SlidingWindowBudgetImpl; }
77
111
  });
78
112
  Object.defineProperty(exports, "TimeoutManager", {
79
113
  enumerable: true,
80
- get: function () { return chunkMTBUSC7V_cjs.TimeoutManager; }
114
+ get: function () { return chunkVHMSEPWD_cjs.TimeoutManager; }
81
115
  });
82
116
  Object.defineProperty(exports, "applyJitter", {
83
117
  enumerable: true,
84
- get: function () { return chunkMTBUSC7V_cjs.applyJitter; }
85
- });
86
- Object.defineProperty(exports, "defaultAbortCondition", {
87
- enumerable: true,
88
- get: function () { return chunkMTBUSC7V_cjs.defaultAbortCondition; }
89
- });
90
- Object.defineProperty(exports, "defaultRetryCondition", {
91
- enumerable: true,
92
- get: function () { return chunkMTBUSC7V_cjs.defaultRetryCondition; }
118
+ get: function () { return chunkVHMSEPWD_cjs.applyJitter; }
93
119
  });
94
120
  exports.BudgetExhaustedError = BudgetExhaustedError;
95
121
  exports.RetryExhaustedError = RetryExhaustedError;
122
+ exports.defaultAbortCondition = defaultAbortCondition;
123
+ exports.defaultRetryCondition = defaultRetryCondition;
96
124
  exports.retry = retry;
97
125
  //# sourceMappingURL=index.cjs.map
98
126
  //# sourceMappingURL=index.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/retry/retry.fn.ts","../src/retry/retry.errors.ts"],"names":["RetryRegistry"],"mappings":";;;;;AAIA,IAAM,eAAA,GAAkB,IAAIA,+BAAA,EAAc;AAe1C,eAAsB,KAAA,CACpB,MACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,WAAA,CAAY,aAAa,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACrC;;;ACzBO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,CACE,OAAA,EACgB,QAAA,EACA,cAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AACA,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AAAA,EALkB,QAAA;AAAA,EACA,cAAA;AAKpB;AAEO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;AAAA,EAC9C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF","file":"index.cjs","sourcesContent":["import { type Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from './types.js';\nimport { RetryRegistry } from './retry.registry.js';\n\nconst defaultRegistry = new RetryRegistry();\n\n/**\n * Standalone sugar function for simple retry cases.\n * Uses a global default RetryRegistry under the hood.\n *\n * @example\n * ```ts\n * const result = await retry(() => fetchUser(id), { maxAttempts: 3 });\n * result.match(\n * (user) => res.json(user),\n * (error) => res.status(502).json({ error: error.message }),\n * );\n * ```\n */\nexport async function retry<T>(\n task: () => Promise<T>,\n options?: Partial<RetryConfig>,\n): Promise<Result<T, RetryError>> {\n const engine = defaultRegistry.getOrCreate('__default__');\n return engine.execute(task, options);\n}\n","export class RetryExhaustedError extends Error {\n constructor(\n message: string,\n public readonly attempts: number,\n public readonly totalElapsedMs: number,\n ) {\n super(message);\n this.name = 'RetryExhaustedError';\n }\n}\n\nexport class BudgetExhaustedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BudgetExhaustedError';\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/retry/retry.fn.ts","../src/conditions/http.conditions.ts","../src/retry/retry.errors.ts"],"names":["RetryRegistry"],"mappings":";;;;;AAIA,IAAM,eAAA,GAAkB,IAAIA,+BAAA,EAAc;AAa1C,eAAsB,KAAA,CACpB,MACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,WAAA,CAAY,aAAa,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACrC;;;ACjBO,IAAM,qBAAA,GAAwC;AAAA,EACnD,YAAY,KAAA,EAAmC;AAC7C,IAAA,QAAQ,MAAM,IAAA;AAAM,MAClB,KAAK,MAAA;AACH,QAAA,OAAO,MAAM,MAAA,KAAW,GAAA,IAAQ,MAAM,MAAA,IAAU,IAAA,IAAQ,MAAM,MAAA,IAAU,GAAA;AAAA,MAC1E,KAAK,SAAA;AAAA,MACL,KAAK,SAAA;AAAA,MACL,KAAK,cAAA;AAAA,MACL,KAAK,mBAAA;AACH,QAAA,OAAO,IAAA;AAAA,MACT,KAAK,UAAA;AAAA,MACL,KAAK,SAAA;AACH,QAAA,OAAO,KAAA;AAAA;AACX,EACF;AACF;AAMO,IAAM,qBAAA,GAAwC;AAAA,EACnD,YAAY,KAAA,EAAmC;AAC7C,IAAA,QAAQ,MAAM,IAAA;AAAM,MAClB,KAAK,MAAA;AACH,QAAA,OAAO,MAAM,MAAA,IAAU,IAAA,IAAQ,MAAM,MAAA,GAAS,GAAA,IAAO,MAAM,MAAA,KAAW,GAAA;AAAA,MACxE,KAAK,UAAA;AACH,QAAA,OAAO,IAAA;AAAA,MACT,KAAK,SAAA;AAAA,MACL,KAAK,SAAA;AAAA,MACL,KAAK,cAAA;AAAA,MACL,KAAK,mBAAA;AAAA,MACL,KAAK,SAAA;AACH,QAAA,OAAO,KAAA;AAAA;AACX,EACF;AACF;;;AC1CO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,CACE,OAAA,EACgB,QAAA,EACA,cAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AACA,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AAAA,EALkB,QAAA;AAAA,EACA,cAAA;AAKpB;AAEO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;AAAA,EAC9C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF","file":"index.cjs","sourcesContent":["import { type Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from './types.js';\nimport { RetryRegistry } from './retry.registry.js';\n\nconst defaultRegistry = new RetryRegistry();\n\n/**\n * Standalone sugar function for simple retry cases.\n * Uses a global default RetryRegistry under the hood.\n *\n * @example\n * ```ts\n * const result = await retry(() => fetchUser(id), { maxAttempts: 3 });\n * if (result.ok) res.json(result.value);\n * else res.status(502).json({ error: result.error.message });\n * ```\n */\nexport async function retry<T>(\n task: (signal: AbortSignal) => Promise<T>,\n options?: Partial<RetryConfig>,\n): Promise<Result<T, RetryError>> {\n const engine = defaultRegistry.getOrCreate('__default__');\n return engine.execute(task, options);\n}\n","import type { RetryCondition, AbortCondition, RetryErrorPayload } from '../retry/types.js';\n\n/**\n * Default retry condition: retry on transient HTTP errors (429, 5xx),\n * network errors, timeouts, circuit-open, and bulkhead-rejected.\n */\nexport const defaultRetryCondition: RetryCondition = {\n shouldRetry(error: RetryErrorPayload): boolean {\n switch (error.type) {\n case 'http':\n return error.status === 429 || (error.status != null && error.status >= 500);\n case 'network':\n case 'timeout':\n case 'circuit-open':\n case 'bulkhead-rejected':\n return true;\n case 'business':\n case 'unknown':\n return false;\n }\n },\n};\n\n/**\n * Default abort condition: abort on 4xx client errors (except 429),\n * business errors, and permanent classifications.\n */\nexport const defaultAbortCondition: AbortCondition = {\n shouldAbort(error: RetryErrorPayload): boolean {\n switch (error.type) {\n case 'http':\n return error.status != null && error.status < 500 && error.status !== 429;\n case 'business':\n return true;\n case 'network':\n case 'timeout':\n case 'circuit-open':\n case 'bulkhead-rejected':\n case 'unknown':\n return false;\n }\n },\n};\n","export class RetryExhaustedError extends Error {\n constructor(\n message: string,\n public readonly attempts: number,\n public readonly totalElapsedMs: number,\n ) {\n super(message);\n this.name = 'RetryExhaustedError';\n }\n}\n\nexport class BudgetExhaustedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BudgetExhaustedError';\n }\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as RetryConfig, a as RetryError, B as BackoffStrategy, b as BackoffConfig, J as JitterType, A as AbortCondition, c as RetryCondition, C as ClassifierRule, d as RetryErrorPayload, E as ErrorClassification, e as RetryBudgetConfig, T as TimeoutConfig, I as IdempotencyConfig, f as IdempotencyStore } from './retry.engine-ETXna-Ud.cjs';
2
- export { g as AbortConditionFn, h as AfterRetryContext, i as BeforeRetryContext, j as BkLoggerLike, k as BudgetExhaustedContext, l as BulkheadLike, m as CircuitBreakerLike, n as ErrorType, o as ExhaustedContext, M as MetricEvent, p as MetricsEmitterLike, q as RetryConditionFn, r as RetryEngine, s as RetryEngineConfig, t as RetryHooks, u as RetryMetadata, v as RetryMetricsSnapshot, w as RetryRegistry, x as RetrySuccessContext } from './retry.engine-ETXna-Ud.cjs';
1
+ import { R as RetryConfig, a as RetryError, B as BackoffStrategy, b as BackoffConfig, J as JitterType, A as AbortCondition, c as RetryCondition, C as ClassifierRule, d as RetryErrorPayload, E as ErrorClassification, e as RetryBudgetConfig, T as TimeoutConfig, I as IdempotencyConfig, f as IdempotencyStore } from './retry.engine-C2SjDj64.cjs';
2
+ export { g as AbortConditionFn, h as AfterRetryContext, i as BeforeRetryContext, j as BkLoggerLike, k as BudgetExhaustedContext, l as BulkheadLike, m as CircuitBreakerLike, n as ErrorType, o as ExhaustedContext, M as MetricEvent, p as MetricsEmitterLike, q as RetryConditionFn, r as RetryEngine, s as RetryEngineConfig, t as RetryHooks, u as RetryMetadata, v as RetryMetricsSnapshot, w as RetryRegistry, x as RetrySuccessContext } from './retry.engine-C2SjDj64.cjs';
3
3
  import { Result } from '@backendkit-labs/result';
4
4
 
5
5
  /**
@@ -9,13 +9,11 @@ import { Result } from '@backendkit-labs/result';
9
9
  * @example
10
10
  * ```ts
11
11
  * const result = await retry(() => fetchUser(id), { maxAttempts: 3 });
12
- * result.match(
13
- * (user) => res.json(user),
14
- * (error) => res.status(502).json({ error: error.message }),
15
- * );
12
+ * if (result.ok) res.json(result.value);
13
+ * else res.status(502).json({ error: result.error.message });
16
14
  * ```
17
15
  */
18
- declare function retry<T>(task: () => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
16
+ declare function retry<T>(task: (signal: AbortSignal) => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
19
17
 
20
18
  declare class FixedBackoff implements BackoffStrategy {
21
19
  private config;
@@ -132,15 +130,22 @@ declare class SlidingWindowBudgetImpl implements SlidingWindowBudget {
132
130
  declare class TimeoutManager {
133
131
  private config;
134
132
  private startTime;
133
+ private readonly globalController;
134
+ private readonly globalTimer;
135
135
  constructor(config: TimeoutConfig);
136
136
  /**
137
- * Execute a task with per-attempt timeout.
138
- * Throws AttemptTimeoutError if the task exceeds attemptTimeoutMs.
137
+ * Execute a task with a per-attempt timeout, passing it an `AbortSignal`
138
+ * that fires when the attempt (or the overall global timeout) expires.
139
+ *
140
+ * A task that doesn't check the signal (e.g. doesn't pass it to `fetch`)
141
+ * keeps running in the background after we give up waiting on it -- we
142
+ * can only abandon the wait, not force JS execution to stop.
139
143
  */
140
- executeWithAttemptTimeout<T>(task: () => Promise<T>): Promise<T>;
144
+ executeWithAttemptTimeout<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;
141
145
  /**
142
- * Check if the global timeout has been exceeded.
143
- * Throws GlobalTimeoutError if exceeded.
146
+ * Check if the global timeout has already fired. Called at the start of
147
+ * each attempt loop iteration -- the AbortSignal handles cutting off an
148
+ * attempt that's already in flight when the deadline hits.
144
149
  */
145
150
  checkGlobalTimeout(): void;
146
151
  /**
@@ -150,6 +155,8 @@ declare class TimeoutManager {
150
155
  getRemainingTime(): number;
151
156
  /** Reset the start time (for reuse across retry cycles). */
152
157
  reset(): void;
158
+ /** Release the global timeout timer. Call once the retry loop is done. */
159
+ dispose(): void;
153
160
  }
154
161
 
155
162
  declare class AttemptTimeoutError extends Error {
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { R as RetryConfig, a as RetryError, B as BackoffStrategy, b as BackoffConfig, J as JitterType, A as AbortCondition, c as RetryCondition, C as ClassifierRule, d as RetryErrorPayload, E as ErrorClassification, e as RetryBudgetConfig, T as TimeoutConfig, I as IdempotencyConfig, f as IdempotencyStore } from './retry.engine-ETXna-Ud.js';
2
- export { g as AbortConditionFn, h as AfterRetryContext, i as BeforeRetryContext, j as BkLoggerLike, k as BudgetExhaustedContext, l as BulkheadLike, m as CircuitBreakerLike, n as ErrorType, o as ExhaustedContext, M as MetricEvent, p as MetricsEmitterLike, q as RetryConditionFn, r as RetryEngine, s as RetryEngineConfig, t as RetryHooks, u as RetryMetadata, v as RetryMetricsSnapshot, w as RetryRegistry, x as RetrySuccessContext } from './retry.engine-ETXna-Ud.js';
1
+ import { R as RetryConfig, a as RetryError, B as BackoffStrategy, b as BackoffConfig, J as JitterType, A as AbortCondition, c as RetryCondition, C as ClassifierRule, d as RetryErrorPayload, E as ErrorClassification, e as RetryBudgetConfig, T as TimeoutConfig, I as IdempotencyConfig, f as IdempotencyStore } from './retry.engine-C2SjDj64.js';
2
+ export { g as AbortConditionFn, h as AfterRetryContext, i as BeforeRetryContext, j as BkLoggerLike, k as BudgetExhaustedContext, l as BulkheadLike, m as CircuitBreakerLike, n as ErrorType, o as ExhaustedContext, M as MetricEvent, p as MetricsEmitterLike, q as RetryConditionFn, r as RetryEngine, s as RetryEngineConfig, t as RetryHooks, u as RetryMetadata, v as RetryMetricsSnapshot, w as RetryRegistry, x as RetrySuccessContext } from './retry.engine-C2SjDj64.js';
3
3
  import { Result } from '@backendkit-labs/result';
4
4
 
5
5
  /**
@@ -9,13 +9,11 @@ import { Result } from '@backendkit-labs/result';
9
9
  * @example
10
10
  * ```ts
11
11
  * const result = await retry(() => fetchUser(id), { maxAttempts: 3 });
12
- * result.match(
13
- * (user) => res.json(user),
14
- * (error) => res.status(502).json({ error: error.message }),
15
- * );
12
+ * if (result.ok) res.json(result.value);
13
+ * else res.status(502).json({ error: result.error.message });
16
14
  * ```
17
15
  */
18
- declare function retry<T>(task: () => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
16
+ declare function retry<T>(task: (signal: AbortSignal) => Promise<T>, options?: Partial<RetryConfig>): Promise<Result<T, RetryError>>;
19
17
 
20
18
  declare class FixedBackoff implements BackoffStrategy {
21
19
  private config;
@@ -132,15 +130,22 @@ declare class SlidingWindowBudgetImpl implements SlidingWindowBudget {
132
130
  declare class TimeoutManager {
133
131
  private config;
134
132
  private startTime;
133
+ private readonly globalController;
134
+ private readonly globalTimer;
135
135
  constructor(config: TimeoutConfig);
136
136
  /**
137
- * Execute a task with per-attempt timeout.
138
- * Throws AttemptTimeoutError if the task exceeds attemptTimeoutMs.
137
+ * Execute a task with a per-attempt timeout, passing it an `AbortSignal`
138
+ * that fires when the attempt (or the overall global timeout) expires.
139
+ *
140
+ * A task that doesn't check the signal (e.g. doesn't pass it to `fetch`)
141
+ * keeps running in the background after we give up waiting on it -- we
142
+ * can only abandon the wait, not force JS execution to stop.
139
143
  */
140
- executeWithAttemptTimeout<T>(task: () => Promise<T>): Promise<T>;
144
+ executeWithAttemptTimeout<T>(task: (signal: AbortSignal) => Promise<T>): Promise<T>;
141
145
  /**
142
- * Check if the global timeout has been exceeded.
143
- * Throws GlobalTimeoutError if exceeded.
146
+ * Check if the global timeout has already fired. Called at the start of
147
+ * each attempt loop iteration -- the AbortSignal handles cutting off an
148
+ * attempt that's already in flight when the deadline hits.
144
149
  */
145
150
  checkGlobalTimeout(): void;
146
151
  /**
@@ -150,6 +155,8 @@ declare class TimeoutManager {
150
155
  getRemainingTime(): number;
151
156
  /** Reset the start time (for reuse across retry cycles). */
152
157
  reset(): void;
158
+ /** Release the global timeout timer. Call once the retry loop is done. */
159
+ dispose(): void;
153
160
  }
154
161
 
155
162
  declare class AttemptTimeoutError extends Error {
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
- import { RetryRegistry } from './chunk-6UD5URCQ.js';
2
- export { AttemptTimeoutError, DefaultErrorClassifier, ExponentialBackoff, FixedBackoff, GlobalTimeoutError, IdempotencyManager, InMemoryIdempotencyStore, JitterDecorator, LinearBackoff, RetryEngine, RetryRegistry, SlidingWindowBudgetImpl, TimeoutManager, applyJitter, defaultAbortCondition, defaultRetryCondition } from './chunk-6UD5URCQ.js';
1
+ import { RetryRegistry } from './chunk-ZZ6WRRGP.js';
2
+ export { AttemptTimeoutError, DefaultErrorClassifier, ExponentialBackoff, FixedBackoff, GlobalTimeoutError, IdempotencyManager, InMemoryIdempotencyStore, JitterDecorator, LinearBackoff, RetryEngine, RetryRegistry, SlidingWindowBudgetImpl, TimeoutManager, applyJitter } from './chunk-ZZ6WRRGP.js';
3
3
 
4
4
  // src/retry/retry.fn.ts
5
5
  var defaultRegistry = new RetryRegistry();
@@ -8,6 +8,40 @@ async function retry(task, options) {
8
8
  return engine.execute(task, options);
9
9
  }
10
10
 
11
+ // src/conditions/http.conditions.ts
12
+ var defaultRetryCondition = {
13
+ shouldRetry(error) {
14
+ switch (error.type) {
15
+ case "http":
16
+ return error.status === 429 || error.status != null && error.status >= 500;
17
+ case "network":
18
+ case "timeout":
19
+ case "circuit-open":
20
+ case "bulkhead-rejected":
21
+ return true;
22
+ case "business":
23
+ case "unknown":
24
+ return false;
25
+ }
26
+ }
27
+ };
28
+ var defaultAbortCondition = {
29
+ shouldAbort(error) {
30
+ switch (error.type) {
31
+ case "http":
32
+ return error.status != null && error.status < 500 && error.status !== 429;
33
+ case "business":
34
+ return true;
35
+ case "network":
36
+ case "timeout":
37
+ case "circuit-open":
38
+ case "bulkhead-rejected":
39
+ case "unknown":
40
+ return false;
41
+ }
42
+ }
43
+ };
44
+
11
45
  // src/retry/retry.errors.ts
12
46
  var RetryExhaustedError = class extends Error {
13
47
  constructor(message, attempts, totalElapsedMs) {
@@ -26,6 +60,6 @@ var BudgetExhaustedError = class extends Error {
26
60
  }
27
61
  };
28
62
 
29
- export { BudgetExhaustedError, RetryExhaustedError, retry };
63
+ export { BudgetExhaustedError, RetryExhaustedError, defaultAbortCondition, defaultRetryCondition, retry };
30
64
  //# sourceMappingURL=index.js.map
31
65
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/retry/retry.fn.ts","../src/retry/retry.errors.ts"],"names":[],"mappings":";;;;AAIA,IAAM,eAAA,GAAkB,IAAI,aAAA,EAAc;AAe1C,eAAsB,KAAA,CACpB,MACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,WAAA,CAAY,aAAa,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACrC;;;ACzBO,IAAM,mBAAA,GAAN,cAAkC,KAAA,CAAM;AAAA,EAC7C,WAAA,CACE,OAAA,EACgB,QAAA,EACA,cAAA,EAChB;AACA,IAAA,KAAA,CAAM,OAAO,CAAA;AAHG,IAAA,IAAA,CAAA,QAAA,GAAA,QAAA;AACA,IAAA,IAAA,CAAA,cAAA,GAAA,cAAA;AAGhB,IAAA,IAAA,CAAK,IAAA,GAAO,qBAAA;AAAA,EACd;AAAA,EALkB,QAAA;AAAA,EACA,cAAA;AAKpB;AAEO,IAAM,oBAAA,GAAN,cAAmC,KAAA,CAAM;AAAA,EAC9C,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF","file":"index.js","sourcesContent":["import { type Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from './types.js';\nimport { RetryRegistry } from './retry.registry.js';\n\nconst defaultRegistry = new RetryRegistry();\n\n/**\n * Standalone sugar function for simple retry cases.\n * Uses a global default RetryRegistry under the hood.\n *\n * @example\n * ```ts\n * const result = await retry(() => fetchUser(id), { maxAttempts: 3 });\n * result.match(\n * (user) => res.json(user),\n * (error) => res.status(502).json({ error: error.message }),\n * );\n * ```\n */\nexport async function retry<T>(\n task: () => Promise<T>,\n options?: Partial<RetryConfig>,\n): Promise<Result<T, RetryError>> {\n const engine = defaultRegistry.getOrCreate('__default__');\n return engine.execute(task, options);\n}\n","export class RetryExhaustedError extends Error {\n constructor(\n message: string,\n public readonly attempts: number,\n public readonly totalElapsedMs: number,\n ) {\n super(message);\n this.name = 'RetryExhaustedError';\n }\n}\n\nexport class BudgetExhaustedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BudgetExhaustedError';\n }\n}\n"]}
1
+ {"version":3,"sources":["../src/retry/retry.fn.ts","../src/conditions/http.conditions.ts","../src/retry/retry.errors.ts"],"names":[],"mappings":";;;;AAIA,IAAM,eAAA,GAAkB,IAAI,aAAA,EAAc;AAa1C,eAAsB,KAAA,CACpB,MACA,OAAA,EACgC;AAChC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,WAAA,CAAY,aAAa,CAAA;AACxD,EAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AACrC;;;ACjBO,IAAM,qB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AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,sBAAA;AAAA,EACd;AACF","file":"index.js","sourcesContent":["import { type Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from './types.js';\nimport { RetryRegistry } from './retry.registry.js';\n\nconst defaultRegistry = new RetryRegistry();\n\n/**\n * Standalone sugar function for simple retry cases.\n * Uses a global default RetryRegistry under the hood.\n *\n * @example\n * ```ts\n * const result = await retry(() => fetchUser(id), { maxAttempts: 3 });\n * if (result.ok) res.json(result.value);\n * else res.status(502).json({ error: result.error.message });\n * ```\n */\nexport async function retry<T>(\n task: (signal: AbortSignal) => Promise<T>,\n options?: Partial<RetryConfig>,\n): Promise<Result<T, RetryError>> {\n const engine = defaultRegistry.getOrCreate('__default__');\n return engine.execute(task, options);\n}\n","import type { RetryCondition, AbortCondition, RetryErrorPayload } from '../retry/types.js';\n\n/**\n * Default retry condition: retry on transient HTTP errors (429, 5xx),\n * network errors, timeouts, circuit-open, and bulkhead-rejected.\n */\nexport const defaultRetryCondition: RetryCondition = {\n shouldRetry(error: RetryErrorPayload): boolean {\n switch (error.type) {\n case 'http':\n return error.status === 429 || (error.status != null && error.status >= 500);\n case 'network':\n case 'timeout':\n case 'circuit-open':\n case 'bulkhead-rejected':\n return true;\n case 'business':\n case 'unknown':\n return false;\n }\n },\n};\n\n/**\n * Default abort condition: abort on 4xx client errors (except 429),\n * business errors, and permanent classifications.\n */\nexport const defaultAbortCondition: AbortCondition = {\n shouldAbort(error: RetryErrorPayload): boolean {\n switch (error.type) {\n case 'http':\n return error.status != null && error.status < 500 && error.status !== 429;\n case 'business':\n return true;\n case 'network':\n case 'timeout':\n case 'circuit-open':\n case 'bulkhead-rejected':\n case 'unknown':\n return false;\n }\n },\n};\n","export class RetryExhaustedError extends Error {\n constructor(\n message: string,\n public readonly attempts: number,\n public readonly totalElapsedMs: number,\n ) {\n super(message);\n this.name = 'RetryExhaustedError';\n }\n}\n\nexport class BudgetExhaustedError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BudgetExhaustedError';\n }\n}\n"]}
@@ -1,6 +1,6 @@
1
1
  'use strict';
2
2
 
3
- var chunkMTBUSC7V_cjs = require('../chunk-MTBUSC7V.cjs');
3
+ var chunkVHMSEPWD_cjs = require('../chunk-VHMSEPWD.cjs');
4
4
  var common = require('@nestjs/common');
5
5
  var core = require('@nestjs/core');
6
6
  var rxjs = require('rxjs');
@@ -18,12 +18,27 @@ exports.RetryService = class RetryService {
18
18
  return this.engine;
19
19
  }
20
20
  };
21
- exports.RetryService = chunkMTBUSC7V_cjs.__decorateClass([
21
+ exports.RetryService = chunkVHMSEPWD_cjs.__decorateClass([
22
22
  common.Injectable()
23
23
  ], exports.RetryService);
24
24
  var RETRY_METADATA_KEY = "retry:config";
25
+ var defaultRegistry = new chunkVHMSEPWD_cjs.RetryRegistry();
25
26
  function Retry(config) {
26
- return common.SetMetadata(RETRY_METADATA_KEY, config);
27
+ return function(target, propertyKey, descriptor) {
28
+ const originalMethod = descriptor.value;
29
+ const className = target.constructor?.name ?? "anonymous";
30
+ const engineName = `method:${className}.${String(propertyKey)}`;
31
+ descriptor.value = function(...args) {
32
+ const registry = this.retryRegistry ?? defaultRegistry;
33
+ const engine = registry.getOrCreate(engineName);
34
+ return engine.execute(() => Promise.resolve(originalMethod.apply(this, args)), config).then((result) => {
35
+ if (result.ok) return result.value;
36
+ throw result.error;
37
+ });
38
+ };
39
+ common.SetMetadata(RETRY_METADATA_KEY, config)(target, propertyKey, descriptor);
40
+ return descriptor;
41
+ };
27
42
  }
28
43
 
29
44
  // src/nestjs/retry.interceptor.ts
@@ -56,8 +71,10 @@ exports.RetryInterceptor = class RetryInterceptor {
56
71
  );
57
72
  }
58
73
  };
59
- exports.RetryInterceptor = chunkMTBUSC7V_cjs.__decorateClass([
60
- common.Injectable()
74
+ exports.RetryInterceptor = chunkVHMSEPWD_cjs.__decorateClass([
75
+ common.Injectable(),
76
+ chunkVHMSEPWD_cjs.__decorateParam(0, common.Inject(exports.RetryService)),
77
+ chunkVHMSEPWD_cjs.__decorateParam(1, common.Inject(core.Reflector))
61
78
  ], exports.RetryInterceptor);
62
79
 
63
80
  // src/nestjs/retry.constants.ts
@@ -71,7 +88,7 @@ exports.RetryModule = class RetryModule {
71
88
  const providers = [
72
89
  {
73
90
  provide: RETRY_REGISTRY_TOKEN,
74
- useFactory: () => new chunkMTBUSC7V_cjs.RetryRegistry()
91
+ useFactory: () => new chunkVHMSEPWD_cjs.RetryRegistry()
75
92
  },
76
93
  {
77
94
  provide: RETRY_ENGINE_TOKEN,
@@ -84,7 +101,7 @@ exports.RetryModule = class RetryModule {
84
101
  inject: [RETRY_ENGINE_TOKEN]
85
102
  }
86
103
  ];
87
- if (options?.globalInterceptor !== false) {
104
+ if (options?.globalInterceptor === true) {
88
105
  providers.push({
89
106
  provide: core.APP_INTERCEPTOR,
90
107
  useClass: exports.RetryInterceptor
@@ -97,7 +114,7 @@ exports.RetryModule = class RetryModule {
97
114
  };
98
115
  }
99
116
  };
100
- exports.RetryModule = chunkMTBUSC7V_cjs.__decorateClass([
117
+ exports.RetryModule = chunkVHMSEPWD_cjs.__decorateClass([
101
118
  common.Module({})
102
119
  ], exports.RetryModule);
103
120
 
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/nestjs/retry.service.ts","../../src/nestjs/retry.decorator.ts","../../src/nestjs/retry.interceptor.ts","../../src/nestjs/retry.constants.ts","../../src/nestjs/retry.module.ts"],"names":["RetryService","__decorateClass","Injectable","SetMetadata","RetryInterceptor","from","switchMap","Observable","RetryModule","RetryRegistry","APP_INTERCEPTOR","Module"],"mappings":";;;;;;;;AAMaA,uBAAN,kBAAA,CAAmB;AAAA,EACxB,YAAoB,MAAA,EAAqB;AAArB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAAsB;AAAA,EAAtB,MAAA;AAAA,EAEpB,MAAM,OAAA,CACJ,IAAA,EACA,OAAA,EACgC;AA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AANP,iCAAA,CAAA;AAAA,EADNU,aAAA,CAAO,EAAE;AAAA,CAAA,EACGH,mBAAA,CAAA","file":"index.cjs","sourcesContent":["import { Injectable } from '@nestjs/common';\nimport type { Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from '../retry/types.js';\nimport { RetryEngine } from '../retry/retry.engine.js';\n\n@Injectable()\nexport class RetryService {\n constructor(private engine: RetryEngine) {}\n\n async execute<T>(\n task: () => Promise<T>,\n options?: Partial<RetryConfig>,\n ): Promise<Result<T, RetryError>> {\n return this.engine.execute(task, options);\n }\n\n getEngine(): RetryEngine {\n return this.engine;\n }\n}\n","import { SetMetadata } from '@nestjs/common';\nimport type { RetryConfig } from '../retry/types.js';\n\nexport const RETRY_METADATA_KEY = 'retry:config';\n\n/**\n * Decorator that marks a method for retry.\n *\n * @example\n * ```ts\n * @Retry({ maxAttempts: 3, backoff: { type: 'exponential', baseDelay: 200 } })\n * async fetchData() { ... }\n * ```\n */\nexport function Retry(config: Partial<RetryConfig>): MethodDecorator {\n return SetMetadata(RETRY_METADATA_KEY, config);\n}\n","import {\n Injectable,\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n} from '@nestjs/common';\nimport { Observable, from } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\nimport { Reflector } from '@nestjs/core';\nimport { RetryService } from './retry.service.js';\nimport { RETRY_METADATA_KEY } from './retry.decorator.js';\nimport type { RetryConfig } from '../retry/types.js';\n\n@Injectable()\nexport class RetryInterceptor implements NestInterceptor {\n constructor(\n private readonly RetryService: RetryService,\n private readonly reflector: Reflector,\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n const RetryConfig = this.reflector.get<Partial<RetryConfig> | undefined>(\n RETRY_METADATA_KEY,\n context.getHandler(),\n );\n\n if (!RetryConfig) {\n return next.handle();\n }\n\n return from(\n this.RetryService.execute(() => next.handle().toPromise(), RetryConfig),\n ).pipe(\n switchMap((result) => {\n if (result.ok) {\n const value = result.value;\n if (value instanceof Observable) return value;\n return from(Promise.resolve(value));\n }\n throw result.error;\n }),\n );\n }\n}\n","export const RETRY_ENGINE_TOKEN = Symbol('RETRY_ENGINE_TOKEN');\nexport const RETRY_REGISTRY_TOKEN = Symbol('RETRY_REGISTRY_TOKEN');\n","import { Module, DynamicModule, Provider } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport { RetryEngine } from '../retry/retry.engine.js';\nimport { RetryRegistry } from '../retry/retry.registry.js';\nimport { RetryService } from './retry.service.js';\nimport { RetryInterceptor } from './retry.interceptor.js';\nimport { RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN } from './retry.constants.js';\nimport type { RetryEngineConfig } from '../retry/types.js';\n\nexport interface RetryModuleOptions {\n engineConfig?: Partial<RetryEngineConfig>;\n globalInterceptor?: boolean;\n}\n\n@Module({})\nexport class RetryModule {\n static forRoot(options?: RetryModuleOptions): DynamicModule {\n const engineConfig = options?.engineConfig ?? { name: 'default' };\n\n const providers: Provider[] = [\n {\n provide: RETRY_REGISTRY_TOKEN,\n useFactory: () => new RetryRegistry(),\n },\n {\n provide: RETRY_ENGINE_TOKEN,\n useFactory: (registry: RetryRegistry) =>\n registry.getOrCreate(engineConfig.name ?? 'default', engineConfig),\n inject: [RETRY_REGISTRY_TOKEN],\n },\n {\n provide: RetryService,\n useFactory: (engine: RetryEngine) => new RetryService(engine),\n inject: [RETRY_ENGINE_TOKEN],\n },\n ];\n\n if (options?.globalInterceptor !== false) {\n providers.push({\n provide: APP_INTERCEPTOR,\n useClass: RetryInterceptor,\n });\n }\n\n return {\n module: RetryModule,\n providers,\n exports: [RetryService, RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN],\n };\n }\n}\n"]}
1
+ {"version":3,"sources":["../../src/nestjs/retry.service.ts","../../src/nestjs/retry.decorator.ts","../../src/nestjs/retry.interceptor.ts","../../src/nestjs/retry.constants.ts","../../src/nestjs/retry.module.ts"],"names":["RetryService","__decorateClass","Injectable","RetryRegistry","SetMetadata","RetryInterceptor","from","switchMap","Observable","__decorateParam","Reflector","RetryModule","APP_INTERCEPTOR","Module"],"mappings":";;;;;;;;AAMaA,uBAAN,kBAAA,CAAmB;AAAA,EACxB,YAAoB,MAAA,EAAqB;AAArB,IAAA,IAAA,CAAA,MAAA,GAAA,MAAA;AAAA,EAAsB;AAAA,EAAtB,MAAA;AAAA,EAEpB,MAAM,OAAA,CACJ,IAAA,EACA,OAAA,EACgC;AAChC,IAAA,OAAO,IAAA,CAAK,MAAA,CAAO,OAAA,CAAQ,IAAA,EAAM,OAAO,CAAA;AAAA,EAC1C;AAAA,EAEA,SAAA,GAAyB;AACvB,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AACF;AAbaA,oBAAA,GAANC,iCAAA,CAAA;AAAA,EADNC,iBAAA;AAAW,CAAA,EACCF,oBAAA,CAAA;ACFN,IAAM,kBAAA,GAAqB,cAAA;AAOlC,IAAM,eAAA,GAAkB,IAAIG,+BAAA,EAAc;AAqBnC,SAAS,MAAM,MAAA,EAA+C;AACnE,EAAA,OAAO,SAAU,MAAA,EAAgB,WAAA,EAA8B,UAAA,EAAoD;AACjH,IAAA,MAAM,iBAAiB,UAAA,CAAW,KAAA;AAClC,IAAA,MAAM,SAAA,GAAa,MAAA,CAA+C,WAAA,EAAa,IAAA,IAAQ,WAAA;AACvF,IAAA,MAAM,aAAa,CAAA,OAAA,EAAU,SAAS,CAAA,CAAA,EAAI,MAAA,CAAO,WAAW,CAAC,CAAA,CAAA;AAE7D,IAAA,UAAA,CAAW,KAAA,GAAQ,YAA4B,IAAA,EAAiB;AAC9D,MAAA,MAAM,QAAA,GAAY,KAA2C,aAAA,IAAiB,eAAA;AAC9E,MAAA,MAAM,MAAA,GAAS,QAAA,CAAS,WAAA,CAAY,UAAU,CAAA;AAE9C,MAAA,OAAO,MAAA,CAAO,OAAA,CAAQ,MAAM,OAAA,CAAQ,QAAQ,cAAA,CAAe,KAAA,CAAM,IAAA,EA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,EAAoB,oBAAoB;AAAA,KAClE;AAAA,EACF;AACF;AAnCaW,mBAAA,GAANV,iCAAA,CAAA;AAAA,EADNY,aAAA,CAAO,EAAE;AAAA,CAAA,EACGF,mBAAA,CAAA","file":"index.cjs","sourcesContent":["import { Injectable } from '@nestjs/common';\nimport type { Result } from '@backendkit-labs/result';\nimport type { RetryConfig, RetryError } from '../retry/types.js';\nimport { RetryEngine } from '../retry/retry.engine.js';\n\n@Injectable()\nexport class RetryService {\n constructor(private engine: RetryEngine) {}\n\n async execute<T>(\n task: () => Promise<T>,\n options?: Partial<RetryConfig>,\n ): Promise<Result<T, RetryError>> {\n return this.engine.execute(task, options);\n }\n\n getEngine(): RetryEngine {\n return this.engine;\n }\n}\n","import { SetMetadata } from '@nestjs/common';\nimport { RetryRegistry } from '../retry/retry.registry.js';\nimport type { RetryConfig } from '../retry/types.js';\n\nexport const RETRY_METADATA_KEY = 'retry:config';\n\n/**\n * Own default registry, used when the decorated class has no `retryRegistry`\n * property injected -- mirrors the standalone `retry()` function's registry\n * so `@Retry` works without requiring DI wiring.\n */\nconst defaultRegistry = new RetryRegistry();\n\n/**\n * Wraps a method in retry logic directly -- works on any method (service or\n * controller), with or without NestJS DI. Also sets metadata for\n * introspection/RetryInterceptor, but the decorator itself is what actually\n * retries; enabling RetryModule's global interceptor on top of `@Retry`-\n * decorated methods double-retries them (see RetryModule's\n * `globalInterceptor` option, off by default for this reason).\n *\n * Optionally inject `public readonly retryRegistry: RetryRegistry` on the\n * class to get a named, shared RetryEngine per method (so budget/idempotency\n * config actually accumulates across calls, and metrics are inspectable via\n * the registry) instead of the internal default registry.\n *\n * @example\n * ```ts\n * @Retry({ maxAttempts: 3, backoff: { type: 'exponential', baseDelay: 200 } })\n * async fetchData() { ... }\n * ```\n */\nexport function Retry(config: Partial<RetryConfig>): MethodDecorator {\n return function (target: object, propertyKey: string | symbol, descriptor: PropertyDescriptor): PropertyDescriptor {\n const originalMethod = descriptor.value as (...args: unknown[]) => unknown;\n const className = (target as { constructor?: { name?: string } }).constructor?.name ?? 'anonymous';\n const engineName = `method:${className}.${String(propertyKey)}`;\n\n descriptor.value = function (this: unknown, ...args: unknown[]) {\n const registry = (this as { retryRegistry?: RetryRegistry }).retryRegistry ?? defaultRegistry;\n const engine = registry.getOrCreate(engineName);\n\n return engine.execute(() => Promise.resolve(originalMethod.apply(this, args)), config)\n .then((result) => {\n if (result.ok) return result.value;\n throw result.error;\n });\n };\n\n SetMetadata(RETRY_METADATA_KEY, config)(target, propertyKey, descriptor);\n return descriptor;\n };\n}\n","import {\n Injectable,\n Inject,\n NestInterceptor,\n ExecutionContext,\n CallHandler,\n} from '@nestjs/common';\nimport { Observable, from } from 'rxjs';\nimport { switchMap } from 'rxjs/operators';\nimport { Reflector } from '@nestjs/core';\nimport { RetryService } from './retry.service.js';\nimport { RETRY_METADATA_KEY } from './retry.decorator.js';\nimport type { RetryConfig } from '../retry/types.js';\n\n@Injectable()\nexport class RetryInterceptor implements NestInterceptor {\n constructor(\n @Inject(RetryService) private readonly RetryService: RetryService,\n @Inject(Reflector) private readonly reflector: Reflector,\n ) {}\n\n intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {\n const RetryConfig = this.reflector.get<Partial<RetryConfig> | undefined>(\n RETRY_METADATA_KEY,\n context.getHandler(),\n );\n\n if (!RetryConfig) {\n return next.handle();\n }\n\n return from(\n this.RetryService.execute(() => next.handle().toPromise(), RetryConfig),\n ).pipe(\n switchMap((result) => {\n if (result.ok) {\n const value = result.value;\n if (value instanceof Observable) return value;\n return from(Promise.resolve(value));\n }\n throw result.error;\n }),\n );\n }\n}\n","export const RETRY_ENGINE_TOKEN = Symbol('RETRY_ENGINE_TOKEN');\nexport const RETRY_REGISTRY_TOKEN = Symbol('RETRY_REGISTRY_TOKEN');\n","import { Module, DynamicModule, Provider } from '@nestjs/common';\nimport { APP_INTERCEPTOR } from '@nestjs/core';\nimport { RetryEngine } from '../retry/retry.engine.js';\nimport { RetryRegistry } from '../retry/retry.registry.js';\nimport { RetryService } from './retry.service.js';\nimport { RetryInterceptor } from './retry.interceptor.js';\nimport { RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN } from './retry.constants.js';\nimport type { RetryEngineConfig } from '../retry/types.js';\n\nexport interface RetryModuleOptions {\n engineConfig?: Partial<RetryEngineConfig>;\n /**\n * Registers RetryInterceptor as a global APP_INTERCEPTOR, retrying the\n * whole request pipeline (`next.handle()`) for handlers carrying\n * `@Retry` metadata.\n *\n * Default: `false`. `@Retry` already retries the decorated method\n * directly -- turning this on for methods that also use `@Retry` retries\n * them twice (once via the decorator's own wrapping, once via the\n * interceptor re-running the whole pipeline around it). Only enable this\n * if you specifically want pipeline-level retry instead of method-level.\n */\n globalInterceptor?: boolean;\n}\n\n@Module({})\nexport class RetryModule {\n static forRoot(options?: RetryModuleOptions): DynamicModule {\n const engineConfig = options?.engineConfig ?? { name: 'default' };\n\n const providers: Provider[] = [\n {\n provide: RETRY_REGISTRY_TOKEN,\n useFactory: () => new RetryRegistry(),\n },\n {\n provide: RETRY_ENGINE_TOKEN,\n useFactory: (registry: RetryRegistry) =>\n registry.getOrCreate(engineConfig.name ?? 'default', engineConfig),\n inject: [RETRY_REGISTRY_TOKEN],\n },\n {\n provide: RetryService,\n useFactory: (engine: RetryEngine) => new RetryService(engine),\n inject: [RETRY_ENGINE_TOKEN],\n },\n ];\n\n if (options?.globalInterceptor === true) {\n providers.push({\n provide: APP_INTERCEPTOR,\n useClass: RetryInterceptor,\n });\n }\n\n return {\n module: RetryModule,\n providers,\n exports: [RetryService, RETRY_ENGINE_TOKEN, RETRY_REGISTRY_TOKEN],\n };\n }\n}\n"]}
@@ -1,11 +1,22 @@
1
1
  import { DynamicModule, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
2
- import { s as RetryEngineConfig, R as RetryConfig, r as RetryEngine, a as RetryError } from '../retry.engine-ETXna-Ud.cjs';
2
+ import { s as RetryEngineConfig, R as RetryConfig, r as RetryEngine, a as RetryError } from '../retry.engine-C2SjDj64.cjs';
3
3
  import { Observable } from 'rxjs';
4
4
  import { Reflector } from '@nestjs/core';
5
5
  import { Result } from '@backendkit-labs/result';
6
6
 
7
7
  interface RetryModuleOptions {
8
8
  engineConfig?: Partial<RetryEngineConfig>;
9
+ /**
10
+ * Registers RetryInterceptor as a global APP_INTERCEPTOR, retrying the
11
+ * whole request pipeline (`next.handle()`) for handlers carrying
12
+ * `@Retry` metadata.
13
+ *
14
+ * Default: `false`. `@Retry` already retries the decorated method
15
+ * directly -- turning this on for methods that also use `@Retry` retries
16
+ * them twice (once via the decorator's own wrapping, once via the
17
+ * interceptor re-running the whole pipeline around it). Only enable this
18
+ * if you specifically want pipeline-level retry instead of method-level.
19
+ */
9
20
  globalInterceptor?: boolean;
10
21
  }
11
22
  declare class RetryModule {
@@ -13,7 +24,17 @@ declare class RetryModule {
13
24
  }
14
25
 
15
26
  /**
16
- * Decorator that marks a method for retry.
27
+ * Wraps a method in retry logic directly -- works on any method (service or
28
+ * controller), with or without NestJS DI. Also sets metadata for
29
+ * introspection/RetryInterceptor, but the decorator itself is what actually
30
+ * retries; enabling RetryModule's global interceptor on top of `@Retry`-
31
+ * decorated methods double-retries them (see RetryModule's
32
+ * `globalInterceptor` option, off by default for this reason).
33
+ *
34
+ * Optionally inject `public readonly retryRegistry: RetryRegistry` on the
35
+ * class to get a named, shared RetryEngine per method (so budget/idempotency
36
+ * config actually accumulates across calls, and metrics are inspectable via
37
+ * the registry) instead of the internal default registry.
17
38
  *
18
39
  * @example
19
40
  * ```ts
@@ -1,11 +1,22 @@
1
1
  import { DynamicModule, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
2
- import { s as RetryEngineConfig, R as RetryConfig, r as RetryEngine, a as RetryError } from '../retry.engine-ETXna-Ud.js';
2
+ import { s as RetryEngineConfig, R as RetryConfig, r as RetryEngine, a as RetryError } from '../retry.engine-C2SjDj64.js';
3
3
  import { Observable } from 'rxjs';
4
4
  import { Reflector } from '@nestjs/core';
5
5
  import { Result } from '@backendkit-labs/result';
6
6
 
7
7
  interface RetryModuleOptions {
8
8
  engineConfig?: Partial<RetryEngineConfig>;
9
+ /**
10
+ * Registers RetryInterceptor as a global APP_INTERCEPTOR, retrying the
11
+ * whole request pipeline (`next.handle()`) for handlers carrying
12
+ * `@Retry` metadata.
13
+ *
14
+ * Default: `false`. `@Retry` already retries the decorated method
15
+ * directly -- turning this on for methods that also use `@Retry` retries
16
+ * them twice (once via the decorator's own wrapping, once via the
17
+ * interceptor re-running the whole pipeline around it). Only enable this
18
+ * if you specifically want pipeline-level retry instead of method-level.
19
+ */
9
20
  globalInterceptor?: boolean;
10
21
  }
11
22
  declare class RetryModule {
@@ -13,7 +24,17 @@ declare class RetryModule {
13
24
  }
14
25
 
15
26
  /**
16
- * Decorator that marks a method for retry.
27
+ * Wraps a method in retry logic directly -- works on any method (service or
28
+ * controller), with or without NestJS DI. Also sets metadata for
29
+ * introspection/RetryInterceptor, but the decorator itself is what actually
30
+ * retries; enabling RetryModule's global interceptor on top of `@Retry`-
31
+ * decorated methods double-retries them (see RetryModule's
32
+ * `globalInterceptor` option, off by default for this reason).
33
+ *
34
+ * Optionally inject `public readonly retryRegistry: RetryRegistry` on the
35
+ * class to get a named, shared RetryEngine per method (so budget/idempotency
36
+ * config actually accumulates across calls, and metrics are inspectable via
37
+ * the registry) instead of the internal default registry.
17
38
  *
18
39
  * @example
19
40
  * ```ts
@@ -1,6 +1,6 @@
1
- import { __decorateClass, RetryRegistry } from '../chunk-6UD5URCQ.js';
2
- import { Injectable, Module, SetMetadata } from '@nestjs/common';
3
- import { APP_INTERCEPTOR } from '@nestjs/core';
1
+ import { __decorateClass, RetryRegistry, __decorateParam } from '../chunk-ZZ6WRRGP.js';
2
+ import { Injectable, Inject, Module, SetMetadata } from '@nestjs/common';
3
+ import { Reflector, APP_INTERCEPTOR } from '@nestjs/core';
4
4
  import { from, Observable } from 'rxjs';
5
5
  import { switchMap } from 'rxjs/operators';
6
6
 
@@ -20,8 +20,23 @@ RetryService = __decorateClass([
20
20
  Injectable()
21
21
  ], RetryService);
22
22
  var RETRY_METADATA_KEY = "retry:config";
23
+ var defaultRegistry = new RetryRegistry();
23
24
  function Retry(config) {
24
- return SetMetadata(RETRY_METADATA_KEY, config);
25
+ return function(target, propertyKey, descriptor) {
26
+ const originalMethod = descriptor.value;
27
+ const className = target.constructor?.name ?? "anonymous";
28
+ const engineName = `method:${className}.${String(propertyKey)}`;
29
+ descriptor.value = function(...args) {
30
+ const registry = this.retryRegistry ?? defaultRegistry;
31
+ const engine = registry.getOrCreate(engineName);
32
+ return engine.execute(() => Promise.resolve(originalMethod.apply(this, args)), config).then((result) => {
33
+ if (result.ok) return result.value;
34
+ throw result.error;
35
+ });
36
+ };
37
+ SetMetadata(RETRY_METADATA_KEY, config)(target, propertyKey, descriptor);
38
+ return descriptor;
39
+ };
25
40
  }
26
41
 
27
42
  // src/nestjs/retry.interceptor.ts
@@ -55,7 +70,9 @@ var RetryInterceptor = class {
55
70
  }
56
71
  };
57
72
  RetryInterceptor = __decorateClass([
58
- Injectable()
73
+ Injectable(),
74
+ __decorateParam(0, Inject(RetryService)),
75
+ __decorateParam(1, Inject(Reflector))
59
76
  ], RetryInterceptor);
60
77
 
61
78
  // src/nestjs/retry.constants.ts
@@ -82,7 +99,7 @@ var RetryModule = class {
82
99
  inject: [RETRY_ENGINE_TOKEN]
83
100
  }
84
101
  ];
85
- if (options?.globalInterceptor !== false) {
102
+ if (options?.globalInterceptor === true) {
86
103
  providers.push({
87
104
  provide: APP_INTERCEPTOR,
88
105
  useClass: RetryInterceptor