kuzzle 2.61.3 → 2.61.4-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.
package/dist/index.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import "./lib/kuzzle/earlySignals";
1
2
  export * from "./lib/core/backend";
2
3
  export * from "./lib/types";
3
4
  export * from "./lib/core/plugin/pluginContext";
package/dist/index.js CHANGED
@@ -15,6 +15,9 @@ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
15
  };
16
16
  Object.defineProperty(exports, "__esModule", { value: true });
17
17
  exports.WebSocket = exports.UserSearchResult = exports.UserOption = exports.User = exports.SpecificationsSearchResult = exports.ServerController = exports.SearchResultBase = exports.ScopeOption = exports.RoleSearchResult = exports.Role = exports.RealtimeDocument = exports.RealtimeController = exports.ProfileSearchResult = exports.Profile = exports.Observer = exports.KuzzleEventEmitter = exports.KuzzleAbstractProtocol = exports.Kuzzle = exports.IndexController = exports.Http = exports.DocumentSearchResult = exports.DocumentController = exports.Document = exports.CollectionController = exports.BatchController = exports.BaseController = exports.AuthController = exports.NameGenerator = exports.withLock = exports.MutexLockLostError = exports.MutexAcquireError = void 0;
18
+ // First: exits on SIGTERM / SIGINT while the rest loads, until Kuzzle starts
19
+ // (#3087)
20
+ require("./lib/kuzzle/earlySignals");
18
21
  __exportStar(require("./lib/core/backend"), exports);
19
22
  __exportStar(require("./lib/types"), exports);
