-
Notifications
You must be signed in to change notification settings - Fork 77
/
http.ts
363 lines (296 loc) · 11.1 KB
/
http.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
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
/*
* Copyright (c) 2018 by Filestack
* Some rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import * as url from 'url';
import * as zlib from 'zlib';
import Debug from 'debug';
import { AdapterInterface } from './interface';
import { getVersion } from '../../utils';
import * as Stream from 'stream';
import { FsRequestOptions, FsResponse } from '../types';
import * as utils from '../utils';
import { prepareData, parseResponse, combineURL, set as setHeader, normalizeHeaders } from './../helpers';
import { FsRequestErrorCode, FsRequestError } from '../error';
import { FsHttpMethod } from './../types';
const HTTPS_REGEXP = /https:?/;
const HTTP_CHUNK_SIZE = 16 * 1024;
const MAX_REDIRECTS = 10;
const CANCEL_CLEAR = `FsCleanMemory`;
const debug = Debug('fs:request:http');
/**
* Writable stream thats overwrap http request for progress event
*
* @class HttpWritableStream
* @extends {Stream.Writable}
*/
class HttpWritableStream extends Stream.Writable {
private request;
constructor(req, opts = {}) {
super(opts);
this.request = req;
req.once('drain', () => this.emit('drain'));
}
_write(chunk: any, encoding?: string, cb?: (error: Error | null | undefined) => void): void {
this.request.write(chunk, encoding, cb);
}
end(chunk) {
if (chunk) {
this.request.write(chunk);
}
this.request.end();
}
}
/**
* Node http request class
*
* @export
* @class HttpAdapter
* @implements {AdapterInterface}
*/
export class HttpAdapter implements AdapterInterface {
private redirectHoops = 0;
private redirectPaths = [];
/**
* do request based on configuration
*
* @param {FsRequestOptions} config
* @returns
* @memberof HttpAdapter
*/
request(config: FsRequestOptions) {
// if this option is unspecified set it by default
if (typeof config.filestackHeaders === 'undefined') {
config.filestackHeaders = true;
}
config.headers = normalizeHeaders(config.headers);
let { data, headers } = prepareData(config);
headers = setHeader(headers, 'user-agent', `filestack-request/${getVersion()}`);
// for now we are not using streams
if (data) {
debug('Request data %O', data);
if (!Buffer.isBuffer(data)) {
if (!utils.isString(data)) {
return Promise.reject(new FsRequestError('Data must be a string, JSON or a Buffer', config));
}
data = Buffer.from(data, 'utf-8');
}
headers = setHeader(headers, 'content-length', data.length, true);
}
// HTTP basic authentication
let auth;
if (config.auth) {
if (!config.auth.username || config.auth.username.length === 0) {
return Promise.reject(new FsRequestError(`Basic auth: username is required ${config.auth}`, config));
}
auth = `${config.auth.username}:${config.auth.password}`;
}
// Parse url
let parsed = url.parse(config.url);
// try to add default https protocol
if (!parsed.protocol) {
parsed = url.parse(`https://${config.url}`);
}
/* istanbul ignore next: just be sure that the host is parsed correctly, not needed to test */
if (!parsed.host) {
return Promise.reject(new FsRequestError(`Cannot parse provided url ${config.url}`, config));
}
// normalize auth header
if (auth && headers.Authorization) {
delete headers.Authorization;
}
const isHttpsRequest = HTTPS_REGEXP.test(parsed.protocol);
const agent = isHttpsRequest ? require('https') : require('http');
const options = {
path: combineURL(parsed.path, config.params),
host: parsed.host,
port: parsed.port,
protocol: parsed.protocol,
method: config.method.toUpperCase(),
headers: headers,
agent: new agent.Agent(),
auth: auth,
};
debug('Starting %s request with options %O', isHttpsRequest ? 'https' : 'http', options);
return new Promise<FsResponse>((resolve, reject): any => {
let req = agent.request(options, res => {
/* istanbul ignore next: just be sure that response will not be called after request is aborted */
if (!req || req.aborted) {
return reject(new FsRequestError('Request aborted', config));
}
let stream = res;
debug('Response statusCode: %d, Response Headers: %O', res.statusCode, res.headers);
const compressHeaders = res.headers['content-encoding'];
if (compressHeaders && compressHeaders.length && ['gzip', 'compress', 'deflate'].some((v) => compressHeaders.indexOf(v) > -1)) {
// add the unzipper to the body stream processing pipeline
stream = res.statusCode === 204 ? stream : stream.pipe(zlib.createUnzip());
// remove the content-encoding in order to not confuse downstream operations
delete res.headers['content-encoding'];
}
let response: FsResponse = {
status: res.statusCode,
statusText: res.statusMessage,
headers: res.headers,
config,
data: {},
};
// we need to follow redirect so make same request with new location
if ([301, 302].indexOf(res.statusCode) > -1) {
debug('Redirect received %s', res.statusCode);
if (this.redirectHoops >= MAX_REDIRECTS) {
return reject(new FsRequestError(`Max redirects (${this.redirectHoops}) reached. Exiting`, config, response, FsRequestErrorCode.REDIRECT));
}
const url = res.headers['location'];
if (!url || url.length === 0) {
return reject(new FsRequestError(`Redirect header location not found`, config, response, FsRequestErrorCode.REDIRECT));
}
if (this.redirectPaths.indexOf(url) > -1) {
return reject(new FsRequestError(`Redirect loop detected at url ${url}`, config, response, FsRequestErrorCode.REDIRECT));
}
this.redirectPaths.push(url);
this.redirectHoops++;
// free resources
res = undefined;
req = undefined;
debug('Redirecting request to %s (hoop-count: %d)', url, this.redirectHoops);
// clear cancel token to avoid memory leak
if (config.cancelToken) {
config.cancelToken.cancel(CANCEL_CLEAR);
}
return resolve(this.request(Object.assign({}, config, { url })));
}
let responseBuffer = [];
stream.on('data', chunk => responseBuffer.push(chunk));
/* istanbul ignore next: its hard to test socket events with jest and nock - tested manually */
stream.on('error', err => {
res = undefined;
req = undefined;
responseBuffer = undefined;
debug('Request error: Aborted %O', err);
if (req.aborted) {
return;
}
return reject(new FsRequestError(err.message, config, null, FsRequestErrorCode.NETWORK));
});
stream.on('end', async () => {
// check if there is any response data inside
if (res.statusCode !== 204) {
// prepare response
response.data = Buffer.concat(responseBuffer);
response = await parseResponse(response);
} else {
response.data = null;
}
// free resources
res = undefined;
req = undefined;
responseBuffer = undefined;
if (500 <= response.status && response.status <= 599) {
// server error throw
debug('Server error(5xx) - %O', response);
return reject(new FsRequestError(`Server error ${url}`, config, response, FsRequestErrorCode.SERVER));
} else if (400 <= response.status && response.status <= 499) {
debug('Request error(4xx) - %O', response);
return reject(new FsRequestError(`Request error ${url}`, config, response, FsRequestErrorCode.REQUEST));
}
debug('Request ends: %O', response);
return resolve(response);
});
});
if (config.cancelToken) {
config.cancelToken
.getSource()
.then(reason => {
// do nothing if promise is resolved by system
if (reason && reason.message === CANCEL_CLEAR) {
return;
}
/* istanbul ignore next: if request is done cancel token should not throw any error */
if (req) {
req.abort();
req = null;
}
debug('Request canceled by user %s, config: %O', reason, config);
return reject(new FsRequestError(`Request aborted. Reason: ${reason}`, config, null, FsRequestErrorCode.ABORTED));
})
/* istanbul ignore next: only for safety */
.catch(() => {/* empty */});
}
if (config.timeout) {
req.setTimeout(config.timeout, () => {
req.abort();
return reject(new FsRequestError('Request timeout', config, null, FsRequestErrorCode.TIMEOUT));
});
}
req.on('error', err => {
if (!req || req.aborted) {
return;
}
debug('Request error: %s - %O', err, err.code);
return reject(new FsRequestError(`Request error: ${err.code}`, config, null, FsRequestErrorCode.NETWORK));
});
if (Buffer.isBuffer(data) && ['POST', 'PUT'].indexOf(config.method) > -1) {
return this.bufferToChunks(data).pipe(this.getProgressMonitor(config, data.length)).pipe(new HttpWritableStream(req));
}
req.end(data);
});
}
/**
* Monitor and emit progress event if needed
*
* @private
* @memberof HttpAdapter
*/
private getProgressMonitor = (config, total) => {
let loaded = 0;
const progress = new Stream.Transform();
progress._transform = (chunk, encoding, cb) => {
if (typeof config.onProgress === 'function' && [FsHttpMethod.POST, FsHttpMethod.PUT].indexOf(config.method) > -1) {
loaded += chunk.length;
config.onProgress({
lengthComputable: true,
loaded,
total,
});
}
cb(null, chunk);
};
return progress;
}
/**
* Convert buffer to stream
*
* @private
* @param {*} buffer
* @returns {Stream.Readable}
* @memberof HttpAdapter
*/
private bufferToChunks(buffer): Stream.Readable {
const chunking = new Stream.Readable();
const totalLength = buffer.length;
const remainder = totalLength % HTTP_CHUNK_SIZE;
const cutoff = totalLength - remainder;
for (let i = 0; i < cutoff; i += HTTP_CHUNK_SIZE) {
const chunk = buffer.slice(i, i + HTTP_CHUNK_SIZE);
chunking.push(chunk);
}
if (remainder > 0) {
const remainderBuffer = buffer.slice(-remainder);
chunking.push(remainderBuffer);
}
chunking.push(null);
return chunking;
}
}