kuzzle 2.61.2 → 2.61.3-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.
@@ -324,12 +324,11 @@ function inheritInput(target, source, data) {
324
324
  /**
325
325
  * Lock options of `auth:strategies:add` and `auth:strategies:remove`: wait
326
326
  * as long as it takes, as the deprecated `Mutex` did (no acquisition
327
- * timeout), with the same 30 s TTL — now refreshed while the strategy is
328
- * being added or removed.
327
+ * timeout). The lock is refreshed while the strategy is being added or
328
+ * removed.
329
329
  */
330
330
  const STRATEGY_LOCK = {
331
331
  retryAttempts: Number.POSITIVE_INFINITY,
332
- ttl: 30000,
333
332
  };
334
333
  /**
335
334
  * Returns a currified function of pluginsManager.registerStrategy
@@ -68,6 +68,7 @@ const didYouMean_1 = __importDefault(require("../../util/didYouMean"));
68
68
  const Inflector_1 = require("../../util/Inflector");
69
69
  const safeObject_1 = require("../../util/safeObject");
70
70
  const thrown_1 = require("../../util/thrown");
71
+ const distributedLock_1 = require("../../util/distributedLock");
71
72
  const plugin_1 = __importDefault(require("./plugin"));
72
73
  const debug = (0, debug_1.default)("kuzzle:plugins");
73
74
  const assertionError = kerror.wrap("plugin", "assert");
@@ -283,15 +284,19 @@ class PluginsManager {
283
284
  if (!isPluginMethod(init)) {
284
285
  throw assertionError.get("init_not_found", plugin.name);
285
286
  }
286
- const promise = bluebird_1.default.resolve((async () => {
287
+ const initialization = (0, distributedLock_1.trackLockWaits)(async () => {
287
288
  try {
288
289
  await init.call(plugin.instance, plugin.config, plugin.context);
289
290
  }
290
291
  catch (error) {
291
292
  throw runtimeError.get("failed_init", plugin.name, error);
292
293
  }
293
- })())
294
- .timeout(initTimeout, `${plugin.logPrefix} Initialization timed out after ${initTimeout}ms. Try to increase the configuration "plugins.common.initTimeout".`)
294
+ });
295
+ const promise = bluebird_1.default.resolve(initialization.promise)
296
+ .timeout(initTimeout)
297
+ .catch(bluebird_1.default.TimeoutError, () => {
298
+ throw new bluebird_1.default.TimeoutError(initTimeoutMessage(plugin.logPrefix, initTimeout, initialization.waitingFor()));
299
+ })
295
300
  .then(async () => {
296
301
  plugin.initCalled = true;
297
302
  if (!(0, lodash_1.isEmpty)(plugin.instance.controllers) &&
@@ -1060,5 +1065,31 @@ function getMethods(object) {
1060
1065
  const objectMethods = Object.getOwnPropertyNames(object).filter((key) => typeof Reflect.get(object, key) === "function");
1061
1066
  return [...instanceMethods, ...objectMethods];
1062
1067
  }
1068
+ /**
1069
+ * A plugin's `init` waiting for a cluster-wide lock is the usual way to run
1070
+ * out of time while the cluster starts: the message names the lock and who
1071
+ * holds it, and says that one left behind by a node that died is only freed
1072
+ * when it expires (#3156). A lock can also be held by another task of this
1073
+ * node, e.g. parallel collection creations.
1074
+ */
1075
+ function initTimeoutMessage(logPrefix, initTimeout, locks) {
1076
+ let waiting = "";
1077
+ if (locks.length > 0) {
1078
+ const plural = locks.length > 1 ? "s" : "";
1079
+ const remote = locks.filter((key) => !(0, distributedLock_1.isLockHeldHere)(key));
1080
+ const names = locks
1081
+ .map((key) => {
1082
+ const holder = remote.includes(key) ? "another node" : "this node";
1083
+ return `"${key}" (held by ${holder})`;
1084
+ })
1085
+ .join(", ");
1086
+ waiting = ` It was waiting for the cluster-wide lock${plural} ${names}.`;
1087
+ if (remote.length > 0) {
1088
+ waiting +=
1089
+ " A lock left by a node that stopped abruptly is only released when it expires.";
1090
+ }
1091
+ }
1092
+ return `${logPrefix} Initialization timed out after ${initTimeout}ms.${waiting} Try to increase the configuration "plugins.common.initTimeout".`;
1093
+ }
1063
1094
  module.exports = PluginsManager;
1064
1095
  //# sourceMappingURL=pluginsManager.js.map
@@ -1116,7 +1116,7 @@ class ClientAdapter {
1116
1116
  // Sequential by design: one index at a time under the lock
1117
1117
  await this._loadIndexMappings(index, collections, options); // NOSONAR (S9382)
1118
1118
  }
1119
- }, { retryAttempts: Number.POSITIVE_INFINITY, ttl: 60000 });
1119
+ }, { retryAttempts: Number.POSITIVE_INFINITY });
1120
1120
  }
