This repository has been archived by the owner on Feb 17, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
transport.js
522 lines (447 loc) · 13.3 KB
/
transport.js
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
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/**
* Class that manages making request, called by all of the API methods.
* @type {[type]}
*/
module.exports = Transport;
var _ = require('lodash');
var utils = require('./utils');
var errors = require('./errors');
var Host = require('./host');
var patchSniffOnConnectionFault = require('./transport/sniff_on_connection_fault');
var findCommonProtocol = require('./transport/find_common_protocol');
function Transport(config) {
var self = this;
config = self._config = config || {};
var LogClass =
typeof config.log === 'function' ? config.log : require('./log');
config.log = self.log = new LogClass(config);
// setup the connection pool
var ConnectionPool = utils.funcEnum(
config,
'connectionPool',
Transport.connectionPools,
'main'
);
self.connectionPool = new ConnectionPool(config);
// setup the serializer
var Serializer = utils.funcEnum(
config,
'serializer',
Transport.serializers,
'json'
);
self.serializer = new Serializer(config);
// setup the nodesToHostCallback
self.nodesToHostCallback = utils.funcEnum(
config,
'nodesToHostCallback',
Transport.nodesToHostCallbacks,
'main'
);
// setup max retries
self.maxRetries = config.hasOwnProperty('maxRetries') ? config.maxRetries : 3;
// setup endpoint to use for sniffing
self.sniffEndpoint = config.hasOwnProperty('sniffEndpoint')
? config.sniffEndpoint
: '/_nodes/_all/http';
// setup requestTimeout default
self.requestTimeout = config.hasOwnProperty('requestTimeout')
? config.requestTimeout
: 30000;
self.pingTimeout = config.hasOwnProperty('pingTimeout')
? config.pingTimeout
: 3000;
if (config.hasOwnProperty('defer')) {
self.defer = config.defer;
}
// randomizeHosts option
var randomizeHosts = config.hasOwnProperty('randomizeHosts')
? !!config.randomizeHosts
: true;
if (config.host) {
config.hosts = config.host;
}
if (config.hosts) {
var hostsConfig = utils.createArray(config.hosts, function(val) {
if (_.isPlainObject(val) || _.isString(val) || val instanceof Host) {
return val;
}
});
if (!hostsConfig) {
throw new TypeError(
'Invalid hosts config. Expected a URL, an array of urls, a host config object, ' +
'or an array of host config objects.'
);
}
if (randomizeHosts) {
hostsConfig = _.shuffle(hostsConfig);
}
self.setHosts(hostsConfig);
}
if (config.hasOwnProperty('sniffedNodesProtocol')) {
self.sniffedNodesProtocol = config.sniffedNodesProtocol || null;
} else {
self.sniffedNodesProtocol =
findCommonProtocol(self.connectionPool.getAllHosts()) || null;
}
if (config.hasOwnProperty('sniffedNodesFilterPath')) {
self.sniffedNodesFilterPath = config.sniffedNodesFilterPath;
} else {
self.sniffedNodesFilterPath = [
'nodes.*.http.publish_address',
'nodes.*.name',
'nodes.*.hostname',
'nodes.*.host',
'nodes.*.version',
].join(',');
}
if (config.sniffOnStart) {
self.sniff();
}
if (config.sniffInterval) {
self._timeout(function doSniff() {
self.sniff();
self._timeout(doSniff, config.sniffInterval);
}, config.sniffInterval);
}
if (config.sniffOnConnectionFault) {
patchSniffOnConnectionFault(self);
}
}
Transport.connectionPools = {
main: require('./connection_pool'),
};
Transport.serializers = require('./serializers');
Transport.nodesToHostCallbacks = {
main: require('./nodes_to_host'),
};
Transport.prototype.defer = function() {
if (typeof Promise === 'undefined') {
throw new Error(
'No Promise implementation found. In order for elasticsearch-js to create promises ' +
'either specify the `defer` configuration or include a global Promise shim'
);
}
var defer = {};
defer.promise = new Promise(function(resolve, reject) {
defer.resolve = resolve;
defer.reject = reject;
});
return defer;
};
/**
* Perform a request with the client's transport
*
* @method request
* @todo async body writing
* @todo abort
* @todo access to custom headers, modifying of request in general
* @param {object} params
* @param {Number} params.requestTimeout - timeout for the entire request (inculding all retries)
* @param {Number} params.maxRetries - number of times to re-run request if the
* original node chosen can not be connected to.
* @param {string} [params.path="/"] - URL pathname. Do not include query string.
* @param {string|object} [params.query] - Query string.
* @param {String} params.method - The HTTP method for the request
* @param {String} params.body - The body of the HTTP request
* @param {Function} cb - A function to call back with (error, responseBody, responseStatus)
*/
Transport.prototype.request = function(params, cb) {
var self = this;
var remainingRetries = this.maxRetries;
var requestTimeout = this.requestTimeout;
var connection; // set in sendReqWithConnection
var aborted = false; // several connector will respond with an error when the request is aborted
var requestAborter; // an abort function, returned by connection#request()
var requestTimeoutId; // the id of the ^timeout
var ret; // the object returned to the user, might be a promise
var defer; // the defer object, will be set when we are using promises.
var body = params.body;
var headers = !params.headers
? {}
: _.transform(params.headers, function(headers, val, name) {
headers[String(name).toLowerCase()] = val;
});
self.log.debug('starting request', params);
// determine the response based on the presense of a callback
if (typeof cb === 'function') {
// handle callbacks within a domain
if (process.domain) {
cb = process.domain.bind(cb);
}
ret = {
abort: abortRequest,
};
} else {
defer = this.defer();
ret = defer.promise;
ret.abort = abortRequest;
}
if (body && params.method === 'GET') {
utils.nextTick(
respond,
new TypeError('Body can not be sent with method "GET"')
);
return ret;
}
// serialize the body
if (body) {
var serializer = self.serializer;
var serializeFn = serializer[params.bulkBody ? 'bulkBody' : 'serialize'];
body = serializeFn.call(serializer, body);
if (!headers['content-type']) {
headers['content-type'] = serializeFn.contentType;
}
}
if (params.hasOwnProperty('maxRetries')) {
remainingRetries = params.maxRetries;
}
if (params.hasOwnProperty('requestTimeout')) {
requestTimeout = params.requestTimeout;
}
const pingRequest = params.path === '/' && params.method === 'HEAD';
if (pingRequest) {
const requestParam =
params.hasOwnProperty('requestTimeout') && params.requestTimeout;
requestTimeout = requestParam || this.pingTimeout;
}
params.req = {
method: params.method,
path: params.path || '/',
query: params.query,
body: body,
headers: headers,
};
function sendReqWithConnection(err, _connection) {
if (aborted) {
return;
}
if (err) {
respond(err);
} else if (_connection) {
connection = _connection;
requestAborter = connection.request(params.req, checkRespForFailure);
} else {
self.log.warning('No living connections');
respond(new errors.NoConnections());
}
}
function checkRespForFailure(err, body, status, headers) {
if (aborted) {
return;
}
requestAborter = void 0;
if (err instanceof errors.RequestTypeError) {
self.log.error('Connection refused to execute the request', err);
respond(err, body, status, headers);
return;
}
if (err) {
connection.setStatus('dead');
var errMsg = err.message || '';
errMsg =
'\n' +
params.req.method +
' ' +
connection.host.makeUrl(params.req) +
(errMsg.length ? ' => ' : '') +
errMsg;
if (remainingRetries) {
remainingRetries--;
self.log.error('Request error, retrying' + errMsg);
self.connectionPool.select(sendReqWithConnection);
} else {
self.log.error('Request complete with error' + errMsg);
respond(new errors.ConnectionFault(err));
}
} else {
self.log.debug('Request complete');
respond(void 0, body, status, headers);
}
}
function respond(err, body, status, headers) {
if (aborted) {
return;
}
self._timeout(requestTimeoutId);
var parsedBody;
var isJson =
!headers ||
(headers['content-type'] &&
~headers['content-type'].indexOf('application/json'));
if (!err && body) {
if (isJson) {
parsedBody = self.serializer.deserialize(body);
if (parsedBody == null) {
err = new errors.Serialization();
parsedBody = body;
}
} else {
parsedBody = body;
}
}
// does the response represent an error?
if (
(!err || err instanceof errors.Serialization) &&
(status < 200 || status >= 300) &&
(!params.ignore || !_.includes(params.ignore, status))
) {
var errorMetadata = _.pick(params.req, ['path', 'query', 'body']);
errorMetadata.statusCode = status;
errorMetadata.response = body;
if (status === 401 && headers && headers['www-authenticate']) {
errorMetadata.wwwAuthenticateDirective = headers['www-authenticate'];
}
if (errors[status]) {
err = new errors[status](parsedBody && parsedBody.error, errorMetadata);
} else {
err = new errors.Generic('unknown error', errorMetadata);
}
}
// can we cast notfound to false?
if (params.castExists) {
if (err && err instanceof errors.NotFound) {
parsedBody = false;
err = void 0;
} else {
parsedBody = !err;
}
}
// how do we send the response?
if (typeof cb === 'function') {
if (err) {
cb(err, parsedBody, status);
} else {
cb(void 0, parsedBody, status);
}
} else if (err) {
err.body = parsedBody;
err.status = status;
defer.reject(err);
} else {
defer.resolve(parsedBody);
}
}
function abortRequest() {
if (aborted) {
return;
}
aborted = true;
remainingRetries = 0;
self._timeout(requestTimeoutId);
if (typeof requestAborter === 'function') {
requestAborter();
}
}
if (requestTimeout && requestTimeout !== Infinity) {
requestTimeoutId = this._timeout(function() {
respond(
new errors.RequestTimeout(
'Request Timeout after ' + requestTimeout + 'ms'
)
);
abortRequest();
}, requestTimeout);
}
if (connection) {
sendReqWithConnection(void 0, connection);
} else {
self.connectionPool.select(sendReqWithConnection);
}
return ret;
};
Transport.prototype._timeout = function(cb, delay) {
if (this.closed) return;
var id;
var timers = this._timers || (this._timers = []);
if (typeof cb !== 'function') {
id = cb;
cb = void 0;
}
if (cb) {
// set the timer
id = setTimeout(function() {
_.pull(timers, id);
cb();
}, delay);
timers.push(id);
return id;
}
if (id) {
clearTimeout(id);
var i = this._timers.indexOf(id);
if (i !== -1) {
this._timers.splice(i, 1);
}
}
};
/**
* Ask an ES node for a list of all the nodes, add/remove nodes from the connection
* pool as appropriate
*
* @param {Function} cb - Function to call back once complete
*/
Transport.prototype.sniff = function(cb) {
var self = this;
var nodesToHostCallback = this.nodesToHostCallback;
var log = this.log;
var sniffedNodesProtocol = this.sniffedNodesProtocol;
var sniffedNodesFilterPath = this.sniffedNodesFilterPath;
// make cb a function if it isn't
cb = typeof cb === 'function' ? cb : _.noop;
this.request(
{
path: this.sniffEndpoint,
query: { filter_path: sniffedNodesFilterPath },
method: 'GET',
},
function(err, resp, status) {
if (!err && resp && resp.nodes) {
var hostsConfigs;
try {
hostsConfigs = nodesToHostCallback(resp.nodes);
} catch (e) {
log.error(
new Error(
'Unable to convert node list from ' +
self.sniffEndpoint +
' to hosts durring sniff. Encountered error:\n' +
(e.stack || e.message)
)
);
return;
}
_.forEach(hostsConfigs, function(hostConfig) {
if (sniffedNodesProtocol) hostConfig.protocol = sniffedNodesProtocol;
});
self.setHosts(hostsConfigs);
}
cb(err, resp, status);
}
);
};
/**
* Set the host list that the transport should use.
*
* @param {Array<HostConfig>} hostsConfigs - an array of Hosts, or configuration objects
* that will be used to create Host objects.
*/
Transport.prototype.setHosts = function(hostsConfigs) {
var globalConfig = this._config;
this.connectionPool.setHosts(
_.map(hostsConfigs, function(conf) {
return conf instanceof Host ? conf : new Host(conf, globalConfig);
})
);
};
/**
* Close the Transport, which closes the logs and connection pool
* @return {[type]} [description]
*/
Transport.prototype.close = function() {
this.log.close();
this.closed = true;
_.each(this._timers, clearTimeout);
this._timers = null;
this.connectionPool.close();
};