@opensearch-project/opensearch 1.1.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/.eslintignore +2 -0
  2. package/.eslintrc.json +26 -0
  3. package/.prettierrc.json +5 -0
  4. package/.whitesource +15 -0
  5. package/ADMINS.md +18 -11
  6. package/COMPATIBILITY.md +24 -0
  7. package/DEVELOPER_GUIDE.md +22 -5
  8. package/MAINTAINERS.md +23 -18
  9. package/README.md +100 -101
  10. package/RELEASING.md +3 -3
  11. package/SECURITY.md +1 -1
  12. package/api/api/bulk.js +53 -26
  13. package/api/api/cat.js +354 -264
  14. package/api/api/clear_scroll.js +17 -17
  15. package/api/api/cluster.js +366 -219
  16. package/api/api/count.js +55 -24
  17. package/api/api/create.js +50 -24
  18. package/api/api/dangling_indices.js +95 -51
  19. package/api/api/delete.js +49 -22
  20. package/api/api/delete_by_query.js +88 -25
  21. package/api/api/delete_by_query_rethrottle.js +33 -19
  22. package/api/api/delete_script.js +31 -17
  23. package/api/api/exists.js +55 -22
  24. package/api/api/exists_source.js +60 -27
  25. package/api/api/explain.js +60 -22
  26. package/api/api/features.js +56 -35
  27. package/api/api/field_caps.js +36 -18
  28. package/api/api/get.js +55 -22
  29. package/api/api/get_script.js +30 -17
  30. package/api/api/get_script_context.js +15 -15
  31. package/api/api/get_script_languages.js +15 -15
  32. package/api/api/get_source.js +55 -22
  33. package/api/api/index.js +60 -28
  34. package/api/api/indices.js +1068 -857
  35. package/api/api/info.js +15 -15
  36. package/api/api/ingest.js +132 -96
  37. package/api/api/mget.js +50 -26
  38. package/api/api/msearch.js +49 -26
  39. package/api/api/msearch_template.js +53 -26
  40. package/api/api/mtermvectors.js +48 -24
  41. package/api/api/nodes.js +281 -154
  42. package/api/api/ping.js +15 -15
  43. package/api/api/put_script.js +40 -25
  44. package/api/api/rank_eval.js +37 -20
  45. package/api/api/reindex.js +38 -17
  46. package/api/api/reindex_rethrottle.js +32 -19
  47. package/api/api/render_search_template.js +18 -18
  48. package/api/api/scripts_painless_execute.js +15 -15
  49. package/api/api/scroll.js +31 -17
  50. package/api/api/search.js +108 -24
  51. package/api/api/search_shards.js +36 -18
  52. package/api/api/search_template.js +64 -26
  53. package/api/api/shutdown.js +66 -54
  54. package/api/api/snapshot.js +347 -224
  55. package/api/api/tasks.js +65 -46
  56. package/api/api/terms_enum.js +17 -17
  57. package/api/api/termvectors.js +57 -26
  58. package/api/api/update.js +64 -24
  59. package/api/api/update_by_query.js +89 -23
  60. package/api/api/update_by_query_rethrottle.js +33 -19
  61. package/api/index.js +267 -179
  62. package/api/new.d.ts +2042 -529
  63. package/api/opensearch_dashboards.d.ts +239 -236
  64. package/api/requestParams.d.ts +301 -69
  65. package/api/types.d.ts +6204 -5719
  66. package/api/utils.js +22 -22
  67. package/codecov.yml +2 -2
  68. package/index.d.ts +4776 -935
  69. package/index.js +152 -140
  70. package/index.mjs +9 -9
  71. package/lib/Connection.d.ts +37 -26
  72. package/lib/Connection.js +163 -168
  73. package/lib/Helpers.d.ts +103 -64
  74. package/lib/Helpers.js +398 -371
  75. package/lib/Serializer.d.ts +2 -2
  76. package/lib/Serializer.js +39 -39
  77. package/lib/Transport.d.ts +30 -12
  78. package/lib/Transport.js +375 -336
  79. package/lib/errors.d.ts +25 -7
  80. package/lib/errors.js +75 -71
  81. package/lib/pool/BaseConnectionPool.js +100 -97
  82. package/lib/pool/CloudConnectionPool.js +16 -16
  83. package/lib/pool/ConnectionPool.js +105 -105
  84. package/lib/pool/index.d.ts +8 -6
  85. package/lib/pool/index.js +6 -6
  86. package/package.json +13 -8
package/lib/Transport.js CHANGED
@@ -28,105 +28,108 @@
28
28
  * under the License.
29
29
  */
30
30
 
