-
Notifications
You must be signed in to change notification settings - Fork 35
Expand file tree
/
Copy pathclient.ts
More file actions
281 lines (250 loc) · 9.48 KB
/
client.ts
File metadata and controls
281 lines (250 loc) · 9.48 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
// Copyright 2022 DeepL SE (https://www.deepl.com)
// Use of this source code is governed by an MIT
// license that can be found in the LICENSE file.
import { ConnectionError } from './errors';
import { logDebug, logInfo, timeout } from './utils';
import axios, { AxiosError, AxiosRequestConfig } from 'axios';
import { URLSearchParams } from 'url';
import FormData from 'form-data';
import { IncomingMessage } from 'http';
import { ProxyConfig } from './types';
type HttpMethod = 'GET' | 'DELETE' | 'POST';
/**
* Options for sending HTTP requests.
* @private
*/
interface SendRequestOptions {
/**
* Fields to include in message body (or params). Values must be either strings, or arrays of
* strings (for repeated parameters).
*/
data?: URLSearchParams;
/** Extra HTTP headers to include in request, in addition to headers defined in constructor. */
headers?: Record<string, string>;
/** Buffer containing file data to include. */
fileBuffer?: Buffer;
/** Filename of file to include. */
filename?: string;
}
/**
* Internal class implementing exponential-backoff timer.
* @private
*/
class BackoffTimer {
private backoffInitial = 1.0;
private backoffMax = 120.0;
private backoffJitter = 0.23;
private backoffMultiplier = 1.6;
private numRetries: number;
private backoff: number;
private deadline: number;
constructor() {
this.numRetries = 0;
this.backoff = this.backoffInitial * 1000.0;
this.deadline = Date.now() + this.backoff;
}
getNumRetries(): number {
return this.numRetries;
}
getTimeout(): number {
return this.getTimeUntilDeadline();
}
getTimeUntilDeadline(): number {
return Math.max(this.deadline - Date.now(), 0.0);
}
async sleepUntilDeadline() {
await timeout(this.getTimeUntilDeadline());
// Apply multiplier to current backoff time
this.backoff = Math.min(this.backoff * this.backoffMultiplier, this.backoffMax * 1000.0);
// Get deadline by applying jitter as a proportion of backoff:
// if jitter is 0.1, then multiply backoff by random value in [0.9, 1.1]
this.deadline =
Date.now() + this.backoff * (1 + this.backoffJitter * (2 * Math.random() - 1));
this.numRetries++;
}
}
/**
* Internal class implementing HTTP requests.
* @private
*/
export class HttpClient {
private readonly serverUrl: string;
private readonly headers: Record<string, string>;
private readonly minTimeout: number;
private readonly maxRetries: number;
private readonly proxy?: ProxyConfig;
constructor(
serverUrl: string,
headers: Record<string, string>,
maxRetries: number,
minTimeout: number,
proxy?: ProxyConfig,
) {
this.serverUrl = serverUrl;
this.headers = headers;
this.maxRetries = maxRetries;
this.minTimeout = minTimeout;
this.proxy = proxy;
}
prepareRequest(
method: HttpMethod,
url: string,
timeoutMs: number,
responseAsStream: boolean,
isDeepL: boolean,
options: SendRequestOptions,
): AxiosRequestConfig {
const headers = Object.assign({}, this.headers, options.headers);
logDebug(`isDeepL: ${isDeepL}`);
const axiosRequestConfig: AxiosRequestConfig = {
url,
method,
baseURL: isDeepL ? this.serverUrl : undefined,
headers,
responseType: responseAsStream ? 'stream' : 'text',
timeout: timeoutMs,
validateStatus: null, // do not throw errors for any status codes
};
if (options.fileBuffer) {
const form = new FormData();
form.append('file', options.fileBuffer, { filename: options.filename });
if (options.data) {
for (const [key, value] of options.data.entries()) {
form.append(key, value);
}
}
axiosRequestConfig.data = form;
if (axiosRequestConfig.headers === undefined) {
axiosRequestConfig.headers = {};
}
Object.assign(axiosRequestConfig.headers, form.getHeaders());
} else if (options.data) {
if (method === 'GET') {
axiosRequestConfig.params = options.data;
} else {
axiosRequestConfig.data = options.data;
}
}
axiosRequestConfig.proxy = this.proxy;
return axiosRequestConfig;
}
/**
* Makes API request retrying if necessary, and returns (as Promise) response.
* @param method HTTP method, for example 'GET'
* @param url Path to endpoint, excluding base server URL if DeepL API request, including base server URL if a webpage.
* @param options Additional options controlling request.
* @param responseAsStream Set to true if the return type is IncomingMessage.
* @return Fulfills with status code, content type, and response (as text or stream).
*/
async sendRequestWithBackoff<TContent extends string | IncomingMessage>(
method: HttpMethod,
url: string,
options?: SendRequestOptions,
responseAsStream = false,
): Promise<{ statusCode: number; content: TContent; contentType?: string }> {
let isDeepLUrl: boolean;
try {
isDeepLUrl = !!new URL(url);
} catch {
isDeepLUrl = true;
}
options = options === undefined ? {} : options;
logInfo(`${isDeepLUrl ? 'Request to DeepL API' : 'Request to webpage'} ${method} ${url}`);
logDebug(`Request details: ${options.data}`);
const backoff = new BackoffTimer();
let response, error;
while (backoff.getNumRetries() <= this.maxRetries) {
const timeoutMs = Math.max(this.minTimeout, backoff.getTimeout());
const axiosRequestConfig = this.prepareRequest(
method,
url,
timeoutMs,
responseAsStream,
isDeepLUrl,
options,
);
if (!isDeepLUrl && axiosRequestConfig.headers) {
delete axiosRequestConfig.headers.Authorization;
}
try {
response = await HttpClient.sendAxiosRequest<TContent>(axiosRequestConfig);
error = undefined;
} catch (e) {
response = undefined;
error = e as ConnectionError;
}
if (
!HttpClient.shouldRetry(response?.statusCode, error) ||
backoff.getNumRetries() + 1 >= this.maxRetries
) {
break;
}
if (error !== undefined) {
logDebug(`Encountered a retryable-error: ${error.message}`);
}
logInfo(
`Starting retry ${backoff.getNumRetries() + 1} for request ${method}` +
` ${url} after sleeping for ${backoff.getTimeUntilDeadline()} seconds.`,
);
await backoff.sleepUntilDeadline();
}
if (response !== undefined) {
const { statusCode, content, contentType } = response;
logInfo(
`${
isDeepLUrl ? 'DeepL API response' : 'Webpage response'
} ${method} ${url} ${statusCode}${!isDeepLUrl ? ` ${contentType}` : ''}`,
);
if (!responseAsStream) {
logDebug('Response details:', { content: content });
}
return response;
} else {
throw error as Error;
}
}
/**
* Performs given HTTP request and returns status code and response content (text or stream).
* @param axiosRequestConfig
* @private
*/
private static async sendAxiosRequest<TContent extends string | IncomingMessage>(
axiosRequestConfig: AxiosRequestConfig,
): Promise<{ statusCode: number; content: TContent; contentType?: string }> {
try {
const response = await axios.request(axiosRequestConfig);
if (axiosRequestConfig.responseType === 'text') {
// Workaround for axios-bug: https://github.com/axios/axios/issues/907
if (typeof response.data === 'object') {
response.data = JSON.stringify(response.data);
}
}
return {
statusCode: response.status,
content: response.data,
contentType: response.headers['content-type'],
};
} catch (axios_error_raw) {
const axiosError = axios_error_raw as AxiosError;
const message: string = axiosError.message || '';
const error = new ConnectionError(`Connection failure: ${message}`);
error.error = axiosError;
if (axiosError.code === 'ETIMEDOUT') {
error.shouldRetry = true;
} else if (axiosError.code === 'ECONNABORTED') {
error.shouldRetry = true;
} else {
logDebug('Unrecognized axios error', axiosError);
error.shouldRetry = false;
}
throw error;
}
}
private static shouldRetry(statusCode?: number, error?: ConnectionError): boolean {
if (statusCode === undefined) {
return (error as ConnectionError).shouldRetry;
}
// Retry on Too-Many-Requests error and internal errors
return statusCode === 429 || statusCode >= 500;
}
}