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