kuzzle 2.61.0-beta.5 → 2.61.0-beta.7

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 (41) hide show
  1. package/dist/lib/api/controllers/serverController.js +1 -1
  2. package/dist/lib/api/funnel.d.ts +5 -0
  3. package/dist/lib/api/funnel.js +9 -0
  4. package/dist/lib/cluster/idCardHandler.d.ts +41 -19
  5. package/dist/lib/cluster/idCardHandler.js +73 -45
  6. package/dist/lib/cluster/node.d.ts +8 -2
  7. package/dist/lib/cluster/node.js +9 -11
  8. package/dist/lib/cluster/storageDriverCheck.d.ts +31 -0
  9. package/dist/lib/cluster/storageDriverCheck.js +142 -0
  10. package/dist/lib/config/default.config.js +1 -0
  11. package/dist/lib/core/backend/backendStorage.d.ts +9 -0
  12. package/dist/lib/core/backend/backendStorage.js +48 -0
  13. package/dist/lib/core/plugin/pluginContext.d.ts +10 -0
  14. package/dist/lib/core/plugin/pluginContext.js +1 -0
  15. package/dist/lib/core/storage/clientAdapter.d.ts +13 -0
  16. package/dist/lib/core/storage/clientAdapter.js +26 -2
  17. package/dist/lib/core/storage/conformance/capabilityCases.js +41 -0
  18. package/dist/lib/core/storage/conformance/conformanceContext.d.ts +11 -1
  19. package/dist/lib/core/storage/conformance/conformanceContext.js +7 -1
  20. package/dist/lib/core/storage/conformance/coreCases.js +136 -0
  21. package/dist/lib/core/storage/conformance/storageDriverConformance.js +19 -3
  22. package/dist/lib/core/storage/indexCache.d.ts +9 -0
  23. package/dist/lib/core/storage/indexCache.js +20 -1
  24. package/dist/lib/core/storage/storageDriverLoader.d.ts +24 -5
  25. package/dist/lib/core/storage/storageDriverLoader.js +177 -25
  26. package/dist/lib/core/storage/storageEngine.d.ts +11 -0
  27. package/dist/lib/core/storage/storageEngine.js +47 -5
  28. package/dist/lib/kerror/codes/1-services.json +18 -12
  29. package/dist/lib/kerror/codes/2-api.json +1 -1
  30. package/dist/lib/kerror/codes/8-cluster.json +1 -1
  31. package/dist/lib/kuzzle/kuzzle.d.ts +2 -0
  32. package/dist/lib/kuzzle/kuzzle.js +37 -1
  33. package/dist/lib/service/storage/builtInDrivers.d.ts +7 -0
  34. package/dist/lib/service/storage/builtInDrivers.js +18 -35
  35. package/dist/lib/service/storage/driverPackage.d.ts +20 -0
  36. package/dist/lib/service/storage/driverPackage.js +101 -0
  37. package/dist/lib/service/storage/storageService.js +3 -3
  38. package/dist/lib/types/config/storageEngine/StorageEngineElasticsearchConfiguration.d.ts +12 -0
  39. package/dist/lib/types/storage/StorageDriver.d.ts +24 -2
  40. package/dist/package.json +21 -21
  41. package/package.json +21 -21
@@ -1,6 +1,7 @@
1
1
  import { Koncorde } from "../shared/KoncordeWrapper";
2
2
  import type { JSONObject } from "../../types/JSONObject";
3
3
  import { KuzzleRequest, RequestContext, RequestInput } from "../../api/request";
4
+ import type { StorageEngineInfo } from "../../types/storage/StorageDriver";
4
5
  import { Mutex } from "../../util/mutex";
5
6
  import { BackendCluster } from "../backend/backendCluster";
6
7
  import { EmbeddedSDK } from "../shared/sdk/embeddedSdk";
@@ -95,6 +96,15 @@ export declare class PluginContext {
95
96
  */
96
97
  createCollection(collection: string, mappings: unknown): Promise<void>;
97
98
  };
99
+ /**
100
+ * The storage engine Kuzzle runs on: its driver's package, the engine
101
+ * family and the engine server's version. What `constructors.ESClient`'s
102
+ * API follows, unlike `services.storageEngine.majorVersion`.
103
+ *
104
+ * Asks the engine: call it once (e.g. in the plugin's `init()`), not on
105
+ * every request.
106
+ */
107
+ getStorageEngine(): Promise<StorageEngineInfo>;
98
108
  /**
99
109
  * Cluster accessor
100
110
  * @type {BackendCluster}
@@ -160,6 +160,7 @@ class PluginContext {
160
160
  this.accessors = {
161
161
  cluster: new backendCluster_1.BackendCluster(),
162
162
  execute,
163
+ getStorageEngine: storageDriverLoader_1.getStorageEngineInfo,
163
164
  nodeId: global.nodeId,
164
165
  sdk: new embeddedSdk_1.EmbeddedSDK(),
165
166
  storage: {
@@ -31,6 +31,13 @@ declare class ClientAdapter {
31
31
  cache: IndexCache;
32
32
  /** The storage read under way to catch the cache up, shared by its callers */
