@opensearch-project/opensearch 1.0.0 → 2.0.0

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