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