20
23
  __exportStar(require("./lib/core/plugin/pluginContext"), exports);
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Exits on `SIGINT` / `SIGTERM` while Kuzzle loads, until `Kuzzle.start()`
3
+ * replaces these handlers with its graceful ones (#3087).
4
+ *
5
+ * Node.js ends a process on these signals when nothing listens to them, but
6
+ * the kernel drops a signal that has no handler when it is sent to PID 1:
7
+ * `node` run as a container's main process, without an init, ignored a
8
+ * `SIGTERM` received while it loaded its modules, and `docker stop` waited
9
+ * for its grace period before killing it.
10
+ *
11
+ * Armed when the `kuzzle` package is imported, the earliest point there is.
12
+ * A process that imports it without starting Kuzzle keeps Node.js' own
13
+ * behaviour: the handler steps aside when anything else listens to the
14
+ * signal, and otherwise ends the process as Node.js would have, with the
15
+ * usual `128 + signal number` exit code.
16
+ *
17
+ * Signal handling, called before the funnel exists: synchronous on purpose.
18
+ * Internal to Kuzzle: not exported by the package.
19
+ */
20
+ declare const EXIT_CODES: {
21
+ readonly SIGINT: 130;
22
+ readonly SIGTERM: 143;
23
+ };
24
+ type EarlySignal = keyof typeof EXIT_CODES;
25
+ type EarlyHandlers = Record<EarlySignal, () => void>;
26
+ declare global {
27
+ /**
28
+ * Process-wide, so that two copies of this module (e.g. two installs of
29
+ * the package) never register the handlers twice
30
+ */
31
+ var kuzzleEarlySignalHandlers: EarlyHandlers | undefined;
32
+ }
33
+ export declare function armEarlySignalHandlers(): void;
34
+ /**
35
+ * Removes the handlers, once `Kuzzle.start()` installs the graceful ones
36
+ */
37
+ export declare function disarmEarlySignalHandlers(): void;
38
+ export {};
@@ -0,0 +1,82 @@
1
+ "use strict";
2
+ /*
3
+ * Kuzzle, a backend software, self-hostable and ready to use
4
+ * to power modern apps
5
+ *
6
+ * Copyright 2015-2022 Kuzzle
7
+ * mailto: support AT kuzzle.io
8
+ * website: http://kuzzle.io
9
+ *
10
+ * Licensed under the Apache License, Version 2.0 (the "License");
11
+ * you may not use this file except in compliance with the License.
12
+ * You may obtain a copy of the License at
13
+ *
14
+ * https://www.apache.org/licenses/LICENSE-2.0
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ Object.defineProperty(exports, "__esModule", { value: true });
23
+ exports.armEarlySignalHandlers = armEarlySignalHandlers;
24
+ exports.disarmEarlySignalHandlers = disarmEarlySignalHandlers;
25
+ /**
26
+ * Exits on `SIGINT` / `SIGTERM` while Kuzzle loads, until `Kuzzle.start()`
27
+ * replaces these handlers with its graceful ones (#3087).
28
+ *
29
+ * Node.js ends a process on these signals when nothing listens to them, but
30
+ * the kernel drops a signal that has no handler when it is sent to PID 1:
31
+ * `node` run as a container's main process, without an init, ignored a
32
+ * `SIGTERM` received while it loaded its modules, and `docker stop` waited
33
+ * for its grace period before killing it.
34
+ *
35
+ * Armed when the `kuzzle` package is imported, the earliest point there is.
36
+ * A process that imports it without starting Kuzzle keeps Node.js' own
37
+ * behaviour: the handler steps aside when anything else listens to the
38
+ * signal, and otherwise ends the process as Node.js would have, with the
39
+ * usual `128 + signal number` exit code.
40
+ *
41
+ * Signal handling, called before the funnel exists: synchronous on purpose.
42
+ * Internal to Kuzzle: not exported by the package.
43
+ */
44
+ const EXIT_CODES = { SIGINT: 130, SIGTERM: 143 };
45
+ const SIGNALS = ["SIGINT", "SIGTERM"];
46
+ function onEarlySignal(signal) {
47
+ // Someone else listens to it (the application, a test runner): theirs to
48
+ // handle, as it would have been without this handler
49
+ if (process.listenerCount(signal) > 1) {
50
+ return;
51
+ }
52
+ process.stderr.write(`Caught signal ${signal} before Kuzzle started: exiting now\n`);
53
+ process.exit(EXIT_CODES[signal]);
54
+ }
55
+ function armEarlySignalHandlers() {
56
+ if (globalThis.kuzzleEarlySignalHandlers) {
57
+ return;
58
+ }
59
+ const handlers = {
60
+ SIGINT: () => onEarlySignal("SIGINT"),
61
+ SIGTERM: () => onEarlySignal("SIGTERM"),
62
+ };
63
+ globalThis.kuzzleEarlySignalHandlers = handlers;
64
+ for (const signal of SIGNALS) {
65
+ process.on(signal, handlers[signal]);
66
+ }
67
+ }
68
+ /**
69
+ * Removes the handlers, once `Kuzzle.start()` installs the graceful ones
70
+ */
71
+ function disarmEarlySignalHandlers() {
72
+ const handlers = globalThis.kuzzleEarlySignalHandlers;
73
+ if (!handlers) {
74
+ return;
75
+ }
76
+ for (const signal of SIGNALS) {
77
+ process.removeListener(signal, handlers[signal]);
78
+ }
79
+ globalThis.kuzzleEarlySignalHandlers = undefined;
80
+ }
81
+ armEarlySignalHandlers();
82
+ //# sourceMappingURL=earlySignals.js.map
@@ -90,6 +90,7 @@ const crypto_1 = require("../util/crypto");
90
90
  const distributedLock_1 = require("../util/distributedLock");
91
91
  const mutex_1 = require("../util/mutex"); // NOSONAR: only to free locks taken through the deprecated API, see shutdown()
92
92
  const dumpGenerator_1 = __importDefault(require("./dumpGenerator"));
93
+ const earlySignals_1 = require("./earlySignals");
93
94
  const KuzzleEventEmitter_1 = __importDefault(require("./event/KuzzleEventEmitter"));
94
95
  const internalIndexHandler_1 = __importDefault(require("./internalIndexHandler"));
95
96
  const kuzzleStateEnum_1 = __importDefault(require("./kuzzleStateEnum"));
@@ -776,7 +777,9 @@ class Kuzzle extends KuzzleEventEmitter_1.default {
776
777
  this.log.error(`Unable to dump on SIGTRAP: ${error instanceof Error ? error.message : String(error)}`);
777
778
  });
778
779
  });
