kuzzle 2.60.1 → 2.61.0-beta.2

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 (52) hide show
  1. package/dist/index.d.ts +2 -0
  2. package/dist/index.js +2 -0
  3. package/dist/lib/cluster/idCardHandler.d.ts +11 -1
  4. package/dist/lib/cluster/idCardHandler.js +10 -2
  5. package/dist/lib/cluster/node.d.ts +14 -0
  6. package/dist/lib/cluster/node.js +19 -0
  7. package/dist/lib/config/index.js +43 -8
  8. package/dist/lib/core/backend/backendStorage.js +4 -6
  9. package/dist/lib/core/plugin/pluginContext.js +2 -2
  10. package/dist/lib/core/storage/clientAdapter.d.ts +13 -10
  11. package/dist/lib/core/storage/clientAdapter.js +112 -60
  12. package/dist/lib/core/storage/conformance/capabilityCases.d.ts +3 -0
  13. package/dist/lib/core/storage/conformance/capabilityCases.js +121 -0
  14. package/dist/lib/core/storage/conformance/conformanceContext.d.ts +33 -0
  15. package/dist/lib/core/storage/conformance/conformanceContext.js +97 -0
  16. package/dist/lib/core/storage/conformance/conformanceEnvironment.d.ts +7 -0
  17. package/dist/lib/core/storage/conformance/conformanceEnvironment.js +136 -0
  18. package/dist/lib/core/storage/conformance/coreCases.d.ts +3 -0
  19. package/dist/lib/core/storage/conformance/coreCases.js +381 -0
  20. package/dist/lib/core/storage/conformance/storageDriverConformance.d.ts +53 -0
  21. package/dist/lib/core/storage/conformance/storageDriverConformance.js +89 -0
  22. package/dist/lib/core/storage/indexCache.d.ts +26 -2
  23. package/dist/lib/core/storage/indexCache.js +100 -2
  24. package/dist/lib/core/storage/storageDriverLoader.d.ts +41 -0
  25. package/dist/lib/core/storage/storageDriverLoader.js +276 -0
  26. package/dist/lib/core/storage/storageEngine.js +9 -1
  27. package/dist/lib/core/storage/storageError.d.ts +15 -0
  28. package/dist/lib/core/storage/storageError.js +36 -0
  29. package/dist/lib/kerror/codes/1-services.json +35 -0
  30. package/dist/lib/kerror/codes/8-cluster.json +6 -0
  31. package/dist/lib/service/storage/builtInDrivers.d.ts +6 -0
  32. package/dist/lib/service/storage/builtInDrivers.js +103 -0
  33. package/dist/lib/service/storage/storageService.d.ts +13 -0
  34. package/dist/lib/service/storage/storageService.js +44 -0
  35. package/dist/lib/types/config/KuzzleConfiguration.d.ts +8 -0
  36. package/dist/lib/types/config/storageEngine/StorageEngineElasticsearchConfiguration.d.ts +13 -1
  37. package/dist/lib/types/index.d.ts +1 -0
  38. package/dist/lib/types/index.js +1 -0
  39. package/dist/lib/types/storage/StorageDriver.d.ts +306 -0
  40. package/dist/lib/types/storage/StorageDriver.js +41 -0
  41. package/dist/package.json +4 -1
  42. package/package.json +4 -1
  43. package/dist/lib/service/storage/7/elasticsearch.d.ts +0 -1054
  44. package/dist/lib/service/storage/7/elasticsearch.js +0 -3063
  45. package/dist/lib/service/storage/7/esWrapper.d.ts +0 -36
  46. package/dist/lib/service/storage/7/esWrapper.js +0 -295
  47. package/dist/lib/service/storage/8/elasticsearch.d.ts +0 -1047
  48. package/dist/lib/service/storage/8/elasticsearch.js +0 -3096
  49. package/dist/lib/service/storage/8/esWrapper.d.ts +0 -36
  50. package/dist/lib/service/storage/8/esWrapper.js +0 -295
  51. package/dist/lib/service/storage/Elasticsearch.d.ts +0 -16
  52. package/dist/lib/service/storage/Elasticsearch.js +0 -48