31
- 'use strict'
32
-
33
- const debug = require('debug')('opensearch')
34
- const os = require('os')
35
- const { gzip, unzip, createGzip } = require('zlib')
36
- const buffer = require('buffer')
37
- const ms = require('ms')
38
- const { EventEmitter } = require('events')
31
+ 'use strict';
32
+
33
+ const debug = require('debug')('opensearch');
34
+ const os = require('os');
35
+ const { gzip, unzip, createGzip } = require('zlib');
36
+ const buffer = require('buffer');
37
+ const ms = require('ms');
38
+ const { EventEmitter } = require('events');
39
39
  const {
40
40
  ConnectionError,
41
41
  RequestAbortedError,
42
42
  NoLivingConnectionsError,
43
43
  ResponseError,
44
- ConfigurationError
45
- } = require('./errors')
46
-
47
- const noop = () => { }
48
-
49
- const compatibleCheckEmitter = new EventEmitter()
50
- const clientVersion = require('../package.json').version
51
- const userAgent = `opensearch-js/${clientVersion} (${os.platform()} ${os.release()}-${os.arch()}; Node.js ${process.version})`
52
- const MAX_BUFFER_LENGTH = buffer.constants.MAX_LENGTH
53
- const MAX_STRING_LENGTH = buffer.constants.MAX_STRING_LENGTH
54
- const HEAP_SIZE_LIMIT = require('v8').getHeapStatistics().heap_size_limit
55
- const kCompatibleCheck = Symbol('compatible check')
56
- const kApiVersioning = Symbol('api versioning')
44
+ ConfigurationError,
45
+ } = require('./errors');
46
+
47
+ const noop = () => {};
48
+
49
+ const compatibleCheckEmitter = new EventEmitter();
50
+ const clientVersion = require('../package.json').version;
51
+ const userAgent = `opensearch-js/${clientVersion} (${os.platform()} ${os.release()}-${os.arch()}; Node.js ${
52
+ process.version
53
+ })`;
54
+ const MAX_BUFFER_LENGTH = buffer.constants.MAX_LENGTH;
55
+ const MAX_STRING_LENGTH = buffer.constants.MAX_STRING_LENGTH;
56
+ const HEAP_SIZE_LIMIT = require('v8').getHeapStatistics().heap_size_limit;
57
+ const kCompatibleCheck = Symbol('compatible check');
58
+ const kApiVersioning = Symbol('api versioning');
57
59
 
58
60
  class Transport {
59
- constructor (opts) {
61
+ constructor(opts) {
60
62
  if (typeof opts.compression === 'string' && opts.compression !== 'gzip') {
61
- throw new ConfigurationError(`Invalid compression: '${opts.compression}'`)
63
+ throw new ConfigurationError(`Invalid compression: '${opts.compression}'`);
62
64
  }
63
65
 
64
- this.emit = opts.emit
65
- this.connectionPool = opts.connectionPool
66
- this.serializer = opts.serializer
67
- this.maxRetries = opts.maxRetries
68
- this.requestTimeout = toMs(opts.requestTimeout)
69
- this.suggestCompression = opts.suggestCompression === true
70
- this.compression = opts.compression || false
71
- this.context = opts.context || null
72
- this.headers = Object.assign({},
66
+ this.emit = opts.emit;
67
+ this.connectionPool = opts.connectionPool;
68
+ this.serializer = opts.serializer;
69
+ this.maxRetries = opts.maxRetries;
70
+ this.requestTimeout = toMs(opts.requestTimeout);
71
+ this.suggestCompression = opts.suggestCompression === true;
72
+ this.compression = opts.compression || false;
73
+ this.context = opts.context || null;
74
+ this.headers = Object.assign(
75
+ {},
73
76
  { 'user-agent': userAgent },
74
77
  opts.suggestCompression === true ? { 'accept-encoding': 'gzip,deflate' } : null,
75
78
  lowerCaseHeaders(opts.headers)
76
- )
77
- this.sniffInterval = opts.sniffInterval
78
- this.sniffOnConnectionFault = opts.sniffOnConnectionFault
79
- this.sniffEndpoint = opts.sniffEndpoint
80
- this.generateRequestId = opts.generateRequestId || generateRequestId()
81
- this.name = opts.name
82
- this.opaqueIdPrefix = opts.opaqueIdPrefix
83
- this[kCompatibleCheck] = 0 // 0 = to be checked, 1 = checking, 2 = checked-ok, 3 checked-notok
84
- this[kApiVersioning] = process.env.OPENSEARCH_CLIENT_APIVERSIONING === 'true'
85
- this.memoryCircuitBreaker = opts.memoryCircuitBreaker
86
-
87
- this.nodeFilter = opts.nodeFilter || defaultNodeFilter
79
+ );
80
+ this.sniffInterval = opts.sniffInterval;
81
+ this.sniffOnConnectionFault = opts.sniffOnConnectionFault;
82
+ this.sniffEndpoint = opts.sniffEndpoint;
83
+ this.generateRequestId = opts.generateRequestId || generateRequestId();
84
+ this.name = opts.name;
85
+ this.opaqueIdPrefix = opts.opaqueIdPrefix;
86
+ this[kCompatibleCheck] = 0; // 0 = to be checked, 1 = checking, 2 = checked-ok, 3 checked-notok
87
+ this[kApiVersioning] = process.env.OPENSEARCH_CLIENT_APIVERSIONING === 'true';
88
+ this.memoryCircuitBreaker = opts.memoryCircuitBreaker;
89
+
90
+ this.nodeFilter = opts.nodeFilter || defaultNodeFilter;
88
91
  if (typeof opts.nodeSelector === 'function') {
89
- this.nodeSelector = opts.nodeSelector
92
+ this.nodeSelector = opts.nodeSelector;
90
93
  } else if (opts.nodeSelector === 'round-robin') {
91
- this.nodeSelector = roundRobinSelector()
94
+ this.nodeSelector = roundRobinSelector();
92
95
  } else if (opts.nodeSelector === 'random') {
93
- this.nodeSelector = randomSelector
96
+ this.nodeSelector = randomSelector;
94
97
  } else {
95
- this.nodeSelector = roundRobinSelector()
98
+ this.nodeSelector = roundRobinSelector();
96
99
  }
97
100
 
98
- this._sniffEnabled = typeof this.sniffInterval === 'number'
99
- this._nextSniff = this._sniffEnabled ? (Date.now() + this.sniffInterval) : 0
100
- this._isSniffing = false
101
+ this._sniffEnabled = typeof this.sniffInterval === 'number';
102
+ this._nextSniff = this._sniffEnabled ? Date.now() + this.sniffInterval : 0;
103
+ this._isSniffing = false;
101
104
 
102
105
  if (opts.sniffOnStart === true) {
103
106
  // timer needed otherwise it will clash
104
107
  // with the compatible check testing
105
108
  setTimeout(() => {
106
- this.sniff({ reason: Transport.sniffReasons.SNIFF_ON_START })
107
- }, 10)
109
+ this.sniff({ reason: Transport.sniffReasons.SNIFF_ON_START });
110
+ }, 10);
108
111
  }
109
112
  }