779
- // gracefully exits on normal termination
780
+ // gracefully exits on normal termination, in place of the handlers that
781
+ // exited at once while Kuzzle was loading (#3087)
782
+ (0, earlySignals_1.disarmEarlySignalHandlers)();
780
783
  for (const signal of ["SIGINT", "SIGTERM"]) {
781
784
  process.removeAllListeners(signal);
782
785
  process.on(signal, () => {
@@ -65,6 +65,18 @@ class MutexAcquireError extends Error {
65
65
  }
66
66
  }
67
67
  exports.MutexAcquireError = MutexAcquireError;
68
+ /**
69
+ * Deletes the lock only if it still holds our token, as redis-semaphore's own
70
+ * release script does, but answers whether it did: redis-semaphore drops that
71
+ * answer, and with it the only sign that the lock was lost (#3212).
72
+ */
73
+ const RELEASE_SCRIPT = `
74
+ if redis.call('get', KEYS[1]) == ARGV[1] then
75
+ return redis.call('del', KEYS[1])
76
+ end
77
+
78
+ return 0
79
+ `;
68
80
  /**
69
81
  * redis-semaphore's mutex, adjusted to what `withLock` promises:
70
82
  *
@@ -74,17 +86,34 @@ exports.MutexAcquireError = MutexAcquireError;
74
86
  * - a TTL extension that fails with a Redis error counts as a lost lock
75
87
  * (redis-semaphore would let the error escape its refresh timer as an
76
88
  * unhandled rejection, without knowing whether the lock is still held).
77
- * The error is kept, to be reported as the loss's cause.
89
+ * The error is kept, to be reported as the loss's cause;
90
+ * - a lost lock is logged, even when nobody waits for `withLock` any more,
91
+ * and so is a release that finds the lock expired or owned by another
92
+ * node, which redis-semaphore silently ignores (#3212).
78
93
  */
79
94
  class ResourceMutex extends redis_semaphore_1.Mutex {
80
95
  constructor(client, key, options) {
81
96
  super(client, key, options);
97
+ // When this node last knew it held the lock: acquired, or extended
98
+ this.heldAt = 0;
99
+ this.lossReported = false;
82
100
  this._key = key;
83
101
  this.resource = key;
84
102
  }
103
+ async _acquire(abortSignal) {
104
+ const acquired = await super._acquire(abortSignal);
105
+ if (acquired) {
106
+ this.heldAt = Date.now();
107
+ }
108
+ return acquired;
109
+ }
85
110
  async _refresh() {
86
111
  try {
87
- return await super._refresh();
112
+ const refreshed = await super._refresh();
113
+ if (refreshed) {
114
+ this.heldAt = Date.now();
115
+ }
116
+ return refreshed;
88
117
  }
89
118
  catch (error) {
90
119
  this.refreshError =
@@ -92,6 +121,39 @@ class ResourceMutex extends redis_semaphore_1.Mutex {
92
121
  return false;
93
122
  }
94
123
  }
124
+ /**
125
+ * Releases once, however many callers ask: a lock freed before exiting
126
+ * (`releaseAllLocksBeforeExit`) is released again by its `withLock` call
127
+ * if its callback ends first, and the second release would find the key
128
+ * gone and report the lock as lost.
129
+ */
130
+ release() {
131
+ this.releasing ?? (this.releasing = super.release());
132
+ return this.releasing;
133
+ }
134
+ async _release() {
135
+ const args = [1, this._key, this._identifier];
136
+ // Plain EVAL: a release runs once per lock, and EVALSHA would need a
137
+ // local SHA-1 of the script, which code scanners flag as a weak hash
138
+ const deleted = await this._client.eval(RELEASE_SCRIPT, ...args);
139
+ if (Number(deleted) !== 1) {
140
+ this.reportLoss("it had expired, or another node held it, on release");
141
+ }
142
+ }
143
+ /**
144
+ * Logs, once, that this node lost the lock while it thought it held it:
145
+ * it went longer than the TTL without extending it (event-loop stall,
146
+ * paused process, unreachable Redis), so another node may have run the
147
+ * same critical section at the same time. A TTL lock cannot be taken back
148
+ * from a frozen process: it can only be told afterwards.
149
+ */
150
+ reportLoss(reason) {
151
+ if (this.lossReported) {
152
+ return;
153
+ }
154
+ this.lossReported = true;
155
+ global.kuzzle.log.warn(`Lock "${this.resource}" lost: ${reason}. This node last extended it ${Date.now() - this.heldAt} ms ago (TTL: ${this._acquireOptions.lockTimeout} ms): it may have been unresponsive, and another node may have held the lock while its own critical section was still running.`);
156
+ }
95
157
  }
96
158
  /**
97
159
  * Tracks, per async context, the set of lock keys already held by an
@@ -249,6 +311,10 @@ async function withLock(key, callback, config = {}) {
249
311
  lockTimeout: ttl,
250
312
  refreshInterval: Math.round(ttl / 3),
251
313
  onLockLost: (error) => {
314
+ // Also when withLock has already settled: then nothing else reports it
315
+ mutex.reportLoss(mutex.refreshError
316
+ ? `it could not be extended (${mutex.refreshError.message})`
317
+ : "it expired, or another node holds it");
252
318
  loss.abort(new MutexLockLostError(key, mutex.refreshError ?? error));
253
319
  },
254
320
  // redis-semaphore waits `retryInterval` after every failed attempt, the
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.3",
4
+ "version": "2.61.4-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.3",
4
+ "version": "2.61.4-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",