@opensearch-project/opensearch 1.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 (84) hide show
  1. package/.dockerignore +5 -0
  2. package/ADMINS.md +34 -0
  3. package/DEVELOPER_GUIDE.md +60 -0
  4. package/LICENSE.txt +201 -0
  5. package/MAINTAINERS.md +73 -0
  6. package/Makefile +27 -0
  7. package/NOTICE.txt +8 -0
  8. package/README.md +183 -0
  9. package/RELEASING.md +34 -0
  10. package/SECURITY.md +3 -0
  11. package/api/api/bulk.js +81 -0
  12. package/api/api/cat.js +525 -0
  13. package/api/api/clear_scroll.js +66 -0
  14. package/api/api/cluster.js +431 -0
  15. package/api/api/count.js +75 -0
  16. package/api/api/create.js +80 -0
  17. package/api/api/dangling_indices.js +126 -0
  18. package/api/api/delete.js +76 -0
  19. package/api/api/delete_by_query.js +82 -0
  20. package/api/api/delete_by_query_rethrottle.js +71 -0
  21. package/api/api/delete_script.js +67 -0
  22. package/api/api/exists.js +76 -0
  23. package/api/api/exists_source.js +85 -0
  24. package/api/api/explain.js +76 -0
  25. package/api/api/features.js +92 -0
  26. package/api/api/field_caps.js +66 -0
  27. package/api/api/get.js +76 -0
  28. package/api/api/get_script.js +67 -0
  29. package/api/api/get_script_context.js +61 -0
  30. package/api/api/get_script_languages.js +61 -0
  31. package/api/api/get_source.js +76 -0
  32. package/api/api/index.js +82 -0
  33. package/api/api/indices.js +1516 -0
  34. package/api/api/info.js +61 -0
  35. package/api/api/ingest.js +211 -0
  36. package/api/api/mget.js +81 -0
  37. package/api/api/msearch.js +81 -0
  38. package/api/api/msearch_template.js +81 -0
  39. package/api/api/mtermvectors.js +75 -0
  40. package/api/api/nodes.js +279 -0
  41. package/api/api/ping.js +61 -0
  42. package/api/api/put_script.js +82 -0
  43. package/api/api/rank_eval.js +72 -0
  44. package/api/api/reindex.js +67 -0
  45. package/api/api/reindex_rethrottle.js +71 -0
  46. package/api/api/render_search_template.js +66 -0
  47. package/api/api/scripts_painless_execute.js +61 -0
  48. package/api/api/scroll.js +66 -0
  49. package/api/api/search.js +75 -0
  50. package/api/api/search_shards.js +66 -0
  51. package/api/api/search_template.js +81 -0
  52. package/api/api/shutdown.js +135 -0
  53. package/api/api/snapshot.js +450 -0
  54. package/api/api/tasks.js +119 -0
  55. package/api/api/terms_enum.js +67 -0
  56. package/api/api/termvectors.js +78 -0
  57. package/api/api/update.js +80 -0
  58. package/api/api/update_by_query.js +78 -0
  59. package/api/api/update_by_query_rethrottle.js +71 -0
  60. package/api/index.js +254 -0
  61. package/api/new.d.ts +716 -0
  62. package/api/requestParams.d.ts +1583 -0
  63. package/api/types.d.ts +9481 -0
  64. package/api/utils.js +69 -0
  65. package/codecov.yml +14 -0
  66. package/index.d.ts +1210 -0
  67. package/index.js +338 -0
  68. package/index.mjs +40 -0
  69. package/lib/Connection.d.ts +107 -0
  70. package/lib/Connection.js +345 -0
  71. package/lib/Helpers.d.ts +135 -0
  72. package/lib/Helpers.js +779 -0
  73. package/lib/Serializer.d.ts +41 -0
  74. package/lib/Serializer.js +105 -0
  75. package/lib/Transport.d.ts +173 -0
  76. package/lib/Transport.js +646 -0
  77. package/lib/errors.d.ts +101 -0
  78. package/lib/errors.js +168 -0
  79. package/lib/pool/BaseConnectionPool.js +269 -0
  80. package/lib/pool/CloudConnectionPool.js +75 -0
  81. package/lib/pool/ConnectionPool.js +257 -0
  82. package/lib/pool/index.d.ts +215 -0
  83. package/lib/pool/index.js +41 -0
  84. package/package.json +102 -0
