kuzzle 2.60.1 → 2.61.0-beta.1

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 (43) 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/core/backend/backendStorage.js +4 -6
  8. package/dist/lib/core/plugin/pluginContext.js +2 -2
  9. package/dist/lib/core/storage/clientAdapter.d.ts +13 -10
  10. package/dist/lib/core/storage/clientAdapter.js +112 -60
  11. package/dist/lib/core/storage/conformance/capabilityCases.d.ts +3 -0
  12. package/dist/lib/core/storage/conformance/capabilityCases.js +121 -0
  13. package/dist/lib/core/storage/conformance/conformanceContext.d.ts +33 -0
  14. package/dist/lib/core/storage/conformance/conformanceContext.js +97 -0
  15. package/dist/lib/core/storage/conformance/conformanceEnvironment.d.ts +7 -0
  16. package/dist/lib/core/storage/conformance/conformanceEnvironment.js +136 -0
  17. package/dist/lib/core/storage/conformance/coreCases.d.ts +3 -0
  18. package/dist/lib/core/storage/conformance/coreCases.js +381 -0
  19. package/dist/lib/core/storage/conformance/storageDriverConformance.d.ts +53 -0
  20. package/dist/lib/core/storage/conformance/storageDriverConformance.js +89 -0
  21. package/dist/lib/core/storage/indexCache.d.ts +26 -2
  22. package/dist/lib/core/storage/indexCache.js +100 -2
  23. package/dist/lib/core/storage/storageDriverLoader.d.ts +41 -0
  24. package/dist/lib/core/storage/storageDriverLoader.js +276 -0
  25. package/dist/lib/core/storage/storageEngine.js +5 -1
  26. package/dist/lib/core/storage/storageError.d.ts +15 -0
  27. package/dist/lib/core/storage/storageError.js +36 -0
  28. package/dist/lib/kerror/codes/1-services.json +35 -0
  29. package/dist/lib/kerror/codes/8-cluster.json +6 -0
  30. package/dist/lib/service/storage/7/elasticsearch.d.ts +5 -1
  31. package/dist/lib/service/storage/builtInDrivers.d.ts +17 -0
  32. package/dist/lib/service/storage/builtInDrivers.js +61 -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/storageEngine/StorageEngineElasticsearchConfiguration.d.ts +8 -1
  36. package/dist/lib/types/index.d.ts +1 -0
  37. package/dist/lib/types/index.js +1 -0
  38. package/dist/lib/types/storage/StorageDriver.d.ts +306 -0
  39. package/dist/lib/types/storage/StorageDriver.js +41 -0
  40. package/dist/package.json +2 -1
  41. package/package.json +2 -1
  42. package/dist/lib/service/storage/Elasticsearch.d.ts +0 -16
  43. package/dist/lib/service/storage/Elasticsearch.js +0 -48