1121
1121
  /**
1122
1122
  * Loads the mappings of an index's collections, one at a time
@@ -146,7 +146,7 @@ class InternalIndexHandler extends store_1.Store {
146
146
  }
147
147
  throw error;
148
148
  }
149
- }, { retryAttempts: Number.POSITIVE_INFINITY, ttl: 30000 });
149
+ }, { retryAttempts: Number.POSITIVE_INFINITY });
150
150
  }
151
151
  /**
152
152
  * @override
@@ -23,6 +23,12 @@ declare class Kuzzle extends KuzzleEventEmitter {
23
23
  private shutdownExitCode;
24
24
  /** Ends a failure's shutdown that does not finish in time */
25
25
  private shutdownWatchdog;
26
+ /**
27
+ * The error a failed `start()` has already logged and handed to its
28
+ * caller: an application that does not catch it must not get it logged
29
+ * once more as an unhandled rejection (#3156)
30
+ */
31
+ private reportedStartFailure;
26
32
  /** Built by `start()`; its storage drivers are closed on shutdown */
27
33
  private storageEngine;
28
34
  log: Logger;
@@ -150,6 +150,12 @@ class Kuzzle extends KuzzleEventEmitter_1.default {
150
150
  this.shutdownExitCode = 0;
151
151
  /** Ends a failure's shutdown that does not finish in time */
152
152
  this.shutdownWatchdog = null;
153
+ /**
154
+ * The error a failed `start()` has already logged and handed to its
155
+ * caller: an application that does not catch it must not get it logged
156
+ * once more as an unhandled rejection (#3156)
157
+ */
158
+ this.reportedStartFailure = undefined;
153
159
  /** Built by `start()`; its storage drivers are closed on shutdown */
154
160
  this.storageEngine = null;
155
161
  global.kuzzle = this;
@@ -265,6 +271,7 @@ class Kuzzle extends KuzzleEventEmitter_1.default {
265
271
  // awaited, so the caller still gets the error before the process exits;
266
272
  // `shutdown` never rejects, and exits even when it fails.
267
273
  void this.shutdown(1);
274
+ this.reportedStartFailure = error;
268
275
  throw error;
269
276
  }
270
277
  }
@@ -666,7 +673,6 @@ class Kuzzle extends KuzzleEventEmitter_1.default {
666
673
  // `MutexLockLostError` (the bookkeeping write stays idempotent, TD-69).
667
674
  await (0, distributedLock_1.withLock)(`backend:import:${type}`, importType, {
668
675
  retryAttempts: Number.POSITIVE_INFINITY,
669
- ttl: 60000,
670
676
  });
671
677
  };
672
678
  await importFrom(0);
@@ -707,6 +713,10 @@ class Kuzzle extends KuzzleEventEmitter_1.default {
707
713
  void this.shutdown();
708
714
  });