110
113
 
111
- request (params, options, callback) {
112
- options = options || {}
114
+ request(params, options, callback) {
115
+ options = options || {};
113
116
  if (typeof options === 'function') {
114
- callback = options
115
- options = {}
117
+ callback = options;
118
+ options = {};
116
119
  }
117
- let p = null
120
+ let p = null;
118
121
 
119
122
  // promises support
120
123
  if (callback === undefined) {
121
- let onFulfilled = null
122
- let onRejected = null
124
+ let onFulfilled = null;
125
+ let onRejected = null;
123
126
  p = new Promise((resolve, reject) => {
124
- onFulfilled = resolve
125
- onRejected = reject
126
- })
127
- callback = function callback (err, result) {
128
- err ? onRejected(err) : onFulfilled(result)
129
- }
127
+ onFulfilled = resolve;
128
+ onRejected = reject;
129
+ });
130
+ callback = function callback(err, result) {
131
+ err ? onRejected(err) : onFulfilled(result);
132
+ };
130
133
  }
131
134
 
132
135
  const meta = {
@@ -134,453 +137,486 @@ class Transport {
134
137
  request: {
135
138
  params: null,
136
139
  options: null,
137
- id: options.id || this.generateRequestId(params, options)
140
+ id: options.id || this.generateRequestId(params, options),
138
141
  },
139
142
  name: this.name,
140
143
  connection: null,
141
144
  attempts: 0,
142
- aborted: false
143
- }
145
+ aborted: false,
146
+ };
144
147
 
145
148
  if (this.context != null && options.context != null) {
146
- meta.context = Object.assign({}, this.context, options.context)
149
+ meta.context = Object.assign({}, this.context, options.context);
147
150
  } else if (this.context != null) {
148
- meta.context = this.context
151
+ meta.context = this.context;
149
152
  } else if (options.context != null) {
150
- meta.context = options.context
153
+ meta.context = options.context;
151
154
  }
152
155
 
153
156
  const result = {
154
157
  body: null,
155
158
  statusCode: null,
156
159
  headers: null,
157
- meta
158
- }
160
+ meta,
161
+ };
159
162
 
160
163
  Object.defineProperty(result, 'warnings', {
161
- get () {
164
+ get() {
162
165
  return this.headers && this.headers.warning
163
166
  ? this.headers.warning.split(/(?!\B"[^"]*),(?![^"]*"\B)/)
164
- : null
165
- }
166
- })
167
+ : null;
168
+ },
169
+ });
167
170
 
168
171
  // We should not retry if we are sending a stream body, because we should store in memory
169
172
  // a copy of the stream to be able to send it again, but since we don't know in advance
170
173
  // the size of the stream, we risk to take too much memory.
171
174
  // Furthermore, copying everytime the stream is very a expensive operation.
172
- const maxRetries = isStream(params.body) || isStream(params.bulkBody)
173
- ? 0
174
- : (typeof options.maxRetries === 'number' ? options.maxRetries : this.maxRetries)
175
- const compression = options.compression !== undefined ? options.compression : this.compression
176
- let request = { abort: noop }
175
+ const maxRetries =
176
+ isStream(params.body) || isStream(params.bulkBody)
177
+ ? 0
178
+ : typeof options.maxRetries === 'number'
179
+ ? options.maxRetries
180
+ : this.maxRetries;
181
+ const compression = options.compression !== undefined ? options.compression : this.compression;
182
+ let request = { abort: noop };
177
183
  const transportReturn = {
178
- then (onFulfilled, onRejected) {
179
- return p.then(onFulfilled, onRejected)
184
+ then(onFulfilled, onRejected) {
185
+ return p.then(onFulfilled, onRejected);
180
186
  },
181
- catch (onRejected) {
182
- return p.catch(onRejected)
187
+ catch(onRejected) {
188
+ return p.catch(onRejected);
183
189
  },
184
- abort () {
185
- meta.aborted = true
186
- request.abort()
187
- debug('Aborting request', params)
188
- return this
190
+ abort() {
191
+ meta.aborted = true;
192
+ request.abort();
193
+ debug('Aborting request', params);
194
+ return this;
189
195
  },
190
- finally (onFinally) {
191
- return p.finally(onFinally)
192
- }
193
- }
196
+ finally(onFinally) {
197
+ return p.finally(onFinally);
198
+ },
199
+ };
194
200
 
195
201
  const makeRequest = () => {
196
202
  if (meta.aborted === true) {
197
- return process.nextTick(callback, new RequestAbortedError(), result)
203
+ return process.nextTick(callback, new RequestAbortedError(), result);
198
204
  }
199
- meta.connection = this.getConnection({ requestId: meta.request.id })
205
+ meta.connection = this.getConnection({ requestId: meta.request.id });
200
206
  if (meta.connection == null) {
201
- return process.nextTick(callback, new NoLivingConnectionsError(), result)
207
+ return process.nextTick(callback, new NoLivingConnectionsError(), result);
202
208
  }
203
- this.emit('request', null, result)
209
+ this.emit('request', null, result);
204
210
  // perform the actual http request
205
- request = meta.connection.request(params, onResponse)
206
- }
211
+ request = meta.connection.request(params, onResponse);
212
+ };
207
213
 
208
214
  const onConnectionError = (err) => {
209
215
  if (err.name !== 'RequestAbortedError') {
210
216
  // if there is an error in the connection
211
217
  // let's mark the connection as dead
212
- this.connectionPool.markDead(meta.connection)
218
+ this.connectionPool.markDead(meta.connection);
213
219
 
214
220
  if (this.sniffOnConnectionFault === true) {
215
221
  this.sniff({
216
222
  reason: Transport.sniffReasons.SNIFF_ON_CONNECTION_FAULT,
217
- requestId: meta.request.id
218
- })
223
+ requestId: meta.request.id,
224
+ });
219
225
  }
220
226
 
221
227
  // retry logic
222
228
  if (meta.attempts < maxRetries) {
223
- meta.attempts++
224
- debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params)
225
- makeRequest()
226
- return
229
+ meta.attempts++;
230
+ debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params);
231
+ makeRequest();
232
+ return;
227
233
  }