@@ -1,3063 +0,0 @@
1
- "use strict";
2
- /*
3
- * Kuzzle, a backend software, self-hostable and ready to use
4
- * to power modern apps
5
- *
6
- * Copyright 2015-2022 Kuzzle
7
- * mailto: support AT kuzzle.io
8
- * website: http://kuzzle.io
9
- *
10
- * Licensed under the Apache License, Version 2.0 (the "License");
11
- * you may not use this file except in compliance with the License.
12
- * You may obtain a copy of the License at
13
- *
14
- * https://www.apache.org/licenses/LICENSE-2.0
15
- *
16
- * Unless required by applicable law or agreed to in writing, software
17
- * distributed under the License is distributed on an "AS IS" BASIS,
18
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
- * See the License for the specific language governing permissions and
20
- * limitations under the License.
21
- */
22
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
23
- if (k2 === undefined) k2 = k;
24
- var desc = Object.getOwnPropertyDescriptor(m, k);
25
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
26
- desc = { enumerable: true, get: function() { return m[k]; } };
27
- }
28
- Object.defineProperty(o, k2, desc);
29
- }) : (function(o, m, k, k2) {
30
- if (k2 === undefined) k2 = k;
31
- o[k2] = m[k];
32
- }));
33
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
34
- Object.defineProperty(o, "default", { enumerable: true, value: v });
35
- }) : function(o, v) {
36
- o["default"] = v;
37
- });
38
- var __importStar = (this && this.__importStar) || (function () {
39
- var ownKeys = function(o) {
40
- ownKeys = Object.getOwnPropertyNames || function (o) {
41
- var ar = [];
42
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
43
- return ar;
44
- };
45
- return ownKeys(o);
46
- };
47
- return function (mod) {
48
- if (mod && mod.__esModule) return mod;
49
- var result = {};
50
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
51
- __setModuleDefault(result, mod);
52
- return result;
53
- };
54
- })();
55
- var __importDefault = (this && this.__importDefault) || function (mod) {
56
- return (mod && mod.__esModule) ? mod : { "default": mod };
57
- };
58
- Object.defineProperty(exports, "__esModule", { value: true });
59
- exports.ES7 = void 0;
60
- const lodash_1 = __importDefault(require("lodash"));
61
- const sdk_es7_1 = require("sdk-es7");
62
- const assert_1 = __importDefault(require("assert"));
63
- const bluebird_1 = __importDefault(require("bluebird"));
64
- const ms_1 = __importDefault(require("ms"));
65
- const semver_1 = __importDefault(require("semver"));
66
- const storeScopeEnum_1 = require("../../../core/storage/storeScopeEnum");
67
- const kerror = __importStar(require("../../../kerror"));
68
- const didYouMean_1 = __importDefault(require("../../../util/didYouMean"));
69
- const extractFields_1 = __importDefault(require("../../../util/extractFields"));
70
- const distributedLock_1 = require("../../../util/distributedLock");
71
- const name_generator_1 = require("../../../util/name-generator");
72
- const requestAssertions_1 = require("../../../util/requestAssertions");
73
- const safeObject_1 = require("../../../util/safeObject");
74
- const queryTranslator_1 = require("../commons/queryTranslator");
75
- const esWrapper_1 = __importDefault(require("./esWrapper"));
76
- const SCROLL_CACHE_PREFIX = "_docscroll_";
77
- const ROOT_MAPPING_PROPERTIES = [
78
- "properties",
79
- "_meta",
80
- "dynamic",
81
- "dynamic_templates",
82
- ];
83
- const CHILD_MAPPING_PROPERTIES = ["type"];
84
- // Used for collection emulation
85
- const HIDDEN_COLLECTION = "_kuzzle_keep";
86
- // The hidden collection locks wait for as long as it takes, as the `Mutex`
87
- // they replace did: they guard a collection creation, which must not fail
88
- // only because another request on the same index got there first. The lock
89
- // is refreshed while held, so a live holder is never overtaken; a crashed
90
- // one leaves it for at most `ttl` (30 s).
91
- const HIDDEN_COLLECTION_LOCK = { retryAttempts: Number.POSITIVE_INFINITY };
92
- // How long `waitForCollectionShards` lets Elasticsearch wait for a
93
- // collection's primary shards, which is also Elasticsearch's own default
94
- const COLLECTION_SHARDS_TIMEOUT = "30s";
95
- const ALIAS_PREFIX = "@"; // @todo next major release: Add ALIAS_PREFIX in FORBIDDEN_CHARS
96
- const PRIVATE_PREFIX = "%";
97
- const PUBLIC_PREFIX = "&";
98
- const INDEX_PREFIX_POSITION_IN_INDICE = 0;
99
- const INDEX_PREFIX_POSITION_IN_ALIAS = 1;
100
- const NAME_SEPARATOR = ".";
101
- const FORBIDDEN_CHARS = `\\/*?"<>| \t\r\n,+#:${NAME_SEPARATOR}${PUBLIC_PREFIX}${PRIVATE_PREFIX}`;
102
- const DYNAMIC_PROPERTY_VALUES = ["true", "false", "strict"];
103
- // used to check whether we need to wait for ES to initialize or not
104
- var esStateEnum;
105
- (function (esStateEnum) {
106
- esStateEnum[esStateEnum["AWAITING"] = 1] = "AWAITING";
107
- esStateEnum[esStateEnum["NONE"] = 2] = "NONE";
108
- esStateEnum[esStateEnum["OK"] = 3] = "OK";
109
- })(esStateEnum || (esStateEnum = {}));
110
- let esState = esStateEnum.NONE;
111
- /**
112
- * @param {Kuzzle} kuzzle kuzzle instance
113
- * @param {Object} config Service configuration
114
- * @param {storeScopeEnum} scope
115
- * @constructor
116
- */
117
- class ES7 {
118
- constructor(config, scope = storeScopeEnum_1.storeScopeEnum.PUBLIC) {
119
- this.logger = global.kuzzle.log.child("service:storage:elasticsearch:7");
120
- this._config = config;
121
- this._scope = scope;
122
- this._indexPrefix =
123
- scope === storeScopeEnum_1.storeScopeEnum.PRIVATE ? PRIVATE_PREFIX : PUBLIC_PREFIX;
124
- this._esVersion = null;
125
- this._translator = new queryTranslator_1.QueryTranslator();
126
- // Allowed root key of a search query
127
- this.searchBodyKeys = [
128
- "aggregations",
129
- "aggs",
130
- "collapse",
131
- "explain",
132
- "fields",
133
- "from",
134
- "highlight",
135
- "post_filter",
136
- "query",
137
- "search_after",
138
- "search_timeout",
139
- "size",
140
- "sort",
141
- "suggest",
142
- "_name",
143
- "_source",
144
- "_source_excludes",
145
- "_source_includes",
146
- ];
147
- /**
148
- * Only allow stored-scripts in queries
149
- */
150
- this.scriptKeys = ["script", "_script"];
151
- this.scriptAllowedArgs = ["id", "params"];
152
- this.maxScrollDuration = this._loadMsConfig("maxScrollDuration");
153
- this.scrollTTL = this._loadMsConfig("defaults.scrollTTL");
154
- }
155
- get scope() {
156
- return this._scope;
157
- }
158
- /**
159
- * Initializes the elasticsearch client
160
- *
161
- * @override
162
- * @returns {Promise}
163
- */
164
- async _initSequence() {
165
- if (this._client) {
166
- return;
167
- }
168
- if (global.NODE_ENV !== "development" &&
169
- this._config.commonMapping.dynamic === "true") {
170
- this.logger.warn([
171
- "Your dynamic mapping policy is set to 'true' for new fields.",
172
- "Elasticsearch will try to automatically infer mapping for new fields, and those cannot be changed afterward.",
173
- 'See the "services.storageEngine.commonMapping.dynamic" option in the kuzzlerc configuration file to change this value.',
174
- ].join("\n"));
175
- }
176
- this._client = new sdk_es7_1.Client(this._config.client);
177
- await this.waitForElasticsearch();
178
- this._esWrapper = new esWrapper_1.default(this._client);
179
- const { body: { version }, } = await this._client.info();
180
- if (version) {
181
- const coerced = semver_1.default.coerce(version.number);
182
- if (coerced === null || !semver_1.default.satisfies(coerced, ">= 7.0.0")) {
183
- throw kerror.get("services", "storage", "version_mismatch", version.number);
184
- }
185
- }
186
- this._esVersion = version;
187
- }
188
- /**
189
- * Translate Koncorde filters to Elasticsearch query
190
- *
191
- * @param {Object} filters - Set of valid Koncorde filters
192
- * @returns {Object} Equivalent Elasticsearch query
193
- */
194
- translateKoncordeFilters(filters) {
195
- return this._translator.translate(filters);
196
- }
197
- /**
198
- * Returns some basic information about this service
199
- * @override
200
- *
201
- * @returns {Promise.<Object>} service informations
202
- */
203
- info() {
204
- const result = {
205
- type: "elasticsearch",
206
- version: this._esVersion?.number ?? "",
207
- };
208
- return this._client
209
- .info()
210
- .then(({ body }) => {
211
- result.version = body.version.number;
212
- result.lucene = body.version.lucene_version;
213
- return this._client.cluster.health();
214
- })
215
- .then(({ body }) => {
216
- result.status = body.status;
217
- return this._client.cluster.stats({ human: true });
218
- })
219
- .then(({ body }) => {
220
- result.spaceUsed = body.indices.store.size;
221
- result.nodes = body.nodes;
222
- return result;
223
- })
224
- .catch((error) => this._esWrapper.reject(error));
225
- }
226
- /**
227
- * Returns detailed multi-level storage stats data
228
- *
229
- * @returns {Promise.<Object>}
230
- */
231
- async stats() {
232
- const esRequest = {
233
- metric: ["docs", "store"],
234
- };
235
- const { body } = await this._client.indices.stats(esRequest);
236
- const indexes = {};
237
- let size = 0;
238
- for (const [indice, indiceInfo] of Object.entries(body.indices ?? {})) {
239
- // Ignore non-Kuzzle indices
240
- if (!indice.startsWith(PRIVATE_PREFIX) &&
241
- !indice.startsWith(PUBLIC_PREFIX)) {
242
- continue;
243
- }
244
- const aliases = await this._getAliasFromIndice(indice);
245
- const alias = aliases[0];
246
- const indexName = this._extractIndex(alias);
247
- const collectionName = this._extractCollection(alias);
248
- if (alias[INDEX_PREFIX_POSITION_IN_ALIAS] !== this._indexPrefix ||
249
- collectionName === HIDDEN_COLLECTION) {
250
- continue;
251
- }
252
- const indexStats = (indexes[indexName] ?? (indexes[indexName] = {
253
- collections: [],
254
- name: indexName,
255
- size: 0,
256
- }));
257
- indexStats.collections.push({
258
- documentCount: indiceInfo.total.docs.count,
259
- name: collectionName,
260
- size: indiceInfo.total.store.size_in_bytes,
261
- });
262
- indexStats.size += indiceInfo.total.store.size_in_bytes;
263
- size += indiceInfo.total.store.size_in_bytes;
264
- }
265
- return {
266
- indexes: Object.values(indexes),
267
- size,
268
- };
269
- }
270
- /**
271
- * Scrolls results from previous elasticsearch query.
272
- * Automatically clears the scroll context after the last result page has
273
- * been fetched.
274
- *
275
- * @param {String} scrollId - Scroll identifier
276
- * @param {Object} options - scrollTTL (default scrollTTL)
277
- *
278
- * @returns {Promise.<{ scrollId, hits, aggregations, total }>}
279
- */
280
- async scroll(scrollId, { scrollTTL } = {}) {
281
- const _scrollTTL = scrollTTL || this._config.defaults.scrollTTL;
282
- const esRequest = {
283
- scroll: _scrollTTL,
284
- scroll_id: scrollId,
285
- };
286
- const cacheKey = SCROLL_CACHE_PREFIX + global.kuzzle.hash(esRequest.scroll_id);
287
- this.logger.debug("Scroll: %o", esRequest);
288
- if (_scrollTTL) {
289
- const scrollDuration = (0, ms_1.default)(_scrollTTL) ?? 0;
290
- if (scrollDuration > this.maxScrollDuration) {
291
- throw kerror.get("services", "storage", "scroll_duration_too_great", _scrollTTL);
292
- }
293
- }
294
- const stringifiedScrollInfo = await global.kuzzle.ask("core:cache:internal:get", cacheKey);
295
- if (!stringifiedScrollInfo) {
296
- throw kerror.get("services", "storage", "unknown_scroll_id");
297
- }
298
- const scrollInfo = JSON.parse(stringifiedScrollInfo);
299
- try {
300
- const { body } = await this._client.scroll(esRequest);
301
- scrollInfo.fetched += body.hits.hits.length;
302
- if (scrollInfo.fetched >= body.hits.total.value) {
303
- this.logger.debug("Last scroll page fetched: deleting scroll %s", body._scroll_id);
304
- await global.kuzzle.ask("core:cache:internal:del", cacheKey);
305
- await this.clearScroll(body._scroll_id);
306
- }
307
- else {
308
- await global.kuzzle.ask("core:cache:internal:store", cacheKey, JSON.stringify(scrollInfo), {
309
- ttl: (0, ms_1.default)(_scrollTTL) || this.scrollTTL,
310
- });
311
- }
312
- body.remaining = body.hits.total.value - scrollInfo.fetched;
313
- return await this._formatSearchResult(body, scrollInfo);
314
- }
315
- catch (error) {
316
- throw this._esWrapper.formatESError(error);
317
- }
318
- }
319
- /**
320
- * Searches documents from elasticsearch with a query
321
- *
322
- * @param {String} index - Index name
323
- * @param {String} collection - Collection name
324
- * @param {Object} searchBody - Search request body (query, sort, etc.)
325
- * @param {Object} options - from (undefined), size (undefined), scroll (undefined)
326
- *
327
- * @returns {Promise.<{ scrollId, hits, aggregations, suggest, total }>}
328
- */
329
- async search({ index, collection, searchBody, targets, } = {}, { from, size, scroll, } = {}) {
330
- let esIndexes;
331
- if (targets && targets.length > 0) {
332
- esIndexes = this._targetsToIndexes(targets);
333
- }
334
- else {
335
- if (index === undefined) {
336
- throw kerror.get("services", "storage", "missing_argument", "index");
337
- }
338
- esIndexes = this._getAlias(index, collection);
339
- }
340
- const esRequest = {
341
- body: this._sanitizeSearchBody(searchBody),
342
- from,
343
- index: esIndexes,
344
- scroll,
345
- size,
346
- trackTotalHits: true,
347
- };
348
- if (scroll) {
349
- const scrollDuration = (0, ms_1.default)(scroll) ?? 0;
350
- if (scrollDuration > this.maxScrollDuration) {
351
- throw kerror.get("services", "storage", "scroll_duration_too_great", scroll);
352
- }
353
- }
354
- this.logger.debug("Search: %j", esRequest);
355
- try {
356
- const { body } = await this._client.search(esRequest);
357
- if (body._scroll_id) {
358
- const ttl = (esRequest.scroll && (0, ms_1.default)(esRequest.scroll)) ||
359
- (0, ms_1.default)(this._config.defaults.scrollTTL);
360
- await global.kuzzle.ask("core:cache:internal:store", SCROLL_CACHE_PREFIX + global.kuzzle.hash(body._scroll_id), JSON.stringify({
361
- collection,
362
- fetched: body.hits.hits.length,
363
- index,
364
- targets,
365
- }), { ttl });
366
- body.remaining = body.hits.total.value - body.hits.hits.length;
367
- }
368
- return await this._formatSearchResult(body, {
369
- collection,
370
- index,
371
- targets,
372
- });
373
- }
374
- catch (error) {
375
- throw this._esWrapper.formatESError(error);
376
- }
377
- }
378
- /**
379
- * The comma-separated alias list a multi-target search is run against.
380
- *
381
- * @param targets - targets already through `assertTargetsAreValid`
382
- */
383
- _targetsToIndexes(targets) {
384
- const indexes = new Set();
385
- for (const target of targets) {
386
- for (const targetCollection of target.collections) {
387
- indexes.add(this._getAlias(target.index, targetCollection));
388
- }
389
- }
390
- return Array.from(indexes).join(",");
391
- }
392
- /**
393
- * Generate a map that associate an alias to a pair of index and collection
394
- *
395
- * @param {*} targets
396
- * @returns
397
- */
398
- _mapTargetsToAlias(targets) {
399
- const aliasToTargets = {};
400
- for (const target of targets) {
401
- for (const targetCollection of target.collections) {
402
- const alias = this._getAlias(target.index, targetCollection);
403
- if (!aliasToTargets[alias]) {
404
- aliasToTargets[alias] = {
405
- collection: targetCollection,
406
- index: target.index,
407
- };
408
- }
409
- }
410
- }
411
- return aliasToTargets;
412
- }
413
- async _formatSearchResult(
414
- // The ES 7 client does not type its answers.
415
- body, searchInfo = {}) {
416
- let aliasToTargets = {};
417
- const aliasCache = new Map();
418
- if (searchInfo.targets) {
419
- /**
420
- * We need to map the alias to the target index and collection,
421
- * so we can later retrieve informations about an index & collection
422
- * based on its alias.
423
- */
424
- aliasToTargets = this._mapTargetsToAlias(searchInfo.targets);
425
- }
426
- const formatHit = async (hit) => {
427
- let index = searchInfo.index;
428
- let collection = searchInfo.collection;
429
- /**
430
- * If the search has been done on multiple targets, we need to
431
- * retrieve the appropriate index and collection based on the alias
432
- */
433
- if (hit._index && searchInfo.targets) {
434
- // Caching to reduce call to ES
435
- let aliases = aliasCache.get(hit._index);
436
- if (!aliases) {
437
- // Retrieve all the alias associated to one index
438
- aliases = await this._getAliasFromIndice(hit._index);
439
- aliasCache.set(hit._index, aliases);
440
- }
441
- /**
442
- * Since multiple alias can point to the same index in ES, we need to
443
- * find the first alias that exists in the map of aliases associated
444
- * to the targets.
445
- */
446
- // Retrieve index and collection information based on the matching alias
447
- for (const _alias of aliases) {
448
- const target = aliasToTargets[_alias];
449
- if (target) {
450
- index = target.index;
451
- collection = target.collection;
452
- break;
453
- }
454
- }
455
- }
456
- return {
457
- _id: hit._id,
458
- _score: hit._score,
459
- _source: hit._source,
460
- collection,
461
- highlight: hit.highlight,
462
- index,
463
- };
464
- };
465
- async function formatInnerHits(innerHits) {
466
- if (!innerHits) {
467
- return undefined;
468
- }
469
- const formatted = await Promise.all(Object.entries(innerHits).map(async ([name, innerHit]) => [
470
- name,
471
- await bluebird_1.default.map(innerHit.hits.hits, formatHit),
472
- ]));
473
- return Object.fromEntries(formatted);
474
- }
475
- const hits = await bluebird_1.default.map(body.hits.hits, async (hit) => ({
476
- inner_hits: await formatInnerHits(hit.inner_hits),
477
- ...(await formatHit(hit)),
478
- }));
479
- return {
480
- aggregations: body.aggregations,
481
- hits,
482
- remaining: body.remaining,
483
- scrollId: body._scroll_id,
484
- suggest: body.suggest,
485
- total: body.hits.total.value,
486
- };
487
- }
488
- /**
489
- * Gets the document with given ID
490
- *
491
- * @param {String} index - Index name
492
- * @param {String} collection - Collection name
493
- * @param {String} id - Document ID
494
- *
495
- * @returns {Promise.<{ _id, _version, _source }>}
496
- */
497
- async get(index, collection, id) {
498
- const esRequest = {
499
- id,
500
- index: this._getAlias(index, collection),
501
- };
502
- // Just in case the user make a GET on url /mainindex/test/_search
503
- // Without this test we return something weird: a result.hits.hits with all
504
- // document without filter because the body is empty in HTTP by default
505
- if (esRequest.id === "_search") {
506
- return kerror.reject("services", "storage", "search_as_an_id");
507
- }
508
- this.logger.debug("Get document: %o", esRequest);
509
- try {
510
- const { body } = await this._client.get(esRequest);
511
- return {
512
- _id: body._id,
513
- _source: body._source,
514
- _version: body._version,
515
- };
516
- }
517
- catch (error) {
518
- throw this._esWrapper.formatESError(error);
519
- }
520
- }
521
- /**
522
- * Returns the list of documents matching the ids given in the body param
523
- * NB: Due to internal Kuzzle mechanism, can only be called on a single
524
- * index/collection, using the body { ids: [.. } syntax.
525
- *
526
- * @param {String} index - Index name
527
- * @param {String} collection - Collection name
528
- * @param {Array.<String>} ids - Document IDs
529
- *
530
- * @returns {Promise.<{ items: Array<{ _id, _source, _version }>, errors }>}
531
- */
532
- async mGet(index, collection, ids) {
533
- if (ids.length === 0) {
534
- return { errors: [], items: [] };
535
- }
536
- const esRequest = {
537
- body: {
538
- docs: ids.map((_id) => ({
539
- _id,
540
- _index: this._getAlias(index, collection),
541
- })),
542
- },
543
- };
544
- this.logger.debug("Multi-get documents: %o", esRequest);
545
- let body;
546
- try {
547
- ({ body } = await this._client.mget(esRequest)); // NOSONAR
548
- }
549
- catch (e) {
550
- throw this._esWrapper.formatESError(e);
551
- }
552
- const errors = [];
553
- const items = [];
554
- for (const doc of body.docs) {
555
- if (doc.found) {
556
- items.push({
557
- _id: doc._id,
558
- _source: doc._source,
559
- _version: doc._version,
560
- });
561
- }
562
- else {
563
- errors.push(doc._id);
564
- }
565
- }
566
- return { errors, items };
567
- }
568
- /**
569
- * Counts how many documents match the filter given in body
570
- *
571
- * @param {String} index - Index name
572
- * @param {String} collection - Collection name
573
- * @param {Object} searchBody - Search request body (query, sort, etc.)
574
- *
575
- * @returns {Promise.<Number>} count
576
- */
577
- async count(index, collection, searchBody = {}) {
578
- const esRequest = {
579
- body: this._sanitizeSearchBody(searchBody),
580
- index: this._getAlias(index, collection),
581
- };
582
- this.logger.debug("Count: %o", esRequest);
583
- try {
584
- const { body } = await this._client.count(esRequest);
585
- return body.count;
586
- }
587
- catch (error) {
588
- throw this._esWrapper.formatESError(error);
589
- }
590
- }
591
- /**
592
- * Sends the new document to elasticsearch
593
- * Cleans data to match elasticsearch specifications
594
- *
595
- * @param {String} index - Index name
596
- * @param {String} collection - Collection name
597
- * @param {Object} content - Document content
598
- * @param {Object} options - id (undefined), refresh (undefined), userId (null)
599
- *
600
- * @returns {Promise.<Object>} { _id, _version, _source }
601
- */
602
- async create(index, collection, content, { id, refresh, userId = null, injectKuzzleMeta = true, } = {}) {
603
- (0, requestAssertions_1.assertIsObject)(content);
604
- const esRequest = {
605
- body: content,
606
- id,
607
- index: this._getAlias(index, collection),
608
- op_type: id ? "create" : "index",
609
- refresh,
610
- };
611
- assertNoRouting(esRequest);
612
- assertWellFormedRefresh(esRequest);
613
- // Add metadata
614
- if (injectKuzzleMeta) {
615
- esRequest.body._kuzzle_info = {
616
- author: getKuid(userId),
617
- createdAt: Date.now(),
618
- updatedAt: null,
619
- updater: null,
620
- };
621
- }
622
- this.logger.debug("Create document: %o", esRequest);
623
- try {
624
- const { body } = await this._client.index(esRequest);
625
- return {
626
- _id: body._id,
627
- _source: esRequest.body,
628
- _version: body._version,
629
- };
630
- }
631
- catch (error) {
632
- throw this._esWrapper.formatESError(error);
633
- }
634
- }
635
- /**
636
- * Creates a new document to Elasticsearch, or replace it if it already exist
637
- *
638
- * @param {String} index - Index name
639
- * @param {String} collection - Collection name
640
- * @param {String} id - Document id
641
- * @param {Object} content - Document content
642
- * @param {Object} options - refresh (undefined), userId (null), injectKuzzleMeta (true)
643
- *
644
- * @returns {Promise.<Object>} { _id, _version, _source, created }
645
- */
646
- async createOrReplace(index, collection, id, content, { refresh, userId = null, injectKuzzleMeta = true, } = {}) {
647
- const esRequest = {
648
- body: content,
649
- id,
650
- index: this._getAlias(index, collection),
651
- refresh,
652
- };
653
- assertNoRouting(esRequest);
654
- assertWellFormedRefresh(esRequest);
655
- // Add metadata
656
- if (injectKuzzleMeta) {
657
- esRequest.body._kuzzle_info = {
658
- author: getKuid(userId),
659
- createdAt: Date.now(),
660
- updatedAt: Date.now(),
661
- updater: getKuid(userId),
662
- };
663
- }
664
- this.logger.debug("Create or replace document: %o", esRequest);
665
- try {
666
- const { body } = await this._client.index(esRequest);
667
- return {
668
- _id: body._id,
669
- _source: esRequest.body,
670
- _version: body._version,
671
- created: body.result === "created", // Needed by the notifier
672
- };
673
- }
674
- catch (error) {
675
- throw this._esWrapper.formatESError(error);
676
- }
677
- }
678
- /**
679
- * Sends the partial document to elasticsearch with the id to update
680
- *
681
- * @param {String} index - Index name
682
- * @param {String} collection - Collection name
683
- * @param {String} id - Document id
684
- * @param {Object} content - Updated content
685
- * @param {Object} options - refresh (undefined), userId (null), retryOnConflict (0)
686
- *
687
- * @returns {Promise.<{ _id, _version }>}
688
- */
689
- async update(index, collection, id, content, { refresh, userId = null, retryOnConflict, injectKuzzleMeta = true, } = {}) {
690
- const esRequest = {
691
- _source: "true",
692
- body: { doc: content },
693
- id,
694
- index: this._getAlias(index, collection),
695
- refresh,
696
- retry_on_conflict: retryOnConflict || this._config.defaults.onUpdateConflictRetries,
697
- };
698
- assertNoRouting(esRequest);
699
- assertWellFormedRefresh(esRequest);
700
- if (injectKuzzleMeta) {
701
- // Add metadata
702
- esRequest.body.doc._kuzzle_info = {
703
- updatedAt: Date.now(),
704
- updater: getKuid(userId),
705
- };
706
- }
707
- this.logger.debug("Update document: %o", esRequest);
708
- try {
709
- const { body } = await this._client.update(esRequest);
710
- return {
711
- _id: body._id,
712
- _source: body.get._source,
713
- _version: body._version,
714
- };
715
- }
716
- catch (error) {
717
- throw this._esWrapper.formatESError(error);
718
- }
719
- }
720
- /**
721
- * Sends the partial document to elasticsearch with the id to update
722
- * Creates the document if it doesn't already exist
723
- *
724
- * @param {String} index - Index name
725
- * @param {String} collection - Collection name
726
- * @param {String} id - Document id
727
- * @param {Object} content - Updated content
728
- * @param {Object} options - defaultValues ({}), refresh (undefined), userId (null), retryOnConflict (0)
729
- *
730
- * @returns {Promise.<{ _id, _version }>}
731
- */
732
- async upsert(index, collection, id, content, { defaultValues = {}, refresh, userId = null, retryOnConflict, injectKuzzleMeta = true, } = {}) {
733
- const esRequest = {
734
- _source: "true",
735
- body: {
736
- doc: content,
737
- upsert: { ...defaultValues, ...content },
738
- },
739
- id,
740
- index: this._getAlias(index, collection),
741
- refresh,
742
- retry_on_conflict: retryOnConflict || this._config.defaults.onUpdateConflictRetries,
743
- };
744
- assertNoRouting(esRequest);
745
- assertWellFormedRefresh(esRequest);
746
- // Add metadata
747
- const user = getKuid(userId);
748
- const now = Date.now();
749
- if (injectKuzzleMeta) {
750
- esRequest.body.doc._kuzzle_info = {
751
- updatedAt: now,
752
- updater: user,
753
- };
754
- esRequest.body.upsert._kuzzle_info = {
755
- author: user,
756
- createdAt: now,
757
- };
758
- }
759
- this.logger.debug("Upsert document: %o", esRequest);
760
- try {
761
- const { body } = await this._client.update(esRequest);
762
- return {
763
- _id: body._id,
764
- _source: body.get._source,
765
- _version: body._version,
766
- created: body.result === "created",
767
- };
768
- }
769
- catch (error) {
770
- throw this._esWrapper.formatESError(error);
771
- }
772
- }
773
- /**
774
- * Replaces a document to Elasticsearch
775
- *
776
- * @param {String} index - Index name
777
- * @param {String} collection - Collection name
778
- * @param {String} id - Document id
779
- * @param {Object} content - Document content
780
- * @param {Object} options - refresh (undefined), userId (null)
781
- *
782
- * @returns {Promise.<{ _id, _version, _source }>}
783
- */
784
- async replace(index, collection, id, content, { refresh, userId = null, injectKuzzleMeta = true, } = {}) {
785
- const alias = this._getAlias(index, collection);
786
- const esRequest = {
787
- body: content,
788
- id,
789
- index: alias,
790
- refresh,
791
- };
792
- assertNoRouting(esRequest);
793
- assertWellFormedRefresh(esRequest);
794
- if (injectKuzzleMeta) {
795
- // Add metadata
796
- esRequest.body._kuzzle_info = {
797
- author: getKuid(userId),
798
- createdAt: Date.now(),
799
- updatedAt: Date.now(),
800
- updater: getKuid(userId),
801
- };
802
- }
803
- try {
804
- const { body: exists } = await this._client.exists({ id, index: alias });
805
- if (!exists) {
806
- throw kerror.get("services", "storage", "not_found", id, index, collection);
807
- }
808
- this.logger.debug("Replace document: %o", esRequest);
809
- const { body } = await this._client.index(esRequest);
810
- return {
811
- _id: id,
812
- _source: esRequest.body,
813
- _version: body._version,
814
- };
815
- }
816
- catch (error) {
817
- throw this._esWrapper.formatESError(error);
818
- }
819
- }
820
- /**
821
- * Sends to elasticsearch the document id to delete
822
- *
823
- * @param {String} index - Index name
824
- * @param {String} collection - Collection name
825
- * @param {String} id - Document id
826
- * @param {Object} options - refresh (undefined)
827
- *
828
- * @returns {Promise}
829
- */
830
- async delete(index, collection, id, { refresh, } = {}) {
831
- const esRequest = {
832
- id,
833
- index: this._getAlias(index, collection),
834
- refresh,
835
- };
836
- assertWellFormedRefresh(esRequest);
837
- this.logger.debug("Delete document: %o", esRequest);
838
- try {
839
- await this._client.delete(esRequest);
840
- }
841
- catch (error) {
842
- throw this._esWrapper.formatESError(error);
843
- }
844
- return null;
845
- }
846
- /**
847
- * Deletes all documents matching the provided filters.
848
- * If fetch=false, the max documents write limit is not applied.
849
- *
850
- * Options:
851
- * - size: size of the batch to retrieve documents (no-op if fetch=false)
852
- * - refresh: refresh option for ES
853
- * - fetch: if true, will fetch the documents before delete them
854
- *
855
- * @param {String} index - Index name
856
- * @param {String} collection - Collection name
857
- * @param {Object} query - Query to match documents
858
- * @param {Object} options - size (undefined), refresh (undefined), fetch (true)
859
- *
860
- * @returns {Promise.<{ documents, total, deleted, failures: Array<{ _shardId, reason }> }>}
861
- */
862
- async deleteByQuery(index, collection, query, { refresh, size = 1000, fetch = true, } = {}) {
863
- const esRequest = {
864
- body: this._sanitizeSearchBody({ query }),
865
- index: this._getAlias(index, collection),
866
- scroll: "5s",
867
- size,
868
- };
869
- if (!(0, safeObject_1.isPlainObject)(query)) {
870
- throw kerror.get("services", "storage", "missing_argument", "body.query");
871
- }
872
- try {
873
- let documents = [];
874
- if (fetch) {
875
- documents = await this._getAllDocumentsFromQuery(esRequest);
876
- }
877
- this.logger.debug("Delete by query: %o", esRequest);
878
- esRequest.refresh = refresh === "wait_for" ? true : refresh;
879
- const { body } = await this._client.deleteByQuery(esRequest);
880
- return {
881
- deleted: body.deleted,
882
- documents,
883
- failures: (body.failures ?? []).map(({ shardId, reason }) => ({
884
- reason,
885
- shardId,
886
- })),
887
- total: body.total,
888
- };
889
- }
890
- catch (error) {
891
- throw this._esWrapper.formatESError(error);
892
- }
893
- }
894
- /**
895
- * Delete fields of a document and replace it
896
- *
897
- * @param {String} index - Index name
898
- * @param {String} collection - Collection name
899
- * @param {String} id - Document id
900
- * @param {Array} fields - Document fields to be removed
901
- * @param {Object} options - refresh (undefined), userId (null)
902
- *
903
- * @returns {Promise.<{ _id, _version, _source }>}
904
- */
905
- async deleteFields(index, collection, id, fields, { refresh, userId = null, } = {}) {
906
- const alias = this._getAlias(index, collection);
907
- const esRequest = {
908
- id,
909
- index: alias,
910
- };
911
- try {
912
- this.logger.debug("DeleteFields document: %o", esRequest);
913
- const { body } = await this._client.get(esRequest);
914
- for (const field of fields) {
915
- if (lodash_1.default.has(body._source, field)) {
916
- lodash_1.default.set(body._source, field, undefined);
917
- }
918
- }
919
- body._source._kuzzle_info = {
920
- ...body._source._kuzzle_info,
921
- updatedAt: Date.now(),
922
- updater: getKuid(userId),
923
- };
924
- const newEsRequest = {
925
- body: body._source,
926
- id,
927
- index: alias,
928
- refresh,
929
- };
930
- assertNoRouting(newEsRequest);
931
- assertWellFormedRefresh(newEsRequest);
932
- const { body: updated } = await this._client.index(newEsRequest);
933
- return {
934
- _id: id,
935
- _source: body._source,
936
- _version: updated._version,
937
- };
938
- }
939
- catch (error) {
940
- throw this._esWrapper.formatESError(error);
941
- }
942
- }
943
- /**
944
- * Updates all documents matching the provided filters
945
- *
946
- * @param {String} index - Index name
947
- * @param {String} collection - Collection name
948
- * @param {Object} query - Query to match documents
949
- * @param {Object} changes - Changes wanted on documents
950
- * @param {Object} options - refresh (undefined), size (undefined)
951
- *
952
- * @returns {Promise.<{ successes: [_id, _source, _status], errors: [ document, status, reason ] }>}
953
- */
954
- async updateByQuery(index, collection, query, changes, { refresh, size = 1000, userId = null, } = {}) {
955
- try {
956
- const esRequest = {
957
- body: this._sanitizeSearchBody({ query }),
958
- index: this._getAlias(index, collection),
959
- scroll: "5s",
960
- size,
961
- };
962
- const documents = await this._getAllDocumentsFromQuery(esRequest);
963
- for (const document of documents) {
964
- document._source = undefined;
965
- document.body = changes;
966
- }
967
- this.logger.debug("Update by query: %o", esRequest);
968
- const { errors, items } = await this.mUpdate(index, collection, documents, { refresh, userId });
969
- return {
970
- errors,
971
- successes: items,
972
- };
973
- }
974
- catch (error) {
975
- throw this._esWrapper.formatESError(error);
976
- }
977
- }
978
- /**
979
- * Updates all documents matching the provided filters
980
- *
981
- * @param {String} index - Index name
982
- * @param {String} collection - Collection name
983
- * @param {Object} query - Query to match documents
984
- * @param {Object} changes - Changes wanted on documents
985
- * @param {Object} options - refresh (undefined)
986
- *
987
- * @returns {Promise.<{ successes: [_id, _source, _status], errors: [ document, status, reason ] }>}
988
- */
989
- async bulkUpdateByQuery(index, collection, query, changes, { refresh = false, } = {}) {
990
- // `body` is optional on the request params, so the script is written
991
- // through the local the request holds by reference rather than read back
992
- // off the request.
993
- const requestBody = {
994
- query: this._sanitizeSearchBody({ query }).query,
995
- };
996
- const esRequest = {
997
- body: requestBody,
998
- index: this._getAlias(index, collection),
999
- refresh,
1000
- };
1001
- const script = {
1002
- params: {},
1003
- source: "",
1004
- };
1005
- const flatChanges = (0, extractFields_1.default)(changes, { alsoExtractValues: true });
1006
- for (const { key, value } of flatChanges) {
1007
- script.source += `ctx._source.${key} = params['${key}'];`;
1008
- script.params[key] = value;
1009
- }
1010
- if (script.source !== "") {
1011
- requestBody.script = script;
1012
- }
1013
- this.logger.debug("Bulk Update by query: %o", esRequest);
1014
- let response;
1015
- try {
1016
- response = await this._client.updateByQuery(esRequest);
1017
- }
1018
- catch (error) {
1019
- throw this._esWrapper.formatESError(error);
1020
- }
1021
- const failures = response.body.failures ?? [];
1022
- if (failures.length) {
1023
- const errors = failures.map(({ shardId, reason }) => ({
1024
- reason,
1025
- shardId,
1026
- }));
1027
- throw kerror.get("services", "storage", "incomplete_update", response.body.updated, errors);
1028
- }
1029
- return {
1030
- updated: response.body.updated,
1031
- };
1032
- }
1033
- /**
1034
- * Execute the callback with a batch of documents of specified size until all
1035
- * documents matched by the query have been processed.
1036
- *
1037
- * @param {String} index - Index name
1038
- * @param {String} collection - Collection name
1039
- * @param {Object} query - Query to match documents
1040
- * @param {Function} callback - callback that will be called with the "hits" array
1041
- * @param {Object} options - size (10), scrollTTL ('5s')
1042
- *
1043
- * @returns {Promise.<any[]>} Array of results returned by the callback
1044
- */
1045
- async mExecute(index, collection, query, callback, { size = 10, scrollTTl = "5s", } = {}) {
1046
- const esRequest = {
1047
- body: this._sanitizeSearchBody({ query }),
1048
- from: 0,
1049
- index: this._getAlias(index, collection),
1050
- scroll: scrollTTl,
1051
- size,
1052
- };
1053
- if (!(0, safeObject_1.isPlainObject)(query)) {
1054
- throw kerror.get("services", "storage", "missing_argument", "body.query");
1055
- }
1056
- const client = this._client;
1057
- let results = [];
1058
- let processed = 0;
1059
- let scrollId;
1060
- try {
1061
- results = await new bluebird_1.default((resolve, reject) => {
1062
- this._client.search(esRequest, async function getMoreUntilDone(error, { body: { hits, _scroll_id } }) {
1063
- if (error) {
1064
- reject(error);
1065
- return;
1066
- }
1067
- scrollId = _scroll_id;
1068
- const ret = callback(hits.hits);
1069
- results.push(await ret);
1070
- processed += hits.hits.length;
1071
- if (hits.total.value !== processed) {
1072
- client.scroll({
1073
- scroll: esRequest.scroll,
1074
- scroll_id: _scroll_id,
1075
- }, getMoreUntilDone);
1076
- }
1077
- else {
1078
- resolve(results);
1079
- }
1080
- });
1081
- });
1082
- }
1083
- finally {
1084
- // Not awaited, but not left unhandled either: a scroll that cannot be
1085
- // cleared expires on its own.
1086
- this.clearScroll(scrollId).catch((error) => {
1087
- this.logger.warn(`Unable to clear scroll ${scrollId}: ${error instanceof Error ? error.message : String(error)}`);
1088
- });
1089
- }
1090
- return results;
1091
- }
1092
- /**
1093
- * Creates a new index.
1094
- *
1095
- * This methods creates an hidden collection in the provided index to be
1096
- * able to list it.
1097
- * This methods resolves if the index name does not already exists either as
1098
- * private or public index.
1099
- *
1100
- * @param {String} index - Index name
1101
- *
1102
- * @returns {Promise}
1103
- */
1104
- async createIndex(index) {
1105
- this._assertValidIndexAndCollection(index);
1106
- let body;
1107
- try {
1108
- body = await this._catAliases();
1109
- }
1110
- catch (error) {
1111
- throw this._esWrapper.formatESError(error);
1112
- }
1113
- const aliases = body.map(({ alias: name }) => name);
1114
- for (const alias of aliases) {
1115
- const indexName = this._extractIndex(alias);
1116
- if (index === indexName) {
1117
- const indexType = alias[INDEX_PREFIX_POSITION_IN_ALIAS] === PRIVATE_PREFIX
1118
- ? "private"
1119
- : "public";
1120
- throw kerror.get("services", "storage", "index_already_exists", indexType, index);
1121
- }
1122
- }
1123
- await this._createHiddenCollection(index);
1124
- return null;
1125
- }
1126
- /**
1127
- * Creates an empty collection.
1128
- * Mappings and settings will be applied if supplied.
1129
- *
1130
- * @param {String} index - Index name
1131
- * @param {String} collection - Collection name
1132
- * @param {Object} config - mappings ({}), settings ({})
1133
- *
1134
- * @returns {Promise}
1135
- */
1136
- async createCollection(index, collection, { mappings = {}, settings = {}, } = {}) {
1137
- this._assertValidIndexAndCollection(index, collection);
1138
- if (collection === HIDDEN_COLLECTION) {
1139
- throw kerror.get("services", "storage", "collection_reserved", HIDDEN_COLLECTION);
1140
- }
1141
- const requestBody = {
1142
- aliases: {
1143
- [this._getAlias(index, collection)]: {},
1144
- },
1145
- mappings: {},
1146
- settings,
1147
- };
1148
- const esRequest = {
1149
- body: requestBody,
1150
- index: await this._getAvailableIndice(index, collection),
1151
- wait_for_active_shards: await this._getWaitForActiveShards(),
1152
- };
1153
- this._checkDynamicProperty(mappings);
1154
- const exists = await this.hasCollection(index, collection);
1155
- if (exists) {
1156
- return this._updateConcurrentlyCreatedCollection(index, collection, mappings, settings);
1157
- }
1158
- this._checkMappings(mappings);
1159
- // Copies, not in-place changes: the race branch below must hand the
1160
- // caller's own mappings and settings to `updateCollection`
1161
- requestBody.mappings = {
1162
- _meta: mappings._meta || this._config.commonMapping._meta,
1163
- dynamic: mappings.dynamic || this._config.commonMapping.dynamic,
1164
- properties: lodash_1.default.merge({}, mappings.properties, this._config.commonMapping.properties),
1165
- };
1166
- requestBody.settings = {
1167
- ...settings,
1168
- number_of_replicas: settings.number_of_replicas ||
1169
- this._config.defaultSettings.number_of_replicas,
1170
- number_of_shards: settings.number_of_shards ||
1171
- this._config.defaultSettings.number_of_shards,
1172
- };
1173
- try {
1174
- await this._client.indices.create(esRequest);
1175
- }
1176
- catch (error) {
1177
- if (lodash_1.default.get(error, "meta.body.error.type") ===
1178
- "resource_already_exists_exception") {
1179
- // race condition: the indice has been created between the "exists"
1180
- // check above and this "create" attempt, by a request that may not
1181
- // have waited for its shards yet. This request's mappings and
1182
- // settings must still be applied, as if it had seen it exist
1183
- return this._updateConcurrentlyCreatedCollection(index, collection, mappings, settings);
1184
- }
1185
- throw this._esWrapper.formatESError(error);
1186
- }
1187
- // Only once the real collection exists: dropping the placeholder first
1188
- // would leave the index with no indice at all if the creation failed.
1189
- // Lock and ES errors alike reach the caller through `formatESError`
1190
- try {
1191
- await (0, distributedLock_1.withLock)(`hiddenCollection/create/${index}`, async () => {
1192
- if (await this._hasHiddenCollection(index)) {
1193
- await this.deleteCollection(index, HIDDEN_COLLECTION);
1194
- }
1195
- }, HIDDEN_COLLECTION_LOCK);
1196
- }
1197
- catch (error) {
1198
- throw this._esWrapper.formatESError(error);
1199
- }
1200
- return null;
1201
- }
1202
- /**
1203
- * Applies the mappings and settings of a `createCollection` call to a
1204
- * collection that already exists because another request created it,
1205
- * maybe so recently that its primary shards are still initializing.
1206
- */
1207
- async _updateConcurrentlyCreatedCollection(index, collection, mappings, settings) {
1208
- await this.waitForCollectionShards(index, collection);
1209
- return this.updateCollection(index, collection, { mappings, settings });
1210
- }
1211
- /**
1212
- * Waits until the primary shards of a collection are active, for at most
1213
- * `timeout`, and rejects if they are not by then.
1214
- *
1215
- * A collection another node has just created is in the cluster state, so
1216
- * it exists, before its primary shard is active: until then, Elasticsearch
1217
- * answers 503 to any document request on it. The node that creates a
1218
- * collection waits for its shards (`wait_for_active_shards`); a node that
1219
- * finds it already there calls this instead. It answers at once when the
1220
- * shards are already active.
1221
- *
1222
- * A `yellow` status alone does not wait: Elasticsearch reports a new index
1223
- * whose primaries are still initializing as `yellow` (#3074). Asking for as
1224
- * many active shard copies as the index has primaries does, and, unlike
1225
- * `wait_for_no_initializing_shards`, does not also wait for replicas that
1226
- * are recovering, which a collection with data may take longer to do.
1227
- */
1228
- async waitForCollectionShards(index, collection, timeout = COLLECTION_SHARDS_TIMEOUT) {
1229
- const alias = this._getAlias(index, collection);
1230
- try {
1231
- const { body } = await this._client.indices.getSettings({
1232
- index: alias,
1233
- name: "index.number_of_shards",
1234
- });
1235
- const primaries = Object.values(body)[0]?.settings?.index?.number_of_shards;
1236
- await this._client.cluster.health({
1237
- index: alias,
1238
- timeout,
1239
- wait_for_active_shards: String(primaries ?? 1),
1240
- wait_for_status: "yellow",
1241
- });
1242
- }
1243
- catch (error) {
1244
- throw this._esWrapper.formatESError(error);
1245
- }
1246
- }
1247
- /**
1248
- * Retrieves settings definition for index/type
1249
- *
1250
- * @param {String} index - Index name
1251
- * @param {String} collection - Collection name
1252
- *
1253
- * @returns {Promise.<{ settings }>}
1254
- */
1255
- async getSettings(index, collection) {
1256
- const indice = await this._getIndice(index, collection);
1257
- const esRequest = {
1258
- index: indice,
1259
- };
1260
- this.logger.debug("Get settings: %o", esRequest);
1261
- try {
1262
- const { body } = await this._client.indices.getSettings(esRequest);
1263
- return body[indice].settings.index;
1264
- }
1265
- catch (error) {
1266
- throw this._esWrapper.formatESError(error);
1267
- }
1268
- }
1269
- /**
1270
- * Retrieves mapping definition for index/type
1271
- *
1272
- * @param {String} index - Index name
1273
- * @param {String} collection - Collection name
1274
- * @param {Object} options - includeKuzzleMeta (false)
1275
- *
1276
- * @returns {Promise.<{ dynamic, _meta, properties }>}
1277
- */
1278
- async getMapping(index, collection, { includeKuzzleMeta = false, } = {}) {
1279
- const indice = await this._getIndice(index, collection);
1280
- const esRequest = {
1281
- index: indice,
1282
- };
1283
- this.logger.debug("Get mapping: %o", esRequest);
1284
- try {
1285
- const { body } = await this._client.indices.getMapping(esRequest);
1286
- const properties = includeKuzzleMeta
1287
- ? body[indice].mappings.properties
1288
- : lodash_1.default.omit(body[indice].mappings.properties, "_kuzzle_info");
1289
- return {
1290
- _meta: body[indice].mappings._meta,
1291
- dynamic: body[indice].mappings.dynamic,
1292
- properties,
1293
- };
1294
- }
1295
- catch (error) {
1296
- throw this._esWrapper.formatESError(error);
1297
- }
1298
- }
1299
- /**
1300
- * Updates a collection mappings and settings
1301
- *
1302
- * @param {String} index - Index name
1303
- * @param {String} collection - Collection name
1304
- * @param {Object} config - mappings ({}), settings ({})
1305
- *
1306
- * @returns {Promise}
1307
- */
1308
- async updateCollection(index, collection, { mappings = {}, reindexCollection = false, settings = {}, } = {}) {
1309
- const esRequest = {
1310
- index: await this._getIndice(index, collection),
1311
- };
1312
- // If either the putMappings or the putSettings operation fail, we need to
1313
- // rollback the whole operation. Since mappings can't be rollback, we try to
1314
- // update the settings first, then the mappings and we rollback the settings
1315
- // if putMappings fail.
1316
- let indexSettings;
1317
- try {
1318
- indexSettings = await this._getSettings(esRequest);
1319
- }
1320
- catch (error) {
1321
- throw this._esWrapper.formatESError(error);
1322
- }
1323
- if (!lodash_1.default.isEmpty(settings)) {
1324
- await this.updateSettings(index, collection, settings);
1325
- }
1326
- try {
1327
- if (!lodash_1.default.isEmpty(mappings)) {
1328
- const previousMappings = await this.getMapping(index, collection, {
1329
- includeKuzzleMeta: true,
1330
- });
1331
- await this.updateMapping(index, collection, mappings);
1332
- if (reindexCollection ||
1333
- this._dynamicChanges(previousMappings, mappings)) {
1334
- await this.updateSearchIndex(index, collection);
1335
- }
1336
- }
1337
- }
1338
- catch (error) {
1339
- const allowedSettings = this.getAllowedIndexSettings(indexSettings);
1340
- // Rollback to previous settings
1341
- if (!lodash_1.default.isEmpty(settings)) {
1342
- await this.updateSettings(index, collection, allowedSettings);
1343
- }
1344
- throw error;
1345
- }
1346
- return null;
1347
- }
1348
- /**
1349
- * Given index settings we return a new version of index settings
1350
- * only with allowed settings that can be set (during update or create index).
1351
- * @param indexSettings the index settings
1352
- * @returns {{index: *}} a new index settings with only allowed settings.
1353
- */
1354
- getAllowedIndexSettings(indexSettings) {
1355
- return {
1356
- index: lodash_1.default.omit(indexSettings.index, [
1357
- "creation_date",
1358
- "provided_name",
1359
- "uuid",
1360
- "version",
1361
- ]),
1362
- };
1363
- }
1364
- /**
1365
- * Sends an empty UpdateByQuery request to update the search index
1366
- *
1367
- * @param {String} index - Index name
1368
- * @param {String} collection - Collection name
1369
- * @returns {Promise.<Object>} {}
1370
- */
1371
- async updateSearchIndex(index, collection) {
1372
- const esRequest = {
1373
- body: {},
1374
- // @cluster: conflicts when two nodes start at the same time
1375
- conflicts: "proceed",
1376
- index: this._getAlias(index, collection),
1377
- refresh: true,
1378
- // This operation can take some time: this should be an ES
1379
- // background task. And it's preferable to a request timeout when
1380
- // processing large indexes.
1381
- wait_for_completion: false,
1382
- };
1383
- this.logger.debug("UpdateByQuery: %o", esRequest);
1384
- try {
1385
- await this._client.updateByQuery(esRequest);
1386
- }
1387
- catch (error) {
1388
- throw this._esWrapper.formatESError(error);
1389
- }
1390
- }
1391
- /**
1392
- * Update a collection mappings
1393
- *
1394
- * @param {String} index - Index name
1395
- * @param {String} collection - Collection name
1396
- * @param {Object} mappings - Collection mappings in ES format
1397
- *
1398
- * @returns {Promise.<{ dynamic, _meta, properties }>}
1399
- */
1400
- async updateMapping(index, collection, mappings = {}) {
1401
- const esRequest = {
1402
- body: {},
1403
- index: this._getAlias(index, collection),
1404
- };
1405
- this._checkDynamicProperty(mappings);
1406
- const collectionMappings = await this.getMapping(index, collection, {
1407
- includeKuzzleMeta: true,
1408
- });
1409
- this._checkMappings(mappings);
1410
- esRequest.body = {
1411
- _meta: mappings._meta || collectionMappings._meta,
1412
- dynamic: mappings.dynamic || collectionMappings.dynamic,
1413
- properties: mappings.properties,
1414
- };
1415
- this.logger.debug("Update mapping: %o", esRequest);
1416
- try {
1417
- await this._client.indices.putMapping(esRequest);
1418
- }
1419
- catch (error) {
1420
- throw this._esWrapper.formatESError(error);
1421
- }
1422
- const fullProperties = lodash_1.default.merge(collectionMappings.properties, mappings.properties);
1423
- return {
1424
- _meta: esRequest.body._meta,
1425
- dynamic: esRequest.body.dynamic,
1426
- properties: fullProperties,
1427
- };
1428
- }
1429
- /**
1430
- * Updates a collection settings (eg: analyzers)
1431
- *
1432
- * @param {String} index - Index name
1433
- * @param {String} collection - Collection name
1434
- * @param {Object} settings - Collection settings in ES format
1435
- *
1436
- * @returns {Promise}
1437
- */
1438
- async updateSettings(index, collection, settings = {}) {
1439
- const esRequest = {
1440
- index: this._getAlias(index, collection),
1441
- };
1442
- await this._client.indices.close(esRequest);
1443
- try {
1444
- await this._client.indices.putSettings({ ...esRequest, body: settings });
1445
- }
1446
- catch (error) {
1447
- throw this._esWrapper.formatESError(error);
1448
- }
1449
- finally {
1450
- await this._client.indices.open(esRequest);
1451
- }
1452
- return null;
1453
- }
1454
- /**
1455
- * Empties the content of a collection. Keep the existing mapping and settings.
1456
- *
1457
- * @param {String} index - Index name
1458
- * @param {String} collection - Collection name
1459
- *
1460
- * @returns {Promise}
1461
- */
1462
- async truncateCollection(index, collection) {
1463
- let mappings;
1464
- let settings;
1465
- const esRequest = {
1466
- index: await this._getIndice(index, collection),
1467
- };
1468
- try {
1469
- mappings = await this.getMapping(index, collection, {
1470
- includeKuzzleMeta: true,
1471
- });
1472
- settings = await this._getSettings(esRequest);
1473
- settings = {
1474
- ...settings,
1475
- ...this.getAllowedIndexSettings(settings),
1476
- };
1477
- await this._client.indices.delete(esRequest);
1478
- await this._client.indices.create({
1479
- ...esRequest,
1480
- body: {
1481
- aliases: {
1482
- [this._getAlias(index, collection)]: {},
1483
- },
1484
- mappings,
1485
- settings,
1486
- },
1487
- wait_for_active_shards: await this._getWaitForActiveShards(),
1488
- });
1489
- return null;
1490
- }
1491
- catch (error) {
1492
- throw this._esWrapper.formatESError(error);
1493
- }
1494
- }
1495
- /**
1496
- * Runs several action and document
1497
- *
1498
- * @param {String} index - Index name
1499
- * @param {String} collection - Collection name
1500
- * @param {Object[]} documents - Documents to import
1501
- * @param {Object} options - timeout (undefined), refresh (undefined), userId (null)
1502
- *
1503
- * @returns {Promise.<{ items, errors }>
1504
- */
1505
- async import(index, collection, documents, { refresh, timeout, userId = null, } = {}) {
1506
- const alias = this._getAlias(index, collection);
1507
- const dateNow = Date.now();
1508
- const esRequest = {
1509
- body: documents,
1510
- refresh,
1511
- timeout,
1512
- };
1513
- const kuzzleMeta = {
1514
- created: {
1515
- author: getKuid(userId),
1516
- createdAt: dateNow,
1517
- updatedAt: null,
1518
- updater: null,
1519
- },
1520
- updated: {
1521
- updatedAt: dateNow,
1522
- updater: getKuid(userId),
1523
- },
1524
- };
1525
- assertWellFormedRefresh(esRequest);
1526
- this._scriptCheck(documents);
1527
- this._setLastActionToKuzzleMeta(esRequest, alias, kuzzleMeta);
1528
- let response;
1529
- try {
1530
- response = await this._client.bulk(esRequest);
1531
- }
1532
- catch (error) {
1533
- throw this._esWrapper.formatESError(error);
1534
- }
1535
- const body = response.body;
1536
- const result = {
1537
- errors: [],
1538
- items: [],
1539
- };
1540
- let idx = 0;
1541
- /**
1542
- * @warning Critical code section
1543
- *
1544
- * bulk body can contain more than 10K elements
1545
- */
1546
- for (const row of body.items) {
1547
- // Elasticsearch answers exactly one action per row; a row carrying none
1548
- // describes no document, so there is nothing to report on it.
1549
- const [action = ""] = Object.keys(row);
1550
- const item = Object.values(row)[0];
1551
- if (item === undefined) {
1552
- continue;
1553
- }
1554
- if (item.status >= 400) {
1555
- result.errors.push({
1556
- [action]: this._importError(action, item, documents[idx + 1]),
1557
- });
1558
- }
1559
- else {
1560
- result.items.push({
1561
- [action]: {
1562
- _id: item._id,
1563
- status: item.status,
1564
- },
1565
- });
1566
- }
1567
- // the delete action is not followed by an action payload
1568
- idx = action === "delete" ? idx + 1 : idx + 2;
1569
- }
1570
- /* end critical code section */
1571
- return result;
1572
- }
1573
- /**
1574
- * The error entry `import` reports for one rejected bulk row.
1575
- *
1576
- * @param action - the bulk action Elasticsearch echoed back
1577
- * @param item - that action's answer
1578
- * @param payload - the action's payload, absent for a delete
1579
- */
1580
- _importError(action, item, payload) {
1581
- const error = {
1582
- _id: item._id,
1583
- status: item.status,
1584
- };
1585
- // update action contain body in "doc" field
1586
- // the delete action is not followed by an action payload
1587
- if (action !== "delete") {
1588
- const source = (action === "update" ? payload?.doc : payload) ?? {};
1589
- source._kuzzle_info = undefined;
1590
- error._source = source;
1591
- }
1592
- // ES response does not systematicaly include an error object
1593
- // (e.g. delete action with 404 status)
1594
- if (item.error) {
1595
- error.error = {
1596
- reason: item.error.reason,
1597
- type: item.error.type,
1598
- };
1599
- }
1600
- return error;
1601
- }
1602
- /**
1603
- * Retrieves the complete list of existing collections in the current index
1604
- *
1605
- * @param {String} index - Index name
1606
- * @param {Object.Boolean} includeHidden - Optional: include HIDDEN_COLLECTION in results
1607
- *
1608
- * @returns {Promise.<Array>} Collection names
1609
- */
1610
- async listCollections(index, { includeHidden = false } = {}) {
1611
- let body;
1612
- try {
1613
- body = await this._catAliases();
1614
- }
1615
- catch (error) {
1616
- throw this._esWrapper.formatESError(error);
1617
- }
1618
- const aliases = body.map(({ alias }) => alias);
1619
- const schema = this._extractSchema(aliases, { includeHidden });
1620
- return schema[index] || [];
1621
- }
1622
- /**
1623
- * Retrieves the complete list of indexes
1624
- *
1625
- * @returns {Promise.<Array>} Index names
1626
- */
1627
- async listIndexes() {
1628
- let body;
1629
- try {
1630
- body = await this._catAliases();
1631
- }
1632
- catch (error) {
1633
- throw this._esWrapper.formatESError(error);
1634
- }
1635
- const aliases = body.map(({ alias }) => alias);
1636
- const schema = this._extractSchema(aliases);
1637
- return Object.keys(schema);
1638
- }
1639
- /**
1640
- * Returns an object containing the list of indexes and collections
1641
- *
1642
- * @returns {Object.<String, String[]>} Object<index, collections>
1643
- */
1644
- async getSchema() {
1645
- let body;
1646
- try {
1647
- body = await this._catAliases();
1648
- }
1649
- catch (error) {
1650
- throw this._esWrapper.formatESError(error);
1651
- }
1652
- const aliases = body.map(({ alias }) => alias);
1653
- const schema = this._extractSchema(aliases, { includeHidden: true });
1654
- for (const [index, collections] of Object.entries(schema)) {
1655
- schema[index] = collections.filter((c) => c !== HIDDEN_COLLECTION);
1656
- }
1657
- return schema;
1658
- }
1659
- /**
1660
- * Retrieves the complete list of aliases
1661
- *
1662
- * @returns {Promise.<Object[]>} [ { alias, index, collection, indice } ]
1663
- */
1664
- async listAliases() {
1665
- let body;
1666
- try {
1667
- body = await this._catAliases();
1668
- }
1669
- catch (error) {
1670
- throw this._esWrapper.formatESError(error);
1671
- }
1672
- const aliases = [];
1673
- for (const { alias, index: indice } of body) {
1674
- if (alias[INDEX_PREFIX_POSITION_IN_ALIAS] === this._indexPrefix) {
1675
- aliases.push({
1676
- alias,
1677
- collection: this._extractCollection(alias),
1678
- index: this._extractIndex(alias),
1679
- indice,
1680
- });
1681
- }
1682
- }
1683
- return aliases;
1684
- }
1685
- /**
1686
- * Deletes a collection
1687
- *
1688
- * @param {String} index - Index name
1689
- * @param {String} collection - Collection name
1690
- *
1691
- * @returns {Promise}
1692
- */
1693
- async deleteCollection(index, collection) {
1694
- const indice = await this._getIndice(index, collection);
1695
- const esRequest = {
1696
- index: indice,
1697
- };
1698
- try {
1699
- await this._client.indices.delete(esRequest);
1700
- const alias = this._getAlias(index, collection);
1701
- if (await this._checkIfAliasExists(alias)) {
1702
- await this._client.indices.deleteAlias({
1703
- index: indice,
1704
- name: alias,
1705
- });
1706
- }
1707
- // `createCollection` drops the placeholder through here: recreating it
1708
- // would undo that.
1709
- if (collection !== HIDDEN_COLLECTION) {
1710
- await this._createHiddenCollection(index);
1711
- }
1712
- }
1713
- catch (e) {
1714
- throw this._esWrapper.formatESError(e);
1715
- }
1716
- return null;
1717
- }
1718
- /**
1719
- * Deletes multiple indexes
1720
- *
1721
- * @param {String[]} indexes - Index names
1722
- *
1723
- * @returns {Promise.<String[]>}
1724
- */
1725
- async deleteIndexes(indexes = []) {
1726
- if (indexes.length === 0) {
1727
- return bluebird_1.default.resolve([]);
1728
- }
1729
- const deleted = new Set();
1730
- try {
1731
- const body = await this._catAliases();
1732
- const esRequest = body.reduce((request, { alias, index: indice }) => {
1733
- const index = this._extractIndex(alias);
1734
- if (alias[INDEX_PREFIX_POSITION_IN_ALIAS] !== this._indexPrefix ||
1735
- !indexes.includes(index)) {
1736
- return request;
1737
- }
1738
- deleted.add(index);
1739
- request.index.push(indice);
1740
- return request;
1741
- }, { index: [] });
1742
- if (esRequest.index.length === 0) {
1743
- return [];
1744
- }
1745
- this.logger.debug("Delete indexes: %o", esRequest);
1746
- await this._client.indices.delete(esRequest);
1747
- }
1748
- catch (error) {
1749
- throw this._esWrapper.formatESError(error);
1750
- }
1751
- return Array.from(deleted);
1752
- }
1753
- /**
1754
- * Deletes an index
1755
- *
1756
- * @param {String} index - Index name
1757
- *
1758
- * @returns {Promise}
1759
- */
1760
- async deleteIndex(index) {
1761
- await this.deleteIndexes([index]);
1762
- return null;
1763
- }
1764
- /**
1765
- * Forces a refresh on the collection.
1766
- *
1767
- * /!\ Can lead to some performance issues.
1768
- * cf https://www.elastic.co/guide/en/elasticsearch/guide/current/near-real-time.html for more details
1769
- *
1770
- * @param {String} index - Index name
1771
- * @param {String} collection - Collection name
1772
- *
1773
- * @returns {Promise.<Object>} { _shards }
1774
- */
1775
- async refreshCollection(index, collection) {
1776
- const esRequest = {
1777
- index: this._getAlias(index, collection),
1778
- };
1779
- let _shards;
1780
- try {
1781
- ({
1782
- body: { _shards },
1783
- } = await this._client.indices.refresh(esRequest));
1784
- }
1785
- catch (error) {
1786
- throw this._esWrapper.formatESError(error);
1787
- }
1788
- return { _shards };
1789
- }
1790
- /**
1791
- * Returns true if the document exists
1792
- *
1793
- * @param {String} index - Index name
1794
- * @param {String} collection - Collection name
1795
- * @param {String} id - Document ID
1796
- *
1797
- * @returns {Promise.<boolean>}
1798
- */
1799
- async exists(index, collection, id) {
1800
- const esRequest = {
1801
- id,
1802
- index: this._getAlias(index, collection),
1803
- };
1804
- try {
1805
- const { body: exists } = await this._client.exists(esRequest);
1806
- return exists;
1807
- }
1808
- catch (error) {
1809
- throw this._esWrapper.formatESError(error);
1810
- }
1811
- }
1812
- /**
1813
- * Returns the list of documents existing with the ids given in the body param
1814
- * NB: Due to internal Kuzzle mechanism, can only be called on a single
1815
- * index/collection, using the body { ids: [.. } syntax.
1816
- *
1817
- * @param {String} index - Index name
1818
- * @param {String} collection - Collection name
1819
- * @param {Array.<String>} ids - Document IDs
1820
- *
1821
- * @returns {Promise.<{ items: Array<{ _id, _source, _version }>, errors }>}
1822
- */
1823
- async mExists(index, collection, ids) {
1824
- if (ids.length === 0) {
1825
- return { errors: [], items: [] };
1826
- }
1827
- const esRequest = {
1828
- _source: "false",
1829
- body: {
1830
- docs: ids.map((_id) => ({ _id })),
1831
- },
1832
- index: this._getAlias(index, collection),
1833
- };
1834
- this.logger.debug("mExists: %o", esRequest);
1835
- let body;
1836
- try {
1837
- ({ body } = await this._client.mget(esRequest)); // NOSONAR
1838
- }
1839
- catch (e) {
1840
- throw this._esWrapper.formatESError(e);
1841
- }
1842
- const errors = [];
1843
- const items = [];
1844
- for (let i = 0; i < body.docs.length; i++) {
1845
- const doc = body.docs[i];
1846
- if (doc.found) {
1847
- items.push(doc._id);
1848
- }
1849
- else {
1850
- errors.push(doc._id);
1851
- }
1852
- }
1853
- return { errors, items };
1854
- }
1855
- /**
1856
- * Returns true if the index exists
1857
- *
1858
- * @param {String} index - Index name
1859
- *
1860
- * @returns {Promise.<boolean>}
1861
- */
1862
- async hasIndex(index) {
1863
- const indexes = await this.listIndexes();
1864
- return indexes.some((idx) => idx === index);
1865
- }
1866
- /**
1867
- * Returns true if the collection exists
1868
- *
1869
- * @param {String} index - Index name
1870
- * @param {String} collection - Collection name
1871
- *
1872
- * @returns {Promise.<boolean>}
1873
- */
1874
- async hasCollection(index, collection) {
1875
- const collections = await this.listCollections(index);
1876
- return collections.some((col) => col === collection);
1877
- }
1878
- /**
1879
- * Returns true if the index has the hidden collection
1880
- *
1881
- * @param {String} index - Index name
1882
- *
1883
- * @returns {Promise.<boolean>}
1884
- */
1885
- async _hasHiddenCollection(index) {
1886
- const collections = await this.listCollections(index, {
1887
- includeHidden: true,
1888
- });
1889
- return collections.includes(HIDDEN_COLLECTION);
1890
- }
1891
- /**
1892
- * Creates multiple documents at once.
1893
- * If a content has no id, one is automatically generated and assigned to it.
1894
- * If a content has a specified identifier, it is rejected if it already exists
1895
- *
1896
- * @param {String} index - Index name
1897
- * @param {String} collection - Collection name
1898
- * @param {Object[]} documents - Documents
1899
- * @param {Object} options - timeout (undefined), refresh (undefined), userId (null)
1900
- *
1901
- * @returns {Promise.<Object>} { items, errors }
1902
- */
1903
- async mCreate(index, collection, documents, { refresh, timeout, userId = null, } = {}) {
1904
- const alias = this._getAlias(index, collection), kuzzleMeta = {
1905
- _kuzzle_info: {
1906
- author: getKuid(userId),
1907
- createdAt: Date.now(),
1908
- updatedAt: null,
1909
- updater: null,
1910
- },
1911
- }, { rejected, extractedDocuments, documentsToGet } = this._extractMDocuments(documents, kuzzleMeta, { prepareMGet: true });
1912
- // prepare the mget request, but only for document having a specified id
1913
- const { body } = documentsToGet.length > 0
1914
- ? await this._client.mget({
1915
- body: { docs: documentsToGet },
1916
- index: alias,
1917
- })
1918
- : { body: { docs: [] } };
1919
- const existingDocuments = body.docs;
1920
- const esRequest = {
1921
- body: [],
1922
- index: alias,
1923
- refresh,
1924
- timeout,
1925
- };
1926
- const toImport = [];
1927
- /**
1928
- * @warning Critical code section
1929
- *
1930
- * request can contain more than 10K elements
1931
- */
1932
- let idx = 0;
1933
- for (const document of extractedDocuments) {
1934
- // Documents are retrieved in the same order than we got them from user
1935
- if (typeof document._id === "string" && existingDocuments[idx]) {
1936
- if (existingDocuments[idx].found) {
1937
- document._source._kuzzle_info = undefined;
1938
- rejected.push({
1939
- document: {
1940
- _id: document._id,
1941
- body: document._source,
1942
- },
1943
- reason: "document already exists",
1944
- status: 400,
1945
- });
1946
- }
1947
- else {
1948
- esRequest.body.push({
1949
- index: {
1950
- _id: document._id,
1951
- _index: alias,
1952
- },
1953
- }, document._source);
1954
- toImport.push(document);
1955
- }
1956
- idx++;
1957
- }
1958
- else {
1959
- esRequest.body.push({ index: { _index: alias } }, document._source);
1960
- toImport.push(document);
1961
- }
1962
- }
1963
- /* end critical code section */
1964
- return this._mExecute(esRequest, toImport, rejected);
1965
- }
1966
- /**
1967
- * Creates or replaces multiple documents at once.
1968
- *
1969
- * @param {String} index - Index name
1970
- * @param {String} collection - Collection name
1971
- * @param {Object[]} documents - Documents
1972
- * @param {Object} options - timeout (undefined), refresh (undefined), userId (null), injectKuzzleMeta (false), limits (true)
1973
- *
1974
- * @returns {Promise.<{ items, errors }>
1975
- */
1976
- async mCreateOrReplace(index, collection, documents, { refresh, timeout, userId = null, injectKuzzleMeta = true, limits = true, source = true, } = {}) {
1977
- let kuzzleMeta = {};
1978
- if (injectKuzzleMeta) {
1979
- kuzzleMeta = {
1980
- _kuzzle_info: {
1981
- author: getKuid(userId),
1982
- createdAt: Date.now(),
1983
- updatedAt: null,
1984
- updater: null,
1985
- },
1986
- };
1987
- }
1988
- const alias = this._getAlias(index, collection);
1989
- const esRequest = {
1990
- body: [],
1991
- index: alias,
1992
- refresh,
1993
- timeout,
1994
- };
1995
- const { rejected, extractedDocuments } = this._extractMDocuments(documents, kuzzleMeta);
1996
- /**
1997
- * @warning Critical code section
1998
- *
1999
- * request can contain more than 10K elements
2000
- */
2001
- for (const extractedDocument of extractedDocuments) {
2002
- esRequest.body.push({
2003
- index: {
2004
- _id: extractedDocument._id,
2005
- _index: alias,
2006
- },
2007
- }, extractedDocument._source);
2008
- }
2009
- /* end critical code section */
2010
- return this._mExecute(esRequest, extractedDocuments, rejected, {
2011
- limits,
2012
- source,
2013
- });
2014
- }
2015
- /**
2016
- * Updates multiple documents with one request
2017
- * Replacements are rejected if targeted documents do not exist
2018
- * (like with the normal "update" method)
2019
- *
2020
- * @param {String} index - Index name
2021
- * @param {String} collection - Collection name
2022
- * @param {Object[]} documents - Documents
2023
- * @param {Object} options - timeout (undefined), refresh (undefined), retryOnConflict (0), userId (null)
2024
- *
2025
- * @returns {Promise.<Object>} { items, errors }
2026
- */
2027
- async mUpdate(index, collection, documents, { refresh, retryOnConflict = 0, timeout, userId = null, } = {}) {
2028
- const alias = this._getAlias(index, collection), toImport = [], esRequest = {
2029
- body: [],
2030
- index: alias,
2031
- refresh,
2032
- timeout,
2033
- }, kuzzleMeta = {
2034
- _kuzzle_info: {
2035
- updatedAt: Date.now(),
2036
- updater: getKuid(userId),
2037
- },
2038
- }, { rejected, extractedDocuments } = this._extractMDocuments(documents, kuzzleMeta);
2039
- /**
2040
- * @warning Critical code section
2041
- *
2042
- * request can contain more than 10K elements
2043
- */
2044
- for (const extractedDocument of extractedDocuments) {
2045
- if (typeof extractedDocument._id === "string") {
2046
- // _source: true => makes ES return the updated document source in the
2047
- // response. Required by the real-time notifier component
2048
- esRequest.body.push({
2049
- update: {
2050
- _id: extractedDocument._id,
2051
- _index: alias,
2052
- retry_on_conflict: retryOnConflict ||
2053
- this._config.defaults.onUpdateConflictRetries,
2054
- },
2055
- }, {
2056
- _source: true,
2057
- doc: extractedDocument._source,
2058
- });
2059
- toImport.push(extractedDocument);
2060
- }
2061
- else {
2062
- extractedDocument._source._kuzzle_info = undefined;
2063
- rejected.push({
2064
- document: {
2065
- _id: extractedDocument._id,
2066
- body: extractedDocument._source,
2067
- },
2068
- reason: "document _id must be a string",
2069
- status: 400,
2070
- });
2071
- }
2072
- }
2073
- /* end critical code section */
2074
- const response = await this._mExecute(esRequest, toImport, rejected);
2075
- // with _source: true, ES returns the updated document in
2076
- // response.result.get._source
2077
- // => we replace response.result._source with it so that the notifier
2078
- // module can seamlessly process all kind of m* response*
2079
- response.items = response.items.map((item) => ({
2080
- _id: item._id,
2081
- _source: item.get._source,
2082
- _version: item._version,
2083
- status: item.status,
2084
- }));
2085
- return response;
2086
- }
2087
- /**
2088
- * Creates or replaces multiple documents at once.
2089
- *
2090
- * @param {String} index - Index name
2091
- * @param {String} collection - Collection name
2092
- * @param {Object[]} documents - Documents
2093
- * @param {Object} options - refresh (undefined), retryOnConflict (0), timeout (undefined), userId (null)
2094
- *
2095
- * @returns {Promise.<{ items, errors }>
2096
- */
2097
- async mUpsert(index, collection, documents, { refresh, retryOnConflict = 0, timeout, userId = null, } = {}) {
2098
- const alias = this._getAlias(index, collection);
2099
- const esRequest = {
2100
- body: [],
2101
- refresh,
2102
- timeout,
2103
- };
2104
- const user = getKuid(userId);
2105
- const now = Date.now();
2106
- const kuzzleMeta = {
2107
- doc: {
2108
- _kuzzle_info: {
2109
- updatedAt: now,
2110
- updater: user,
2111
- },
2112
- },
2113
- upsert: {
2114
- _kuzzle_info: {
2115
- author: user,
2116
- createdAt: now,
2117
- },
2118
- },
2119
- };
2120
- const { rejected, extractedDocuments } = this._extractMDocuments(documents, kuzzleMeta, {
2121
- prepareMUpsert: true,
2122
- requireId: true,
2123
- });
2124
- /**
2125
- * @warning Critical code section
2126
- *
2127
- * request can contain more than 10K elements
2128
- */
2129
- for (const extractedDocument of extractedDocuments) {
2130
- esRequest.body.push({
2131
- update: {
2132
- _id: extractedDocument._id,
2133
- _index: alias,
2134
- _source: true,
2135
- retry_on_conflict: retryOnConflict || this._config.defaults.onUpdateConflictRetries,
2136
- },
2137
- }, {
2138
- doc: extractedDocument._source.changes,
2139
- upsert: extractedDocument._source.default,
2140
- });
2141
- // _source: true
2142
- // Makes ES return the updated document source in the response.
2143
- // Required by the real-time notifier component
2144
- }
2145
- /* end critical code section */
2146
- const response = await this._mExecute(esRequest, extractedDocuments, rejected);
2147
- // with _source: true, ES returns the updated document in
2148
- // response.result.get._source
2149
- // => we replace response.result._source with it so that the notifier
2150
- // module can seamlessly process all kind of m* response*
2151
- response.items = response.items.map((item) => ({
2152
- _id: item._id,
2153
- _source: item.get._source,
2154
- _version: item._version,
2155
- created: item.result === "created", // Needed by the notifier
2156
- status: item.status,
2157
- }));
2158
- return response;
2159
- }
2160
- /**
2161
- * Replaces multiple documents at once.
2162
- * Replacements are rejected if targeted documents do not exist
2163
- * (like with the normal "replace" method)
2164
- *
2165
- * @param {String} index - Index name
2166
- * @param {String} collection - Collection name
2167
- * @param {Object[]} documents - Documents
2168
- * @param {Object} options - timeout (undefined), refresh (undefined), userId (null)
2169
- *
2170
- * @returns {Promise.<Object>} { items, errors }
2171
- */
2172
- async mReplace(index, collection, documents, { refresh, timeout, userId = null, } = {}) {
2173
- const alias = this._getAlias(index, collection), kuzzleMeta = {
2174
- _kuzzle_info: {
2175
- author: getKuid(userId),
2176
- createdAt: Date.now(),
2177
- updatedAt: null,
2178
- updater: null,
2179
- },
2180
- }, { rejected, extractedDocuments, documentsToGet } = this._extractMDocuments(documents, kuzzleMeta, {
2181
- prepareMGet: true,
2182
- requireId: true,
2183
- });
2184
- if (documentsToGet.length < 1) {
2185
- return { errors: rejected, items: [] };
2186
- }
2187
- const { body } = await this._client.mget({
2188
- body: { docs: documentsToGet },
2189
- index: alias,
2190
- });
2191
- const existingDocuments = body.docs;
2192
- const esRequest = {
2193
- body: [],
2194
- refresh,
2195
- timeout,
2196
- };
2197
- const toImport = [];
2198
- /**
2199
- * @warning Critical code section
2200
- *
2201
- * request can contain more than 10K elements
2202
- */
2203
- for (const [i, document] of extractedDocuments.entries()) {
2204
- // Documents are retrieved in the same order than we got them from user
2205
- if (existingDocuments[i]?.found) {
2206
- esRequest.body.push({
2207
- index: {
2208
- _id: document._id,
2209
- _index: alias,
2210
- },
2211
- }, document._source);
2212
- toImport.push(document);
2213
- }
2214
- else {
2215
- document._source._kuzzle_info = undefined;
2216
- rejected.push({
2217
- document: {
2218
- _id: document._id,
2219
- body: document._source,
2220
- },
2221
- reason: "document not found",
2222
- status: 404,
2223
- });
2224
- }
2225
- }
2226
- /* end critical code section */
2227
- return this._mExecute(esRequest, toImport, rejected);
2228
- }
2229
- /**
2230
- * Deletes multiple documents with one request
2231
- *
2232
- * @param {String} index - Index name
2233
- * @param {String} collection - Collection name
2234
- * @param {Array.<String>} ids - Documents IDs
2235
- * @param {Object} options - timeout (undefined), refresh (undefined)
2236
- *
2237
- * @returns {Promise.<{ documents, errors }>
2238
- */
2239
- async mDelete(index, collection, ids, { refresh, } = {}) {
2240
- const query = { ids: { values: [] } };
2241
- const validIds = [];
2242
- const partialErrors = [];
2243
- /**
2244
- * @warning Critical code section
2245
- *
2246
- * request can contain more than 10K elements
2247
- */
2248
- for (let i = 0; i < ids.length; i++) {
2249
- const _id = ids[i];
2250
- if (typeof _id === "string") {
2251
- validIds.push(_id);
2252
- }
2253
- else {
2254
- partialErrors.push({
2255
- _id,
2256
- reason: "document _id must be a string",
2257
- status: 400,
2258
- });
2259
- }
2260
- }
2261
- /* end critical code section */
2262
- await this.refreshCollection(index, collection);
2263
- const { items } = await this.mGet(index, collection, validIds);
2264
- let idx = 0;
2265
- /**
2266
- * @warning Critical code section
2267
- *
2268
- * request can contain more than 10K elements
2269
- */
2270
- for (const validId of validIds) {
2271
- const item = items[idx];
2272
- if (item && item._id === validId) {
2273
- query.ids.values.push(validId);
2274
- idx++;
2275
- }
2276
- else {
2277
- partialErrors.push({
2278
- _id: validId,
2279
- reason: "document not found",
2280
- status: 404,
2281
- });
2282
- }
2283
- }
2284
- /* end critical code section */
2285
- // @todo duplicated query to get documents body, mGet here and search in
2286
- // deleteByQuery
2287
- const { documents } = await this.deleteByQuery(index, collection, query, {
2288
- refresh,
2289
- });
2290
- return { documents, errors: partialErrors };
2291
- }
2292
- /**
2293
- * Executes an ES request prepared by mcreate, mupdate, mreplace, mdelete or mwriteDocuments
2294
- * Returns a standardized ES response object, containing the list of
2295
- * successfully performed operations, and the rejected ones
2296
- *
2297
- * @param {Object} esRequest - Elasticsearch request
2298
- * @param {Object[]} documents - Document sources (format: {_id, _source})
2299
- * @param {Object[]} partialErrors - pre-rejected documents
2300
- * @param {Object} options - limits (true)
2301
- *
2302
- * @returns {Promise.<Object[]>} results
2303
- */
2304
- async _mExecute(esRequest, documents, partialErrors = [], { limits = true, source = true } = {}) {
2305
- assertWellFormedRefresh(esRequest);
2306
- if (this._hasExceededLimit(limits, documents)) {
2307
- return kerror.reject("services", "storage", "write_limit_exceeded");
2308
- }
2309
- let items = [];
2310
- if (documents.length > 0) {
2311
- try {
2312
- ({
2313
- body: { items },
2314
- } = await this._client.bulk(esRequest));
2315
- }
2316
- catch (error) {
2317
- throw this._esWrapper.formatESError(error);
2318
- }
2319
- }
2320
- const successes = [];
2321
- /**
2322
- * @warning Critical code section
2323
- *
2324
- * request can contain more than 10K elements
2325
- */
2326
- for (const [i, item] of items.entries()) {
2327
- const result = Object.values(item)[0];
2328
- const document = documents[i];
2329
- // An answer carries exactly one result per document sent; a row without
2330
- // its counterpart is one neither branch below could describe.
2331
- if (result === undefined || document === undefined) {
2332
- continue;
2333
- }
2334
- if (result.status >= 400) {
2335
- partialErrors.push(this._mExecuteRejection(result, document));
2336
- }
2337
- else {
2338
- successes.push({
2339
- _id: result._id,
2340
- _source: source ? document._source : undefined,
2341
- _version: result._version,
2342
- created: result.result === "created",
2343
- get: result.get,
2344
- result: result.result,
2345
- status: result.status, // used by mUpdate to get the full document body
2346
- });
2347
- }
2348
- }
2349
- /* end critical code section */
2350
- return {
2351
- errors: partialErrors, // @todo rename items to documents
2352
- items: successes,
2353
- };
2354
- }
2355
- /**
2356
- * The partial-error entry `_mExecute` reports for one rejected bulk row.
2357
- *
2358
- * A 404 answers no reason of its own, and reports the document by id and
2359
- * body rather than whole, which is what the m* callers read back.
2360
- */
2361
- _mExecuteRejection(result, document) {
2362
- if (result.status === 404) {
2363
- return {
2364
- document: {
2365
- _id: document._id,
2366
- body: document._source,
2367
- },
2368
- reason: "document not found",
2369
- status: result.status,
2370
- };
2371
- }
2372
- return {
2373
- document,
2374
- reason: result.error?.reason,
2375
- status: result.status,
2376
- };
2377
- }
2378
- /**
2379
- * Extracts, injects metadata and validates documents contained
2380
- * in a Request
2381
- *
2382
- * Used by mCreate, mUpdate, mUpsert, mReplace and mCreateOrReplace
2383
- *
2384
- * @param {Object[]} documents - Documents
2385
- * @param {Object} metadata - Kuzzle metadata
2386
- * @param {Object} options - prepareMGet (false), requireId (false)
2387
- *
2388
- * @returns {Object} { rejected, extractedDocuments, documentsToGet }
2389
- */
2390
- _extractMDocuments(documents, metadata, { prepareMGet = false, requireId = false, prepareMUpsert = false } = {}) {
2391
- const rejected = [];
2392
- const extractedDocuments = [];
2393
- const documentsToGet = [];
2394
- /**
2395
- * @warning Critical code section
2396
- *
2397
- * request can contain more than 10K elements
2398
- */
2399
- for (const document of documents) {
2400
- if (!(0, safeObject_1.isPlainObject)(document.body) && !prepareMUpsert) {
2401
- rejected.push({
2402
- document,
2403
- reason: "document body must be an object",
2404
- status: 400,
2405
- });
2406
- }
2407
- else if (!(0, safeObject_1.isPlainObject)(document.changes) && prepareMUpsert) {
2408
- rejected.push({
2409
- document,
2410
- reason: "document changes must be an object",
2411
- status: 400,
2412
- });
2413
- }
2414
- else if (prepareMUpsert &&
2415
- document.default &&
2416
- !(0, safeObject_1.isPlainObject)(document.default)) {
2417
- rejected.push({
2418
- document,
2419
- reason: "document default must be an object",
2420
- status: 400,
2421
- });
2422
- }
2423
- else if (requireId && typeof document._id !== "string") {
2424
- rejected.push({
2425
- document,
2426
- reason: "document _id must be a string",
2427
- status: 400,
2428
- });
2429
- }
2430
- else {
2431
- this._processExtract(prepareMUpsert, prepareMGet, metadata, document, extractedDocuments, documentsToGet);
2432
- }
2433
- }
2434
- /* end critical code section */
2435
- return { documentsToGet, extractedDocuments, rejected };
2436
- }
2437
- _hasExceededLimit(limits, documents) {
2438
- return (limits &&
2439
- documents.length > global.kuzzle.config.limits.documentsWriteCount);
2440
- }
2441
- _processExtract(prepareMUpsert, prepareMGet, metadata, document, extractedDocuments, documentsToGet) {
2442
- let extractedDocument;
2443
- if (prepareMUpsert) {
2444
- if (document.changes !== undefined && document.changes !== null) {
2445
- delete document.changes._kuzzle_info;
2446
- }
2447
- extractedDocument = {
2448
- _source: {
2449
- // Do not use destructuring, it's 10x slower
2450
- changes: Object.assign({}, metadata.doc, document.changes),
2451
- default: Object.assign({}, metadata.upsert, document.changes, document.default),
2452
- },
2453
- };
2454
- }
2455
- else {
2456
- extractedDocument = {
2457
- // Do not use destructuring, it's 10x slower
2458
- _source: Object.assign({}, metadata, document.body),
2459
- };
2460
- }
2461
- if (document._id) {
2462
- extractedDocument._id = document._id;
2463
- }
2464
- extractedDocuments.push(extractedDocument);
2465
- if (prepareMGet && typeof document._id === "string") {
2466
- documentsToGet.push({
2467
- _id: document._id,
2468
- _source: false,
2469
- });
2470
- }
2471
- }
2472
- /**
2473
- * Throws an error if the provided mapping is invalid
2474
- *
2475
- * @param {Object} mapping
2476
- * @throws
2477
- */
2478
- _checkMappings(mapping, path = [], check = true) {
2479
- const properties = Object.keys(mapping);
2480
- const mappingProperties = path.length === 0
2481
- ? ROOT_MAPPING_PROPERTIES
2482
- : [...ROOT_MAPPING_PROPERTIES, ...CHILD_MAPPING_PROPERTIES];
2483
- for (const property of properties) {
2484
- if (check && !mappingProperties.includes(property)) {
2485
- const currentPath = [...path, property].join(".");
2486
- throw kerror.get("services", "storage", "invalid_mapping", currentPath, (0, didYouMean_1.default)(property, mappingProperties));
2487
- }
2488
- if (property === "properties") {
2489
- // type definition level, we don't check
2490
- this._checkMappings(mapping[property], [...path, "properties"], false);
2491
- }
2492
- else if (mapping[property]?.properties) {
2493
- // root properties level, check for "properties", "dynamic" and "_meta"
2494
- this._checkMappings(mapping[property], [...path, property], true);
2495
- }
2496
- }
2497
- }
2498
- /**
2499
- * Given index + collection, returns the associated alias name.
2500
- * Prefer this function to `_getIndice` and `_getAvailableIndice` whenever it is possible.
2501
- *
2502
- * @param {String} index
2503
- * @param {String} collection
2504
- *
2505
- * @returns {String} Alias name (eg: '@&nepali.liia')
2506
- */
2507
- _getAlias(index, collection) {
2508
- return `${ALIAS_PREFIX}${this._indexPrefix}${index}${NAME_SEPARATOR}${collection}`;
2509
- }
2510
- /**
2511
- * Given an alias name, returns the associated index name.
2512
- */
2513
- async _checkIfAliasExists(aliasName) {
2514
- const { body } = await this._client.indices.existsAlias({
2515
- name: aliasName,
2516
- });
2517
- return body;
2518
- }
2519
- /**
2520
- * Given index + collection, returns the associated indice name.
2521
- * Use this function if ES does not accept aliases in the request. Otherwise use `_getAlias`.
2522
- *
2523
- * @param {String} index
2524
- * @param {String} collection
2525
- *
2526
- * @returns {String} Indice name (eg: '&nepali.liia')
2527
- * @throws If there is not exactly one indice associated
2528
- */
2529
- async _getIndice(index, collection) {
2530
- const alias = `${ALIAS_PREFIX}${this._indexPrefix}${index}${NAME_SEPARATOR}${collection}`;
2531
- const body = await this._catAliases(alias);
2532
- const [record] = body;
2533
- if (record === undefined) {
2534
- throw kerror.get("services", "storage", "unknown_index_collection");
2535
- }
2536
- else if (body.length > 1) {
2537
- throw kerror.get("services", "storage", "multiple_indice_alias", `"alias" starting with "${ALIAS_PREFIX}"`, '"indices"');
2538
- }
2539
- return record.index;
2540
- }
2541
- /**
2542
- * Given an ES Request returns the settings of the corresponding indice.
2543
- *
2544
- * @param esRequest the ES Request with wanted settings.
2545
- * @return {Promise<*>} the settings of the indice.
2546
- * @private
2547
- */
2548
- async _getSettings(esRequest) {
2549
- const response = await this._client.indices.getSettings(esRequest);
2550
- const index = esRequest.index;
2551
- return response.body[index].settings;
2552
- }
2553
- /**
2554
- * Given index + collection, returns an available indice name.
2555
- * Use this function when creating the associated indice. Otherwise use `_getAlias`.
2556
- *
2557
- * @param {String} index
2558
- * @param {String} collection
2559
- *
2560
- * @returns {String} Available indice name (eg: '&nepali.liia2')
2561
- */
2562
- async _getAvailableIndice(index, collection) {
2563
- let indice = this._getAlias(index, collection).substring(INDEX_PREFIX_POSITION_IN_ALIAS);
2564
- if (!(await this._client.indices.exists({ index: indice })).body) {
2565
- return indice;
2566
- }
2567
- let notAvailable;
2568
- let suffix;
2569
- do {
2570
- suffix = `.${this._getRandomNumber(100000)}`;
2571
- const overflow = Buffer.from(indice + suffix).length - 255;
2572
- if (overflow > 0) {
2573
- const indiceBuffer = Buffer.from(indice);
2574
- indice = indiceBuffer
2575
- .subarray(0, indiceBuffer.length - overflow)
2576
- .toString();
2577
- }
2578
- const response = await this._client.indices.exists({
2579
- index: indice + suffix,
2580
- });
2581
- notAvailable = response.body;
2582
- } while (notAvailable);
2583
- return indice + suffix;
2584
- }
2585
- /**
2586
- * Given an indice, returns the associated alias name.
2587
- *
2588
- * @param {String} indice
2589
- *
2590
- * @returns {String} Alias name (eg: '@&nepali.liia')
2591
- * @throws If there is not exactly one alias associated that is prefixed with @
2592
- */
2593
- /**
2594
- * `cat.aliases` answers untyped rows whose `alias` and `index` the client
2595
- * declares as optional. Defaulting them once here is what lets every caller
2596
- * index into an alias without repeating the check — and an empty alias fails
2597
- * the index-prefix test every caller applies, which is what a row without one
2598
- * used to throw on.
2599
- */
2600
- async _catAliases(name) {
2601
- const { body } = await this._client.cat.aliases(name === undefined ? { format: "json" } : { format: "json", name });
2602
- return body.map(({ alias, index }) => ({
2603
- alias: alias ?? "",
2604
- index: index ?? "",
2605
- }));
2606
- }
2607
- async _getAliasFromIndice(indice) {
2608
- const { body } = await this._client.indices.getAlias({ index: indice });
2609
- const indiceAliases = body[indice]?.aliases ?? {};
2610
- const [first, ...others] = Object.keys(indiceAliases).filter((alias) => alias.startsWith(ALIAS_PREFIX));
2611
- // The non-empty tuple is what lets every caller read aliases[0] without a
2612
- // guard the throw below already made redundant.
2613
- if (first === undefined) {
2614
- throw kerror.get("services", "storage", "unknown_index_collection");
2615
- }
2616
- return [first, ...others];
2617
- }
2618
- /**
2619
- * Check for each indice whether it has an alias or not.
2620
- * When the latter is missing, create one based on the indice name.
2621
- *
2622
- * This check avoids a breaking change for those who were using Kuzzle before
2623
- * alias attribution for each indice turned into a standard (appear in 2.14.0).
2624
- */
2625
- async generateMissingAliases() {
2626
- try {
2627
- const { body } = await this._client.cat.indices({ format: "json" });
2628
- const indices = body.flatMap(({ index: indice }) => indice === undefined ? [] : [indice]);
2629
- const aliases = await this.listAliases();
2630
- const indicesWithoutAlias = indices.filter((indice) => indice[INDEX_PREFIX_POSITION_IN_INDICE] === this._indexPrefix &&
2631
- !aliases.some((alias) => alias.indice === indice));
2632
- const esRequest = {
2633
- body: { actions: [] },
2634
- };
2635
- for (const indice of indicesWithoutAlias) {
2636
- esRequest.body.actions.push({
2637
- add: { alias: `${ALIAS_PREFIX}${indice}`, index: indice },
2638
- });
2639
- }
2640
- if (esRequest.body.actions.length > 0) {
2641
- await this._client.indices.updateAliases(esRequest);
2642
- }
2643
- }
2644
- catch (error) {
2645
- throw this._esWrapper.formatESError(error);
2646
- }
2647
- }
2648
- /**
2649
- * Throws if index or collection includes forbidden characters
2650
- *
2651
- * @param {String} index
2652
- * @param {String} collection
2653
- */
2654
- _assertValidIndexAndCollection(index, collection = null) {
2655
- if (!this.isIndexNameValid(index)) {
2656
- throw kerror.get("services", "storage", "invalid_index_name", index);
2657
- }
2658
- if (collection !== null && !this.isCollectionNameValid(collection)) {
2659
- throw kerror.get("services", "storage", "invalid_collection_name", collection);
2660
- }
2661
- }
2662
- /**
2663
- * Given an alias, extract the associated index.
2664
- *
2665
- * @param {String} alias
2666
- *
2667
- * @returns {String} Index name
2668
- */
2669
- _extractIndex(alias) {
2670
- return alias.substr(INDEX_PREFIX_POSITION_IN_ALIAS + 1, alias.indexOf(NAME_SEPARATOR) - INDEX_PREFIX_POSITION_IN_ALIAS - 1);
2671
- }
2672
- /**
2673
- * Given an alias, extract the associated collection.
2674
- *
2675
- * @param {String} alias
2676
- *
2677
- * @returns {String} Collection name
2678
- */
2679
- _extractCollection(alias) {
2680
- const separatorPos = alias.indexOf(NAME_SEPARATOR);
2681
- return alias.substr(separatorPos + 1, alias.length);
2682
- }
2683
- /**
2684
- * Given aliases, extract indexes and collections.
2685
- *
2686
- * @param {Array.<String>} aliases
2687
- * @param {Object.Boolean} includeHidden Only refers to `HIDDEN_COLLECTION` occurences. An empty index will still be listed. Default to `false`.
2688
- *
2689
- * @returns {Object.<String, String[]>} Indexes as key and an array of their collections as value
2690
- */
2691
- _extractSchema(aliases, { includeHidden = false } = {}) {
2692
- const schema = {};
2693
- for (const alias of aliases) {
2694
- // `split` always yields a first element; the defaults are what make that
2695
- // readable to the compiler.
2696
- const [indexName = "", collectionName = ""] = alias
2697
- .slice(INDEX_PREFIX_POSITION_IN_ALIAS + 1)
2698
- .split(NAME_SEPARATOR);
2699
- if (alias[INDEX_PREFIX_POSITION_IN_ALIAS] === this._indexPrefix &&
2700
- (collectionName !== HIDDEN_COLLECTION || includeHidden)) {
2701
- const collections = (schema[indexName] ?? (schema[indexName] = []));
2702
- if (!collections.includes(collectionName)) {
2703
- collections.push(collectionName);
2704
- }
2705
- }
2706
- }
2707
- return schema;
2708
- }
2709
- /**
2710
- * Creates the hidden collection on the provided index if it does not already
2711
- * exists
2712
- *
2713
- * @param {String} index Index name
2714
- */
2715
- async _createHiddenCollection(index) {
2716
- try {
2717
- await (0, distributedLock_1.withLock)(`hiddenCollection/${index}`, async () => {
2718
- if (await this._hasHiddenCollection(index)) {
2719
- return;
2720
- }
2721
- const esRequest = {
2722
- body: {
2723
- aliases: {
2724
- [this._getAlias(index, HIDDEN_COLLECTION)]: {},
2725
- },
2726
- settings: {
2727
- number_of_replicas: this._config.defaultSettings.number_of_replicas,
2728
- number_of_shards: this._config.defaultSettings.number_of_shards,
2729
- },
2730
- },
2731
- index: await this._getAvailableIndice(index, HIDDEN_COLLECTION),
2732
- wait_for_active_shards: await this._getWaitForActiveShards(),
2733
- };
2734
- await this._client.indices.create(esRequest);
2735
- }, HIDDEN_COLLECTION_LOCK);
2736
- }
2737
- catch (e) {
2738
- throw this._esWrapper.formatESError(e);
2739
- }
2740
- }
2741
- /**
2742
- * We need to always wait for a minimal number of shards to be available
2743
- * before answering to the client. This is to avoid Elasticsearch node
2744
- * to return a 404 Not Found error when the client tries to index a
2745
- * document in the index.
2746
- * To find the best value for this setting, we need to take into account
2747
- * the number of nodes in the cluster and the number of shards per index.
2748
- */
2749
- async _getWaitForActiveShards() {
2750
- const { body } = await this._client.cat.nodes({ format: "json" });
2751
- const numberOfNodes = body.length;
2752
- if (numberOfNodes > 1) {
2753
- return "all";
2754
- }
2755
- return "1";
2756
- }
2757
- /**
2758
- * Scroll indice in elasticsearch and return all document that match the filter
2759
- * /!\ throws a write_limit_exceed error: this method is intended to be used
2760
- * by deleteByQuery and updateByQuery
2761
- *
2762
- * @param {Object} esRequest - Search request body
2763
- *
2764
- * @returns {Promise.<Array>} resolve to an array of documents
2765
- */
2766
- async _getAllDocumentsFromQuery(esRequest) {
2767
- let { body: { hits, _scroll_id }, } = await this._client.search(esRequest);
2768
- if (hits.total.value > global.kuzzle.config.limits.documentsWriteCount) {
2769
- throw kerror.get("services", "storage", "write_limit_exceeded");
2770
- }
2771
- let documents = hits.hits.map((h) => ({
2772
- _id: h._id,
2773
- _source: h._source,
2774
- }));
2775
- while (hits.total.value !== documents.length) {
2776
- ({
2777
- body: { hits, _scroll_id },
2778
- } = await this._client.scroll({
2779
- scroll: esRequest.scroll,
2780
- scroll_id: _scroll_id,
2781
- }));
2782
- documents = documents.concat(hits.hits.map((h) => ({
2783
- _id: h._id,
2784
- _source: h._source,
2785
- })));
2786
- }
2787
- await this.clearScroll(_scroll_id);
2788
- return documents;
2789
- }
2790
- /**
2791
- * Clean and normalize the searchBody
2792
- * Ensure only allowed parameters are passed to ES
2793
- *
2794
- * @param {Object} searchBody - ES search body (with query, aggregations, sort, etc)
2795
- */
2796
- _sanitizeSearchBody(searchBody = {}) {
2797
- // Only allow a whitelist of top level properties
2798
- for (const key of Object.keys(searchBody)) {
2799
- if (searchBody[key] !== undefined && !this.searchBodyKeys.includes(key)) {
2800
- throw kerror.get("services", "storage", "invalid_search_query", key);
2801
- }
2802
- }
2803
- // Ensure that the body does not include a script
2804
- this._scriptCheck(searchBody);
2805
- // Avoid empty queries that causes ES to respond with an error.
2806
- // Empty queries are turned into match_all queries
2807
- if (lodash_1.default.isEmpty(searchBody.query)) {
2808
- searchBody.query = { match_all: {} };
2809
- }
2810
- return searchBody;
2811
- }
2812
- /**
2813
- * Throw if a script is used in the query.
2814
- *
2815
- * Only Stored Scripts are accepted
2816
- *
2817
- * @param {Object} object
2818
- */
2819
- _scriptCheck(object) {
2820
- for (const [key, value] of Object.entries(object)) {
2821
- if (this.scriptKeys.includes(key)) {
2822
- for (const scriptArg of Object.keys(value)) {
2823
- if (!this.scriptAllowedArgs.includes(scriptArg)) {
2824
- throw kerror.get("services", "storage", "invalid_query_keyword", `${key}.${scriptArg}`);
2825
- }
2826
- }
2827
- }
2828
- // Every object must be checked here, even the ones nested into an array
2829
- else if (typeof value === "object" && value !== null) {
2830
- this._scriptCheck(value);
2831
- }
2832
- }
2833
- }
2834
- /**
2835
- * Checks if a collection name is valid
2836
- * @param {string} name
2837
- * @returns {Boolean}
2838
- */
2839
- isCollectionNameValid(name) {
2840
- return _isObjectNameValid(name);
2841
- }
2842
- /**
2843
- * Checks if a collection name is valid
2844
- * @param {string} name
2845
- * @returns {Boolean}
2846
- */
2847
- isIndexNameValid(name) {
2848
- return _isObjectNameValid(name);
2849
- }
2850
- /**
2851
- * Clears an allocated scroll
2852
- * @param {[type]} id [description]
2853
- * @returns {[type]} [description]
2854
- */
2855
- async clearScroll(id) {
2856
- if (id) {
2857
- this.logger.debug("clearing scroll: %s", id);
2858
- await this._client.clearScroll({ scroll_id: id });
2859
- }
2860
- }
2861
- /**
2862
- * Loads a configuration value from services.storageEngine and assert a valid
2863
- * ms format.
2864
- *
2865
- * @param {String} key - relative path to the key in configuration
2866
- *
2867
- * @returns {Number} milliseconds
2868
- */
2869
- _loadMsConfig(key) {
2870
- const configValue = lodash_1.default.get(this._config, key);
2871
- (0, assert_1.default)(typeof configValue === "string", `services.storageEngine.${key} must be a string.`);
2872
- const parsedValue = (0, ms_1.default)(configValue);
2873
- (0, assert_1.default)(typeof parsedValue === "number", `Invalid parsed value from ms() for services.storageEngine.${key} ("${typeof parsedValue}").`);
2874
- return parsedValue;
2875
- }
2876
- /**
2877
- * Returns true if one of the mappings dynamic property changes value from
2878
- * false to true
2879
- */
2880
- _dynamicChanges(previousMappings, newMappings) {
2881
- const previousValues = findDynamic(previousMappings);
2882
- for (const [path, previousValue] of Object.entries(previousValues)) {
2883
- if (previousValue.toString() !== "false") {
2884
- continue;
2885
- }
2886
- const newValue = lodash_1.default.get(newMappings, path);
2887
- if (newValue && newValue.toString() !== "false") {
2888
- return true;
2889
- }
2890
- }
2891
- return false;
2892
- }
2893
- async waitForElasticsearch() {
2894
- if (esState !== esStateEnum.NONE) {
2895
- while (esState !== esStateEnum.OK) {
2896
- await bluebird_1.default.delay(1000);
2897
- }
2898
- return;
2899
- }
2900
- esState = esStateEnum.AWAITING;
2901
- this.logger.info("[ℹ] Trying to connect to Elasticsearch...");
2902
- while (esState !== esStateEnum.OK) {
2903
- try {
2904
- // Wait for at least 1 shard to be initialized
2905
- const health = await this._client.cluster.health({
2906
- wait_for_no_initializing_shards: true,
2907
- });
2908
- if (health.body.number_of_pending_tasks === 0) {
2909
- this.logger.info("[✔] Elasticsearch is ready");
2910
- esState = esStateEnum.OK;
2911
- }
2912
- else {
2913
- this.logger.info(`[ℹ] Still waiting for Elasticsearch: ${health.body.number_of_pending_tasks} cluster tasks remaining`);
2914
- await bluebird_1.default.delay(1000);
2915
- }
2916
- }
2917
- catch {
2918
- await bluebird_1.default.delay(1000);
2919
- }
2920
- }
2921
- }
2922
- /**
2923
- * Checks if the dynamic properties are correct
2924
- */
2925
- _checkDynamicProperty(mappings) {
2926
- const dynamicProperties = findDynamic(mappings);
2927
- for (const [path, value] of Object.entries(dynamicProperties)) {
2928
- // Prevent common mistake
2929
- if (typeof value === "boolean") {
2930
- lodash_1.default.set(mappings, path, value.toString());
2931
- }
2932
- else if (typeof value !== "string") {
2933
- throw kerror.get("services", "storage", "invalid_mapping", path, "Dynamic property value should be a string.");
2934
- }
2935
- if (!DYNAMIC_PROPERTY_VALUES.includes(value.toString())) {
2936
- throw kerror.get("services", "storage", "invalid_mapping", path, `Incorrect dynamic property value (${value}). Should be one of "${DYNAMIC_PROPERTY_VALUES.join('", "')}"`);
2937
- }
2938
- }
2939
- }
2940
- _setLastActionToKuzzleMeta(esRequest, alias, kuzzleMeta) {
2941
- /**
2942
- * @warning Critical code section
2943
- *
2944
- * bulk body can contain more than 10K elements
2945
- */
2946
- let lastAction = "";
2947
- const actionNames = ["index", "create", "update", "delete"];
2948
- for (const item of esRequest.body) {
2949
- const action = Object.keys(item)[0] ?? "";
2950
- if (actionNames.indexOf(action) !== -1) {
2951
- lastAction = action;
2952
- item[action]._index = alias;
2953
- if (item[action]?._type) {
2954
- item[action]._type = undefined;
2955
- }
2956
- }
2957
- else if (lastAction === "index" || lastAction === "create") {
2958
- item._kuzzle_info = kuzzleMeta.created;
2959
- }
2960
- else if (lastAction === "update") {
2961
- this._setLastActionToKuzzleMetaUpdate(item, kuzzleMeta);
2962
- }
2963
- }
2964
- /* end critical code section */
2965
- }
2966
- _setLastActionToKuzzleMetaUpdate(item, kuzzleMeta) {
2967
- for (const prop of ["doc", "upsert"]) {
2968
- if ((0, safeObject_1.isPlainObject)(item[prop])) {
2969
- item[prop]._kuzzle_info = kuzzleMeta.updated;
2970
- }
2971
- }
2972
- }
2973
- _getRandomNumber(number) {
2974
- return (0, name_generator_1.randomNumber)(number);
2975
- }
2976
- }
2977
- exports.ES7 = ES7;
2978
- /**
2979
- * Finds paths and values of mappings dynamic properties
2980
- *
2981
- * @example
2982
- *
2983
- * findDynamic(mappings);
2984
- * {
2985
- * "properties.metadata.dynamic": "true",
2986
- * "properties.user.properties.address.dynamic": "strict"
2987
- * }
2988
- */
2989
- function findDynamic(mappings, path = [], results = {}) {
2990
- if (mappings.dynamic !== undefined) {
2991
- results[path.concat("dynamic").join(".")] = mappings.dynamic;
2992
- }
2993
- for (const [key, value] of Object.entries(mappings)) {
2994
- if ((0, safeObject_1.isPlainObject)(value)) {
2995
- findDynamic(value, path.concat(key), results);
2996
- }
2997
- }
2998
- return results;
2999
- }
3000
- /**
3001
- * Forbids the use of the _routing ES option
3002
- *
3003
- * @param {Object} esRequest
3004
- * @throws
3005
- */
3006
- function assertNoRouting(esRequest) {
3007
- if (esRequest.body._routing) {
3008
- throw kerror.get("services", "storage", "no_routing");
3009
- }
3010
- }
3011
- /**
3012
- * Checks if the optional "refresh" argument is well-formed
3013
- *
3014
- * @param {Object} esRequest
3015
- * @throws
3016
- */
3017
- function assertWellFormedRefresh(esRequest) {
3018
- if (!["wait_for", "false", false, undefined].includes(esRequest.refresh)) {
3019
- throw kerror.get("services", "storage", "invalid_argument", "refresh", '"wait_for", false');
3020
- }
3021
- }
3022
- function getKuid(userId) {
3023
- if (!userId) {
3024
- return null;
3025
- }
3026
- return String(userId);
3027
- }
3028
- /**
3029
- * Checks if an index or collection name is valid
3030
- *
3031
- * @see https://www.elastic.co/guide/en/elasticsearch/reference/7.4/indices-create-index.html
3032
- *
3033
- * Beware of the length check: ES allows indice names up to 255 bytes, but since
3034
- * in Kuzzle we emulate collections as indices, we have to make sure
3035
- * that the privacy prefix, the index name, the separator and the collection
3036
- * name ALL fit within the 255-bytes limit of Elasticsearch. The simplest way
3037
- * is to limit index and collection names to 126 bytes and document that
3038
- * limitation (prefix(1) + index(1..126) + sep(1) + collection(1..126) = 4..254)
3039
- *
3040
- * @param {string} name
3041
- * @returns {Boolean}
3042
- */
3043
- function _isObjectNameValid(name) {
3044
- if (typeof name !== "string" || name.length === 0) {
3045
- return false;
3046
- }
3047
- if (name.toLowerCase() !== name) {
3048
- return false;
3049
- }
3050
- if (Buffer.from(name).length > 126) {
3051
- return false;
3052
- }
3053
- if (name === "_all") {
3054
- return false;
3055
- }
3056
- for (const forbiddenChar of FORBIDDEN_CHARS) {
3057
- if (name.includes(forbiddenChar)) {
3058
- return false;
3059
- }
3060
- }
3061
- return true;
3062
- }
3063
- //# sourceMappingURL=elasticsearch.js.map