forked from SoroLabs/SoroTask
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathretry.js
More file actions
340 lines (309 loc) · 7.83 KB
/
Copy pathretry.js
File metadata and controls
340 lines (309 loc) · 7.83 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
/**
* Error classifications for retry logic.
*/
const ErrorClassification = {
RETRYABLE: "retryable",
NON_RETRYABLE: "non_retryable",
DUPLICATE: "duplicate",
UNKNOWN: "unknown",
};
/**
* Soroban/RPC error codes that indicate retryable conditions.
*/
const RETRYABLE_ERROR_CODES = [
"TIMEOUT",
"NETWORK_ERROR",
"RATE_LIMITED",
"SERVER_ERROR",
"SERVICE_UNAVAILABLE",
"TIMEOUT_ERROR",
"TX_BAD_SEQ",
"TX_INSUFFICIENT_BALANCE",
"TEMPORARY_UNAVAILABLE",
"ECONNRESET",
"ECONNREFUSED",
"ETIMEDOUT",
"ENOTFOUND",
"EAI_AGAIN",
];
/**
* Error codes that indicate non-retryable conditions.
*/
const NON_RETRYABLE_ERROR_CODES = [
"INVALID_ARGS",
"INSUFFICIENT_GAS",
"CONTRACT_PANIC",
"INVALID_TRANSACTION",
"SIMULATION_FAILED",
"VALIDATION_ERROR",
"TX_INSUFFICIENT_FEE",
"TX_BAD_AUTH",
"TX_BAD_AUTH_EXTRA",
"TX_TOO_EARLY",
"TX_TOO_LATE",
"TX_MISSING_OPERATION",
"TX_NOT_SUPPORTED",
"TX_FAILED",
];
/**
* Error codes indicating duplicate transaction (already accepted).
*/
const DUPLICATE_ERROR_CODES = [
"DUPLICATE_TRANSACTION",
"TX_ALREADY_IN_LEDGER",
"TX_DUPLICATE",
];
/**
* Extract error code from various error formats.
* @param {Error|object} error
* @returns {string|null}
*/
function extractErrorCode(error) {
if (!error) return null;
if (error.code && typeof error.code === "string") {
return error.code;
}
if (error.errorCode && typeof error.errorCode === "string") {
return error.errorCode;
}
if (error.status && typeof error.status === "string") {
return error.status;
}
if (error.resultXdr) {
const xdrStr = error.resultXdr.toString
? error.resultXdr.toString()
: String(error.resultXdr);
const patterns = [
"txBadSeq",
"txInsufficientBalance",
"txInsufficientFee",
"txBadAuth",
];
for (const pattern of patterns) {
if (xdrStr.includes(pattern)) return pattern.toUpperCase();
}
}
return null;
}
/**
* Classify an error based on code/message.
* @param {Error|object} error
* @returns {string}
*/
function classifyError(error) {
if (!error) return ErrorClassification.UNKNOWN;
const errorCode = extractErrorCode(error);
const normalizedCode =
typeof errorCode === "string" ? errorCode.toUpperCase() : "";
const normalizedMessage = String(
error.message || error.error || error.resultXdr || "",
).toLowerCase();
if (
DUPLICATE_ERROR_CODES.some(
(code) =>
normalizedCode === code ||
normalizedMessage.includes(code.toLowerCase()) ||
normalizedMessage.includes("duplicate") ||
normalizedMessage.includes("already in ledger"),
)
) {
return ErrorClassification.DUPLICATE;
}
if (
NON_RETRYABLE_ERROR_CODES.some(
(code) =>
normalizedCode === code ||
normalizedMessage.includes(code.toLowerCase()),
)
) {
return ErrorClassification.NON_RETRYABLE;
}
if (
RETRYABLE_ERROR_CODES.some(
(code) =>
normalizedCode === code ||
normalizedMessage.includes(code.toLowerCase()),
)
) {
return ErrorClassification.RETRYABLE;
}
if (
normalizedMessage.includes("timeout") ||
normalizedMessage.includes("network") ||
normalizedMessage.includes("socket hang up") ||
normalizedMessage.includes("fetch failed") ||
normalizedMessage.includes("temporarily unavailable")
) {
return ErrorClassification.RETRYABLE;
}
return ErrorClassification.UNKNOWN;
}
/**
* Calculate delay with exponential backoff and jitter.
* @param {number} attempt Current attempt number (0-indexed)
* @param {number} baseDelay Base delay in milliseconds
* @param {number} maxDelay Maximum delay in milliseconds
* @returns {number}
*/
function calculateDelay(attempt, baseDelay, maxDelay) {
const exponentialDelay = baseDelay * Math.pow(2, attempt);
const cappedDelay = Math.min(exponentialDelay, maxDelay);
const jitter = Math.random() * baseDelay;
return Math.floor(cappedDelay + jitter);
}
/**
* Sleep for a given number of milliseconds.
* @param {number} ms
* @returns {Promise<void>}
*/
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
const DEFAULT_OPTIONS = {
maxRetries: parseInt(process.env.MAX_RETRIES, 10) || 3,
baseDelayMs: parseInt(process.env.RETRY_BASE_DELAY_MS, 10) || 1000,
maxDelayMs: parseInt(process.env.MAX_RETRY_DELAY_MS, 10) || 30000,
retryUnknown: false,
onRetry: null,
onMaxRetries: null,
onDuplicate: null,
};
/**
* Generic async retry wrapper with classification-driven behavior.
*
* @param {Function} fn
* @param {Object} options
* @returns {Promise<Object>}
*/
async function withRetry(fn, options = {}) {
const opts = { ...DEFAULT_OPTIONS, ...options };
let lastError;
let attempt = 0;
while (attempt <= opts.maxRetries) {
try {
const result = await fn();
return {
success: true,
result,
attempts: attempt + 1,
retries: attempt,
};
} catch (error) {
lastError = error;
const classification = classifyError(error);
const context = {
code: extractErrorCode(error),
classification,
message: error?.message || String(error),
};
if (classification === ErrorClassification.DUPLICATE) {
if (opts.onDuplicate) {
opts.onDuplicate(context);
}
return {
success: true,
result: null,
attempts: attempt + 1,
retries: attempt,
duplicate: true,
classification,
};
}
if (classification === ErrorClassification.NON_RETRYABLE) {
throw {
success: false,
error,
attempts: attempt + 1,
retries: attempt,
classification,
context,
maxRetriesExceeded: false,
};
}
if (
classification === ErrorClassification.UNKNOWN &&
!opts.retryUnknown
) {
throw {
success: false,
error,
attempts: attempt + 1,
retries: attempt,
classification,
context,
maxRetriesExceeded: false,
};
}
if (attempt >= opts.maxRetries) {
if (opts.onMaxRetries) {
opts.onMaxRetries(error, attempt + 1, context);
}
throw {
success: false,
error,
attempts: attempt + 1,
retries: attempt,
classification,
context,
maxRetriesExceeded: true,
};
}
const delay = calculateDelay(attempt, opts.baseDelayMs, opts.maxDelayMs);
if (opts.onRetry) {
opts.onRetry(error, attempt + 1, delay, context);
}
await sleep(delay);
attempt++;
}
}
throw {
success: false,
error: lastError,
attempts: attempt + 1,
retries: attempt,
classification: classifyError(lastError),
maxRetriesExceeded: true,
context: {
code: extractErrorCode(lastError),
classification: classifyError(lastError),
message: lastError?.message || String(lastError),
},
};
}
/**
* Legacy retry function for backward compatibility.
* @param {Function} fn
* @param {number} attempts
* @param {number} delay
* @returns {Promise<*>}
*/
async function retry(fn, attempts = 3, delay = 1000) {
return withRetry(fn, {
maxRetries: attempts - 1,
baseDelayMs: delay,
maxDelayMs: delay,
}).then((result) => result.result);
}
/**
* @param {Error|object} error
* @returns {boolean}
*/
function isRetryableError(error) {
return classifyError(error) === ErrorClassification.RETRYABLE;
}
/**
* @param {Error|object} error
* @returns {boolean}
*/
function isDuplicateTransactionError(error) {
return classifyError(error) === ErrorClassification.DUPLICATE;
}
module.exports = {
withRetry,
retry,
isRetryableError,
isDuplicateTransactionError,
classifyError,
extractErrorCode,
ErrorClassification,
};