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