@@ -0,0 +1,646 @@
1
+ /*
2
+ * SPDX-License-Identifier: Apache-2.0
3
+ *
4
+ * The OpenSearch Contributors require contributions made to
5
+ * this file be licensed under the Apache-2.0 license or a
6
+ * compatible open source license.
7
+ *
8
+ * Modifications Copyright OpenSearch Contributors. See
9
+ * GitHub history for details.
10
+ */
11
+
12
+ /*
13
+ * Licensed to Elasticsearch B.V. under one or more contributor
14
+ * license agreements. See the NOTICE file distributed with
15
+ * this work for additional information regarding copyright
16
+ * ownership. Elasticsearch B.V. licenses this file to you under
17
+ * the Apache License, Version 2.0 (the "License"); you may
18
+ * not use this file except in compliance with the License.
19
+ * You may obtain a copy of the License at
20
+ *
21
+ * http://www.apache.org/licenses/LICENSE-2.0
22
+ *
23
+ * Unless required by applicable law or agreed to in writing,
24
+ * software distributed under the License is distributed on an
25
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
26
+ * KIND, either express or implied. See the License for the
27
+ * specific language governing permissions and limitations
28
+ * under the License.
29
+ */
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')
39
+ const {
40
+ ConnectionError,
41
+ RequestAbortedError,
42
+ NoLivingConnectionsError,
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')
56
+
57
+ class Transport {
58
+ constructor (opts) {
59
+ if (typeof opts.compression === 'string' && opts.compression !== 'gzip') {
60
+ throw new ConfigurationError(`Invalid compression: '${opts.compression}'`)
61
+ }
62
+
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({},
72
+ { 'user-agent': userAgent },
73
+ opts.suggestCompression === true ? { 'accept-encoding': 'gzip,deflate' } : null,
74
+ 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
86
+ if (typeof opts.nodeSelector === 'function') {
87
+ this.nodeSelector = opts.nodeSelector
88
+ } else if (opts.nodeSelector === 'round-robin') {
89
+ this.nodeSelector = roundRobinSelector()
90
+ } else if (opts.nodeSelector === 'random') {
91
+ this.nodeSelector = randomSelector
92
+ } else {
93
+ this.nodeSelector = roundRobinSelector()
94
+ }
95
+
96
+ this._sniffEnabled = typeof this.sniffInterval === 'number'
97
+ this._nextSniff = this._sniffEnabled ? (Date.now() + this.sniffInterval) : 0
98
+ this._isSniffing = false
99
+
100
+ if (opts.sniffOnStart === true) {
101
+ // timer needed otherwise it will clash
102
+ // with the compatible check testing
103
+ setTimeout(() => {
104
+ this.sniff({ reason: Transport.sniffReasons.SNIFF_ON_START })
105
+ }, 10)
106
+ }
107
+ }
108
+
109
+ request (params, options, callback) {
110
+ options = options || {}
111
+ if (typeof options === 'function') {
112
+ callback = options
113
+ options = {}
114
+ }
115
+ let p = null
116
+
117
+ // promises support
118
+ if (callback === undefined) {
119
+ let onFulfilled = null
120
+ let onRejected = null
121
+ 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
+ }
128
+ }
129
+
130
+ const meta = {
131
+ context: null,
132
+ request: {
133
+ params: null,
134
+ options: null,
135
+ id: options.id || this.generateRequestId(params, options)
136
+ },
137
+ name: this.name,
138
+ connection: null,
139
+ attempts: 0,
140
+ aborted: false
141
+ }
142
+
143
+ if (this.context != null && options.context != null) {
144
+ meta.context = Object.assign({}, this.context, options.context)
145
+ } else if (this.context != null) {
146
+ meta.context = this.context
147
+ } else if (options.context != null) {
148
+ meta.context = options.context
149
+ }
150
+
151
+ const result = {
152
+ body: null,
153
+ statusCode: null,
154
+ headers: null,
155
+ meta
156
+ }
157
+
158
+ Object.defineProperty(result, 'warnings', {
159
+ get () {
160
+ return this.headers && this.headers.warning
161
+ ? this.headers.warning.split(/(?!\B"[^"]*),(?![^"]*"\B)/)
162
+ : null
163
+ }
164
+ })
165
+
166
+ // We should not retry if we are sending a stream body, because we should store in memory
167
+ // a copy of the stream to be able to send it again, but since we don't know in advance
168
+ // the size of the stream, we risk to take too much memory.
169
+ // 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 transportReturn = {
176
+ then (onFulfilled, onRejected) {
177
+ return p.then(onFulfilled, onRejected)
178
+ },
179
+ catch (onRejected) {
180
+ return p.catch(onRejected)
181
+ },
182
+ abort () {
183
+ meta.aborted = true
184
+ request.abort()
185
+ debug('Aborting request', params)
186
+ return this
187
+ },
188
+ finally (onFinally) {
189
+ return p.finally(onFinally)
190
+ }
191
+ }
192
+
193
+ const makeRequest = () => {
194
+ if (meta.aborted === true) {
195
+ return process.nextTick(callback, new RequestAbortedError(), result)
196
+ }
197
+ meta.connection = this.getConnection({ requestId: meta.request.id })
198
+ if (meta.connection == null) {
199
+ return process.nextTick(callback, new NoLivingConnectionsError(), result)
200
+ }
201
+ this.emit('request', null, result)
202
+ // perform the actual http request
203
+ request = meta.connection.request(params, onResponse)
204
+ }
205
+
206
+ const onConnectionError = (err) => {
207
+ if (err.name !== 'RequestAbortedError') {
208
+ // if there is an error in the connection
209
+ // let's mark the connection as dead
210
+ this.connectionPool.markDead(meta.connection)
211
+
212
+ if (this.sniffOnConnectionFault === true) {
213
+ this.sniff({
214
+ reason: Transport.sniffReasons.SNIFF_ON_CONNECTION_FAULT,
215
+ requestId: meta.request.id
216
+ })
217
+ }
218
+
219
+ // retry logic
220
+ if (meta.attempts < maxRetries) {
221
+ meta.attempts++
222
+ debug(`Retrying request, there are still ${maxRetries - meta.attempts} attempts`, params)
223
+ makeRequest()
224
+ return
225
+ }
226
+ }
227
+
228
+ err.meta = result
229
+ this.emit('response', err, result)
230
+ return callback(err, result)
231
+ }
232
+
233
+ const onResponse = (err, response) => {
234
+ if (err !== null) {
235
+ return onConnectionError(err)
236
+ }
237
+
238
+ result.statusCode = response.statusCode
239
+ result.headers = response.headers
240
+
241
+ if (options.asStream === true) {
242
+ result.body = response
243
+ this.emit('response', null, result)
244
+ callback(null, result)
245
+ return
246
+ }
247
+
248
+ const contentEncoding = (result.headers['content-encoding'] || '').toLowerCase()
249
+ const isCompressed = contentEncoding.indexOf('gzip') > -1 || contentEncoding.indexOf('deflate') > -1
250
+
251
+ /* istanbul ignore else */
252
+ if (result.headers['content-length'] !== undefined) {
253
+ const contentLength = Number(result.headers['content-length'])
254
+ if (isCompressed && contentLength > MAX_BUFFER_LENGTH) {
255
+ response.destroy()
256
+ return onConnectionError(
257
+ new RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed buffer (${MAX_BUFFER_LENGTH})`, result)
258
+ )
259
+ } else if (contentLength > MAX_STRING_LENGTH) {
260
+ response.destroy()
261
+ return onConnectionError(
262
+ new RequestAbortedError(`The content length (${contentLength}) is bigger than the maximum allowed string (${MAX_STRING_LENGTH})`, result)
263
+ )
264
+ }
265
+ }
266
+ // if the response is compressed, we must handle it
267
+ // as buffer for allowing decompression later
268
+ let payload = isCompressed ? [] : ''
269
+ 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)
277
+
278
+ if (err) {
279
+ return onConnectionError(new ConnectionError(err.message))
280
+ }
281
+
282
+ if (isCompressed) {
283
+ unzip(Buffer.concat(payload), onBody)
284
+ } else {
285
+ onBody(null, payload)
286
+ }
287
+ }
288
+
289
+ const onAbort = () => {
290
+ response.destroy()
291
+ onEnd(new Error('Response aborted while reading the body'))
292
+ }
293
+
294
+ if (!isCompressed) {
295
+ response.setEncoding('utf8')
296
+ }
297
+
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
+ }
304
+
305
+ const onBody = (err, payload) => {
306
+ if (err) {
307
+ this.emit('response', err, result)
308
+ return callback(err, result)
309
+ }
310
+ if (Buffer.isBuffer(payload)) {
311
+ payload = payload.toString()
312
+ }
313
+ const isHead = params.method === 'HEAD'
314
+ // we should attempt the payload deserialization only if:
315
+ // - a `content-type` is defined and is equal to `application/json`
316
+ // - the request is not a HEAD request
317
+ // - the payload is not an empty string
318
+ if (result.headers['content-type'] !== undefined &&
319
+ (result.headers['content-type'].indexOf('application/json') > -1 ||
320
+ result.headers['content-type'].indexOf('application/vnd.opensearch+json') > -1) &&
321
+ isHead === false &&
322
+ payload !== ''
323
+ ) {
324
+ try {
325
+ result.body = this.serializer.deserialize(payload)
326
+ } catch (err) {
327
+ this.emit('response', err, result)
328
+ return callback(err, result)
329
+ }
330
+ } else {
331
+ // cast to boolean if the request method was HEAD and there was no error
332
+ result.body = isHead === true && result.statusCode < 400 ? true : payload
333
+ }
334
+
335
+ // we should ignore the statusCode if the user has configured the `ignore` field with
336
+ // 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)
339
+
340
+ if (ignoreStatusCode === false &&
341
+ (result.statusCode === 502 || result.statusCode === 503 || result.statusCode === 504)) {
342
+ // if the statusCode is 502/3/4 we should run our retry strategy
343
+ // and mark the connection as dead
344
+ this.connectionPool.markDead(meta.connection)
345
+ // retry logic (we shoukd not retry on "429 - Too Many Requests")
346
+ 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
351
+ }
352
+ } else {
353
+ // everything has worked as expected, let's mark
354
+ // the connection as alive (or confirm it)
355
+ this.connectionPool.markAlive(meta.connection)
356
+ }
357
+
358
+ if (ignoreStatusCode === false && result.statusCode >= 400) {
359
+ const error = new ResponseError(result)
360
+ this.emit('response', error, result)
361
+ callback(error, result)
362
+ } else {
363
+ // cast to boolean if the request method was HEAD
364
+ if (isHead === true && result.statusCode === 404) {
365
+ result.body = false
366
+ }
367
+ this.emit('response', null, result)
368
+ callback(null, result)
369
+ }
370
+ }
371
+
372
+ const prepareRequest = () => {
373
+ this.emit('serialization', null, result)
374
+ const headers = Object.assign({}, this.headers, lowerCaseHeaders(options.headers))
375
+
376
+ if (options.opaqueId !== undefined) {
377
+ headers['x-opaque-id'] = this.opaqueIdPrefix !== null
378
+ ? this.opaqueIdPrefix + options.opaqueId
379
+ : options.opaqueId
380
+ }
381
+
382
+ // handle json body
383
+ if (params.body != null) {
384
+ if (shouldSerialize(params.body) === true) {
385
+ try {
386
+ params.body = this.serializer.serialize(params.body)
387
+ } catch (err) {
388
+ this.emit('request', err, result)
389
+ process.nextTick(callback, err, result)
390
+ return transportReturn
391
+ }
392
+ }
393
+
394
+ if (params.body !== '') {
395
+ headers['content-type'] = headers['content-type'] || (this[kApiVersioning] ? 'application/vnd.opensearch+json; compatible-with=7' : 'application/json')
396
+ }
397
+
398
+ // handle ndjson body
399
+ } else if (params.bulkBody != null) {
400
+ if (shouldSerialize(params.bulkBody) === true) {
401
+ try {
402
+ params.body = this.serializer.ndserialize(params.bulkBody)
403
+ } catch (err) {
404
+ this.emit('request', err, result)
405
+ process.nextTick(callback, err, result)
406
+ return transportReturn
407
+ }
408
+ } else {
409
+ params.body = params.bulkBody
410
+ }
411
+ if (params.body !== '') {
412
+ headers['content-type'] = headers['content-type'] || (this[kApiVersioning] ? 'application/vnd.opensearch+x-ndjson; compatible-with=7' : 'application/x-ndjson')
413
+ }
414
+ }
415
+
416
+ params.headers = headers
417
+ // serializes the querystring
418
+ if (options.querystring == null) {
419
+ params.querystring = this.serializer.qserialize(params.querystring)
420
+ } else {
421
+ params.querystring = this.serializer.qserialize(
422
+ Object.assign({}, params.querystring, options.querystring)
423
+ )
424
+ }
425
+
426
+ // 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
431
+
432
+ // handle compression
433
+ if (params.body !== '' && params.body != null) {
434
+ if (isStream(params.body) === true) {
435
+ if (compression === 'gzip') {
436
+ params.headers['content-encoding'] = compression
437
+ params.body = params.body.pipe(createGzip())
438
+ }
439
+ makeRequest()
440
+ } else if (compression === 'gzip') {
441
+ gzip(params.body, (err, buffer) => {
442
+ /* istanbul ignore next */
443
+ if (err) {
444
+ this.emit('request', err, result)
445
+ return callback(err, result)
446
+ }
447
+ params.headers['content-encoding'] = compression
448
+ params.headers['content-length'] = '' + Buffer.byteLength(buffer)
449
+ params.body = buffer
450
+ makeRequest()
451
+ })
452
+ } else {
453
+ params.headers['content-length'] = '' + Buffer.byteLength(params.body)
454
+ makeRequest()
455
+ }
456
+ } else {
457
+ makeRequest()
458
+ }
459
+ }
460
+
461
+ prepareRequest()
462
+
463
+ return transportReturn
464
+ }
465
+
466
+ getConnection (opts) {
467
+ const now = Date.now()
468
+ if (this._sniffEnabled === true && now > this._nextSniff) {
469
+ this.sniff({ reason: Transport.sniffReasons.SNIFF_INTERVAL, requestId: opts.requestId })
470
+ }
471
+ return this.connectionPool.getConnection({
472
+ filter: this.nodeFilter,
473
+ selector: this.nodeSelector,
474
+ requestId: opts.requestId,
475
+ name: this.name,
476
+ now
477
+ })
478
+ }
479
+
480
+ sniff (opts, callback = noop) {
481
+ if (this._isSniffing === true) return
482
+ this._isSniffing = true
483
+ debug('Started sniffing request')
484
+
485
+ if (typeof opts === 'function') {
486
+ callback = opts
487
+ opts = { reason: Transport.sniffReasons.DEFAULT }
488
+ }
489
+
490
+ const { reason } = opts
491
+
492
+ const request = {
493
+ method: 'GET',
494
+ path: this.sniffEndpoint
495
+ }
496
+
497
+ this.request(request, { id: opts.requestId }, (err, result) => {
498
+ this._isSniffing = false
499
+ if (this._sniffEnabled === true) {
500
+ this._nextSniff = Date.now() + this.sniffInterval
501
+ }
502
+
503
+ if (err != null) {
504
+ debug('Sniffing errored', err)
505
+ result.meta.sniff = { hosts: [], reason }
506
+ this.emit('sniff', err, result)
507
+ return callback(err)
508
+ }
509
+
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)
514
+
515
+ result.meta.sniff = { hosts, reason }
516
+ this.emit('sniff', null, result)
517
+ callback(null, hosts)
518
+ })
519
+ }
520
+
521
+ // 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)
536
+ } 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
+ }
546
+
547
+ const distribution = result.body.version.distribution
548
+ const version = result.body.version.number.split('.')
549
+ const major = Number(version[0])
550
+
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
+ }
557
+
558
+ // support odfe > v7 validation
559
+ if (major !== 7) {
560
+ debug('Invalid distribution')
561
+ return compatibleCheckEmitter.emit('compatible-check', false)
562
+ }
563
+
564
+ debug('Valid OpenSearch distribution')
565
+ this[kCompatibleCheck] = 2
566
+ compatibleCheckEmitter.emit('compatible-check', true)
567
+ }
568
+ })
569
+ }
570
+ }
571
+
572
+ Transport.sniffReasons = {
573
+ SNIFF_ON_START: 'sniff-on-start',
574
+ SNIFF_INTERVAL: 'sniff-interval',
575
+ SNIFF_ON_CONNECTION_FAULT: 'sniff-on-connection-fault',
576
+ // TODO: find a better name
577
+ DEFAULT: 'default'
578
+ }
579
+
580
+ function toMs (time) {
581
+ if (typeof time === 'string') {
582
+ return ms(time)
583
+ }
584
+ return time
585
+ }
586
+
587
+ function shouldSerialize (obj) {
588
+ return typeof obj !== 'string' &&
589
+ typeof obj.pipe !== 'function' &&
590
+ Buffer.isBuffer(obj) === false
591
+ }
592
+
593
+ function isStream (obj) {
594
+ return obj != null && typeof obj.pipe === 'function'
595
+ }
596
+
597
+ function defaultNodeFilter (node) {
598
+ // avoid master only nodes
599
+ if (node.roles.master === true &&
600
+ node.roles.data === false &&
601
+ node.roles.ingest === false) {
602
+ return false
603
+ }
604
+ return true
605
+ }
606
+
607
+ function roundRobinSelector () {
608
+ let current = -1
609
+ return function _roundRobinSelector (connections) {
610
+ if (++current >= connections.length) {
611
+ current = 0
612
+ }
613
+ return connections[current]
614
+ }
615
+ }
616
+
617
+ function randomSelector (connections) {
618
+ const index = Math.floor(Math.random() * connections.length)
619
+ return connections[index]
620
+ }
621
+
622
+ function generateRequestId () {
623
+ const maxInt = 2147483647
624
+ let nextReqId = 0
625
+ return function genReqId (params, options) {
626
+ return (nextReqId = (nextReqId + 1) & maxInt)
627
+ }
628
+ }
629
+
630
+ function lowerCaseHeaders (oldHeaders) {
631
+ if (oldHeaders == null) return oldHeaders
632
+ const newHeaders = {}
633
+ for (const header in oldHeaders) {
634
+ newHeaders[header.toLowerCase()] = oldHeaders[header]
635
+ }
636
+ return newHeaders
637
+ }
638
+
639
+ module.exports = Transport
640
+ module.exports.internals = {
641
+ defaultNodeFilter,
642
+ roundRobinSelector,
643
+ randomSelector,
644
+ generateRequestId,
645
+ lowerCaseHeaders
646
+ }