Repository navigation
Expand file tree
/
Copy pathgithub-api-retry.cjs
More file actions
86 lines (77 loc) · 2.44 KB
/
Copy pathgithub-api-retry.cjs
File metadata and controls
86 lines (77 loc) · 2.44 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
'use strict';
/**
* Bounded retries for transient GitHub API 5xx / network errors in github-script steps.
* Kept as CommonJS so `actions/github-script` can `require()` it directly.
*/
const defaultMaxAttempts = 4;
const defaultBaseDelayMs = 1_000;
function isRetryableGithubApiStatus(status) {
return Number.isInteger(status) && status >= 500 && status < 600;
}
function githubApiErrorStatus(error) {
if (error == null || typeof error !== 'object') return undefined;
if (typeof error.status === 'number') return error.status;
const response = error.response;
if (response != null && typeof response === 'object' && typeof response.status === 'number') {
return response.status;
}
return undefined;
}
function isRetryableGithubNetworkError(error) {
if (error == null || typeof error !== 'object') return false;
const code = 'code' in error ? error.code : undefined;
if (
code === 'ECONNRESET' ||
code === 'ETIMEDOUT' ||
code === 'ECONNREFUSED' ||
code === 'ENOTFOUND' ||
code === 'EAI_AGAIN'
) {
return true;
}
const message =
error instanceof Error
? error.message
: typeof error.message === 'string'
? error.message
: '';
return /ECONNRESET|ETIMEDOUT|ECONNREFUSED|ENOTFOUND|EAI_AGAIN|socket hang up|fetch failed|upstream connect error/i.test(
message,
);
}
function isRetryableGithubApiError(error) {
const status = githubApiErrorStatus(error);
if (status !== undefined) return isRetryableGithubApiStatus(status);
return isRetryableGithubNetworkError(error);
}
async function withGithubApiRetry(run, options = {}) {
const maxAttempts = options.maxAttempts ?? defaultMaxAttempts;
const baseDelayMs = options.baseDelayMs ?? defaultBaseDelayMs;
const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
const isRetryable = options.isRetryable ?? isRetryableGithubApiError;
const onRetry = options.onRetry;
let lastError;
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
try {
return await run();
} catch (error) {
lastError = error;
if (attempt === maxAttempts || !isRetryable(error)) {
throw error;
}
const delayMs = baseDelayMs * 2 ** (attempt - 1);
onRetry?.({ attempt, maxAttempts, delayMs, error });
await sleep(delayMs);
}
}
throw lastError;
}
module.exports = {
defaultMaxAttempts,
defaultBaseDelayMs,
isRetryableGithubApiStatus,
githubApiErrorStatus,
isRetryableGithubNetworkError,
isRetryableGithubApiError,
withGithubApiRetry,
};