@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
package/lib/Helpers.js ADDED
@@ -0,0 +1,779 @@
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
+ /* eslint camelcase: 0 */
34
+
35
+ const { Readable } = require('stream')
36
+ const { promisify } = require('util')
37
+ const { ResponseError, ConfigurationError } = require('./errors')
38
+
39
+ const pImmediate = promisify(setImmediate)
40
+ const sleep = promisify(setTimeout)
41
+ const kClient = Symbol('opensearch-client')
42
+ const kMetaHeader = Symbol('meta header')
43
+ /* istanbul ignore next */
44
+ const noop = () => { }
45
+
46
+ class Helpers {
47
+ constructor (opts) {
48
+ this[kClient] = opts.client
49
+ this[kMetaHeader] = opts.metaHeader
50
+ this.maxRetries = opts.maxRetries
51
+ }
52
+
53
+ /**
54
+ * Runs a search operation. The only difference between client.search and this utility,
55
+ * is that we are only returning the hits to the user and not the full OpenSearch response.
56
+ * This helper automatically adds `filter_path=hits.hits._source` to the querystring,
57
+ * as it will only need the documents source.
58
+ * @param {object} params - The OpenSearch's search parameters.
59
+ * @param {object} options - The client optional configuration for this request.
60
+ * @return {array} The documents that matched the request.
61
+ */
62
+ async search (params, options) {
63
+ appendFilterPath('hits.hits._source', params, true)
64
+ const { body } = await this[kClient].search(params, options)
65
+ if (body.hits && body.hits.hits) {
66
+ return body.hits.hits.map(d => d._source)
67
+ }
68
+ return []
69
+ }
70
+
71
+ /**
72
+ * Runs a scroll search operation. This function returns an async iterator, allowing
73
+ * the user to use a for await loop to get all the results of a given search.
74
+ * ```js
75
+ * for await (const result of client.helpers.scrollSearch({ params })) {
76
+ * console.log(result)
77
+ * }
78
+ * ```
79
+ * Each result represents the entire body of a single scroll search request,
80
+ * if you just need to scroll the results, use scrollDocuments.
81
+ * This function handles automatically retries on 429 status code.
82
+ * @param {object} params - The OpenSearch's search parameters.
83
+ * @param {object} options - The client optional configuration for this request.
84
+ * @return {iterator} the async iterator
85
+ */
86
+ async * scrollSearch (params, options = {}) {
87
+ if (this[kMetaHeader] !== null) {
88
+ options.headers = options.headers || {}
89
+ }
90
+ // TODO: study scroll search slices
91
+ const wait = options.wait || 5000
92
+ const maxRetries = options.maxRetries || this.maxRetries
93
+ if (Array.isArray(options.ignore)) {
94
+ options.ignore.push(429)
95
+ } else {
96
+ options.ignore = [429]
97
+ }
98
+ params.scroll = params.scroll || '1m'
99
+ appendFilterPath('_scroll_id', params, false)
100
+ const { method, body, index, ...querystring } = params
101
+
102
+ let response = null
103
+ for (let i = 0; i <= maxRetries; i++) {
104
+ response = await this[kClient].search(params, options)
105
+ if (response.statusCode !== 429) break
106
+ await sleep(wait)
107
+ }
108
+ if (response.statusCode === 429) {
109
+ throw new ResponseError(response)
110
+ }
111
+
112
+ let scroll_id = response.body._scroll_id
113
+ let stop = false
114
+ const clear = async () => {
115
+ stop = true
116
+ await this[kClient].clearScroll(
117
+ { body: { scroll_id } },
118
+ { ignore: [400], ...options }
119
+ )
120
+ }
121
+
122
+ while (response.body.hits && response.body.hits.hits.length > 0) {
123
+ // scroll id is always present in the response, but it might
124
+ // change over time based on the number of shards
125
+ scroll_id = response.body._scroll_id
126
+ response.clear = clear
127
+ addDocumentsGetter(response)
128
+
129
+ yield response
130
+
131
+ if (stop === true) {
132
+ break
133
+ }
134
+
135
+ for (let i = 0; i <= maxRetries; i++) {
136
+ response = await this[kClient].scroll({
137
+ scroll: querystring.scroll,
138
+ rest_total_hits_as_int: querystring.rest_total_hits_as_int || querystring.restTotalHitsAsInt,
139
+ body: { scroll_id }
140
+ }, options)
141
+ if (response.statusCode !== 429) break
142
+ await sleep(wait)
143
+ }
144
+ if (response.statusCode === 429) {
145
+ throw new ResponseError(response)
146
+ }
147
+ }
148
+
149
+ if (stop === false) {
150
+ await clear()
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Runs a scroll search operation. This function returns an async iterator, allowing
156
+ * the user to use a for await loop to get all the documents of a given search.
157
+ * ```js
158
+ * for await (const document of client.helpers.scrollSearch({ params })) {
159
+ * console.log(document)
160
+ * }
161
+ * ```
162
+ * Each document is what you will find by running a scrollSearch and iterating on the hits array.
163
+ * This helper automatically adds `filter_path=hits.hits._source` to the querystring,
164
+ * as it will only need the documents source.
165
+ * @param {object} params - The OpenSearch's search parameters.
166
+ * @param {object} options - The client optional configuration for this request.
167
+ * @return {iterator} the async iterator
168
+ */
169
+ async * scrollDocuments (params, options) {
170
+ appendFilterPath('hits.hits._source', params, true)
171
+ for await (const { documents } of this.scrollSearch(params, options)) {
172
+ for (const document of documents) {
173
+ yield document
174
+ }
175
+ }
176
+ }
177
+
178
+ /**
179
+ * Creates a msearch helper instance. Once you configure it, you can use the provided
180
+ * `search` method to add new searches in the queue.
181
+ * @param {object} options - The configuration of the msearch operations.
182
+ * @param {object} reqOptions - The client optional configuration for this request.
183
+ * @return {object} The possible operations to run.
184
+ */
185
+ msearch (options = {}, reqOptions = {}) {
186
+ const client = this[kClient]
187
+ const {
188
+ operations = 5,
189
+ concurrency = 5,
190
+ flushInterval = 500,
191
+ retries = this.maxRetries,
192
+ wait = 5000,
193
+ ...msearchOptions
194
+ } = options
195
+
196
+ let stopReading = false
197
+ let stopError = null
198
+ let timeoutRef = null
199
+ const operationsStream = new Readable({
200
+ objectMode: true,
201
+ read (size) { }
202
+ })
203
+
204
+ const p = iterate()
205
+ const helper = {
206
+ then (onFulfilled, onRejected) {
207
+ return p.then(onFulfilled, onRejected)
208
+ },
209
+ catch (onRejected) {
210
+ return p.catch(onRejected)
211
+ },
212
+ stop (error = null) {
213
+ if (stopReading === true) return
214
+ stopReading = true
215
+ stopError = error
216
+ operationsStream.push(null)
217
+ },
218
+ // TODO: support abort a single search?
219
+ // NOTE: the validation checks are synchronous and the callback/promise will
220
+ // be resolved in the same tick. We might want to fix this in the future.
221
+ search (header, body, callback) {
222
+ if (stopReading === true) {
223
+ const error = stopError === null
224
+ ? new ConfigurationError('The msearch processor has been stopped')
225
+ : stopError
226
+ return callback ? callback(error, {}) : Promise.reject(error)
227
+ }
228
+
229
+ if (!(typeof header === 'object' && header !== null && !Array.isArray(header))) {
230
+ const error = new ConfigurationError('The header should be an object')
231
+ return callback ? callback(error, {}) : Promise.reject(error)
232
+ }
233
+
234
+ if (!(typeof body === 'object' && body !== null && !Array.isArray(body))) {
235
+ const error = new ConfigurationError('The body should be an object')
236
+ return callback ? callback(error, {}) : Promise.reject(error)
237
+ }
238
+
239
+ let promise = null
240
+ if (callback === undefined) {
241
+ let onFulfilled = null
242
+ let onRejected = null
243
+ promise = new Promise((resolve, reject) => {
244
+ onFulfilled = resolve
245
+ onRejected = reject
246
+ })
247
+ callback = function callback (err, result) {
248
+ err ? onRejected(err) : onFulfilled(result)
249
+ }
250
+ }
251
+
252
+ operationsStream.push([header, body, callback])
253
+
254
+ if (promise !== null) {
255
+ return promise
256
+ }
257
+ }
258
+ }
259
+
260
+ return helper
261
+
262
+ async function iterate () {
263
+ const { semaphore, finish } = buildSemaphore()
264
+ const msearchBody = []
265
+ const callbacks = []
266
+ let loadedOperations = 0
267
+ timeoutRef = setTimeout(onFlushTimeout, flushInterval)
268
+
269
+ for await (const operation of operationsStream) {
270
+ timeoutRef.refresh()
271
+ loadedOperations += 1
272
+ msearchBody.push(operation[0], operation[1])
273
+ callbacks.push(operation[2])
274
+ if (loadedOperations >= operations) {
275
+ const send = await semaphore()
276
+ send(msearchBody.slice(), callbacks.slice())
277
+ msearchBody.length = 0
278
+ callbacks.length = 0
279
+ loadedOperations = 0
280
+ }
281
+ }
282
+
283
+ clearTimeout(timeoutRef)
284
+ // In some cases the previos http call does not have finished,
285
+ // or we didn't reach the flush bytes threshold, so we force one last operation.
286
+ if (loadedOperations > 0) {
287
+ const send = await semaphore()
288
+ send(msearchBody, callbacks)
289
+ }
290
+
291
+ await finish()
292
+
293
+ if (stopError !== null) {
294
+ throw stopError
295
+ }
296
+
297
+ async function onFlushTimeout () {
298
+ if (loadedOperations === 0) return
299
+ const msearchBodyCopy = msearchBody.slice()
300
+ const callbacksCopy = callbacks.slice()
301
+ msearchBody.length = 0
302
+ callbacks.length = 0
303
+ loadedOperations = 0
304
+ try {
305
+ const send = await semaphore()
306
+ send(msearchBodyCopy, callbacksCopy)
307
+ } catch (err) {
308
+ /* istanbul ignore next */
309
+ helper.stop(err)
310
+ }
311
+ }
312
+ }
313
+
314
+ // This function builds a semaphore using the concurrency
315
+ // options of the msearch helper. It is used inside the iterator
316
+ // to guarantee that no more than the number of operations
317
+ // allowed to run at the same time are executed.
318
+ // It returns a semaphore function which resolves in the next tick
319
+ // if we didn't reach the maximim concurrency yet, otherwise it returns
320
+ // a promise that resolves as soon as one of the running request has finshed.
321
+ // The semaphore function resolves a send function, which will be used
322
+ // to send the actual msearch request.
323
+ // It also returns a finish function, which returns a promise that is resolved
324
+ // when there are no longer request running.
325
+ function buildSemaphore () {
326
+ let resolveSemaphore = null
327
+ let resolveFinish = null
328
+ let running = 0
329
+
330
+ return { semaphore, finish }
331
+
332
+ function finish () {
333
+ return new Promise((resolve, reject) => {
334
+ if (running === 0) {
335
+ resolve()
336
+ } else {
337
+ resolveFinish = resolve
338
+ }
339
+ })
340
+ }
341
+
342
+ function semaphore () {
343
+ if (running < concurrency) {
344
+ running += 1
345
+ return pImmediate(send)
346
+ } else {
347
+ return new Promise((resolve, reject) => {
348
+ resolveSemaphore = resolve
349
+ })
350
+ }
351
+ }
352
+
353
+ function send (msearchBody, callbacks) {
354
+ /* istanbul ignore if */
355
+ if (running > concurrency) {
356
+ throw new Error('Max concurrency reached')
357
+ }
358
+ msearchOperation(msearchBody, callbacks, () => {
359
+ running -= 1
360
+ if (resolveSemaphore) {
361
+ running += 1
362
+ resolveSemaphore(send)
363
+ resolveSemaphore = null
364
+ } else if (resolveFinish && running === 0) {
365
+ resolveFinish()
366
+ }
367
+ })
368
+ }
369
+ }
370
+
371
+ function msearchOperation (msearchBody, callbacks, done) {
372
+ let retryCount = retries
373
+
374
+ // Instead of going full on async-await, which would make the code easier to read,
375
+ // we have decided to use callback style instead.
376
+ // This because every time we use async await, V8 will create multiple promises
377
+ // behind the scenes, making the code slightly slower.
378
+ tryMsearch(msearchBody, callbacks, retrySearch)
379
+ function retrySearch (msearchBody, callbacks) {
380
+ if (msearchBody.length > 0 && retryCount > 0) {
381
+ retryCount -= 1
382
+ setTimeout(tryMsearch, wait, msearchBody, callbacks, retrySearch)
383
+ return
384
+ }
385
+
386
+ done()
387
+ }
388
+
389
+ // This function never returns an error, if the msearch operation fails,
390
+ // the error is dispatched to all search executors.
391
+ function tryMsearch (msearchBody, callbacks, done) {
392
+ client.msearch(Object.assign({}, msearchOptions, { body: msearchBody }), reqOptions, (err, results) => {
393
+ const retryBody = []
394
+ const retryCallbacks = []
395
+ if (err) {
396
+ addDocumentsGetter(results)
397
+ for (const callback of callbacks) {
398
+ callback(err, results)
399
+ }
400
+ return done(retryBody, retryCallbacks)
401
+ }
402
+ const { responses } = results.body
403
+ for (let i = 0, len = responses.length; i < len; i++) {
404
+ const response = responses[i]
405
+ if (response.status === 429 && retryCount > 0) {
406
+ retryBody.push(msearchBody[i * 2])
407
+ retryBody.push(msearchBody[(i * 2) + 1])
408
+ retryCallbacks.push(callbacks[i])
409
+ continue
410
+ }
411
+ const result = { ...results, body: response }
412
+ addDocumentsGetter(result)
413
+ if (response.status >= 400) {
414
+ callbacks[i](new ResponseError(result), result)
415
+ } else {
416
+ callbacks[i](null, result)
417
+ }
418
+ }
419
+ done(retryBody, retryCallbacks)
420
+ })
421
+ }
422
+ }
423
+ }
424
+
425
+ /**
426
+ * Creates a bulk helper instance. Once you configure it, you can pick which operation
427
+ * to execute with the given dataset, index, create, update, and delete.
428
+ * @param {object} options - The configuration of the bulk operation.
429
+ * @param {object} reqOptions - The client optional configuration for this request.
430
+ * @return {object} The possible operations to run with the datasource.
431
+ */
432
+ bulk (options, reqOptions = {}) {
433
+ const client = this[kClient]
434
+ const { serializer } = client
435
+ if (this[kMetaHeader] !== null) {
436
+ reqOptions.headers = reqOptions.headers || {}
437
+ }
438
+ const {
439
+ datasource,
440
+ onDocument,
441
+ flushBytes = 5000000,
442
+ flushInterval = 30000,
443
+ concurrency = 5,
444
+ retries = this.maxRetries,
445
+ wait = 5000,
446
+ onDrop = noop,
447
+ refreshOnCompletion = false,
448
+ ...bulkOptions
449
+ } = options
450
+
451
+ if (datasource === undefined) {
452
+ return Promise.reject(new ConfigurationError('bulk helper: the datasource is required'))
453
+ }
454
+ if (!(Array.isArray(datasource) || Buffer.isBuffer(datasource) || typeof datasource.pipe === 'function' || datasource[Symbol.asyncIterator])) {
455
+ return Promise.reject(new ConfigurationError('bulk helper: the datasource must be an array or a buffer or a readable stream or an async generator'))
456
+ }
457
+ if (onDocument === undefined) {
458
+ return Promise.reject(new ConfigurationError('bulk helper: the onDocument callback is required'))
459
+ }
460
+
461
+ let shouldAbort = false
462
+ let timeoutRef = null
463
+ const stats = {
464
+ total: 0,
465
+ failed: 0,
466
+ retry: 0,
467
+ successful: 0,
468
+ noop: 0,
469
+ time: 0,
470
+ bytes: 0,
471
+ aborted: false
472
+ }
473
+
474
+ const p = iterate()
475
+ const helper = {
476
+ get stats () {
477
+ return stats
478
+ },
479
+ then (onFulfilled, onRejected) {
480
+ return p.then(onFulfilled, onRejected)
481
+ },
482
+ catch (onRejected) {
483
+ return p.catch(onRejected)
484
+ },
485
+ abort () {
486
+ clearTimeout(timeoutRef)
487
+ shouldAbort = true
488
+ stats.aborted = true
489
+ return this
490
+ }
491
+ }
492
+
493
+ return helper
494
+
495
+ /**
496
+ * Function that iterates over the given datasource and start a bulk operation as soon
497
+ * as it reaches the configured bulk size. It's designed to use the Node.js asynchronous
498
+ * model at this maximum capacity, as it will collect the next body to send while there is
499
+ * a running http call. In this way, the CPU time will be used carefully.
500
+ * The objects will be serialized right away, to approximate the byte length of the body.
501
+ * It creates an array of strings instead of a ndjson string because the bulkOperation
502
+ * will navigate the body for matching failed operations with the original document.
503
+ */
504
+ async function iterate () {
505
+ const { semaphore, finish } = buildSemaphore()
506
+ const startTime = Date.now()
507
+ const bulkBody = []
508
+ let actionBody = ''
509
+ let payloadBody = ''
510
+ let chunkBytes = 0
511
+ timeoutRef = setTimeout(onFlushTimeout, flushInterval)
512
+
513
+ for await (const chunk of datasource) {
514
+ if (shouldAbort === true) break
515
+ timeoutRef.refresh()
516
+ const action = onDocument(chunk)
517
+ const operation = Array.isArray(action)
518
+ ? Object.keys(action[0])[0]
519
+ : Object.keys(action)[0]
520
+ if (operation === 'index' || operation === 'create') {
521
+ actionBody = serializer.serialize(action)
522
+ payloadBody = typeof chunk === 'string' ? chunk : serializer.serialize(chunk)
523
+ chunkBytes += Buffer.byteLength(actionBody) + Buffer.byteLength(payloadBody)
524
+ bulkBody.push(actionBody, payloadBody)
525
+ } else if (operation === 'update') {
526
+ actionBody = serializer.serialize(action[0])
527
+ payloadBody = typeof chunk === 'string'
528
+ ? `{"doc":${chunk}}`
529
+ : serializer.serialize({ doc: chunk, ...action[1] })
530
+ chunkBytes += Buffer.byteLength(actionBody) + Buffer.byteLength(payloadBody)
531
+ bulkBody.push(actionBody, payloadBody)
532
+ } else if (operation === 'delete') {
533
+ actionBody = serializer.serialize(action)
534
+ chunkBytes += Buffer.byteLength(actionBody)
535
+ bulkBody.push(actionBody)
536
+ } else {
537
+ clearTimeout(timeoutRef)
538
+ throw new ConfigurationError(`Bulk helper invalid action: '${operation}'`)
539
+ }
540
+
541
+ if (chunkBytes >= flushBytes) {
542
+ stats.bytes += chunkBytes
543
+ const send = await semaphore()
544
+ send(bulkBody.slice())
545
+ bulkBody.length = 0
546
+ chunkBytes = 0
547
+ }
548
+ }
549
+
550
+ clearTimeout(timeoutRef)
551
+ // In some cases the previos http call does not have finished,
552
+ // or we didn't reach the flush bytes threshold, so we force one last operation.
553
+ if (shouldAbort === false && chunkBytes > 0) {
554
+ const send = await semaphore()
555
+ stats.bytes += chunkBytes
556
+ send(bulkBody)
557
+ }
558
+
559
+ await finish()
560
+
561
+ if (refreshOnCompletion) {
562
+ await client.indices.refresh({
563
+ index: typeof refreshOnCompletion === 'string'
564
+ ? refreshOnCompletion
565
+ : '_all'
566
+ }, reqOptions)
567
+ }
568
+
569
+ stats.time = Date.now() - startTime
570
+ stats.total = stats.successful + stats.failed
571
+
572
+ return stats
573
+
574
+ async function onFlushTimeout () {
575
+ if (chunkBytes === 0) return
576
+ stats.bytes += chunkBytes
577
+ const bulkBodyCopy = bulkBody.slice()
578
+ bulkBody.length = 0
579
+ chunkBytes = 0
580
+ try {
581
+ const send = await semaphore()
582
+ send(bulkBodyCopy)
583
+ } catch (err) {
584
+ /* istanbul ignore next */
585
+ helper.abort()
586
+ }
587
+ }
588
+ }
589
+
590
+ // This function builds a semaphore using the concurrency
591
+ // options of the bulk helper. It is used inside the iterator
592
+ // to guarantee that no more than the number of operations
593
+ // allowed to run at the same time are executed.
594
+ // It returns a semaphore function which resolves in the next tick
595
+ // if we didn't reach the maximim concurrency yet, otherwise it returns
596
+ // a promise that resolves as soon as one of the running request has finshed.
597
+ // The semaphore function resolves a send function, which will be used
598
+ // to send the actual bulk request.
599
+ // It also returns a finish function, which returns a promise that is resolved
600
+ // when there are no longer request running. It rejects an error if one
601
+ // of the request has failed for some reason.
602
+ function buildSemaphore () {
603
+ let resolveSemaphore = null
604
+ let resolveFinish = null
605
+ let rejectFinish = null
606
+ let error = null
607
+ let running = 0
608
+
609
+ return { semaphore, finish }
610
+
611
+ function finish () {
612
+ return new Promise((resolve, reject) => {
613
+ if (running === 0) {
614
+ if (error) {
615
+ reject(error)
616
+ } else {
617
+ resolve()
618
+ }
619
+ } else {
620
+ resolveFinish = resolve
621
+ rejectFinish = reject
622
+ }
623
+ })
624
+ }
625
+
626
+ function semaphore () {
627
+ if (running < concurrency) {
628
+ running += 1
629
+ return pImmediate(send)
630
+ } else {
631
+ return new Promise((resolve, reject) => {
632
+ resolveSemaphore = resolve
633
+ })
634
+ }
635
+ }
636
+
637
+ function send (bulkBody) {
638
+ /* istanbul ignore if */
639
+ if (running > concurrency) {
640
+ throw new Error('Max concurrency reached')
641
+ }
642
+ bulkOperation(bulkBody, err => {
643
+ running -= 1
644
+ if (err) {
645
+ shouldAbort = true
646
+ error = err
647
+ }
648
+ if (resolveSemaphore) {
649
+ running += 1
650
+ resolveSemaphore(send)
651
+ resolveSemaphore = null
652
+ } else if (resolveFinish && running === 0) {
653
+ if (error) {
654
+ rejectFinish(error)
655
+ } else {
656
+ resolveFinish()
657
+ }
658
+ }
659
+ })
660
+ }
661
+ }
662
+
663
+ function bulkOperation (bulkBody, callback) {
664
+ let retryCount = retries
665
+ let isRetrying = false
666
+
667
+ // Instead of going full on async-await, which would make the code easier to read,
668
+ // we have decided to use callback style instead.
669
+ // This because every time we use async await, V8 will create multiple promises
670
+ // behind the scenes, making the code slightly slower.
671
+ tryBulk(bulkBody, retryDocuments)
672
+ function retryDocuments (err, bulkBody) {
673
+ if (err) return callback(err)
674
+ if (shouldAbort === true) return callback()
675
+
676
+ if (bulkBody.length > 0) {
677
+ if (retryCount > 0) {
678
+ isRetrying = true
679
+ retryCount -= 1
680
+ stats.retry += bulkBody.length
681
+ setTimeout(tryBulk, wait, bulkBody, retryDocuments)
682
+ return
683
+ }
684
+ for (let i = 0, len = bulkBody.length; i < len; i = i + 2) {
685
+ const operation = Object.keys(serializer.deserialize(bulkBody[i]))[0]
686
+ onDrop({
687
+ status: 429,
688
+ error: null,
689
+ operation: serializer.deserialize(bulkBody[i]),
690
+ document: operation !== 'delete'
691
+ ? serializer.deserialize(bulkBody[i + 1])
692
+ /* istanbul ignore next */
693
+ : null,
694
+ retried: isRetrying
695
+ })
696
+ stats.failed += 1
697
+ }
698
+ }
699
+ callback()
700
+ }
701
+
702
+ function tryBulk (bulkBody, callback) {
703
+ if (shouldAbort === true) return callback(null, [])
704
+ client.bulk(Object.assign({}, bulkOptions, { body: bulkBody }), reqOptions, (err, { body }) => {
705
+ if (err) return callback(err, null)
706
+ if (body.errors === false) {
707
+ stats.successful += body.items.length
708
+ for (const item of body.items) {
709
+ if (item.update && item.update.result === 'noop') {
710
+ stats.noop++
711
+ }
712
+ }
713
+ return callback(null, [])
714
+ }
715
+ const retry = []
716
+ const { items } = body
717
+ for (let i = 0, len = items.length; i < len; i++) {
718
+ const action = items[i]
719
+ const operation = Object.keys(action)[0]
720
+ const { status } = action[operation]
721
+ const indexSlice = operation !== 'delete' ? i * 2 : i
722
+
723
+ if (status >= 400) {
724
+ // 429 is the only staus code where we might want to retry
725
+ // a document, because it was not an error in the document itself,
726
+ // but the OpenSearch node were handling too many operations.
727
+ if (status === 429) {
728
+ retry.push(bulkBody[indexSlice])
729
+ /* istanbul ignore next */
730
+ if (operation !== 'delete') {
731
+ retry.push(bulkBody[indexSlice + 1])
732
+ }
733
+ } else {
734
+ onDrop({
735
+ status: status,
736
+ error: action[operation].error,
737
+ operation: serializer.deserialize(bulkBody[indexSlice]),
738
+ document: operation !== 'delete'
739
+ ? serializer.deserialize(bulkBody[indexSlice + 1])
740
+ : null,
741
+ retried: isRetrying
742
+ })
743
+ stats.failed += 1
744
+ }
745
+ } else {
746
+ stats.successful += 1
747
+ }
748
+ }
749
+ callback(null, retry)
750
+ })
751
+ }
752
+ }
753
+ }
754
+ }
755
+
756
+ // Using a getter will improve the overall performances of the code,
757
+ // as we will reed the documents only if needed.
758
+ function addDocumentsGetter (result) {
759
+ Object.defineProperty(result, 'documents', {
760
+ get () {
761
+ if (this.body.hits && this.body.hits.hits) {
762
+ return this.body.hits.hits.map(d => d._source)
763
+ }
764
+ return []
765
+ }
766
+ })
767
+ }
768
+
769
+ function appendFilterPath (filter, params, force) {
770
+ if (params.filter_path !== undefined) {
771
+ params.filter_path += ',' + filter
772
+ } else if (params.filterPath !== undefined) {
773
+ params.filterPath += ',' + filter
774
+ } else if (force === true) {
775
+ params.filter_path = filter
776
+ }
777
+ }
778
+
779
+ module.exports = Helpers