forked from Vesting-Vault/backend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrpc-retry.ts
More file actions
42 lines (40 loc) · 1.18 KB
/
rpc-retry.ts
File metadata and controls
42 lines (40 loc) · 1.18 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
import pRetry, { AbortError, FailedAttemptError } from 'p-retry';
/**
* Wraps an RPC call with an exponential backoff retry mechanism.
*
* Acceptance Criteria:
* 1. Exponential backoff (factor: 2).
* 2. Log warning after 3 failed attempts.
* 3. Crash (throw) only after 10 failed attempts.
*/
export async function executeRpcWithRetry<T>(
rpcFunction: () => Promise<T>,
context: string = 'RPC Call'
): Promise<T> {
const run = async () => {
try {
return await rpcFunction();
} catch (error: any) {
// Stellar SDK / Axios errors usually have a response object.
// We should NOT retry on 4xx errors (Client Error), except for 429 (Rate Limit).
const status = error.response?.status;
if (status && status >= 400 && status < 500 && status !== 429) {
throw new AbortError(error);
}
throw error;
}
};
return pRetry(run, {
retries: 10,
factor: 2,
minTimeout: 1000,
maxTimeout: 60000,
onFailedAttempt: (error: FailedAttemptError) => {
if (error.attemptNumber === 3) {
console.warn(
`[WARNING] ${context}: Failed 3 times. Retrying... Error: ${error.message}`
);
}
},
});
}