@backendkit-labs/retry 0.1.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 +801 -0
- package/dist/chunk-HOW7IDKS.cjs +752 -0
- package/dist/chunk-HOW7IDKS.cjs.map +1 -0
- package/dist/chunk-ZWXN4OXT.js +734 -0
- package/dist/chunk-ZWXN4OXT.js.map +1 -0
- package/dist/index.cjs +98 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +207 -0
- package/dist/index.d.ts +207 -0
- package/dist/index.js +31 -0
- package/dist/index.js.map +1 -0
- package/dist/nestjs/index.cjs +108 -0
- package/dist/nestjs/index.cjs.map +1 -0
- package/dist/nestjs/index.d.cts +43 -0
- package/dist/nestjs/index.d.ts +43 -0
- package/dist/nestjs/index.js +104 -0
- package/dist/nestjs/index.js.map +1 -0
- package/dist/retry.engine-DSm8xWKJ.d.cts +202 -0
- package/dist/retry.engine-DSm8xWKJ.d.ts +202 -0
- package/package.json +100 -0
|
@@ -0,0 +1,734 @@
|
|
|
1
|
+
var __defProp = Object.defineProperty;
|
|
2
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
3
|
+
var __decorateClass = (decorators, target, key, kind) => {
|
|
4
|
+
var result = kind > 1 ? void 0 : kind ? __getOwnPropDesc(target, key) : target;
|
|
5
|
+
for (var i = decorators.length - 1, decorator; i >= 0; i--)
|
|
6
|
+
if (decorator = decorators[i])
|
|
7
|
+
result = (kind ? decorator(target, key, result) : decorator(result)) || result;
|
|
8
|
+
if (kind && result) __defProp(target, key, result);
|
|
9
|
+
return result;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
// src/timeout/timeout.errors.ts
|
|
13
|
+
var AttemptTimeoutError = class extends Error {
|
|
14
|
+
constructor(timeoutMs) {
|
|
15
|
+
super(`Attempt timed out after ${timeoutMs}ms`);
|
|
16
|
+
this.timeoutMs = timeoutMs;
|
|
17
|
+
this.name = "AttemptTimeoutError";
|
|
18
|
+
}
|
|
19
|
+
timeoutMs;
|
|
20
|
+
};
|
|
21
|
+
var GlobalTimeoutError = class extends Error {
|
|
22
|
+
constructor(timeoutMs, elapsedMs) {
|
|
23
|
+
super(`Global timeout of ${timeoutMs}ms exceeded (elapsed: ${elapsedMs}ms)`);
|
|
24
|
+
this.timeoutMs = timeoutMs;
|
|
25
|
+
this.elapsedMs = elapsedMs;
|
|
26
|
+
this.name = "GlobalTimeoutError";
|
|
27
|
+
}
|
|
28
|
+
timeoutMs;
|
|
29
|
+
elapsedMs;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
// src/retry/retry.budget.ts
|
|
33
|
+
var SlidingWindowBudgetImpl = class {
|
|
34
|
+
constructor(config) {
|
|
35
|
+
this.config = config;
|
|
36
|
+
}
|
|
37
|
+
config;
|
|
38
|
+
calls = [];
|
|
39
|
+
retries = [];
|
|
40
|
+
successes = 0;
|
|
41
|
+
failures = 0;
|
|
42
|
+
evict() {
|
|
43
|
+
const cutoff = Date.now() - this.config.windowMs;
|
|
44
|
+
this.calls = this.calls.filter((t) => t > cutoff);
|
|
45
|
+
this.retries = this.retries.filter((t) => t > cutoff);
|
|
46
|
+
}
|
|
47
|
+
recordCall() {
|
|
48
|
+
this.calls.push(Date.now());
|
|
49
|
+
}
|
|
50
|
+
recordSuccess() {
|
|
51
|
+
this.successes++;
|
|
52
|
+
}
|
|
53
|
+
recordFailure() {
|
|
54
|
+
this.failures++;
|
|
55
|
+
}
|
|
56
|
+
tryConsume() {
|
|
57
|
+
this.evict();
|
|
58
|
+
const total = this.calls.length;
|
|
59
|
+
if (total < this.config.minRequestCount) return true;
|
|
60
|
+
const ratio = this.retries.length / total;
|
|
61
|
+
if (ratio >= this.config.maxRetryRatio) return false;
|
|
62
|
+
this.retries.push(Date.now());
|
|
63
|
+
return true;
|
|
64
|
+
}
|
|
65
|
+
getMetrics() {
|
|
66
|
+
this.evict();
|
|
67
|
+
const total = this.calls.length;
|
|
68
|
+
const retries = this.retries.length;
|
|
69
|
+
const ratio = total > 0 ? retries / total : 0;
|
|
70
|
+
return {
|
|
71
|
+
allowed: total < this.config.minRequestCount || ratio < this.config.maxRetryRatio,
|
|
72
|
+
retryCount: retries,
|
|
73
|
+
successCount: this.successes,
|
|
74
|
+
failureCount: this.failures,
|
|
75
|
+
totalCalls: total,
|
|
76
|
+
currentRatio: ratio
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// src/conditions/error.classifier.ts
|
|
82
|
+
var DefaultErrorClassifier = class {
|
|
83
|
+
rules;
|
|
84
|
+
constructor(customRules) {
|
|
85
|
+
this.rules = [
|
|
86
|
+
// Built-in rules (priority 0-99)
|
|
87
|
+
{ name: "http-401", priority: 10, match: (e) => e.type === "http" && e.status === 401, classification: "permanent" },
|
|
88
|
+
{ name: "http-403", priority: 10, match: (e) => e.type === "http" && e.status === 403, classification: "permanent" },
|
|
89
|
+
{ name: "http-404", priority: 10, match: (e) => e.type === "http" && e.status === 404, classification: "permanent" },
|
|
90
|
+
{ name: "http-400", priority: 10, match: (e) => e.type === "http" && e.status === 400, classification: "permanent" },
|
|
91
|
+
{ name: "http-413", priority: 10, match: (e) => e.type === "http" && e.status === 413, classification: "permanent" },
|
|
92
|
+
{ name: "http-422", priority: 10, match: (e) => e.type === "http" && e.status === 422, classification: "permanent" },
|
|
93
|
+
{ name: "http-429", priority: 20, match: (e) => e.type === "http" && e.status === 429, classification: "transient" },
|
|
94
|
+
{ name: "http-5xx", priority: 20, match: (e) => e.type === "http" && e.status != null && e.status >= 500, classification: "transient" },
|
|
95
|
+
{ name: "network", priority: 20, match: (e) => e.type === "network", classification: "transient" },
|
|
96
|
+
{ name: "timeout", priority: 20, match: (e) => e.type === "timeout", classification: "transient" },
|
|
97
|
+
{ name: "circuit-open", priority: 20, match: (e) => e.type === "circuit-open", classification: "transient" },
|
|
98
|
+
{ name: "bulkhead-rejected", priority: 20, match: (e) => e.type === "bulkhead-rejected", classification: "transient" },
|
|
99
|
+
// Fallback: business and unknown are permanent
|
|
100
|
+
{ name: "business", priority: 100, match: (e) => e.type === "business", classification: "permanent" },
|
|
101
|
+
{ name: "unknown", priority: 100, match: () => true, classification: "permanent" }
|
|
102
|
+
];
|
|
103
|
+
if (customRules) {
|
|
104
|
+
this.rules.push(...customRules);
|
|
105
|
+
}
|
|
106
|
+
this.rules.sort((a, b) => (a.priority ?? 100) - (b.priority ?? 100));
|
|
107
|
+
}
|
|
108
|
+
classify(error) {
|
|
109
|
+
for (const rule of this.rules) {
|
|
110
|
+
if (rule.match(error)) {
|
|
111
|
+
return rule.classification;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
return "permanent";
|
|
115
|
+
}
|
|
116
|
+
};
|
|
117
|
+
|
|
118
|
+
// src/timeout/timeout.manager.ts
|
|
119
|
+
var TimeoutManager = class {
|
|
120
|
+
constructor(config) {
|
|
121
|
+
this.config = config;
|
|
122
|
+
this.startTime = Date.now();
|
|
123
|
+
}
|
|
124
|
+
config;
|
|
125
|
+
startTime;
|
|
126
|
+
/**
|
|
127
|
+
* Execute a task with per-attempt timeout.
|
|
128
|
+
* Throws AttemptTimeoutError if the task exceeds attemptTimeoutMs.
|
|
129
|
+
*/
|
|
130
|
+
async executeWithAttemptTimeout(task) {
|
|
131
|
+
if (!this.config.attemptTimeoutMs || this.config.attemptTimeoutMs <= 0) {
|
|
132
|
+
return task();
|
|
133
|
+
}
|
|
134
|
+
return new Promise((resolve, reject) => {
|
|
135
|
+
const timer = setTimeout(() => {
|
|
136
|
+
reject(new AttemptTimeoutError(this.config.attemptTimeoutMs));
|
|
137
|
+
}, this.config.attemptTimeoutMs);
|
|
138
|
+
task().then((val) => {
|
|
139
|
+
clearTimeout(timer);
|
|
140
|
+
resolve(val);
|
|
141
|
+
}).catch((err) => {
|
|
142
|
+
clearTimeout(timer);
|
|
143
|
+
reject(err);
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Check if the global timeout has been exceeded.
|
|
149
|
+
* Throws GlobalTimeoutError if exceeded.
|
|
150
|
+
*/
|
|
151
|
+
checkGlobalTimeout() {
|
|
152
|
+
if (!this.config.globalTimeoutMs || this.config.globalTimeoutMs <= 0) return;
|
|
153
|
+
const elapsed = Date.now() - this.startTime;
|
|
154
|
+
if (elapsed >= this.config.globalTimeoutMs) {
|
|
155
|
+
throw new GlobalTimeoutError(this.config.globalTimeoutMs, elapsed);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Get the remaining time before global timeout (ms).
|
|
160
|
+
* Returns Infinity if no global timeout is configured.
|
|
161
|
+
*/
|
|
162
|
+
getRemainingTime() {
|
|
163
|
+
if (!this.config.globalTimeoutMs || this.config.globalTimeoutMs <= 0) return Infinity;
|
|
164
|
+
const elapsed = Date.now() - this.startTime;
|
|
165
|
+
return Math.max(0, this.config.globalTimeoutMs - elapsed);
|
|
166
|
+
}
|
|
167
|
+
/** Reset the start time (for reuse across retry cycles). */
|
|
168
|
+
reset() {
|
|
169
|
+
this.startTime = Date.now();
|
|
170
|
+
}
|
|
171
|
+
};
|
|
172
|
+
|
|
173
|
+
// src/idempotency/memory.store.ts
|
|
174
|
+
var InMemoryIdempotencyStore = class {
|
|
175
|
+
store = /* @__PURE__ */ new Map();
|
|
176
|
+
get(key) {
|
|
177
|
+
const entry = this.store.get(key);
|
|
178
|
+
if (!entry) return Promise.resolve(null);
|
|
179
|
+
if (Date.now() > entry.expiresAt) {
|
|
180
|
+
this.store.delete(key);
|
|
181
|
+
return Promise.resolve(null);
|
|
182
|
+
}
|
|
183
|
+
return Promise.resolve(entry.value);
|
|
184
|
+
}
|
|
185
|
+
set(key, value, ttlMs) {
|
|
186
|
+
this.store.set(key, {
|
|
187
|
+
value,
|
|
188
|
+
expiresAt: Date.now() + (ttlMs ?? 24 * 60 * 60 * 1e3)
|
|
189
|
+
});
|
|
190
|
+
return Promise.resolve();
|
|
191
|
+
}
|
|
192
|
+
exists(key) {
|
|
193
|
+
const entry = this.store.get(key);
|
|
194
|
+
if (!entry) return Promise.resolve(false);
|
|
195
|
+
if (Date.now() > entry.expiresAt) {
|
|
196
|
+
this.store.delete(key);
|
|
197
|
+
return Promise.resolve(false);
|
|
198
|
+
}
|
|
199
|
+
return Promise.resolve(true);
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// src/idempotency/idempotency.manager.ts
|
|
204
|
+
var IdempotencyManager = class {
|
|
205
|
+
constructor(config) {
|
|
206
|
+
this.config = config;
|
|
207
|
+
this.store = config.store ?? new InMemoryIdempotencyStore();
|
|
208
|
+
}
|
|
209
|
+
config;
|
|
210
|
+
store;
|
|
211
|
+
/**
|
|
212
|
+
* Generate an idempotency key from the request context.
|
|
213
|
+
*/
|
|
214
|
+
generateKey(method, path, bodyHash) {
|
|
215
|
+
return `${method}:${path}:${bodyHash ?? ""}`;
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Check if a key already exists in the store.
|
|
219
|
+
*/
|
|
220
|
+
async hasResult(key) {
|
|
221
|
+
return this.store.exists(key);
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Store a result for a given key.
|
|
225
|
+
*/
|
|
226
|
+
async storeResult(key, result) {
|
|
227
|
+
await this.store.set(key, result, this.config.ttlMs);
|
|
228
|
+
}
|
|
229
|
+
/**
|
|
230
|
+
* Retrieve a stored result.
|
|
231
|
+
*/
|
|
232
|
+
async getResult(key) {
|
|
233
|
+
return this.store.get(key);
|
|
234
|
+
}
|
|
235
|
+
/**
|
|
236
|
+
* Check if the HTTP method should be idempotent.
|
|
237
|
+
*/
|
|
238
|
+
isIdempotentMethod(method) {
|
|
239
|
+
return this.config.idempotentMethods.includes(method.toUpperCase());
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
// src/backoff/fixed.backoff.ts
|
|
244
|
+
var FixedBackoff = class _FixedBackoff {
|
|
245
|
+
constructor(config) {
|
|
246
|
+
this.config = config;
|
|
247
|
+
}
|
|
248
|
+
config;
|
|
249
|
+
nextDelay(_attempt) {
|
|
250
|
+
return this.config.baseDelay;
|
|
251
|
+
}
|
|
252
|
+
reset() {
|
|
253
|
+
}
|
|
254
|
+
clone(overrides) {
|
|
255
|
+
return new _FixedBackoff({
|
|
256
|
+
baseDelay: overrides?.baseDelay ?? this.config.baseDelay
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
// src/backoff/linear.backoff.ts
|
|
262
|
+
var LinearBackoff = class _LinearBackoff {
|
|
263
|
+
constructor(config) {
|
|
264
|
+
this.config = config;
|
|
265
|
+
this.config.multiplier ??= 1;
|
|
266
|
+
this.config.maxDelay ??= Infinity;
|
|
267
|
+
}
|
|
268
|
+
config;
|
|
269
|
+
nextDelay(attempt) {
|
|
270
|
+
const delay = this.config.baseDelay * attempt * (this.config.multiplier ?? 1);
|
|
271
|
+
return Math.min(delay, this.config.maxDelay ?? Infinity);
|
|
272
|
+
}
|
|
273
|
+
reset() {
|
|
274
|
+
}
|
|
275
|
+
clone(overrides) {
|
|
276
|
+
return new _LinearBackoff({
|
|
277
|
+
baseDelay: overrides?.baseDelay ?? this.config.baseDelay,
|
|
278
|
+
multiplier: this.config.multiplier,
|
|
279
|
+
maxDelay: this.config.maxDelay
|
|
280
|
+
});
|
|
281
|
+
}
|
|
282
|
+
};
|
|
283
|
+
|
|
284
|
+
// src/backoff/jitter.decorator.ts
|
|
285
|
+
function applyJitter(delay, type) {
|
|
286
|
+
switch (type) {
|
|
287
|
+
case "full":
|
|
288
|
+
return Math.random() * delay;
|
|
289
|
+
case "equal":
|
|
290
|
+
return delay / 2 + Math.random() * (delay / 2);
|
|
291
|
+
case "decorrelated":
|
|
292
|
+
return delay + Math.random() * (delay * 2);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
var JitterDecorator = class _JitterDecorator {
|
|
296
|
+
constructor(inner, jitterType) {
|
|
297
|
+
this.inner = inner;
|
|
298
|
+
this.jitterType = jitterType;
|
|
299
|
+
}
|
|
300
|
+
inner;
|
|
301
|
+
jitterType;
|
|
302
|
+
nextDelay(attempt) {
|
|
303
|
+
const delay = this.inner.nextDelay(attempt);
|
|
304
|
+
return applyJitter(delay, this.jitterType);
|
|
305
|
+
}
|
|
306
|
+
reset() {
|
|
307
|
+
this.inner.reset();
|
|
308
|
+
}
|
|
309
|
+
clone(overrides) {
|
|
310
|
+
return new _JitterDecorator(this.inner.clone(overrides), this.jitterType);
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
// src/backoff/exponential.backoff.ts
|
|
315
|
+
var ExponentialBackoff = class _ExponentialBackoff {
|
|
316
|
+
constructor(config) {
|
|
317
|
+
this.config = config;
|
|
318
|
+
this.config.multiplier ??= 2;
|
|
319
|
+
this.config.maxDelay ??= Infinity;
|
|
320
|
+
}
|
|
321
|
+
config;
|
|
322
|
+
nextDelay(attempt) {
|
|
323
|
+
const delay = this.config.baseDelay * Math.pow(this.config.multiplier ?? 2, attempt - 1);
|
|
324
|
+
const capped = Math.min(delay, this.config.maxDelay ?? Infinity);
|
|
325
|
+
if (this.config.jitter) {
|
|
326
|
+
return applyJitter(capped, this.config.jitter);
|
|
327
|
+
}
|
|
328
|
+
return capped;
|
|
329
|
+
}
|
|
330
|
+
reset() {
|
|
331
|
+
}
|
|
332
|
+
clone(overrides) {
|
|
333
|
+
return new _ExponentialBackoff({
|
|
334
|
+
baseDelay: overrides?.baseDelay ?? this.config.baseDelay,
|
|
335
|
+
multiplier: this.config.multiplier,
|
|
336
|
+
maxDelay: this.config.maxDelay,
|
|
337
|
+
jitter: this.config.jitter
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
};
|
|
341
|
+
|
|
342
|
+
// src/conditions/http.conditions.ts
|
|
343
|
+
var defaultRetryCondition = {
|
|
344
|
+
shouldRetry(error) {
|
|
345
|
+
switch (error.type) {
|
|
346
|
+
case "http":
|
|
347
|
+
return error.status === 429 || error.status != null && error.status >= 500;
|
|
348
|
+
case "network":
|
|
349
|
+
case "timeout":
|
|
350
|
+
case "circuit-open":
|
|
351
|
+
case "bulkhead-rejected":
|
|
352
|
+
return true;
|
|
353
|
+
case "business":
|
|
354
|
+
case "unknown":
|
|
355
|
+
return false;
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
};
|
|
359
|
+
var defaultAbortCondition = {
|
|
360
|
+
shouldAbort(error) {
|
|
361
|
+
switch (error.type) {
|
|
362
|
+
case "http":
|
|
363
|
+
return error.status != null && error.status < 500 && error.status !== 429;
|
|
364
|
+
case "business":
|
|
365
|
+
return true;
|
|
366
|
+
case "network":
|
|
367
|
+
case "timeout":
|
|
368
|
+
case "circuit-open":
|
|
369
|
+
case "bulkhead-rejected":
|
|
370
|
+
case "unknown":
|
|
371
|
+
return false;
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
};
|
|
375
|
+
|
|
376
|
+
// ../result/dist/chunk-XLOUAMAH.js
|
|
377
|
+
var ok = (value) => ({ ok: true, value });
|
|
378
|
+
var fail = (error) => ({ ok: false, error });
|
|
379
|
+
|
|
380
|
+
// src/retry/retry.executor.ts
|
|
381
|
+
function sleep(ms) {
|
|
382
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
383
|
+
}
|
|
384
|
+
var NETWORK_CODES = /* @__PURE__ */ new Set([
|
|
385
|
+
"ECONNREFUSED",
|
|
386
|
+
"ECONNRESET",
|
|
387
|
+
"ENOTFOUND",
|
|
388
|
+
"ETIMEDOUT",
|
|
389
|
+
"EAI_AGAIN",
|
|
390
|
+
"ECONNABORTED",
|
|
391
|
+
"EPIPE"
|
|
392
|
+
]);
|
|
393
|
+
function getHttpStatus(err) {
|
|
394
|
+
if (err == null || typeof err !== "object") return void 0;
|
|
395
|
+
const e = err;
|
|
396
|
+
if (typeof e["status"] === "number") return e["status"];
|
|
397
|
+
if (typeof e["statusCode"] === "number") return e["statusCode"];
|
|
398
|
+
const response = e["response"];
|
|
399
|
+
if (response != null && typeof response === "object") {
|
|
400
|
+
const r = response;
|
|
401
|
+
if (typeof r["status"] === "number") return r["status"];
|
|
402
|
+
}
|
|
403
|
+
return void 0;
|
|
404
|
+
}
|
|
405
|
+
function normalizeError(err, attempt, startTime) {
|
|
406
|
+
const elapsedMs = Date.now() - startTime;
|
|
407
|
+
if (err instanceof AttemptTimeoutError || err instanceof GlobalTimeoutError) {
|
|
408
|
+
return { type: "timeout", message: err.message, attempt, elapsedMs, cause: err };
|
|
409
|
+
}
|
|
410
|
+
const status = getHttpStatus(err);
|
|
411
|
+
if (status !== void 0) {
|
|
412
|
+
const message2 = err instanceof Error ? err.message : `HTTP ${status}`;
|
|
413
|
+
return { type: "http", message: message2, status, attempt, elapsedMs, cause: err };
|
|
414
|
+
}
|
|
415
|
+
if (err != null && typeof err === "object") {
|
|
416
|
+
const code = err["code"];
|
|
417
|
+
if (typeof code === "string" && NETWORK_CODES.has(code)) {
|
|
418
|
+
const message2 = err instanceof Error ? err.message : "Network error";
|
|
419
|
+
return { type: "network", message: message2, attempt, elapsedMs, cause: err };
|
|
420
|
+
}
|
|
421
|
+
}
|
|
422
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
423
|
+
return { type: "unknown", message, attempt, elapsedMs, cause: err };
|
|
424
|
+
}
|
|
425
|
+
function makeRetryError(payload, attempts, totalElapsedMs, budgetExhausted) {
|
|
426
|
+
return {
|
|
427
|
+
...payload,
|
|
428
|
+
metadata: { attempts, totalElapsedMs, lastError: payload, budgetExhausted }
|
|
429
|
+
};
|
|
430
|
+
}
|
|
431
|
+
var RetryExecutor = class {
|
|
432
|
+
constructor(deps, config) {
|
|
433
|
+
this.deps = deps;
|
|
434
|
+
this.config = config;
|
|
435
|
+
}
|
|
436
|
+
deps;
|
|
437
|
+
config;
|
|
438
|
+
async run(task) {
|
|
439
|
+
const {
|
|
440
|
+
backoff,
|
|
441
|
+
budget,
|
|
442
|
+
classifier,
|
|
443
|
+
timeoutManager,
|
|
444
|
+
RetryCondition,
|
|
445
|
+
abortCondition,
|
|
446
|
+
hooks,
|
|
447
|
+
circuitBreaker,
|
|
448
|
+
bulkhead,
|
|
449
|
+
logger,
|
|
450
|
+
metrics,
|
|
451
|
+
correlationId
|
|
452
|
+
} = this.deps;
|
|
453
|
+
const { maxAttempts = 3, dynamicDelay, fallback } = this.config;
|
|
454
|
+
const startTime = Date.now();
|
|
455
|
+
let lastError;
|
|
456
|
+
budget?.recordCall();
|
|
457
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
|
|
458
|
+
try {
|
|
459
|
+
timeoutManager.checkGlobalTimeout();
|
|
460
|
+
} catch (err) {
|
|
461
|
+
const payload2 = normalizeError(err, attempt, startTime);
|
|
462
|
+
await hooks.onExhausted({ lastError: payload2, totalAttempts: attempt - 1, totalElapsedMs: Date.now() - startTime });
|
|
463
|
+
return fail(makeRetryError(payload2, attempt - 1, Date.now() - startTime));
|
|
464
|
+
}
|
|
465
|
+
if (circuitBreaker && !circuitBreaker.canAttempt()) {
|
|
466
|
+
const payload2 = {
|
|
467
|
+
type: "circuit-open",
|
|
468
|
+
message: "Circuit breaker is open",
|
|
469
|
+
attempt,
|
|
470
|
+
elapsedMs: Date.now() - startTime
|
|
471
|
+
};
|
|
472
|
+
if (attempt >= maxAttempts || await abortCondition.shouldAbort(payload2)) {
|
|
473
|
+
await hooks.onExhausted({ lastError: payload2, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });
|
|
474
|
+
return fail(makeRetryError(payload2, attempt, Date.now() - startTime));
|
|
475
|
+
}
|
|
476
|
+
lastError = payload2;
|
|
477
|
+
const delay = dynamicDelay?.(payload2, attempt) ?? backoff.nextDelay(attempt);
|
|
478
|
+
await hooks.beforeRetry({ attempt, error: payload2, delayMs: delay });
|
|
479
|
+
await sleep(delay);
|
|
480
|
+
await hooks.afterRetry({ attempt, error: payload2, delayMs: delay });
|
|
481
|
+
continue;
|
|
482
|
+
}
|
|
483
|
+
try {
|
|
484
|
+
const executeTask = () => timeoutManager.executeWithAttemptTimeout(task);
|
|
485
|
+
const value = await (bulkhead ? bulkhead.execute(executeTask) : executeTask());
|
|
486
|
+
circuitBreaker?.onSuccess(Date.now() - startTime);
|
|
487
|
+
budget?.recordSuccess();
|
|
488
|
+
if (attempt > 1) {
|
|
489
|
+
await hooks.onRetrySuccess({ attempt, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });
|
|
490
|
+
}
|
|
491
|
+
metrics?.emit({ name: "Retry.success", value: 1, tags: { attempt: String(attempt) } });
|
|
492
|
+
return ok(value);
|
|
493
|
+
} catch (err) {
|
|
494
|
+
const payload2 = normalizeError(err, attempt, startTime);
|
|
495
|
+
lastError = payload2;
|
|
496
|
+
const classification = classifier.classify(payload2);
|
|
497
|
+
circuitBreaker?.onError(err);
|
|
498
|
+
budget?.recordFailure();
|
|
499
|
+
logger?.warn("Retry: attempt failed", { attempt, message: payload2.message, type: payload2.type, classification, correlationId });
|
|
500
|
+
metrics?.emit({ name: "Retry.attempt_failed", value: 1, tags: { attempt: String(attempt), type: payload2.type, classification } });
|
|
501
|
+
if (await abortCondition.shouldAbort(payload2)) {
|
|
502
|
+
return fail(makeRetryError(payload2, attempt, Date.now() - startTime));
|
|
503
|
+
}
|
|
504
|
+
if (!await RetryCondition.shouldRetry(payload2)) {
|
|
505
|
+
await hooks.onExhausted({ lastError: payload2, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });
|
|
506
|
+
if (fallback) return ok(await fallback(payload2));
|
|
507
|
+
return fail(makeRetryError(payload2, attempt, Date.now() - startTime));
|
|
508
|
+
}
|
|
509
|
+
if (attempt >= maxAttempts) {
|
|
510
|
+
await hooks.onExhausted({ lastError: payload2, totalAttempts: attempt, totalElapsedMs: Date.now() - startTime });
|
|
511
|
+
if (fallback) return ok(await fallback(payload2));
|
|
512
|
+
return fail(makeRetryError(payload2, attempt, Date.now() - startTime));
|
|
513
|
+
}
|
|
514
|
+
if (budget && !budget.tryConsume()) {
|
|
515
|
+
await hooks.onBudgetExhausted();
|
|
516
|
+
metrics?.emit({ name: "Retry.budget_exhausted", value: 1 });
|
|
517
|
+
if (fallback) return ok(await fallback(payload2));
|
|
518
|
+
return fail(makeRetryError(payload2, attempt, Date.now() - startTime, true));
|
|
519
|
+
}
|
|
520
|
+
const delay = dynamicDelay?.(payload2, attempt) ?? backoff.nextDelay(attempt);
|
|
521
|
+
await hooks.beforeRetry({ attempt, error: payload2, delayMs: delay });
|
|
522
|
+
await sleep(delay);
|
|
523
|
+
await hooks.afterRetry({ attempt, error: payload2, delayMs: delay });
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
const payload = lastError ?? {
|
|
527
|
+
type: "unknown",
|
|
528
|
+
message: "Retry loop exhausted without error",
|
|
529
|
+
attempt: maxAttempts,
|
|
530
|
+
elapsedMs: Date.now() - startTime
|
|
531
|
+
};
|
|
532
|
+
await hooks.onExhausted({ lastError: payload, totalAttempts: maxAttempts, totalElapsedMs: Date.now() - startTime });
|
|
533
|
+
if (fallback) return ok(await fallback(payload));
|
|
534
|
+
return fail(makeRetryError(payload, maxAttempts, Date.now() - startTime));
|
|
535
|
+
}
|
|
536
|
+
};
|
|
537
|
+
|
|
538
|
+
// src/retry/retry.hooks.ts
|
|
539
|
+
var HookRunner = class {
|
|
540
|
+
constructor(hooks, correlationId) {
|
|
541
|
+
this.hooks = hooks;
|
|
542
|
+
this.correlationId = correlationId;
|
|
543
|
+
}
|
|
544
|
+
hooks;
|
|
545
|
+
correlationId;
|
|
546
|
+
async beforeRetry(ctx) {
|
|
547
|
+
if (!this.hooks.beforeRetry) return;
|
|
548
|
+
try {
|
|
549
|
+
await this.hooks.beforeRetry({ ...ctx, correlationId: this.correlationId });
|
|
550
|
+
} catch {
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
async afterRetry(ctx) {
|
|
554
|
+
if (!this.hooks.afterRetry) return;
|
|
555
|
+
try {
|
|
556
|
+
await this.hooks.afterRetry({ ...ctx, correlationId: this.correlationId });
|
|
557
|
+
} catch {
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
async onRetrySuccess(ctx) {
|
|
561
|
+
if (!this.hooks.onRetrySuccess) return;
|
|
562
|
+
try {
|
|
563
|
+
await this.hooks.onRetrySuccess({ ...ctx, correlationId: this.correlationId });
|
|
564
|
+
} catch {
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
async onExhausted(ctx) {
|
|
568
|
+
if (!this.hooks.onExhausted) return;
|
|
569
|
+
try {
|
|
570
|
+
await this.hooks.onExhausted({ ...ctx, correlationId: this.correlationId });
|
|
571
|
+
} catch {
|
|
572
|
+
}
|
|
573
|
+
}
|
|
574
|
+
async onBudgetExhausted() {
|
|
575
|
+
if (!this.hooks.onBudgetExhausted) return;
|
|
576
|
+
try {
|
|
577
|
+
await this.hooks.onBudgetExhausted({ correlationId: this.correlationId });
|
|
578
|
+
} catch {
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
};
|
|
582
|
+
|
|
583
|
+
// src/retry/retry.engine.ts
|
|
584
|
+
function isBackoffStrategy(b) {
|
|
585
|
+
return typeof b.nextDelay === "function";
|
|
586
|
+
}
|
|
587
|
+
function createBackoff(config) {
|
|
588
|
+
switch (config.type) {
|
|
589
|
+
case "fixed":
|
|
590
|
+
return new FixedBackoff({ baseDelay: config.baseDelay });
|
|
591
|
+
case "linear":
|
|
592
|
+
return new LinearBackoff({ baseDelay: config.baseDelay, multiplier: config.multiplier, maxDelay: config.maxDelay });
|
|
593
|
+
case "exponential":
|
|
594
|
+
return new ExponentialBackoff({ baseDelay: config.baseDelay, multiplier: config.multiplier, maxDelay: config.maxDelay, jitter: config.jitter });
|
|
595
|
+
}
|
|
596
|
+
}
|
|
597
|
+
function wrapRetryCondition(condition) {
|
|
598
|
+
if (!condition) return defaultRetryCondition;
|
|
599
|
+
if (typeof condition === "function") return { shouldRetry: condition };
|
|
600
|
+
return condition;
|
|
601
|
+
}
|
|
602
|
+
function wrapAbortCondition(condition) {
|
|
603
|
+
if (!condition) return defaultAbortCondition;
|
|
604
|
+
if (typeof condition === "function") return { shouldAbort: condition };
|
|
605
|
+
return condition;
|
|
606
|
+
}
|
|
607
|
+
var RetryEngine = class {
|
|
608
|
+
constructor(config) {
|
|
609
|
+
this.config = config;
|
|
610
|
+
}
|
|
611
|
+
config;
|
|
612
|
+
metrics = {
|
|
613
|
+
totalAttempts: 0,
|
|
614
|
+
totalSuccesses: 0,
|
|
615
|
+
totalFailures: 0,
|
|
616
|
+
totalExhausted: 0,
|
|
617
|
+
totalBudgetExhausted: 0,
|
|
618
|
+
totalTimeouts: 0
|
|
619
|
+
};
|
|
620
|
+
async execute(task, options) {
|
|
621
|
+
const merged = { ...this.config.defaultConfig, ...options };
|
|
622
|
+
const backoffConfig = !merged.backoff || isBackoffStrategy(merged.backoff) ? { type: "fixed", baseDelay: 200 } : merged.backoff;
|
|
623
|
+
const backoffStrategy = merged.backoff && isBackoffStrategy(merged.backoff) ? merged.backoff.clone() : createBackoff(backoffConfig);
|
|
624
|
+
const classifier = new DefaultErrorClassifier(merged.classifiers);
|
|
625
|
+
const timeoutManager = new TimeoutManager({
|
|
626
|
+
globalTimeoutMs: 0,
|
|
627
|
+
attemptTimeoutMs: 0,
|
|
628
|
+
...merged.timeout
|
|
629
|
+
});
|
|
630
|
+
const budget = merged.budget ? new SlidingWindowBudgetImpl({ windowMs: 6e4, maxRetryRatio: 0.1, minRequestCount: 10, ...merged.budget }) : void 0;
|
|
631
|
+
const idempotency = merged.idempotency?.enabled ? new IdempotencyManager({
|
|
632
|
+
enabled: true,
|
|
633
|
+
idempotentMethods: ["POST", "PUT", "PATCH"],
|
|
634
|
+
headerName: "Idempotency-Key",
|
|
635
|
+
ttlMs: 24 * 60 * 60 * 1e3,
|
|
636
|
+
...merged.idempotency
|
|
637
|
+
}) : void 0;
|
|
638
|
+
const hookRunner = new HookRunner(merged.hooks ?? {}, merged.correlationId);
|
|
639
|
+
const RetryCondition = wrapRetryCondition(merged.retryIf);
|
|
640
|
+
const abortCondition = wrapAbortCondition(merged.abortIf);
|
|
641
|
+
const fullConfig = {
|
|
642
|
+
maxAttempts: 3,
|
|
643
|
+
backoff: backoffConfig,
|
|
644
|
+
...merged
|
|
645
|
+
};
|
|
646
|
+
const executor = new RetryExecutor(
|
|
647
|
+
{
|
|
648
|
+
backoff: backoffStrategy,
|
|
649
|
+
budget,
|
|
650
|
+
classifier,
|
|
651
|
+
timeoutManager,
|
|
652
|
+
idempotency,
|
|
653
|
+
RetryCondition,
|
|
654
|
+
abortCondition,
|
|
655
|
+
hooks: hookRunner,
|
|
656
|
+
circuitBreaker: this.config.integrations?.circuitBreaker,
|
|
657
|
+
bulkhead: this.config.integrations?.bulkhead,
|
|
658
|
+
logger: this.config.integrations?.observability?.logger,
|
|
659
|
+
metrics: this.config.integrations?.observability?.metrics,
|
|
660
|
+
correlationId: merged.correlationId
|
|
661
|
+
},
|
|
662
|
+
fullConfig
|
|
663
|
+
);
|
|
664
|
+
this.metrics.totalAttempts++;
|
|
665
|
+
const result = await executor.run(task);
|
|
666
|
+
if (result.ok) {
|
|
667
|
+
this.metrics.totalSuccesses++;
|
|
668
|
+
} else {
|
|
669
|
+
this.metrics.totalFailures++;
|
|
670
|
+
if (result.error.metadata.budgetExhausted) this.metrics.totalBudgetExhausted++;
|
|
671
|
+
if (result.error.type === "timeout") this.metrics.totalTimeouts++;
|
|
672
|
+
if (result.error.metadata.attempts >= fullConfig.maxAttempts) this.metrics.totalExhausted++;
|
|
673
|
+
}
|
|
674
|
+
return result;
|
|
675
|
+
}
|
|
676
|
+
async executeWithContext(task, context, options) {
|
|
677
|
+
return this.execute(task, { ...options, correlationId: context.correlationId });
|
|
678
|
+
}
|
|
679
|
+
updateDefaults(partial) {
|
|
680
|
+
this.config.defaultConfig = { ...this.config.defaultConfig, ...partial };
|
|
681
|
+
}
|
|
682
|
+
getMetrics() {
|
|
683
|
+
return { ...this.metrics };
|
|
684
|
+
}
|
|
685
|
+
resetMetrics() {
|
|
686
|
+
this.metrics = {
|
|
687
|
+
totalAttempts: 0,
|
|
688
|
+
totalSuccesses: 0,
|
|
689
|
+
totalFailures: 0,
|
|
690
|
+
totalExhausted: 0,
|
|
691
|
+
totalBudgetExhausted: 0,
|
|
692
|
+
totalTimeouts: 0
|
|
693
|
+
};
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
|
|
697
|
+
// src/retry/retry.registry.ts
|
|
698
|
+
var RetryRegistry = class {
|
|
699
|
+
engines = /* @__PURE__ */ new Map();
|
|
700
|
+
getOrCreate(name, config) {
|
|
701
|
+
if (!this.engines.has(name)) {
|
|
702
|
+
this.engines.set(
|
|
703
|
+
name,
|
|
704
|
+
new RetryEngine({
|
|
705
|
+
name,
|
|
706
|
+
...config,
|
|
707
|
+
defaultConfig: { ...config?.defaultConfig },
|
|
708
|
+
integrations: config?.integrations
|
|
709
|
+
})
|
|
710
|
+
);
|
|
711
|
+
}
|
|
712
|
+
return this.engines.get(name);
|
|
713
|
+
}
|
|
714
|
+
get(name) {
|
|
715
|
+
return this.engines.get(name);
|
|
716
|
+
}
|
|
717
|
+
reset(name) {
|
|
718
|
+
this.engines.delete(name);
|
|
719
|
+
}
|
|
720
|
+
resetAll() {
|
|
721
|
+
this.engines.clear();
|
|
722
|
+
}
|
|
723
|
+
getAllMetrics() {
|
|
724
|
+
const metrics = {};
|
|
725
|
+
for (const [name, engine] of this.engines) {
|
|
726
|
+
metrics[name] = engine.getMetrics();
|
|
727
|
+
}
|
|
728
|
+
return metrics;
|
|
729
|
+
}
|
|
730
|
+
};
|
|
731
|
+
|
|
732
|
+
export { AttemptTimeoutError, DefaultErrorClassifier, ExponentialBackoff, FixedBackoff, GlobalTimeoutError, IdempotencyManager, InMemoryIdempotencyStore, JitterDecorator, LinearBackoff, RetryEngine, RetryRegistry, SlidingWindowBudgetImpl, TimeoutManager, __decorateClass, applyJitter, defaultAbortCondition, defaultRetryCondition };
|
|
733
|
+
//# sourceMappingURL=chunk-ZWXN4OXT.js.map
|
|
734
|
+
//# sourceMappingURL=chunk-ZWXN4OXT.js.map
|