709
715
  process.on("unhandledRejection", (reason, promise) => {
716
+ // Already logged by `start()`, which is shutting Kuzzle down
717
+ if (reason !== undefined && reason === this.reportedStartFailure) {
718
+ return;
719
+ }
710
720
  if (reason !== undefined) {
711
721
  if (reason instanceof Error) {
712
722
  this.log.error(`ERROR: unhandledRejection: ${reason.message}. Reason: ${reason.stack}`);
@@ -735,8 +745,17 @@ class Kuzzle extends KuzzleEventEmitter_1.default {
735
745
  }
736
746
  });
737
747
  process.removeAllListeners("uncaughtException");
748
+ // Anything can be thrown, `undefined` included: the development mode
749
+ // above rethrows whatever a promise was rejected with
738
750
  process.on("uncaughtException", (err) => {
739
- this.log.error(`ERROR: uncaughtException: ${err.message}\n${err.stack}`);
751
+ let description;
752
+ if (err instanceof Error) {
753
+ description = `${err.message}\n${err.stack}`;
754
+ }
755
+ else {
756
+ description = typeof err === "string" ? err : (0, node_util_1.inspect)(err);
757
+ }
758
+ this.log.error(`ERROR: uncaughtException: ${description}`);
740
759
  void this.dumpAndExit("uncaught-exception");
741
760
  });
742
761
  // abnormal termination signals => generate a core dump
@@ -13,7 +13,9 @@ export interface MutexConfig {
13
13
  */
14
14
  retryDelay?: number;
15
15
  /**
16
- * Lock TTL in milliseconds (default: 30000)
16
+ * Lock TTL in milliseconds (default: 10000). The lock is extended every
17
+ * third of it while the callback runs: the TTL only bounds how long a lock
18
+ * outlives a node that stopped extending it.
17
19
  */
18
20
  ttl?: number;
19
21
  }
@@ -32,6 +34,21 @@ export declare class MutexLockLostError extends Error {
32
34
  export declare class MutexAcquireError extends Error {
33
35
  constructor(key: string, attempts: number);
34
36
  }
37
+ /**
38
+ * Runs `fn`, and lets the caller ask at any time which locks the work it
39
+ * started (`withLock` calls made by `fn`, or by anything it awaits) is still
40
+ * waiting to acquire.
41
+ *
42
+ * Used to say what a plugin's `init` was blocked on when it times out: a
43
+ * lock held by another node, or left behind by a node that died, is only
44
+ * released when its TTL expires (#3156).
45
+ *
46
+ * Internal to Kuzzle: not exported by the package.
47
+ */
48
+ export declare function trackLockWaits<T>(fn: () => Promise<T>): {
49
+ promise: Promise<T>;
50
+ waitingFor: () => string[];
51
+ };
35
52
  /**
36
53
  * Frees every lock taken by `withLock` that this process still holds, and
37
54
  * stops it from taking new ones. Only meant to be called right before
@@ -47,6 +64,13 @@ export declare class MutexAcquireError extends Error {
47
64
  * Internal to Kuzzle: not exported by the package.
48
65
  */
49
66
  export declare function releaseAllLocksBeforeExit(): Promise<void>;
67
+ /**
68
+ * Whether this process holds the lock on `key`, taken by `withLock`: a lock
69
+ * awaited by one task can be held by another task of the same node.
70
+ *
71
+ * Internal to Kuzzle: not exported by the package.
72
+ */
73
+ export declare function isLockHeldHere(key: string): boolean;
50
74
  /**
51
75
  * Runs `callback` while holding a distributed, reentrant lock on `key`.
52
76
  *
@@ -24,13 +24,24 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
24
24
  };
25
25
  Object.defineProperty(exports, "__esModule", { value: true });
26
26
  exports.MutexAcquireError = exports.MutexLockLostError = void 0;
27
+ exports.trackLockWaits = trackLockWaits;
27
28
  exports.releaseAllLocksBeforeExit = releaseAllLocksBeforeExit;
29
+ exports.isLockHeldHere = isLockHeldHere;
28
30
  exports.withLock = withLock;
29
31
  const node_async_hooks_1 = require("node:async_hooks");
30
32
  const redis_semaphore_1 = require("redis-semaphore");
31
33
  const debug_1 = __importDefault(require("./debug"));
32
34
  require("../types/Global");
33
35
  const debug = (0, debug_1.default)("kuzzle:distributedLock");
36
+ /**
37
+ * Default `withLock` TTL. A node that dies holding a lock leaves it until it
38
+ * expires, and every node waiting for it waits that long: at startup, inside
39
+ * a plugin `init` that must end within `plugins.common.initTimeout` (10 s by
40
+ * default). A live holder extends it every third of the TTL, so it can stall
41
+ * for about 6.6 s before losing it, as with the former 30 s TTL extended
42
+ * every 24 s (#3156, #3207, #3208).
43
+ */
44
+ const DEFAULT_LOCK_TTL = 10000;
34
45
  /**
35
46
  * Thrown when a lock acquired by `withLock` is lost while its callback is
36
47
  * still running (e.g. TTL extension failed and another node may now hold
@@ -69,6 +80,7 @@ class ResourceMutex extends redis_semaphore_1.Mutex {
69
80
  constructor(client, key, options) {
70
81
  super(client, key, options);
71
82
  this._key = key;
83
+ this.resource = key;
72
84
  }
73
85
  async _refresh() {
74
86
  try {
@@ -90,6 +102,48 @@ class ResourceMutex extends redis_semaphore_1.Mutex {
90
102
  * outside a request scope, e.g. during boot or in background jobs).
91
103
  */
92
104
  const lockContext = new node_async_hooks_1.AsyncLocalStorage();
105
+ /**
106
+ * The locks the async context of a `trackLockWaits` call is waiting for, each
107
+ * with the number of `withLock` calls waiting on it.
108
+ */
109
+ const waitContext = new node_async_hooks_1.AsyncLocalStorage();
110
+ /**
111
+ * Runs `fn`, and lets the caller ask at any time which locks the work it
112
+ * started (`withLock` calls made by `fn`, or by anything it awaits) is still
113
+ * waiting to acquire.
114
+ *
115
+ * Used to say what a plugin's `init` was blocked on when it times out: a
116
+ * lock held by another node, or left behind by a node that died, is only
117
+ * released when its TTL expires (#3156).
118
+ *
119
+ * Internal to Kuzzle: not exported by the package.
120
+ */
121
+ function trackLockWaits(fn) {
122
+ const waits = new Map();
123
+ return {
124
+ promise: waitContext.run(waits, fn),
125
+ waitingFor: () => [...waits.keys()],
126
+ };
127
+ }
128
+ async function acquireTracked(mutex, key) {
129
+ const waits = waitContext.getStore();
130
+ if (!waits) {
131
+ return mutex.tryAcquire();
132
+ }
133
+ waits.set(key, (waits.get(key) ?? 0) + 1);
134
+ try {
135
+ return await mutex.tryAcquire();
136
+ }
137
+ finally {
138
+ const count = (waits.get(key) ?? 1) - 1;
139
+ if (count === 0) {
140
+ waits.delete(key);
141
+ }
142
+ else {
143
+ waits.set(key, count);
144
+ }
145
+ }
146
+ }
93
147
  let clientPromise;
94
148
  // Every lock this process holds, so that it can give them back before it
95
149
  // exits (see `releaseAllLocksBeforeExit`).
@@ -114,6 +168,20 @@ async function releaseAllLocksBeforeExit() {
114
168
  // Best effort: a lock that cannot be freed still expires with its TTL.
115
169
  await Promise.allSettled([...held].map((mutex) => mutex.release()));
116
170
  }
171
+ /**
172
+ * Whether this process holds the lock on `key`, taken by `withLock`: a lock
173
+ * awaited by one task can be held by another task of the same node.
174
+ *
175
+ * Internal to Kuzzle: not exported by the package.
176
+ */
177
+ function isLockHeldHere(key) {
178
+ for (const mutex of held) {
179
+ if (mutex.resource === key) {
180
+ return true;
181
+ }
182
+ }
183
+ return false;
184
+ }
117
185
  /**
118
186
  * Lazily fetches and memoizes the internal cache's raw ioredis client.
119
187
  * Self-healing: if the very first call happens before the cache engine has
@@ -165,7 +233,7 @@ async function withLock(key, callback, config = {}) {
165
233
  if (ancestors?.has(key)) {
166
234
  return callback();
167
235
  }
168
- const { retryAttempts = 10, retryDelay = 200, ttl = 30000 } = config;
236
+ const { retryAttempts = 10, retryDelay = 200, ttl = DEFAULT_LOCK_TTL, } = config;
169
237
  const client = await getClient();
170
238
  const loss = new AbortController();
171
239
  const lockLost = new Promise((_resolve, reject) => {
@@ -179,6 +247,7 @@ async function withLock(key, callback, config = {}) {
179
247
  acquireAttemptsLimit: retryAttempts + 1,
180
248
  acquireTimeout: Number.POSITIVE_INFINITY,
181
249
  lockTimeout: ttl,
250
+ refreshInterval: Math.round(ttl / 3),
182
251
  onLockLost: (error) => {
183
252
  loss.abort(new MutexLockLostError(key, mutex.refreshError ?? error));
184
253
  },
@@ -186,7 +255,7 @@ async function withLock(key, callback, config = {}) {
186
255
  // last one included: with no retry, that wait only delays the failure
187
256
  retryInterval: retryAttempts === 0 ? 0 : retryDelay,
188
257
  });
189
- if (!(await mutex.tryAcquire())) {
258
+ if (!(await acquireTracked(mutex, key))) {
190
259
  throw new MutexAcquireError(key, retryAttempts + 1);
191
260
  }
192
261
  held.add(mutex);
package/dist/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kuzzle",
3
3
  "author": "The Kuzzle Team <support@kuzzle.io>",
4
- "version": "2.61.2",
4
+ "version": "2.61.3-beta.2",
5
5
  "description": "Kuzzle is an open-source solution that handles all the data management through a secured API, with a large choice of protocols.",
6
6
  "scripts": {
7
7
  "build": "rm -Rf ./dist && tsc && node -r ts-node/register/transpile-only ./bin/copy-binaries.ts",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "kuzzle",
3
3
  "author": "The Kuzzle Team <support@kuzzle.io>",
4
- "version": "2.61.2",
4
+ "version": "2.61.3-beta.2",
5
5
  "description": "Kuzzle is an open-source solution that handles all the data management through a secured API, with a large choice of protocols.",
6
6
  "scripts": {
7
7
  "build": "rm -Rf ./dist && tsc && node -r ts-node/register/transpile-only ./bin/copy-binaries.ts",