228
234
  }
229
235
 
230
- err.meta = result
231
- this.emit('response', err, result)
232
- return callback(err, result)
233
- }
236
+ err.meta = result;
237
+ this.emit('response', err, result);
238
+ return callback(err, result);
239
+ };
234
240
 
235
241
  const onResponse = (err, response) => {
236
242
  if (err !== null) {
237
- return onConnectionError(err)
243
+ return onConnectionError(err);
238
244
  }
239
245
 
240
- result.statusCode = response.statusCode
241
- result.headers = response.headers
246
+ result.statusCode = response.statusCode;
247
+ result.headers = response.headers;
242
248
 
243
249
  if (options.asStream === true) {
244
- result.body = response
245
- this.emit('response', null, result)
246
- callback(null, result)
247
- return
250
+ result.body = response;
251
+ this.emit('response', null, result);
252
+ callback(null, result);
253
+ return;
248
254
  }
249
255
 
250
- const contentEncoding = (result.headers['content-encoding'] || '').toLowerCase()
251
- const isCompressed = contentEncoding.indexOf('gzip') > -1 || contentEncoding.indexOf('deflate') > -1
256
+ const contentEncoding = (result.headers['content-encoding'] || '').toLowerCase();
257
+ const isCompressed =
258
+ contentEncoding.indexOf('gzip') > -1 || contentEncoding.indexOf('deflate') > -1;
252
259
  /* istanbul ignore else */
253
260
  if (result.headers['content-length'] !== undefined) {
254
- const contentLength = Number(result.headers['content-length'])
261
+ const contentLength = Number(result.headers['content-length']);
255
262
  // nodeJS data type limit check
256
263
  if (isCompressed && contentLength > MAX_BUFFER_LENGTH) {
257
- response.destroy()
264
+ response.destroy();
258
265
  return onConnectionError(
259
- new RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed buffer (${MAX_BUFFER_LENGTH})`, result)
260
- )
266
+ new RequestAbortedError(
267
+ `The content length (${contentLength}) is bigger than the maximum allowed buffer (${MAX_BUFFER_LENGTH})`,
268
+ result
269
+ )
270
+ );
261
271
  } else if (contentLength > MAX_STRING_LENGTH) {
262
- response.destroy()
272
+ response.destroy();
263
273
  return onConnectionError(
264
- new RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed string (${MAX_STRING_LENGTH})`, result)
265
- )
274
+ new RequestAbortedError(
275
+ `The content length (${contentLength}) is bigger than the maximum allowed string (${MAX_STRING_LENGTH})`,
276
+ result
277
+ )
278
+ );
266
279
  } else if (shouldApplyCircuitBreaker(contentLength)) {
267
280
  // Abort this response to avoid OOM crash of dashboards.
268
- response.destroy()
281
+ response.destroy();
269
282
  return onConnectionError(
270
- new RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed heap memory limit.`, result)
271
- )
283
+ new RequestAbortedError(
284
+ `The content length (${contentLength}) is bigger than the maximum allowed heap memory limit.`,
285
+ result
286
+ )
287
+ );
272
288
  }
273
289
  }
274
290
  // if the response is compressed, we must handle it
275
291
  // as buffer for allowing decompression later
276
- let payload = isCompressed ? [] : ''
292
+ let payload = isCompressed ? [] : '';
277
293
  const onData = isCompressed
278
- ? chunk => { payload.push(chunk) }
279
- : chunk => { payload += chunk }
280
- const onEnd = err => {
281
- response.removeListener('data', onData)
282
- response.removeListener('end', onEnd)
283
- response.removeListener('error', onEnd)
284
- response.removeListener('aborted', onAbort)
294
+ ? (chunk) => {
295
+ payload.push(chunk);
296
+ }
297
+ : (chunk) => {
298
+ payload += chunk;
299
+ };
300
+ const onEnd = (err) => {
301
+ response.removeListener('data', onData);
302
+ response.removeListener('end', onEnd);
303
+ response.removeListener('error', onEnd);
304
+ response.removeListener('aborted', onAbort);
285
305
 
286
306
  if (err) {
287
- return onConnectionError(new ConnectionError(err.message))
307
+ return onConnectionError(new ConnectionError(err.message));
288
308
  }
289
309
 
290
310
  if (isCompressed) {
291
- unzip(Buffer.concat(payload), onBody)
311
+ unzip(Buffer.concat(payload), onBody);
292
312
  } else {
293
- onBody(null, payload)
313
+ onBody(null, payload);
294
314
  }
295
- }
315
+ };
296
316
 
297
317
  const onAbort = () => {
298
- response.destroy()
299
- onEnd(new Error('Response aborted while reading the body'))
300
- }
318
+ response.destroy();
319
+ onEnd(new Error('Response aborted while reading the body'));
320
+ };
301
321
 
302
322
  if (!isCompressed) {
303
- response.setEncoding('utf8')
323
+ response.setEncoding('utf8');
304
324
  }
305
325
 
306
- this.emit('deserialization', null, result)
307
- response.on('data', onData)
308
- response.on('error', onEnd)
309
- response.on('end', onEnd)
310
- response.on('aborted', onAbort)
311
- }
326
+ this.emit('deserialization', null, result);
327
+ response.on('data', onData);
328
+ response.on('error', onEnd);
329
+ response.on('end', onEnd);
330
+ response.on('aborted', onAbort);
331
+ };
312
332
  // Helper function to check if memory circuit breaker enabled and the response payload is too large to fit into available heap memory.
313
333
  const shouldApplyCircuitBreaker = (contentLength) => {
314
- if (!this.memoryCircuitBreaker || !this.memoryCircuitBreaker.enabled) return false
315
- const maxPercentage = validateMemoryPercentage(this.memoryCircuitBreaker.maxPercentage)
316
- const heapUsed = process.memoryUsage().heapUsed
317
- return contentLength + heapUsed > HEAP_SIZE_LIMIT * maxPercentage
318
- }
334
+ if (!this.memoryCircuitBreaker || !this.memoryCircuitBreaker.enabled) return false;
335
+ const maxPercentage = validateMemoryPercentage(this.memoryCircuitBreaker.maxPercentage);
336
+ const heapUsed = process.memoryUsage().heapUsed;
337
+ return contentLength + heapUsed > HEAP_SIZE_LIMIT * maxPercentage;
338
+ };
319
339
 
320
340
  const onBody = (err, payload) => {
321
341
  if (err) {
322
- this.emit('response', err, result)
323
- return callback(err, result)
342
+ this.emit('response', err, result);
343
+ return callback(err, result);
324
344
  }
325
345
  if (Buffer.isBuffer(payload)) {
326
- payload = payload.toString()
346
+ payload = payload.toString();
327
347
  }
328
- const isHead = params.method === 'HEAD'
348
+ const isHead = params.method === 'HEAD';
329
349
  // we should attempt the payload deserialization only if:
330
350
  // - a `content-type` is defined and is equal to `application/json`
331
351
  // - the request is not a HEAD request
332
352
  // - the payload is not an empty string
333
- if (result.headers['content-type'] !== undefined &&
353
+ if (
354
+ result.headers['content-type'] !== undefined &&
334
355
  (result.headers['content-type'].indexOf('application/json') > -1 ||
335
356
  result.headers['content-type'].indexOf('application/vnd.opensearch+json') > -1) &&
336
357
  isHead === false &&
337
358
  payload !== ''
338
359
  ) {
339
360
  try {
340
- result.body = this.serializer.deserialize(payload)
361
+ result.body = this.serializer.deserialize(payload);
341
362
  } catch (err) {
342
- this.emit('response', err, result)
343
- return callback(err, result)
363
+ this.emit('response', err, result);
364
+ return callback(err, result);
344
365
  }
345
366
  } else {
346
367
  // cast to boolean if the request method was HEAD and there was no error
347
- result.body = isHead === true && result.statusCode < 400 ? true : payload
368
+ result.body = isHead === true && result.statusCode < 400 ? true : payload;
348
369
  }
349
370
 
350
371
  // we should ignore the statusCode if the user has configured the `ignore` field with
351
372
  // the statusCode we just got or if the request method is HEAD and the statusCode is 404
352
- const ignoreStatusCode = (Array.isArray(options.ignore) && options.ignore.indexOf(result.statusCode) > -1) ||
353
- (isHead === true && result.statusCode === 404)
373
+ const ignoreStatusCode =
374
+ (Array.isArray(options.ignore) && options.ignore.indexOf(result.statusCode) > -1) ||
375
+ (isHead === true && result.statusCode === 404);
354
376
 
355
- if (ignoreStatusCode === false &&
356
- (result.statusCode === 502 || result.statusCode === 503 || result.statusCode === 504)) {
377
+ if (
378
+ ignoreStatusCode === false &&
379
+ (result.statusCode === 502 || result.statusCode === 503 || result.statusCode === 504)
380
+ ) {
357
381
  // if the statusCode is 502/3/4 we should run our retry strategy
358
382
  // and mark the connection as dead
359
- this.connectionPool.markDead(meta.connection)
383
+ this.connectionPool.markDead(meta.connection);
360
384
  // retry logic (we shoukd not retry on "429 - Too Many Requests")
361
385
  if (meta.attempts < maxRetries && result.statusCode !== 429) {
362
- meta.attempts++
363
- debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params)
364
- makeRequest()
365
- return
386
+ meta.attempts++;
387
+ debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params);
388
+ makeRequest();
389
+ return;
366
390
  }
367
391
  } else {
368
392
  // everything has worked as expected, let's mark
369
393
  // the connection as alive (or confirm it)
370
- this.connectionPool.markAlive(meta.connection)
394
+ this.connectionPool.markAlive(meta.connection);
371
395
  }
372
396
 
373
397
  if (ignoreStatusCode === false && result.statusCode >= 400) {
374
- const error = new ResponseError(result)
375
- this.emit('response', error, result)
376
- callback(error, result)
398
+ const error = new ResponseError(result);
399
+ this.emit('response', error, result);
400
+ callback(error, result);
377
401
  } else {
378
402
  // cast to boolean if the request method was HEAD
379
403
  if (isHead === true && result.statusCode === 404) {
380
- result.body = false
404
+ result.body = false;
381
405
  }
382
- this.emit('response', null, result)
383
- callback(null, result)
406
+ this.emit('response', null, result);
407
+ callback(null, result);
384
408
  }
385
- }
409
+ };
386
410
 
387
411
  const prepareRequest = () => {
388
- this.emit('serialization', null, result)
389
- const headers = Object.assign({}, this.headers, lowerCaseHeaders(options.headers))
412
+ this.emit('serialization', null, result);
413
+ const headers = Object.assign({}, this.headers, lowerCaseHeaders(options.headers));
390
414
 
391
415
  if (options.opaqueId !== undefined) {
392
- headers['x-opaque-id'] = this.opaqueIdPrefix !== null
393
- ? this.opaqueIdPrefix + options.opaqueId
394
- : options.opaqueId
416
+ headers['x-opaque-id'] =
417
+ this.opaqueIdPrefix !== null ? this.opaqueIdPrefix + options.opaqueId : options.opaqueId;
395
418
  }
396
419
 
397
420
  // handle json body
398
421
  if (params.body != null) {
399
422
  if (shouldSerialize(params.body) === true) {
400
423
  try {
401
- params.body = this.serializer.serialize(params.body)
424
+ params.body = this.serializer.serialize(params.body);
402
425
  } catch (err) {
403
- this.emit('request', err, result)
404
- process.nextTick(callback, err, result)
405
- return transportReturn
426
+ this.emit('request', err, result);
427
+ process.nextTick(callback, err, result);
428
+ return transportReturn;
406
429
  }
407
430
  }
408
431
 
409
432
  if (params.body !== '') {
410
- headers['content-type'] = headers['content-type'] || (this[kApiVersioning] ? 'application/vnd.opensearch+json; compatible-with=7' : 'application/json')
433
+ headers['content-type'] =
434
+ headers['content-type'] ||
435
+ (this[kApiVersioning]
436
+ ? 'application/vnd.opensearch+json; compatible-with=7'
437
+ : 'application/json');
411
438
  }
412
439
 
413
440
  // handle ndjson body
414
441
  } else if (params.bulkBody != null) {
415
442
  if (shouldSerialize(params.bulkBody) === true) {
416
443
  try {
417
- params.body = this.serializer.ndserialize(params.bulkBody)
444
+ params.body = this.serializer.ndserialize(params.bulkBody);
418
445
  } catch (err) {
419
- this.emit('request', err, result)
420
- process.nextTick(callback, err, result)
421
- return transportReturn
446
+ this.emit('request', err, result);
447
+ process.nextTick(callback, err, result);
448
+ return transportReturn;
422
449
  }
423
450
  } else {
424
- params.body = params.bulkBody
451
+ params.body = params.bulkBody;
425
452
  }
426
453
  if (params.body !== '') {
427
- headers['content-type'] = headers['content-type'] || (this[kApiVersioning] ? 'application/vnd.opensearch+x-ndjson; compatible-with=7' : 'application/x-ndjson')
454
+ headers['content-type'] =
455
+ headers['content-type'] ||
456
+ (this[kApiVersioning]
457
+ ? 'application/vnd.opensearch+x-ndjson; compatible-with=7'
458
+ : 'application/x-ndjson');
428
459
  }
429
460
  }
430
461
 
431
- params.headers = headers
462
+ params.headers = headers;
432
463
  // serializes the querystring
433
464
  if (options.querystring == null) {
434
- params.querystring = this.serializer.qserialize(params.querystring)
465
+ params.querystring = this.serializer.qserialize(params.querystring);
435
466
  } else {
436
467
  params.querystring = this.serializer.qserialize(
437
468
  Object.assign({}, params.querystring, options.querystring)
438
- )
469
+ );
439
470
  }
440
471
 
441
472
  // handles request timeout
442
- params.timeout = toMs(options.requestTimeout || this.requestTimeout)
443
- if (options.asStream === true) params.asStream = true
444
- meta.request.params = params
445
- meta.request.options = options
473
+ params.timeout = toMs(options.requestTimeout || this.requestTimeout);
474
+ if (options.asStream === true) params.asStream = true;
475
+ meta.request.params = params;
476
+ meta.request.options = options;
446
477
 
447
478
  // handle compression
448
479
  if (params.body !== '' && params.body != null) {
449
480
  if (isStream(params.body) === true) {
450
481
  if (compression === 'gzip') {
451
- params.headers['content-encoding'] = compression
452
- params.body = params.body.pipe(createGzip())
482
+ params.headers['content-encoding'] = compression;
483
+ params.body = params.body.pipe(createGzip());
453
484
  }
454
- makeRequest()
485
+ makeRequest();
455
486
  } else if (compression === 'gzip') {
456
487
  gzip(params.body, (err, buffer) => {
457
488
  /* istanbul ignore next */
458
489
  if (err) {
459
- this.emit('request', err, result)
460
- return callback(err, result)
490
+ this.emit('request', err, result);
491
+ return callback(err, result);
461
492
  }
462
- params.headers['content-encoding'] = compression
463
- params.headers['content-length'] = '' + Buffer.byteLength(buffer)
464
- params.body = buffer
465
- makeRequest()
466
- })
493
+ params.headers['content-encoding'] = compression;
494
+ params.headers['content-length'] = '' + Buffer.byteLength(buffer);
495
+ params.body = buffer;
496
+ makeRequest();
497
+ });
467
498
  } else {
468
- params.headers['content-length'] = '' + Buffer.byteLength(params.body)
469
- makeRequest()
499
+ params.headers['content-length'] = '' + Buffer.byteLength(params.body);
500
+ makeRequest();
470
501
  }
471
502
  } else {
472
- makeRequest()
503
+ makeRequest();
473
504
  }
474
- }
505
+ };
475
506
 
476
- prepareRequest()
507
+ prepareRequest();
477
508
 
478
- return transportReturn
509
+ return transportReturn;
479
510
  }
480
511
 
481
- getConnection (opts) {
482
- const now = Date.now()
512
+ getConnection(opts) {
513
+ const now = Date.now();
483
514
  if (this._sniffEnabled === true && now > this._nextSniff) {
484
- this.sniff({ reason: Transport.sniffReasons.SNIFF_INTERVAL, requestId: opts.requestId })
515
+ this.sniff({ reason: Transport.sniffReasons.SNIFF_INTERVAL, requestId: opts.requestId });
485
516
  }
486
517
  return this.connectionPool.getConnection({
487
518
  filter: this.nodeFilter,
488
519
  selector: this.nodeSelector,
489
520
  requestId: opts.requestId,
490
521
  name: this.name,
491
- now
492
- })
522
+ now,
523
+ });
493
524
  }
494
525
 
495
- sniff (opts, callback = noop) {
496
- if (this._isSniffing === true) return
497
- this._isSniffing = true
498
- debug('Started sniffing request')
526
+ sniff(opts, callback = noop) {
527
+ if (this._isSniffing === true) return;
528
+ this._isSniffing = true;
529
+ debug('Started sniffing request');
499
530
 
500
531
  if (typeof opts === 'function') {
501
- callback = opts
502
- opts = { reason: Transport.sniffReasons.DEFAULT }
532
+ callback = opts;
533
+ opts = { reason: Transport.sniffReasons.DEFAULT };
503
534
  }
504
535
 
505
- const { reason } = opts
536
+ const { reason } = opts;
506
537
 
507
538
  const request = {
508
539
  method: 'GET',
509
- path: this.sniffEndpoint
510
- }
540
+ path: this.sniffEndpoint,
541
+ };
511
542
 
512
543
  this.request(request, { id: opts.requestId }, (err, result) => {
513
- this._isSniffing = false
544
+ this._isSniffing = false;
514
545
  if (this._sniffEnabled === true) {
515
- this._nextSniff = Date.now() + this.sniffInterval
546
+ this._nextSniff = Date.now() + this.sniffInterval;
516
547
  }
517
548
 
518
549
  if (err != null) {
519
- debug('Sniffing errored', err)
520
- result.meta.sniff = { hosts: [], reason }
521
- this.emit('sniff', err, result)
522
- return callback(err)
550
+ debug('Sniffing errored', err);
551
+ result.meta.sniff = { hosts: [], reason };
552
+ this.emit('sniff', err, result);
553
+ return callback(err);
523
554
  }
524
555
 
525
- debug('Sniffing ended successfully', result.body)
526
- const protocol = result.meta.connection.url.protocol || /* istanbul ignore next */ 'http:'
527
- const hosts = this.connectionPool.nodesToHost(result.body.nodes, protocol)
528
- this.connectionPool.update(hosts)
556
+ debug('Sniffing ended successfully', result.body);
557
+ const protocol = result.meta.connection.url.protocol || /* istanbul ignore next */ 'http:';
558
+ const hosts = this.connectionPool.nodesToHost(result.body.nodes, protocol);
559
+ this.connectionPool.update(hosts);
529
560
 
530
- result.meta.sniff = { hosts, reason }
531
- this.emit('sniff', null, result)
532
- callback(null, hosts)
533
- })
561
+ result.meta.sniff = { hosts, reason };
562
+ this.emit('sniff', null, result);
563
+ callback(null, hosts);
564
+ });
534
565
  }
535
566
 
536
567
  // checkCompatibleInfo validates whether the informations are compatible
537
- checkCompatibleInfo () {
538
- debug('Start compatible check')
539
- this[kCompatibleCheck] = 1
540
- this.request({
541
- method: 'GET',
542
- path: '/'
543
- }, (err, result) => {
544
- this[kCompatibleCheck] = 3
545
- if (err) {
546
- debug('compatible check failed', err)
547
- if (err.statusCode === 401 || err.statusCode === 403) {
548
- this[kCompatibleCheck] = 2
549
- process.emitWarning('The client is unable to verify the distribution due to security privileges on the server side. Some functionality may not be compatible if the server is running an unsupported product.')
550
- compatibleCheckEmitter.emit('compatible-check', true)
568
+ checkCompatibleInfo() {
569
+ debug('Start compatible check');
570
+ this[kCompatibleCheck] = 1;
571
+ this.request(
572
+ {
573
+ method: 'GET',
574
+ path: '/',
575
+ },
576
+ (err, result) => {
577
+ this[kCompatibleCheck] = 3;
578
+ if (err) {
579
+ debug('compatible check failed', err);
580
+ if (err.statusCode === 401 || err.statusCode === 403) {
581
+ this[kCompatibleCheck] = 2;
582
+ process.emitWarning(
583
+ 'The client is unable to verify the distribution due to security privileges on the server side. Some functionality may not be compatible if the server is running an unsupported product.'
584
+ );
585
+ compatibleCheckEmitter.emit('compatible-check', true);
586
+ } else {
587
+ this[kCompatibleCheck] = 0;
588
+ compatibleCheckEmitter.emit('compatible-check', false);
589
+ }
551
590
  } else {
552
- this[kCompatibleCheck] = 0
553
- compatibleCheckEmitter.emit('compatible-check', false)
554
- }
555
- } else {
556
- debug('Checking OpenSearch version', result.body, result.headers)
557
- if (result.body.version == null || typeof result.body.version.number !== 'string') {
558
- debug('Can\'t access OpenSearch version')
559
- return compatibleCheckEmitter.emit('compatible-check', false)
560
- }
591
+ debug('Checking OpenSearch version', result.body, result.headers);
592
+ if (result.body.version == null || typeof result.body.version.number !== 'string') {
593
+ debug("Can't access OpenSearch version");
594
+ return compatibleCheckEmitter.emit('compatible-check', false);
595
+ }
561
596
 
562
- const distribution = result.body.version.distribution
563
- const version = result.body.version.number.split('.')
564
- const major = Number(version[0])
597
+ const distribution = result.body.version.distribution;
598
+ const version = result.body.version.number.split('.');
599
+ const major = Number(version[0]);
565
600
 
566
- // support OpenSearch validation
567
- if (distribution === 'opensearch') {
568
- debug('Valid OpenSearch distribution')
569
- this[kCompatibleCheck] = 2
570
- return compatibleCheckEmitter.emit('compatible-check', true)
571
- }
601
+ // support OpenSearch validation
602
+ if (distribution === 'opensearch') {
603
+ debug('Valid OpenSearch distribution');
604
+ this[kCompatibleCheck] = 2;
605
+ return compatibleCheckEmitter.emit('compatible-check', true);
606
+ }
572
607
 
573
- // support odfe > v7 validation
574
- if (major !== 7) {
575
- debug('Invalid distribution')
576
- return compatibleCheckEmitter.emit('compatible-check', false)
577
- }
608
+ // support odfe > v7 validation
609
+ if (major !== 7) {
610
+ debug('Invalid distribution');
611
+ return compatibleCheckEmitter.emit('compatible-check', false);
612
+ }
578
613
 
579
- debug('Valid OpenSearch distribution')
580
- this[kCompatibleCheck] = 2
581
- compatibleCheckEmitter.emit('compatible-check', true)
614
+ debug('Valid OpenSearch distribution');
615
+ this[kCompatibleCheck] = 2;
616
+ compatibleCheckEmitter.emit('compatible-check', true);
617
+ }
582
618
  }
583
- })
619
+ );
584
620
  }
585
621
  }
586
622
 
@@ -589,78 +625,81 @@ Transport.sniffReasons = {
589
625
  SNIFF_INTERVAL: 'sniff-interval',
590
626
  SNIFF_ON_CONNECTION_FAULT: 'sniff-on-connection-fault',
591
627
  // TODO: find a better name
592
- DEFAULT: 'default'
593
- }
628
+ DEFAULT: 'default',
629
+ };
594
630
 
595
- function toMs (time) {
631
+ function toMs(time) {
596
632
  if (typeof time === 'string') {
597
- return ms(time)
633
+ return ms(time);
598
634
  }
599
- return time
635
+ return time;
600
636
  }
601
637
 
602
- function shouldSerialize (obj) {
603
- return typeof obj !== 'string' &&
604
- typeof obj.pipe !== 'function' &&
605
- Buffer.isBuffer(obj) === false
638
+ function shouldSerialize(obj) {
639
+ return (
640
+ typeof obj !== 'string' && typeof obj.pipe !== 'function' && Buffer.isBuffer(obj) === false
641
+ );
606
642
  }
607
643
 
608
- function isStream (obj) {
609
- return obj != null && typeof obj.pipe === 'function'
644
+ function isStream(obj) {
645
+ return obj != null && typeof obj.pipe === 'function';
610
646
  }
611
647
 
612
- function defaultNodeFilter (node) {
613
- // avoid master only nodes
614
- if (node.roles.master === true &&
648
+ function defaultNodeFilter(node) {
649
+ // avoid cluster_manager or master only nodes
650
+ // TODO: remove role check on master when master is not supported
651
+ if (
652
+ (node.roles.cluster_manager === true || node.roles.master === true) &&
615
653
  node.roles.data === false &&
616
- node.roles.ingest === false) {
617
- return false
654
+ node.roles.ingest === false
655
+ ) {
656
+ return false;
618
657
  }
619
- return true
658
+ return true;
620
659
  }
621
660
 
622
- function roundRobinSelector () {
623
- let current = -1
624
- return function _roundRobinSelector (connections) {
661
+ function roundRobinSelector() {
662
+ let current = -1;
663
+ return function _roundRobinSelector(connections) {
625
664
  if (++current >= connections.length) {
626
- current = 0
665
+ current = 0;
627
666
  }
628
- return connections[current]
629
- }
667
+ return connections[current];
668
+ };
630
669
  }
631
670
 
632
- function randomSelector (connections) {
633
- const index = Math.floor(Math.random() * connections.length)
634
- return connections[index]
671
+ function randomSelector(connections) {
672
+ const index = Math.floor(Math.random() * connections.length);
673
+ return connections[index];
635
674
  }
636
675
 
637
- function generateRequestId () {
638
- const maxInt = 2147483647
639
- let nextReqId = 0
640
- return function genReqId (params, options) {
641
- return (nextReqId = (nextReqId + 1) & maxInt)
642
- }
676
+ function generateRequestId() {
677
+ const maxInt = 2147483647;
678
+ let nextReqId = 0;
679
+ return function genReqId(params, options) {
680
+ return (nextReqId = (nextReqId + 1) & maxInt);
681
+ };
643
682
  }
644
683
 
645
- function lowerCaseHeaders (oldHeaders) {
646
- if (oldHeaders == null) return oldHeaders
647
- const newHeaders = {}
684
+ function lowerCaseHeaders(oldHeaders) {
685
+ if (oldHeaders == null) return oldHeaders;
686
+ const newHeaders = {};
648
687
  for (const header in oldHeaders) {
649
- newHeaders[header.toLowerCase()] = oldHeaders[header]
688
+ newHeaders[header.toLowerCase()] = oldHeaders[header];
650
689
  }
651
- return newHeaders
690
+ return newHeaders;
652
691
  }
653
692
 
654
- function validateMemoryPercentage (percentage) {
655
- if (percentage < 0 || percentage > 1) return 1.0
656
- return percentage
693
+ function validateMemoryPercentage(percentage) {
694
+ if (percentage < 0 || percentage > 1) return 1.0;
695
+ return percentage;
657
696
  }
658
697
 
659
- module.exports = Transport
698
+ module.exports = Transport;
660
699
  module.exports.internals = {
661
700
  defaultNodeFilter,
662
701
  roundRobinSelector,
663
702
  randomSelector,
664
703
  generateRequestId,
665
- lowerCaseHeaders
666
- }
704
+ lowerCaseHeaders,
705
+ };