-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathretries.ts
187 lines (157 loc) · 4.28 KB
/
retries.ts
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
/*
* Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT.
*/
import { isConnectionError, isTimeoutError } from "./http.js";
export type BackoffStrategy = {
initialInterval: number;
maxInterval: number;
exponent: number;
maxElapsedTime: number;
};
const defaultBackoff: BackoffStrategy = {
initialInterval: 500,
maxInterval: 60000,
exponent: 1.5,
maxElapsedTime: 3600000,
};
export type RetryConfig =
| { strategy: "none" }
| {
strategy: "backoff";
backoff?: BackoffStrategy;
retryConnectionErrors?: boolean;
};
class PermanentError extends Error {
inner: unknown;
constructor(inner: unknown) {
super("Permanent error");
this.inner = inner;
Object.setPrototypeOf(this, PermanentError.prototype);
}
}
class TemporaryError extends Error {
res: Response;
constructor(res: Response) {
super("Temporary error");
this.res = res;
Object.setPrototypeOf(this, TemporaryError.prototype);
}
}
export async function retry(
fetchFn: () => Promise<Response>,
options: {
config: RetryConfig;
statusCodes: string[];
},
): Promise<Response> {
switch (options.config.strategy) {
case "backoff":
return retryBackoff(
wrapFetcher(fetchFn, {
statusCodes: options.statusCodes,
retryConnectionErrors: !!options.config.retryConnectionErrors,
}),
options.config.backoff ?? defaultBackoff,
);
default:
return await fetchFn();
}
}
function wrapFetcher(
fn: () => Promise<Response>,
options: {
statusCodes: string[];
retryConnectionErrors: boolean;
},
): () => Promise<Response> {
return async () => {
try {
const res = await fn();
if (isRetryableResponse(res, options.statusCodes)) {
throw new TemporaryError(res);
}
return res;
} catch (err) {
if (err instanceof TemporaryError) {
throw err;
}
if (
options.retryConnectionErrors &&
(isTimeoutError(err) || isConnectionError(err))
) {
throw err;
}
throw new PermanentError(err);
}
};
}
const codeRangeRE = new RegExp("^[0-9]xx$", "i");
function isRetryableResponse(res: Response, statusCodes: string[]): boolean {
const actual = `${res.status}`;
return statusCodes.some((code) => {
if (!codeRangeRE.test(code)) {
return code === actual;
}
const expectFamily = code.charAt(0);
if (!expectFamily) {
throw new Error("Invalid status code range");
}
const actualFamily = actual.charAt(0);
if (!actualFamily) {
throw new Error(`Invalid response status code: ${actual}`);
}
return actualFamily === expectFamily;
});
}
async function retryBackoff(
fn: () => Promise<Response>,
strategy: BackoffStrategy,
): Promise<Response> {
const { maxElapsedTime, initialInterval, exponent, maxInterval } = strategy;
const start = Date.now();
let x = 0;
// eslint-disable-next-line no-constant-condition
while (true) {
try {
const res = await fn();
return res;
} catch (err) {
if (err instanceof PermanentError) {
throw err.inner;
}
const elapsed = Date.now() - start;
if (elapsed > maxElapsedTime) {
if (err instanceof TemporaryError) {
return err.res;
}
throw err;
}
let retryInterval = 0;
if (err instanceof TemporaryError && err.res && err.res.headers) {
const retryVal = err.res.headers.get("retry-after") || "";
if (retryVal != "") {
const parsedNumber = Number(retryVal);
if (!isNaN(parsedNumber) && Number.isInteger(parsedNumber)) {
retryInterval = parsedNumber * 1000;
} else {
const parsedDate = Date.parse(retryVal);
if (!isNaN(parsedDate)) {
const deltaMS = parsedDate - Date.now();
retryInterval = deltaMS > 0 ? Math.ceil(deltaMS) : 0;
}
}
}
}
if (retryInterval == 0) {
retryInterval =
initialInterval * Math.pow(x, exponent) + Math.random() * 1000;
}
const d = Math.min(retryInterval, maxInterval);
await delay(d);
x++;
}
}
}
async function delay(delay: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, delay));
}