33
33
  private catchingUp;
34
+ /**
35
+ * When the last catch-up read started, and the cache changes it left: until
36
+ * something changes, the next one waits `catchUpInterval` after it
37
+ */
38
+ private lastCatchUp;
39
+ /** Minimum delay (ms) between two catch-up reads (kuzzle#3140) */
40
+ private readonly catchUpInterval;
34
41
  constructor(scope: storeScopeEnum);
35
42
  init(): Promise<void>;
36
43
  createIndex(index: string, { indexCacheOnly, propagate }?: WriteScopeOptions): Promise<void>;
@@ -59,6 +66,12 @@ declare class ClientAdapter {
59
66
  * waits for: right after a peer creates an index or a collection, a request
60
67
  * this node serves may not find it yet. Storage is asked before such a
61
68
  * request fails, or is answered from the cache alone (kuzzle#3121).
69
+ *
70
+ * Each caller gets a read that starts after it called, as above, but reads
71
+ * start at most once per `catchUpInterval` while the cache does not change:
72
+ * a client looping on a missing index waits instead of costing one full
73
+ * schema read per request (kuzzle#3140). A cached creation or deletion
74
+ * (local, or a peer's broadcast) lifts the wait for the next read.
62
75
  */
63
76
  private catchUpWithStorage;
64
77
  /**
@@ -67,6 +67,8 @@ const servicesError = kerror.wrap("services", "storage");
67
67
  * cluster-wide source of truth that each node mirrors in its index cache.
68
68
  * One field per locked collection: `JSON.stringify([index, collection])`.
69
69
  */
70
+ /** See `services.storageEngine.cacheMissReadInterval` */
71
+ const DEFAULT_CACHE_MISS_READ_INTERVAL = 100;
70
72
  const LOCKS_KEY_PREFIX = "{core/storage}/collection-locks/";
71
73
  /** Hoisted out of the signature: an object literal as a default parameter is
72
74
  * re-allocated on every call, and this one is only ever read. */
@@ -110,14 +112,21 @@ class ClientAdapter {
110
112
  constructor(scope) {
111
113
  /** The storage read under way to catch the cache up, shared by its callers */
112
114
  this.catchingUp = null;
115
+ /**
116
+ * When the last catch-up read started, and the cache changes it left: until
117
+ * something changes, the next one waits `catchUpInterval` after it
118
+ */
119
+ this.lastCatchUp = null;
113
120
  const config = global.kuzzle.config.services.storageEngine;
114
121
  const selected = (0, storageDriverLoader_1.selectStorageDriver)(config);
115
122
  this.service = new storageService_1.StorageService(selected.Driver, config, scope);
116
123
  this.driver = this.service.driver;
117
124
  this.capabilities = selected.capabilities;
118
- (0, storageDriverLoader_1.assertDeclaredCapabilities)(this.driver, selected);
125
+ (0, storageDriverLoader_1.assertDriverContract)(this.driver, selected);
119
126
  this.scope = scope;
120
127
  this.cache = new indexCache_1.IndexCache();
128
+ this.catchUpInterval =
129
+ config.cacheMissReadInterval ?? DEFAULT_CACHE_MISS_READ_INTERVAL;
121
130
  }
122
131
  async init() {
123
132
  await this.service.init();
@@ -280,13 +289,28 @@ class ClientAdapter {
280
289
  * waits for: right after a peer creates an index or a collection, a request
281
290
  * this node serves may not find it yet. Storage is asked before such a
282
291
  * request fails, or is answered from the cache alone (kuzzle#3121).
292
+ *
293
+ * Each caller gets a read that starts after it called, as above, but reads
294
+ * start at most once per `catchUpInterval` while the cache does not change:
295
+ * a client looping on a missing index waits instead of costing one full
296
+ * schema read per request (kuzzle#3140). A cached creation or deletion
297
+ * (local, or a peer's broadcast) lifts the wait for the next read.
283
298
  */
284
299
  catchUpWithStorage() {
285
300
  // Concurrent cache misses share one read
286
301
  this.catchingUp ?? (this.catchingUp = (async () => {
287
- const removals = this.cache.removals;
288
302
  try {
303
+ const last = this.lastCatchUp;
304
+ if (last !== null && last.changes === this.cache.changes) {
305
+ const wait = last.at + this.catchUpInterval - Date.now();
306
+ if (wait > 0) {
307
+ await new Promise((resolve) => setTimeout(resolve, wait));
308
+ }
309
+ }
310
+ const at = Date.now();
311
+ const removals = this.cache.removals;
289
312
  this.cache.learn(await this.driver.getSchema(), removals);
313
+ this.lastCatchUp = { at, changes: this.cache.changes };
290
314
  }
291
315
  finally {
292
316
  this.catchingUp = null;
@@ -31,6 +31,19 @@ const strict_1 = __importDefault(require("node:assert/strict"));
31
31
  const conformanceContext_1 = require("./conformanceContext");
32
32
  const StorageDriver_1 = require("../../../types/storage/StorageDriver");
33
33
  const WAIT = { refresh: "wait_for" };
34
+ /** Polls `condition` until it holds, for at most 10 seconds */
35
+ async function eventually(condition, description) {
36
+ const deadline = Date.now() + 10000;
37
+ const poll = async () => {
38
+ if (await condition()) {
39
+ return;
40
+ }
41
+ strict_1.default.ok(Date.now() < deadline, `timed out waiting until ${description}`);
42
+ await new Promise((resolve) => setTimeout(resolve, 200));
43
+ return poll();
44
+ };
45
+ return poll();
46
+ }
34
47
  const IMPLEMENTED = "a driver declaring a capability implements its methods (Kuzzle checks it when it loads the driver)";
35
48
  const CASES = {
36
49
  aggregations(test, context) {
@@ -70,6 +83,34 @@ const CASES = {
70
83
  strict_1.default.deepEqual((0, conformanceContext_1.field)(mapping, "properties.zip"), { type: "keyword" });
71
84
  strict_1.default.deepEqual((0, conformanceContext_1.field)(mapping, "properties.city"), { type: "keyword" });
72
85
  });
86
+ test.it("adds the new fields of a collection created again", async () => {
87
+ const collection = await context.collection("recreated-mappings");
88
+ await context.driver.createCollection(context.index, collection, {
89
+ mappings: { properties: { country: { type: "keyword" } } },
90
+ });
91
+ const mapping = await context.driver.getMapping(context.index, collection);
92
+ strict_1.default.deepEqual((0, conformanceContext_1.field)(mapping, "properties.country"), {
93
+ type: "keyword",
94
+ });
95
+ strict_1.default.deepEqual((0, conformanceContext_1.field)(mapping, "properties.city"), { type: "keyword" });
96
+ });
97
+ test.it("makes the documents searchable by a new field (reindexCollection)", async () => {
98
+ const collection = context.uniqueName("reindexed");
99
+ await context.driver.createCollection(context.index, collection, {
100
+ mappings: { dynamic: "false", properties: {} },
101
+ });
102
+ await context.driver.create(context.index, collection, { zip: "34000" }, { id: "r1", ...WAIT });
103
+ const { driver } = context;
104
+ strict_1.default.ok(driver.updateCollection, IMPLEMENTED);
105
+ const byZip = { query: { term: { zip: "34000" } } };
106
+ strict_1.default.equal(await driver.count(context.index, collection, byZip), 0);
107
+ await driver.updateCollection(context.index, collection, {
108
+ mappings: { properties: { zip: { type: "keyword" } } },
109
+ reindexCollection: true,
110
+ });
111
+ // The engine may reindex in the background
112
+ await eventually(async () => (await driver.count(context.index, collection, byZip)) === 1, "the document is found by its new field");
113
+ });
73
114
  },
74
115
  stats(test, context) {
75
116
  test.it("answers the document count of each collection", async () => {
@@ -5,12 +5,22 @@ export declare class ConformanceContext {
5
5
  /** The index the kit creates in the public scope, then deletes */
6
6
  readonly index: string;
7
7
  readonly capabilities: ReadonlySet<StorageCapability>;
8
+ /**
9
+ * Builds one more public driver instance, with the kit's configuration,
10
+ * for a case that needs its own (e.g. to close it): that case closes it
11
+ */
12
+ readonly buildDriver: () => StorageDriver;
8
13
  private publicInstance?;
9
14
  private privateInstance?;
10
15
  private collectionCount;
11
16
  constructor(
12
17
  /** The index the kit creates in the public scope, then deletes */
13
- index: string, capabilities: ReadonlySet<StorageCapability>);
18
+ index: string, capabilities: ReadonlySet<StorageCapability>,
19
+ /**
20
+ * Builds one more public driver instance, with the kit's configuration,
21
+ * for a case that needs its own (e.g. to close it): that case closes it
22
+ */
23
+ buildDriver: () => StorageDriver);
14
24
  /** The public scope's driver instance, set before any case runs */
15
25
  get driver(): StorageDriver;
16
26
  /** The private scope's driver instance */
@@ -34,9 +34,15 @@ const has_1 = __importDefault(require("lodash/has"));
34
34
  class ConformanceContext {
35
35
  constructor(
36
36
  /** The index the kit creates in the public scope, then deletes */
37
- index, capabilities) {
37
+ index, capabilities,
38
+ /**
39
+ * Builds one more public driver instance, with the kit's configuration,
40
+ * for a case that needs its own (e.g. to close it): that case closes it
41
+ */
42
+ buildDriver) {
38
43
  this.index = index;
39
44
  this.capabilities = capabilities;
45
+ this.buildDriver = buildDriver;
40
46
  this.collectionCount = 0;
41
47
  }
42
48
  /** The public scope's driver instance, set before any case runs */
@@ -35,6 +35,20 @@ function ids(documents) {
35
35
  .map(({ _id }) => String(_id))
36
36
  .sort((a, b) => a.localeCompare(b));
37
37
  }
38
+ /**
39
+ * Deletes, without fetching them, the Lyon documents of a new collection
40
+ * holding `lyon` of them and one Paris document
41
+ */
42
+ async function deleteLyonUnfetched(context, lyon, size) {
43
+ const deleted = await context.collection("deleted-unfetched");
44
+ await context.driver.mCreate(context.index, deleted, [
45
+ ...Array.from({ length: lyon }, () => ({ body: { city: "Lyon" } })),
46
+ { body: { city: "Paris" } },
47
+ ], WAIT);
48
+ const result = await context.driver.deleteByQuery(context.index, deleted, { term: { city: "Lyon" } }, { fetch: false, ...(size === undefined ? {} : { size }), ...WAIT });
49
+ strict_1.default.equal(await context.driver.count(context.index, deleted), 1);
50
+ return result;
51
+ }
38
52
  function coreCases(test, context) {
39
53
  test.describe("core: engine", () => {
40
54
  test.it("answers its engine type and version", async () => {
@@ -111,6 +125,29 @@ function coreCases(test, context) {
111
125
  strict_1.default.deepEqual(await context.driver.deleteIndexes([index]), [index]);
112
126
  strict_1.default.ok(!Object.hasOwn(await context.driver.getSchema(), index));
113
127
  });
128
+ test.it("deletes indexes, skipping the ones that do not exist", async () => {
129
+ const index = context.uniqueName(`${context.index}-deleted`);
130
+ const missing = context.uniqueName(`${context.index}-missing`);
131
+ await context.driver.createIndex(index);
132
+ strict_1.default.deepEqual(await context.driver.deleteIndexes([index, missing]), [
133
+ index,
134
+ ]);
135
+ strict_1.default.deepEqual(await context.driver.deleteIndexes([missing]), []);
136
+ });
137
+ // `collection:create` on an existing collection: Kuzzle calls the driver
138
+ // as for a new one. What new mappings change there is the
139
+ // `mappingUpdates` capability's.
140
+ test.it("creates a collection that already exists, keeping its documents", async () => {
141
+ const collection = await context.collection("recreated");
142
+ await context.driver.create(context.index, collection, { city: "Lyon" }, WAIT);
143
+ await context.driver.createCollection(context.index, collection, {
144
+ mappings: conformanceContext_1.CONFORMANCE_MAPPINGS,
145
+ });
146
+ const schema = await context.driver.getSchema();
147
+ strict_1.default.ok(schema[context.index]?.includes(collection));
148
+ strict_1.default.equal(await context.driver.count(context.index, collection), 1);
149
+ strict_1.default.deepEqual((0, conformanceContext_1.field)(await context.driver.getMapping(context.index, collection), "properties.city"), { type: "keyword" });
150
+ });
114
151
  });
115
152
  test.describe("core: documents", () => {
116
153
  let collection;
@@ -202,6 +239,49 @@ function coreCases(test, context) {
202
239
  await context.driver.delete(context.index, collection, "del");
203
240
  strict_1.default.equal(await context.driver.exists(context.index, collection, "del"), false);
204
241
  });
242
+ // What `bulk:write` and the document actions run through a pipe do: the
243
+ // document is written as given, with or without `_kuzzle_info`.
244
+ test.it("writes no metadata of its own when told not to (injectKuzzleMeta: false)", async () => {
245
+ const options = { injectKuzzleMeta: false, userId: "author-kuid" };
246
+ const source = async (id) => (await context.driver.get(context.index, collection, id))._source;
247
+ await context.driver.create(context.index, collection, { a: 1 }, { id: "raw-create", ...options });
248
+ strict_1.default.ok(!(0, conformanceContext_1.hasField)(await source("raw-create"), "_kuzzle_info"));
249
+ await context.driver.update(context.index, collection, "raw-create", { b: 2 }, options);
250
+ strict_1.default.ok(!(0, conformanceContext_1.hasField)(await source("raw-create"), "_kuzzle_info"));
251
+ await context.driver.createOrReplace(context.index, collection, "raw-cor", { _kuzzle_info: { author: "given-kuid" }, a: 1 }, options);
252
+ strict_1.default.deepEqual((0, conformanceContext_1.field)(await source("raw-cor"), "_kuzzle_info"), {
253
+ author: "given-kuid",
254
+ });
255
+ await context.driver.replace(context.index, collection, "raw-cor", { c: 3 }, options);
256
+ strict_1.default.ok(!(0, conformanceContext_1.hasField)(await source("raw-cor"), "_kuzzle_info"));
257
+ await context.driver.upsert(context.index, collection, "raw-upsert", { d: 4 }, options);
258
+ strict_1.default.ok(!(0, conformanceContext_1.hasField)(await source("raw-upsert"), "_kuzzle_info"));
259
+ });
260
+ // Twenty concurrent updates of one document, without retries: some meet
261
+ // a version conflict, which Kuzzle answers as `too_many_changes` (the
262
+ // error that tells the client to use `retryOnConflict`).
263
+ test.it("rejects an update meeting a version conflict with too_many_changes", async () => {
264
+ await context.driver.create(context.index, collection, {}, { id: "conflicting" });
265
+ const results = await Promise.allSettled(Array.from({ length: 20 }, (_, value) => context.driver.update(context.index, collection, "conflicting", {
266
+ [`f${value}`]: value,
267
+ })));
268
+ const rejections = results.flatMap((result) => result.status === "rejected" ? [result.reason] : []);
269
+ strict_1.default.ok(rejections.length > 0, "no update met a version conflict");
270
+ for (const error of rejections) {
271
+ strict_1.default.equal((0, conformanceContext_1.field)(error, "id"), "services.storage.too_many_changes", `expected services.storage.too_many_changes, got: ${String(error)}`);
272
+ }
273
+ });
274
+ // Each conflict an update meets means another one went through: with five
275
+ // concurrent updates, four retries each are enough.
276
+ test.it("retries an update on a version conflict, when asked to (retryOnConflict)", async () => {
277
+ await context.driver.create(context.index, collection, {}, { id: "conflicts" });
278
+ const fields = ["f0", "f1", "f2", "f3", "f4"];
279
+ await Promise.all(fields.map((name, value) => context.driver.update(context.index, collection, "conflicts", { [name]: value }, { retryOnConflict: 10 })));
280
+ const { _source } = await context.driver.get(context.index, collection, "conflicts");
281
+ for (const [value, name] of fields.entries()) {
282
+ strict_1.default.equal((0, conformanceContext_1.field)(_source, name), value);
283
+ }
284
+ });
205
285
  });
206
286
  test.describe("core: several documents at once", () => {
207
287
  let collection;
@@ -264,6 +344,28 @@ function coreCases(test, context) {
264
344
  strict_1.default.deepEqual(ids(documents), ["d1", "d2"]);
265
345
  strict_1.default.equal(errors.length, 1);
266
346
  });
347
+ // `bulk:mWrite` writes past the limit (`limits: false`), without
348
+ // metadata, and does not answer the documents' content (`source: false`).
349
+ test.it("applies the write limit to mCreateOrReplace, unless told not to", async () => {
350
+ const limited = context.uniqueName("limited");
351
+ await context.driver.createCollection(context.index, limited);
352
+ const total = global.kuzzle.config.limits.documentsWriteCount + 1;
353
+ const documents = Array.from({ length: total }, (_, n) => ({
354
+ _id: `l${n}`,
355
+ body: { n },
356
+ }));
357
+ await (0, conformanceContext_1.rejectsWith)(context.driver.mCreateOrReplace(context.index, limited, documents), "services.storage.write_limit_exceeded");
358
+ const { errors, items } = await context.driver.mCreateOrReplace(context.index, limited, documents, { injectKuzzleMeta: false, limits: false, source: false, ...WAIT });
359
+ strict_1.default.deepEqual(errors, []);
360
+ strict_1.default.equal(items.length, total);
361
+ for (const item of items) {
362
+ strict_1.default.equal((0, conformanceContext_1.field)(item, "_source"), undefined);
363
+ }
364
+ strict_1.default.equal(await context.driver.count(context.index, limited), total);
365
+ const { _source } = await context.driver.get(context.index, limited, "l0");
366
+ strict_1.default.equal((0, conformanceContext_1.field)(_source, "n"), 0);
367
+ strict_1.default.ok(!(0, conformanceContext_1.hasField)(_source, "_kuzzle_info"));
368
+ });
267
369
  test.it("imports documents in the bulk format", async () => {
268
370
  const imported = context.uniqueName("imported");
269
371
  await context.driver.createCollection(context.index, imported);
@@ -347,6 +449,14 @@ function coreCases(test, context) {
347
449
  strict_1.default.deepEqual([...first.hits, ...second.hits].map(({ _id }) => _id), ["s1", "s2", "s3", "s4"]);
348
450
  strict_1.default.equal(second.remaining, 0);
349
451
  });
452
+ test.it("rejects a scroll that is over, or that it never started", async () => {
453
+ const first = await context.driver.search({ collection, index: context.index, searchBody: {} }, { scroll: "10s", size: 3 });
454
+ const scrollId = String(first.scrollId);
455
+ // The last page: the scroll is over
456
+ await context.driver.scroll(scrollId, { scrollTTL: "10s" });
457
+ await (0, conformanceContext_1.rejectsWith)(context.driver.scroll(scrollId, { scrollTTL: "10s" }), "services.storage.unknown_scroll_id");
458
+ await (0, conformanceContext_1.rejectsWith)(context.driver.scroll("not-a-scroll-id", { scrollTTL: "10s" }), "services.storage.unknown_scroll_id");
459
+ });
350
460
  test.it("runs a callback on every page of documents matching a query", async () => {
351
461
  const pages = await context.driver.mExecute(context.index, collection, { match_all: {} }, (documents) => documents.map(({ _id }) => _id), { size: 3 });
352
462
  strict_1.default.deepEqual(pages
@@ -367,6 +477,18 @@ function coreCases(test, context) {
367
477
  strict_1.default.deepEqual(ids(documents), ["x1"]);
368
478
  strict_1.default.equal(await context.driver.count(context.index, deleted), 1);
369
479
  });
480
+ test.it("deletes the documents matching a query without fetching them (fetch: false)", async () => {
481
+ const result = await deleteLyonUnfetched(context, 2);
482
+ strict_1.default.deepEqual(result.documents, []);
483
+ strict_1.default.equal(result.deleted, 2);
484
+ });
485
+ // What `bulk:deleteByQuery` asks: a negative size is no limit. The first
486
+ // betas of the OpenSearch drivers handed it to the engine, which refused
487
+ // it; only the functional suite caught it.
488
+ test.it("deletes every document matching a query with no limit (size: -1)", async () => {
489
+ const result = await deleteLyonUnfetched(context, 3, -1);
490
+ strict_1.default.equal(result.deleted, 3);
491
+ });
370
492
  });
371
493
  test.describe("core: engine hooks", () => {
372
494
  test.it("waits for a new collection's shards, when the driver can", async () => {
@@ -376,6 +498,20 @@ function coreCases(test, context) {
376
498
  const collection = await context.collection("shards");
377
499
  await context.driver.waitForCollectionShards(context.index, collection, "10s");
378
500
  });
501
+ test.it("closes an instance, leaving the others working, when the driver can", async () => {
502
+ const driver = context.buildDriver();
503
+ if (!driver.close) {
504
+ return;
505
+ }
506
+ try {
507
+ await driver.init();
508
+ strict_1.default.ok(Object.hasOwn(await driver.getSchema(), context.index));
509
+ }
510
+ finally {
511
+ await driver.close();
512
+ }
513
+ strict_1.default.ok(Object.hasOwn(await context.driver.getSchema(), context.index));
514
+ });
379
515
  });
380
516
  }
381
517
  //# sourceMappingURL=coreCases.js.map
@@ -28,6 +28,7 @@ exports.describeStorageDriverConformance = describeStorageDriverConformance;
28
28
  // driver's repository runs against its real engine. It registers its cases
29
29
  // through the test runner's own `describe` / `it` / hooks, and asserts with
30
30
  // `node:assert`, so `kuzzle` needs no test runner and loads none.
31
+ const strict_1 = __importDefault(require("node:assert/strict"));
31
32
  const node_crypto_1 = require("node:crypto");
32
33
  const merge_1 = __importDefault(require("lodash/merge"));
33
34
  const default_config_1 = __importDefault(require("../../../config/default.config"));
@@ -57,15 +58,22 @@ const coreCases_1 = require("./coreCases");
57
58
  function describeStorageDriverConformance(options) {
58
59
  const { test } = options;
59
60
  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 config;
62
+ const context = new conformanceContext_1.ConformanceContext(`${options.indexPrefix ?? "conformance"}-${suffix}`, new Set(options.capabilities), () => {
63
+ strict_1.default.ok(config, "the driver is not initialized");
64
+ return new options.Driver(config, storeScopeEnum_1.storeScopeEnum.PUBLIC);
65
+ });
61
66
  let removeEnvironment = () => undefined;
62
67
  let initialized = false;
68
+ /** Built by the kit, closed at the end of the run, as Kuzzle does */
69
+ const built = [];
63
70
  test.describe("Storage driver conformance", () => {
64
71
  test.beforeAll(async () => {
65
72
  removeEnvironment = (0, conformanceEnvironment_1.installConformanceEnvironment)();
66
- const config = (0, merge_1.default)(structuredClone(default_config_1.default.services.storageEngine), options.config);
73
+ config = (0, merge_1.default)(structuredClone(default_config_1.default.services.storageEngine), options.config);
67
74
  const publicDriver = new options.Driver(config, storeScopeEnum_1.storeScopeEnum.PUBLIC);
68
75
  const privateDriver = new options.Driver(config, storeScopeEnum_1.storeScopeEnum.PRIVATE);
76
+ built.push(publicDriver, privateDriver);
69
77
  await publicDriver.init();
70
78
  await privateDriver.init();
71
79
  context.setDrivers(publicDriver, privateDriver);
@@ -79,7 +87,15 @@ function describeStorageDriverConformance(options) {
79
87
  }
80
88
  }
81
89
  finally {
82
- removeEnvironment();
90
+ try {
91
+ // Even when `init()` failed, as Kuzzle's shutdown does
92
+ await Promise.all(built.map(async (driver) => {
93
+ await driver.close?.();
94
+ }));
95
+ }
96
+ finally {
97
+ removeEnvironment();
98
+ }
83
99
  }
84
100
  });
85
101
  (0, coreCases_1.coreCases)(test, context);
@@ -23,6 +23,11 @@ export declare class IndexCache {
23
23
  * during the read
24
24
  */
25
25
  private removalCount;
26
+ /**
27
+ * How many times an index or a collection entered or left the cache, to
28
+ * tell whether anything changed since storage was last read (kuzzle#3140)
29
+ */
30
+ private changeCount;
26
31
  /**
27
32
  * Collection write locks, a local copy of the cluster-wide state (see
28
33
  * `ClientAdapter`): checking a lock on every write must not cost a round
@@ -71,6 +76,10 @@ export declare class IndexCache {
71
76
  * Removals so far, to pass to `learn` once storage has been read
72
77
  */
73
78
  get removals(): number;
79
+ /**
80
+ * Changes so far: additions and removals alike
81
+ */
82
+ get changes(): number;
74
83
  /**
75
84
  * Add the stored indexes and collections this cache misses, unless one was
76
85
  * removed since `removals` was read: the read may then predate that removal,
@@ -90,6 +90,11 @@ class IndexCache {
90
90
  * during the read
91
91
  */
92
92
  this.removalCount = 0;
93
+ /**
94
+ * How many times an index or a collection entered or left the cache, to
95
+ * tell whether anything changed since storage was last read (kuzzle#3140)
96
+ */
97
+ this.changeCount = 0;
93
98
  /**
94
99
  * Collection write locks, a local copy of the cluster-wide state (see
95
100
  * `ClientAdapter`): checking a lock on every write must not cost a round
@@ -109,6 +114,7 @@ class IndexCache {
109
114
  return false;
110
115
  }
111
116
  this.indexes.set(index, new Set());
117
+ this.changeCount++;
112
118
  return true;
113
119
  }
114
120
  /**
@@ -116,7 +122,11 @@ class IndexCache {
116
122
  */
117
123
  addCollection(index, collection) {
118
124
  this.addIndex(index);
119
- this.getCollections(index).add(collection);
125
+ const collections = this.getCollections(index);
126
+ if (!collections.has(collection)) {
127
+ collections.add(collection);
128
+ this.changeCount++;
129
+ }
120
130
  }
121
131
  /**
122
132
  * Check an index existence
@@ -154,6 +164,7 @@ class IndexCache {
154
164
  removeIndex(index) {
155
165
  this.indexes.delete(index);
156
166
  this.removalCount++;
167
+ this.changeCount++;
157
168
  }
158
169
  /**
159
170
  * Remove a collection from the cache
@@ -164,6 +175,7 @@ class IndexCache {
164
175
  collections.delete(collection);
165
176
  }
166
177
  this.removalCount++;
178
+ this.changeCount++;
167
179
  }
168
180
  /**
169
181
  * Removals so far, to pass to `learn` once storage has been read
@@ -171,6 +183,12 @@ class IndexCache {
171
183
  get removals() {
172
184
  return this.removalCount;
173
185
  }
186
+ /**
187
+ * Changes so far: additions and removals alike
188
+ */
189
+ get changes() {
190
+ return this.changeCount;
191
+ }
174
192
  /**
175
193
  * Add the stored indexes and collections this cache misses, unless one was
176
194
  * removed since `removals` was read: the read may then predate that removal,
@@ -220,6 +238,7 @@ class IndexCache {
220
238
  ]);
221
239
  this.indexes.clear();
222
240
  this.removalCount++;
241
+ this.changeCount++;
223
242
  for (const index of indexes) {
224
243
  const storedCollections = new Set(Object.hasOwn(stored, index) ? stored[index] : []);
225
244
  const was = snapshot.get(index);
@@ -1,9 +1,11 @@
1
1
  import type { JSONObject } from "../../types/JSONObject";
2
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";
3
+ import { type StorageCapability, type StorageDriver, type StorageDriverClass, type StorageDriverCore, type StorageEngineInfo, type StorageMappingUpdates, type StorageStatsCapability, type StorageUpdateByQuery } from "../../types/storage/StorageDriver";
4
4
  import "../../types/Global";
5
5
  /** The methods of the optional capability groups */
6
6
  export type CapabilityMethod = keyof (StorageMappingUpdates & StorageStatsCapability & StorageUpdateByQuery);
7
+ /** The methods every driver must have */
8
+ export declare const CORE_METHODS: readonly (keyof StorageDriverCore)[];
7
9
  /** The methods a driver declaring a capability must have */
8
10
  export declare const CAPABILITY_METHODS: Readonly<Record<StorageCapability, readonly CapabilityMethod[]>>;
9
11
  export type SelectedStorageDriver = {
@@ -15,8 +17,18 @@ export type SelectedStorageDriver = {
15
17
  * one: what the cluster nodes compare at join.
16
18
  */
17
19
  identity: string | null;
20
+ /**
21
+ * The package of a built-in driver (e.g. `kuzzle-storage-es-7`), `null`
22
+ * for an external one: compared at cluster join too, without its version,
23
+ * which comes with Kuzzle's own.
24
+ */
25
+ builtIn: string | null;
18
26
  /** The selected driver, for the logs */
19
27
  description: string;
28
+ /** The driver's package name, built-in or external */
29
+ packageName: string;
30
+ /** The directory an external driver is loaded from, `null` for a built-in one */
31
+ location: string | null;
20
32
  };
21
33
  /**
22
34
  * The driver class `services.storageEngine` selects.
@@ -32,10 +44,17 @@ export declare function selectStorageDriver(config: StorageEngineElasticsearch):
32
44
  */
33
45
  export declare function createNativeStorageClient(config: StorageEngineElasticsearch, clientConfig: JSONObject): unknown;
34
46
  /**
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.
47
+ * The storage engine Kuzzle runs on: the driver's package, and the engine
48
+ * family and server version its `info()` reports. Asks the engine, so only
49
+ * once the storage is initialized.
50
+ */
51
+ export declare function getStorageEngineInfo(): Promise<StorageEngineInfo>;
52
+ /**
53
+ * Checks that a driver instance has the methods of the core contract, and
54
+ * those of the capabilities its driver declares: at startup, rather than
55
+ * with a `TypeError` on the first request needing a missing one. Done on the
56
+ * instance rather than on the class: a method can be an instance property.
38
57
  *
39
58
  * @throws {services.storage_driver.invalid_driver}
40
59
  */
41
- export declare function assertDeclaredCapabilities(driver: StorageDriver, { capabilities, description }: SelectedStorageDriver): void;
60
+ export declare function assertDriverContract(driver: StorageDriver, { capabilities, description }: SelectedStorageDriver): void;