kuzzle 2.61.2 → 2.61.3-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.
@@ -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,20 @@ 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 says
1071
+ * that one left behind by a node that died is only freed when it expires
1072
+ * (#3156).
1073
+ */
1074
+ function initTimeoutMessage(logPrefix, initTimeout, locks) {
1075
+ let waiting = "";
1076
+ if (locks.length > 0) {
1077
+ const plural = locks.length > 1 ? "s" : "";
1078
+ const names = locks.map((key) => `"${key}"`).join(", ");
1079
+ waiting = ` It was waiting for the cluster-wide lock${plural} ${names}, held by another node; a lock left by a node that stopped abruptly is only released when it expires.`;
1080
+ }
1081
+ return `${logPrefix} Initialization timed out after ${initTimeout}ms.${waiting} Try to increase the configuration "plugins.common.initTimeout".`;
1082
+ }
1063
1083
  module.exports = PluginsManager;
1064
1084
  //# sourceMappingURL=pluginsManager.js.map
@@ -60,8 +60,9 @@ export declare class Store {
60
60
  * Initialize the index, and creates provided collections
61
61
  *
62
62
  * Every node creates the collections in turn, under the same lock, and
63
- * waits for it with no limit. The lock is refreshed while the collections
64
- * are created; if it is lost, this rejects with `MutexLockLostError`.
63
+ * waits for it with no limit. The lock (`STORE_INIT_LOCK_TTL`) is refreshed
64
+ * while the collections are created; if it is lost, this rejects with
65
+ * `MutexLockLostError`.
65
66
  */
66
67
  init(collections?: StoreCollectionsDefinition): Promise<void>;
67
68
  /**
@@ -58,6 +58,14 @@ const kerror = __importStar(require("../../kerror"));
58
58
  const async_1 = require("../../util/async");
59
59
  const esRequest_1 = require("../../util/esRequest");
60
60
  const distributedLock_1 = require("../../util/distributedLock");
61
+ /**
62
+ * TTL of the `Store.init` lock, refreshed every 8 s while its holder is alive.
63
+ * Plugins call `Store.init` from their `init`, which must finish within
64
+ * `plugins.common.initTimeout` (10 s by default): a node that dies holding the
65
+ * lock leaves it to expire, and with the 30 s default every node waiting on it
66
+ * ran out of time (#3156).
67
+ */
68
+ const STORE_INIT_LOCK_TTL = 10000;
61
69
  /**
62
70
  * The store methods that are nothing but an ask on a
63
71
  * `core:storage:<scope>:<suffix>` event taking the index as its first
@@ -126,11 +134,12 @@ class Store {
126
134
  * Initialize the index, and creates provided collections
127
135
  *
128
136
  * Every node creates the collections in turn, under the same lock, and
129
- * waits for it with no limit. The lock is refreshed while the collections
130
- * are created; if it is lost, this rejects with `MutexLockLostError`.
137
+ * waits for it with no limit. The lock (`STORE_INIT_LOCK_TTL`) is refreshed
138
+ * while the collections are created; if it is lost, this rejects with
139
+ * `MutexLockLostError`.
131
140
  */
132
141
  async init(collections = {}) {
133
- await (0, distributedLock_1.withLock)(`Store.init(${this.index})`, () => this.createCollections(collections, { indexCacheOnly: false }), { retryAttempts: Number.POSITIVE_INFINITY });
142
+ await (0, distributedLock_1.withLock)(`Store.init(${this.index})`, () => this.createCollections(collections, { indexCacheOnly: false }), { retryAttempts: Number.POSITIVE_INFINITY, ttl: STORE_INIT_LOCK_TTL });
134
143
  }
135
144
  /**
136
145
  * Creates collections with the provided mappings
@@ -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
  }
@@ -707,6 +714,10 @@ class Kuzzle extends KuzzleEventEmitter_1.default {
707
714
  void this.shutdown();
708
715
  });
709
716
  process.on("unhandledRejection", (reason, promise) => {
717
+ // Already logged by `start()`, which is shutting Kuzzle down
718
+ if (reason !== undefined && reason === this.reportedStartFailure) {
719
+ return;
720
+ }
710
721
  if (reason !== undefined) {
711
722
  if (reason instanceof Error) {
712
723
  this.log.error(`ERROR: unhandledRejection: ${reason.message}. Reason: ${reason.stack}`);
@@ -735,8 +746,17 @@ class Kuzzle extends KuzzleEventEmitter_1.default {
735
746
  }
736
747
  });
737
748
  process.removeAllListeners("uncaughtException");
749
+ // Anything can be thrown, `undefined` included: the development mode
750
+ // above rethrows whatever a promise was rejected with
738
751
  process.on("uncaughtException", (err) => {
739
- this.log.error(`ERROR: uncaughtException: ${err.message}\n${err.stack}`);
752
+ let description;
753
+ if (err instanceof Error) {
754
+ description = `${err.message}\n${err.stack}`;
755
+ }
756
+ else {
757
+ description = typeof err === "string" ? err : (0, node_util_1.inspect)(err);
758
+ }
759
+ this.log.error(`ERROR: uncaughtException: ${description}`);
740
760
  void this.dumpAndExit("uncaught-exception");
741
761
  });
742
762
  // abnormal termination signals => generate a core dump
@@ -32,6 +32,21 @@ export declare class MutexLockLostError extends Error {
32
32
  export declare class MutexAcquireError extends Error {
33
33
  constructor(key: string, attempts: number);
34
34
  }
35
+ /**
36
+ * Runs `fn`, and lets the caller ask at any time which locks the work it
37
+ * started (`withLock` calls made by `fn`, or by anything it awaits) is still
38
+ * waiting to acquire.
39
+ *
40
+ * Used to say what a plugin's `init` was blocked on when it times out: a
41
+ * lock held by another node, or left behind by a node that died, is only
42
+ * released when its TTL expires (#3156).
43
+ *
44
+ * Internal to Kuzzle: not exported by the package.
45
+ */
46
+ export declare function trackLockWaits<T>(fn: () => Promise<T>): {
47
+ promise: Promise<T>;
48
+ waitingFor: () => string[];
49
+ };
35
50
  /**
36
51
  * Frees every lock taken by `withLock` that this process still holds, and
37
52
  * stops it from taking new ones. Only meant to be called right before
@@ -24,6 +24,7 @@ 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;
28
29
  exports.withLock = withLock;
29
30
  const node_async_hooks_1 = require("node:async_hooks");
@@ -90,6 +91,48 @@ class ResourceMutex extends redis_semaphore_1.Mutex {
90
91
  * outside a request scope, e.g. during boot or in background jobs).
91
92
  */
92
93
  const lockContext = new node_async_hooks_1.AsyncLocalStorage();
94
+ /**
95
+ * The locks the async context of a `trackLockWaits` call is waiting for, each
96
+ * with the number of `withLock` calls waiting on it.
97
+ */
98
+ const waitContext = new node_async_hooks_1.AsyncLocalStorage();
99
+ /**
100
+ * Runs `fn`, and lets the caller ask at any time which locks the work it
101
+ * started (`withLock` calls made by `fn`, or by anything it awaits) is still
102
+ * waiting to acquire.
103
+ *
104
+ * Used to say what a plugin's `init` was blocked on when it times out: a
105
+ * lock held by another node, or left behind by a node that died, is only
106
+ * released when its TTL expires (#3156).
107
+ *
108
+ * Internal to Kuzzle: not exported by the package.
109
+ */
110
+ function trackLockWaits(fn) {
111
+ const waits = new Map();
112
+ return {
113
+ promise: waitContext.run(waits, fn),
114
+ waitingFor: () => [...waits.keys()],
115
+ };
116
+ }
117
+ async function acquireTracked(mutex, key) {
118
+ const waits = waitContext.getStore();
119
+ if (!waits) {
120
+ return mutex.tryAcquire();
121
+ }
122
+ waits.set(key, (waits.get(key) ?? 0) + 1);
123
+ try {
124
+ return await mutex.tryAcquire();
125
+ }
126
+ finally {
127
+ const count = (waits.get(key) ?? 1) - 1;
128
+ if (count === 0) {
129
+ waits.delete(key);
130
+ }
131
+ else {
132
+ waits.set(key, count);
133
+ }
134
+ }
135
+ }
93
136
  let clientPromise;
94
137
  // Every lock this process holds, so that it can give them back before it
95
138
  // exits (see `releaseAllLocksBeforeExit`).
@@ -186,7 +229,7 @@ async function withLock(key, callback, config = {}) {
186
229
  // last one included: with no retry, that wait only delays the failure
187
230
  retryInterval: retryAttempts === 0 ? 0 : retryDelay,
188
231
  });
189
- if (!(await mutex.tryAcquire())) {
232
+ if (!(await acquireTracked(mutex, key))) {
190
233
  throw new MutexAcquireError(key, retryAttempts + 1);
191
234
  }
192
235
  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.1",
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.1",
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",