@@ -0,0 +1,53 @@
1
+ import type { JSONObject } from "../../../types/JSONObject";
2
+ import type { StorageEngineElasticsearch } from "../../../types/config/storageEngine/StorageEngineElasticsearchConfiguration";
3
+ import type { StorageCapability, StorageDriverClass } from "../../../types/storage/StorageDriver";
4
+ /**
5
+ * The test runner functions the kit registers its cases with: vitest's and
6
+ * jest's as they are, mocha's `before` / `after` as `beforeAll` / `afterAll`.
7
+ */
8
+ export type ConformanceTestApi = {
9
+ describe(name: string, body: () => void): unknown;
10
+ it(name: string, body: () => Promise<void>): unknown;
11
+ beforeAll(body: () => Promise<void>): unknown;
12
+ afterAll(body: () => Promise<void>): unknown;
13
+ };
14
+ export type StorageDriverConformanceOptions = {
15
+ /** The driver class, as the package exports it */
16
+ Driver: StorageDriverClass<unknown, StorageEngineElasticsearch>;
17
+ /**
18
+ * The capability groups the driver declares in its manifest: their cases
19
+ * run, the others are skipped
20
+ */
21
+ capabilities: StorageCapability[];
22
+ /**
23
+ * `services.storageEngine` as the driver reads it, merged over Kuzzle's
24
+ * defaults (e.g. `{ client: { node: "http://localhost:9200" } }`)
25
+ */
26
+ config?: JSONObject;
27
+ test: ConformanceTestApi;
28
+ /**
29
+ * Prefix of the indexes the kit creates, then deletes. Each run adds a
30
+ * random suffix.
31
+ * @default "conformance"
32
+ */
33
+ indexPrefix?: string;
34
+ };
35
+ /**
36
+ * Registers the conformance suite of a storage driver: the mandatory core,
37
+ * and each capability group the driver declares.
38
+ *
39
+ * @example
40
+ * // conformance.test.ts, in the driver's repository
41
+ * import { afterAll, beforeAll, describe, it } from "vitest";
42
+ * import { describeStorageDriverConformance } from "kuzzle";
43
+ * import manifest from "../manifest.json";
44
+ * import { MyDriver } from "../lib";
45
+ *
46
+ * describeStorageDriverConformance({
47
+ * Driver: MyDriver,
48
+ * capabilities: manifest.capabilities,
49
+ * config: { client: { node: "http://localhost:9200" } },
50
+ * test: { afterAll, beforeAll, describe, it },
51
+ * });
52
+ */
53
+ export declare function describeStorageDriverConformance(options: StorageDriverConformanceOptions): void;
@@ -0,0 +1,89 @@
1
+ "use strict";
2
+ /*
3
+ * Kuzzle, a backend software, self-hostable and ready to use
4
+ * to power modern apps
5
+ *
6
+ * Copyright 2015-2026 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 __importDefault = (this && this.__importDefault) || function (mod) {
23
+ return (mod && mod.__esModule) ? mod : { "default": mod };
24
+ };
25
+ Object.defineProperty(exports, "__esModule", { value: true });
26
+ exports.describeStorageDriverConformance = describeStorageDriverConformance;
27
+ // The storage driver conformance kit (ADR-0003 step 04): the test suite a
28
+ // driver's repository runs against its real engine. It registers its cases
29
+ // through the test runner's own `describe` / `it` / hooks, and asserts with
30
+ // `node:assert`, so `kuzzle` needs no test runner and loads none.
31
+ const node_crypto_1 = require("node:crypto");
32
+ const merge_1 = __importDefault(require("lodash/merge"));
33
+ const default_config_1 = __importDefault(require("../../../config/default.config"));
34
+ const storeScopeEnum_1 = require("../storeScopeEnum");
35
+ const capabilityCases_1 = require("./capabilityCases");
36
+ const conformanceContext_1 = require("./conformanceContext");
37
+ const conformanceEnvironment_1 = require("./conformanceEnvironment");
38
+ const coreCases_1 = require("./coreCases");
39
+ /**
40
+ * Registers the conformance suite of a storage driver: the mandatory core,
41
+ * and each capability group the driver declares.
42
+ *
43
+ * @example
44
+ * // conformance.test.ts, in the driver's repository
45
+ * import { afterAll, beforeAll, describe, it } from "vitest";
46
+ * import { describeStorageDriverConformance } from "kuzzle";
47
+ * import manifest from "../manifest.json";
48
+ * import { MyDriver } from "../lib";
49
+ *
50
+ * describeStorageDriverConformance({
51
+ * Driver: MyDriver,
52
+ * capabilities: manifest.capabilities,
53
+ * config: { client: { node: "http://localhost:9200" } },
54
+ * test: { afterAll, beforeAll, describe, it },
55
+ * });
56
+ */
57
+ function describeStorageDriverConformance(options) {
58
+ const { test } = options;
59
+ const suffix = (0, node_crypto_1.randomBytes)(4).toString("hex");
60
+ const context = new conformanceContext_1.ConformanceContext(`${options.indexPrefix ?? "conformance"}-${suffix}`, new Set(options.capabilities));
61
+ let removeEnvironment = () => undefined;
62
+ let initialized = false;
63
+ test.describe("Storage driver conformance", () => {
64
+ test.beforeAll(async () => {
65
+ removeEnvironment = (0, conformanceEnvironment_1.installConformanceEnvironment)();
66
+ const config = (0, merge_1.default)(structuredClone(default_config_1.default.services.storageEngine), options.config);
67
+ const publicDriver = new options.Driver(config, storeScopeEnum_1.storeScopeEnum.PUBLIC);
68
+ const privateDriver = new options.Driver(config, storeScopeEnum_1.storeScopeEnum.PRIVATE);
69
+ await publicDriver.init();
70
+ await privateDriver.init();
71
+ context.setDrivers(publicDriver, privateDriver);
72
+ await publicDriver.createIndex(context.index);
73
+ initialized = true;
74
+ });
75
+ test.afterAll(async () => {
76
+ try {
77
+ if (initialized) {
78
+ await context.driver.deleteIndexes([context.index]);
79
+ }
80
+ }
81
+ finally {
82
+ removeEnvironment();
83
+ }
84
+ });
85
+ (0, coreCases_1.coreCases)(test, context);
86
+ (0, capabilityCases_1.capabilityCases)(test, context);
87
+ });
88
+ }
89
+ //# sourceMappingURL=storageDriverConformance.js.map
@@ -61,6 +61,20 @@ export declare class IndexCache {
61
61
  * Remove a collection from the cache
62
62
  */
63
63
  removeCollection(index: string, collection: string): void;
64
+ /**
65
+ * Return a copy of the cached indexes and collections, to pass to
66
+ * `replaceIndexes` once storage has been read
67
+ */
68
+ snapshotIndexes(): Map<string, Set<string>>;
69
+ /**
70
+ * Replace the cached indexes and collections with the stored ones, except
71
+ * those that changed since `snapshot` was taken: such a change landed while
72
+ * storage was read, and is newer than the read (kuzzle#3040).
73
+ *
74
+ * @param stored - Index name -> its collection names, as storage holds them
75
+ * @param snapshot - Taken by `snapshotIndexes` before storage was read
76
+ */
77
+ replaceIndexes(stored: Record<string, string[]>, snapshot: Map<string, Set<string>>): void;
64
78
  /**
65
79
  * Assert that the provided index exists
66
80
  *
@@ -88,9 +102,19 @@ export declare class IndexCache {
88
102
  */
89
103
  removeLock(index: string, collection: string): void;
90
104
  /**
91
- * Remove every cached collection write lock
105
+ * Return a copy of the cached collection write locks, to pass to
106
+ * `replaceLocks` once the stored locks have been read
107
+ */
108
+ snapshotLocks(): Map<string, Map<string, CollectionLock>>;
109
+ /**
110
+ * Replace the cached collection write locks with the stored ones, except
111
+ * those that changed since `snapshot` was taken: such a change landed while
112
+ * the stored locks were read, and is newer than the read (kuzzle#3040).
113
+ *
114
+ * @param stored - The cluster-wide locks
115
+ * @param snapshot - Taken by `snapshotLocks` before the locks were read
92
116
  */
93
- clearLocks(): void;
117
+ replaceLocks(stored: Map<string, Map<string, CollectionLock>>, snapshot: Map<string, Map<string, CollectionLock>>): void;
94
118
  /**
95
119
  * Return a collection write lock, or null if the collection is not locked
96
120
  */
@@ -56,6 +56,26 @@ Object.defineProperty(exports, "__esModule", { value: true });
56
56
  exports.IndexCache = void 0;
57
57
  const kerror = __importStar(require("../../kerror"));
58
58
  const storageError = kerror.wrap("services", "storage");
59
+ /**
60
+ * One index's collections after a reload: the stored ones, except those whose
61
+ * cached state changed between the snapshot (`was`) and now (`is`), which keep
62
+ * their current state.
63
+ */
64
+ function reconcileCollections(stored, was, is) {
65
+ const collections = new Set();
66
+ for (const collection of new Set([
67
+ ...stored,
68
+ ...(was ?? []),
69
+ ...(is ?? []),
70
+ ])) {
71
+ const wasCached = was?.has(collection) ?? false;
72
+ const isCached = is?.has(collection) ?? false;
73
+ if (wasCached === isCached ? stored.has(collection) : isCached) {
74
+ collections.add(collection);
75
+ }
76
+ }
77
+ return collections;
78
+ }
59
79
  class IndexCache {
60
80
  constructor() {
61
81
  /**
@@ -137,6 +157,49 @@ class IndexCache {
137
157
  collections.delete(collection);
138
158
  }
139
159
  }
160
+ /**
161
+ * Return a copy of the cached indexes and collections, to pass to
162
+ * `replaceIndexes` once storage has been read
163
+ */
164
+ snapshotIndexes() {
165
+ return new Map(Array.from(this.indexes, ([index, collections]) => [
166
+ index,
167
+ new Set(collections),
168
+ ]));
169
+ }
170
+ /**
171
+ * Replace the cached indexes and collections with the stored ones, except
172
+ * those that changed since `snapshot` was taken: such a change landed while
173
+ * storage was read, and is newer than the read (kuzzle#3040).
174
+ *
175
+ * @param stored - Index name -> its collection names, as storage holds them
176
+ * @param snapshot - Taken by `snapshotIndexes` before storage was read
177
+ */
178
+ replaceIndexes(stored, snapshot) {
179
+ const current = this.snapshotIndexes();
180
+ const indexes = new Set([
181
+ ...Object.keys(stored),
182
+ ...snapshot.keys(),
183
+ ...current.keys(),
184
+ ]);
185
+ this.indexes.clear();
186
+ for (const index of indexes) {
187
+ const storedCollections = new Set(Object.hasOwn(stored, index) ? stored[index] : []);
188
+ const was = snapshot.get(index);
189
+ const is = current.get(index);
190
+ const indexChanged = (was === undefined) !== (is === undefined);
191
+ // Deleted during the read: its collections went with it.
192
+ if (indexChanged && is === undefined) {
193
+ continue;
194
+ }
195
+ const collections = reconcileCollections(storedCollections, was, is);
196
+ if (indexChanged ||
197
+ Object.hasOwn(stored, index) ||
198
+ collections.size > 0) {
199
+ this.indexes.set(index, collections);
200
+ }
201
+ }
202
+ }
140
203
  /**
141
204
  * Assert that the provided index exists
142
205
  *
@@ -191,10 +254,45 @@ class IndexCache {
191
254
  }
192
255
  }
193
256
  /**
194
- * Remove every cached collection write lock
257
+ * Return a copy of the cached collection write locks, to pass to
258
+ * `replaceLocks` once the stored locks have been read
259
+ */
260
+ snapshotLocks() {
261
+ return new Map(Array.from(this.locks, ([index, collections]) => [
262
+ index,
263
+ new Map(collections),
264
+ ]));
265
+ }
266
+ /**
267
+ * Replace the cached collection write locks with the stored ones, except
268
+ * those that changed since `snapshot` was taken: such a change landed while
269
+ * the stored locks were read, and is newer than the read (kuzzle#3040).
270
+ *
271
+ * @param stored - The cluster-wide locks
272
+ * @param snapshot - Taken by `snapshotLocks` before the locks were read
195
273
  */
196
- clearLocks() {
274
+ replaceLocks(stored, snapshot) {
275
+ const current = this.snapshotLocks();
276
+ const indexes = new Set([
277
+ ...stored.keys(),
278
+ ...snapshot.keys(),
279
+ ...current.keys(),
280
+ ]);
197
281
  this.locks.clear();
282
+ for (const index of indexes) {
283
+ for (const collection of new Set([
284
+ ...(stored.get(index)?.keys() ?? []),
285
+ ...(snapshot.get(index)?.keys() ?? []),
286
+ ...(current.get(index)?.keys() ?? []),
287
+ ])) {
288
+ const was = snapshot.get(index)?.get(collection);
289
+ const is = current.get(index)?.get(collection);
290
+ const lock = was === is ? stored.get(index)?.get(collection) : is;
291
+ if (lock !== undefined) {
292
+ this.setLock(index, collection, lock);
293
+ }
294
+ }
295
+ }
198
296
  }
199
297
  /**
200
298
  * Return a collection write lock, or null if the collection is not locked
@@ -0,0 +1,41 @@
1
+ import type { JSONObject } from "../../types/JSONObject";
2
+ import type { StorageEngineElasticsearch } from "../../types/config/storageEngine/StorageEngineElasticsearchConfiguration";
3
+ import { type StorageCapability, type StorageDriver, type StorageDriverClass, type StorageMappingUpdates, type StorageStatsCapability, type StorageUpdateByQuery } from "../../types/storage/StorageDriver";
4
+ import "../../types/Global";
5
+ /** The methods of the optional capability groups */
6
+ export type CapabilityMethod = keyof (StorageMappingUpdates & StorageStatsCapability & StorageUpdateByQuery);
7
+ /** The methods a driver declaring a capability must have */
8
+ export declare const CAPABILITY_METHODS: Readonly<Record<StorageCapability, readonly CapabilityMethod[]>>;
9
+ export type SelectedStorageDriver = {
10
+ Driver: StorageDriverClass<unknown, StorageEngineElasticsearch>;
11
+ /** The capability groups the driver declares */
12
+ capabilities: ReadonlySet<StorageCapability>;
13
+ /**
14
+ * `<package name>@<version>` of an external driver, `null` for a built-in
15
+ * one: what the cluster nodes compare at join.
16
+ */
17
+ identity: string | null;
18
+ /** The selected driver, for the logs */
19
+ description: string;
20
+ };
21
+ /**
22
+ * The driver class `services.storageEngine` selects.
23
+ *
24
+ * @throws {services.storage_driver.*} if the configured driver cannot be
25
+ * loaded: Kuzzle does not start
26
+ */
27
+ export declare function selectStorageDriver(config: StorageEngineElasticsearch): SelectedStorageDriver;
28
+ /**
29
+ * A new native client of the configured engine, for
30
+ * `app.storage.storageClient`, `app.storage.StorageClient` and
31
+ * `context.constructors.ESClient`.
32
+ */
33
+ export declare function createNativeStorageClient(config: StorageEngineElasticsearch, clientConfig: JSONObject): unknown;
34
+ /**
35
+ * Checks that a driver instance has the methods of the capabilities its
36
+ * driver declares. Done on the instance rather than on the class: a method
37
+ * can be an instance property.
38
+ *
39
+ * @throws {services.storage_driver.invalid_driver}
40
+ */
41
+ export declare function assertDeclaredCapabilities(driver: StorageDriver, { capabilities, description }: SelectedStorageDriver): void;
@@ -0,0 +1,276 @@
1
+ "use strict";
2
+ /*
3
+ * Kuzzle, a backend software, self-hostable and ready to use
4
+ * to power modern apps
5
+ *
6
+ * Copyright 2015-2026 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
+ Object.defineProperty(exports, "__esModule", { value: true });
56
+ exports.CAPABILITY_METHODS = void 0;
57
+ exports.selectStorageDriver = selectStorageDriver;
58
+ exports.createNativeStorageClient = createNativeStorageClient;
59
+ exports.assertDeclaredCapabilities = assertDeclaredCapabilities;
60
+ // The storage driver loader (ADR-0003 step 03): selects the driver class the
61
+ // storage layer runs on. `services.storageEngine.driver` names an npm package,
62
+ // whose manifest is checked before its code is loaded; without it, the
63
+ // built-in Elasticsearch driver of `majorVersion` is selected, as before.
64
+ const node_fs_1 = require("node:fs");
65
+ const path = __importStar(require("node:path"));
66
+ const semver = __importStar(require("semver"));
67
+ const kerror = __importStar(require("../../kerror"));
68
+ const builtInDrivers_1 = require("../../service/storage/builtInDrivers");
69
+ const StorageDriver_1 = require("../../types/storage/StorageDriver");
70
+ require("../../types/Global");
71
+ const driverError = kerror.wrap("services", "storage_driver");
72
+ /** The methods a driver declaring a capability must have */
73
+ exports.CAPABILITY_METHODS = Object.freeze({
74
+ // A search body option, not a method
75
+ aggregations: [],
76
+ mappingUpdates: ["updateMapping", "updateCollection"],
77
+ stats: ["stats"],
78
+ updateByQuery: ["updateByQuery", "bulkUpdateByQuery"],
79
+ });
80
+ /** The built-in drivers implement every capability */
81
+ const BUILT_IN_CAPABILITIES = new Set(StorageDriver_1.STORAGE_CAPABILITIES);
82
+ /**
83
+ * Keyed by the configuration object: the two storage scopes, the cluster and
84
+ * the raw client surfaces all select the same driver, loaded once.
85
+ */
86
+ const selected = new WeakMap();
87
+ /**
88
+ * The driver class `services.storageEngine` selects.
89
+ *
90
+ * @throws {services.storage_driver.*} if the configured driver cannot be
91
+ * loaded: Kuzzle does not start
92
+ */
93
+ function selectStorageDriver(config) {
94
+ let driver = selected.get(config);
95
+ if (driver === undefined) {
96
+ driver =
97
+ config.driver === undefined
98
+ ? selectBuiltInDriver(config)
99
+ : loadExternalDriver(config.driver);
100
+ selected.set(config, driver);
101
+ }
102
+ return driver;
103
+ }
104
+ /**
105
+ * A new native client of the configured engine, for
106
+ * `app.storage.storageClient`, `app.storage.StorageClient` and
107
+ * `context.constructors.ESClient`.
108
+ */
109
+ function createNativeStorageClient(config, clientConfig) {
110
+ return selectStorageDriver(config).Driver.createNativeClient(clientConfig);
111
+ }
112
+ /**
113
+ * Checks that a driver instance has the methods of the capabilities its
114
+ * driver declares. Done on the instance rather than on the class: a method
115
+ * can be an instance property.
116
+ *
117
+ * @throws {services.storage_driver.invalid_driver}
118
+ */
119
+ function assertDeclaredCapabilities(driver, { capabilities, description }) {
120
+ for (const capability of capabilities) {
121
+ for (const method of exports.CAPABILITY_METHODS[capability]) {
122
+ if (typeof driver[method] !== "function") {
123
+ throw driverError.get("invalid_driver", description, `it declares the "${capability}" capability but has no "${method}" method`);
124
+ }
125
+ }
126
+ }
127
+ }
128
+ function selectBuiltInDriver(config) {
129
+ // Without a `majorVersion`, the raw client surfaces have always built an
130
+ // Elasticsearch 7 client.
131
+ const majorVersion = config.majorVersion ?? "7";
132
+ return {
133
+ Driver: (0, builtInDrivers_1.builtInStorageDriver)(majorVersion),
134
+ capabilities: BUILT_IN_CAPABILITIES,
135
+ description: `the built-in Elasticsearch ${majorVersion} driver`,
136
+ identity: null,
137
+ };
138
+ }
139
+ function loadExternalDriver(name) {
140
+ if (typeof name !== "string" || name.length === 0) {
141
+ throw driverError.get("not_found", String(name), "services.storageEngine.driver must be an npm package name");
142
+ }
143
+ const entry = resolveDriver(name);
144
+ const { root, version } = findPackageRoot(name, entry);
145
+ const capabilities = readManifest(name, root);
146
+ const identity = `${name}@${version}`;
147
+ let exported;
148
+ try {
149
+ // The package the configuration names: only known at runtime.
150
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
151
+ exported = require(entry);
152
+ }
153
+ catch (error) {
154
+ throw driverError.get("invalid_driver", identity, messageOf(error));
155
+ }
156
+ return {
157
+ Driver: driverClass(identity, exported),
158
+ capabilities,
159
+ description: identity,
160
+ identity,
161
+ };
162
+ }
163
+ /**
164
+ * Looked up from the application first, then from Kuzzle itself: the
165
+ * application is what installs the driver, next to `kuzzle`.
166
+ */
167
+ function resolveDriver(name) {
168
+ try {
169
+ return require.resolve(name, { paths: [process.cwd(), __dirname] });
170
+ }
171
+ catch (error) {
172
+ throw driverError.get("not_found", name, messageOf(error));
173
+ }
174
+ }
175
+ /**
176
+ * The directory of the driver's own `package.json`, found from its entry
177
+ * point: `<name>/package.json` cannot be resolved when the package's
178
+ * `exports` does not list it.
179
+ */
180
+ function findPackageRoot(name, entry) {
181
+ let dir = path.dirname(entry);
182
+ while (true) {
183
+ const pkg = readJson(path.join(dir, "package.json"));
184
+ if (pkg?.name === name) {
185
+ return { root: dir, version: String(pkg.version) };
186
+ }
187
+ const parent = path.dirname(dir);
188
+ if (parent === dir) {
189
+ throw driverError.get("not_found", name, `no package.json named "${name}" above ${entry}`);
190
+ }
191
+ dir = parent;
192
+ }
193
+ }
194
+ /**
195
+ * @returns The capabilities the manifest declares
196
+ * @throws {services.storage_driver.invalid_manifest}
197
+ * @throws {services.storage_driver.version_mismatch}
198
+ */
199
+ function readManifest(name, root) {
200
+ const manifestPath = path.join(root, "manifest.json");
201
+ let manifest;
202
+ try {
203
+ manifest = readJson(manifestPath, { required: true });
204
+ }
205
+ catch (error) {
206
+ throw driverError.get("invalid_manifest", name, `cannot read ${manifestPath}: ${messageOf(error)}`);
207
+ }
208
+ const { capabilities, kuzzleVersion } = manifest ?? {};
209
+ if (typeof kuzzleVersion !== "string" ||
210
+ semver.validRange(kuzzleVersion) === null) {
211
+ throw driverError.get("invalid_manifest", name, '"kuzzleVersion" must be a semver range');
212
+ }
213
+ const current = global.kuzzle.config.version;
214
+ if (!semver.satisfies(current, kuzzleVersion, { includePrerelease: true })) {
215
+ throw driverError.get("version_mismatch", name, kuzzleVersion, current);
216
+ }
217
+ if (!Array.isArray(capabilities)) {
218
+ throw driverError.get("invalid_manifest", name, '"capabilities" must be an array');
219
+ }
220
+ const declared = new Set();
221
+ for (const capability of capabilities) {
222
+ if (!isStorageCapability(capability)) {
223
+ throw driverError.get("invalid_manifest", name, `unknown capability "${capability}" (known: ${StorageDriver_1.STORAGE_CAPABILITIES.join(", ")})`);
224
+ }
225
+ declared.add(capability);
226
+ }
227
+ return declared;
228
+ }
229
+ /** Typed for a lookup of any manifest value */
230
+ const KNOWN_CAPABILITIES = new Set(StorageDriver_1.STORAGE_CAPABILITIES);
231
+ function isStorageCapability(value) {
232
+ return KNOWN_CAPABILITIES.has(value);
233
+ }
234
+ /** The class a driver package exports, as its module or its `default` */
235
+ function driverClass(identity, exported) {
236
+ const candidate = typeof exported === "object" && exported !== null && "default" in exported
237
+ ? exported.default
238
+ : exported;
239
+ if (!isDriverClass(candidate)) {
240
+ throw driverError.get("invalid_driver", identity, "the package must export a storage driver class, with a static createNativeClient()");
241
+ }
242
+ return candidate;
243
+ }
244
+ /**
245
+ * What can be checked of a class before building it: the contract of its
246
+ * instances is checked once they exist (`assertDeclaredCapabilities`).
247
+ */
248
+ function isDriverClass(value) {
249
+ return (typeof value === "function" &&
250
+ "createNativeClient" in value &&
251
+ typeof value.createNativeClient === "function");
252
+ }
253
+ /**
254
+ * @returns The parsed file, or `null` when it does not exist and is not
255
+ * `required`
256
+ */
257
+ function readJson(file, { required = false } = {}) {
258
+ let content;
259
+ try {
260
+ content = (0, node_fs_1.readFileSync)(file, "utf8");
261
+ }
262
+ catch (error) {
263
+ if (!required &&
264
+ error instanceof Error &&
265
+ "code" in error &&
266
+ error.code === "ENOENT") {
267
+ return null;
268
+ }
269
+ throw error;
270
+ }
271
+ return JSON.parse(content);
272
+ }
273
+ function messageOf(error) {
274
+ return error instanceof Error ? error.message : String(error);
275
+ }
276
+ //# sourceMappingURL=storageDriverLoader.js.map
@@ -24,6 +24,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
24
24
  };
25
25
  const kerror_1 = require("../../kerror");
26
26
  const clientAdapter_1 = __importDefault(require("./clientAdapter"));
27
+ const storageDriverLoader_1 = require("./storageDriverLoader");
27
28
  const storeScopeEnum_1 = require("./storeScopeEnum");
28
29
  require("../../types/Global");
29
30
  const kerror = (0, kerror_1.wrap)("services", "storage");
@@ -34,7 +35,10 @@ class StorageEngine {
34
35
  // Storage client for private indexes only
35
36
  this.private = new clientAdapter_1.default(storeScopeEnum_1.storeScopeEnum.PRIVATE);
36
37
  this.logger = global.kuzzle.log.child("core:storage:storageEngine");
37
- this.logger.info(`[ℹ] Elasticsearch configuration is set to major version : ${global.kuzzle.config.services.storageEngine.majorVersion}`);
38
+ const { description, identity } = (0, storageDriverLoader_1.selectStorageDriver)(global.kuzzle.config.services.storageEngine);
39
+ this.logger.info(identity === null
40
+ ? `[ℹ] Elasticsearch configuration is set to major version : ${global.kuzzle.config.services.storageEngine.majorVersion}`
41
+ : `[ℹ] Storage driver: ${description}`);
38
42
  }
39
43
  /**
40
44
  * Initialize storage clients and perform integrity checks
@@ -0,0 +1,15 @@
1
+ /**
2
+ * The errors a storage driver throws: Kuzzle's `services.storage.*` error
3
+ * codes, with their documented class, status and message (ADR-0003 step 05).
4
+ * An external driver uses them so that a client gets the same error whatever
5
+ * the engine.
6
+ *
7
+ * @example
8
+ * throw storageError.get("not_found", id, index, collection);
9
+ * throw storageError.getFrom(engineError, "unexpected_error", engineError.message);
10
+ */
11
+ export declare const storageError: {
12
+ get: (error: string, ...placeholders: unknown[]) => import("../../..").KuzzleError;
13
+ getFrom: (source: unknown, error: string, ...placeholders: unknown[]) => import("../../..").KuzzleError;
14
+ reject: (error: string, ...placeholders: unknown[]) => Promise<any>;
15
+ };