@imqueue/rpc 3.6.1 → 3.7.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/CHANGELOG.md CHANGED
@@ -4,8 +4,147 @@ Notable changes to `@imqueue/rpc`. Entries start at 3.3.1 — the first release
4
4
  whose behavior changes needed a written record; earlier history is in the git
5
5
  log.
6
6
 
7
+ A released version absent from this file changed no behavior — it was a
8
+ documentation or CI-only release. Dependency bumps do get an entry, because a
9
+ raised `@imqueue/core` floor is how most fixes in the transport reach a service.
10
+
7
11
  This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
12
 
13
+ ## [3.7.0] - 2026-08-20
14
+
15
+ ### Added
16
+
17
+ - **A response that arrives with no pending call left is now visible in the
18
+ log.** The line is written through the configured logger on every such
19
+ response, names the service, the method and the request id, and never the
20
+ arguments, the request or the response object (which echoes the whole
21
+ request back) or an error text. It tells a late reply apart from a service
22
+ that never answered, and after a restart it names the backlog the previous
23
+ process left behind.
24
+
25
+ A reply that could not be written to the caller's queue is reported by
26
+ `@imqueue/core` itself, as part of its write-failure episode reporting, so
27
+ this package adds no reporting of its own there. A call that got no
28
+ response within `callTimeout` is not logged here either: the caller
29
+ receives the `IMQ_RPC_CALL_TIMEOUT` rejection and decides how to report it.
30
+
31
+ ### Changed
32
+
33
+ - **`@logged()` now names the class and the method instead of dumping the
34
+ error.** The line reads `Class.method() failed, code <code>`. The code is
35
+ never taken from the error as it is: only an allow-listed code is printed —
36
+ an `IMQ_`-prefixed framework code, a system `E…` code, a small integer, a
37
+ known redis reply code or one of a few known redis-client failure messages
38
+ mapped to codes of our own; everything else, the error's class name
39
+ included, is reported as `unknown`. The caught value itself, its message and its
40
+ stack are no longer printed: an application error may carry personal data,
41
+ and an imq error carries the call arguments in its properties. The method
42
+ name now also reaches the line under standard (TC39) decorators, where it was
43
+ previously unavailable. Everything else is unchanged, including which logger
44
+ is resolved, `doNotThrow`, the re-thrown value and the fact that a throwing
45
+ logger replaces the original error.
46
+
47
+ - Raised the `@imqueue/core` dependency to `^3.4.0`, which reports the
48
+ transport's previously silent failures through the configured logger — among
49
+ them a reply that could not be written back to the caller's queue, which is
50
+ why this package adds no reporting of its own there.
51
+
52
+ ## [3.6.1] - 2026-08-18
53
+
54
+ ### Changed
55
+
56
+ - Raised the `@imqueue/core` dependency to `^3.3.3`, which stops a starting
57
+ queue overwriting the server-global `notify-keyspace-events` configuration.
58
+
59
+ ## [3.6.0] - 2026-08-18
60
+
61
+ ### Fixed
62
+
63
+ - **A `@lock()`'d call could resolve waiters with another call's result, and one
64
+ waiter's timeout rejected all of them.** `IMQLock.deadlockTimeout` rejected
65
+ through `release()`, which does two things a timeout has no business doing: it
66
+ deleted the holder's lock while the holder was still running, and it drained
67
+ the whole queue.
68
+
69
+ The first let a later call acquire the freed key and run alongside the original
70
+ holder — and when that holder finally finished, its release landed on the *new*
71
+ holder's lock, resolving waiters with a result computed for a call they had
72
+ nothing to do with and freeing a lock still in use, letting a third call in
73
+ behind it. Silently wrong values, under exactly the overlapping load that
74
+ coalescing `@lock()` exists to collapse. The second meant a call that arrived
75
+ a moment ago died for an older call's patience.
76
+
77
+ Locks now carry a token. `release()` takes it as an optional fourth argument
78
+ and is ignored when a different call owns the key; an unowned key is not a
79
+ conflict, so a straggler can still satisfy waiters nobody else will. `lock()`
80
+ reads the token and passes it, so every decorator user is covered with no code
81
+ change, and a release without a token behaves exactly as before. The timer now
82
+ splices out its own task and rejects only that waiter, while still freeing the
83
+ key — a holder that never releases would otherwise poison it for the life of
84
+ the process.
85
+
86
+ ## [3.5.4] - 2026-08-09
87
+
88
+ ### Fixed
89
+
90
+ - **Tracing hooks installed on the default options could patch a copy nothing
91
+ ever called.** `DEFAULT_IMQ_SERVICE_OPTIONS` and `DEFAULT_IMQ_CLIENT_OPTIONS`
92
+ were plain module-scope objects, so a process that evaluated this module twice
93
+ held two copies — which is what a loader handling ESM and CJS through separate
94
+ pipelines does: under `tsx`, `require('@imqueue/rpc')` and
95
+ `import('@imqueue/rpc')` return distinct instances.
96
+
97
+ Anything that installs behavior by mutating those objects then patched a copy
98
+ the application never calls. `@imqueue/opentelemetry` attaches its
99
+ `beforeCall`/`afterCall`/`wrapCall` hooks that way, and produced no spans at
100
+ all under such a loader — with no error, since the patch itself succeeded.
101
+
102
+ Both are now keyed on `Symbol.for`, making them singletons per process rather
103
+ than per module evaluation, so a mutation through any instance is visible to
104
+ all. This also removes the "duplicate installs at different tree depths"
105
+ caveat the instrumentation documents.
106
+
107
+ ## [3.5.3] - 2026-08-04
108
+
109
+ ### Changed
110
+
111
+ - Raised the `@imqueue/core` dependency to `^3.3.2`.
112
+
113
+ ## [3.5.2] - 2026-08-01
114
+
115
+ ### Changed
116
+
117
+ - Raised the `@imqueue/core` dependency to `^3.3.0`, which keeps safe-delivery
118
+ lease recovery and the cleanup sweep alive after a transient sweep failure,
119
+ and drops the unresolvable `./debug` export subpath.
120
+
121
+ ## [3.5.0] - 2026-07-28
122
+
123
+ ### Fixed
124
+
125
+ - **A concrete service subclass that exposed nothing of its own answered
126
+ nothing.** `getClassMethods()` looked its class up in the description registry
127
+ by name and dereferenced `classInfo.inherits` with no guard, but `@expose()`
128
+ registers only the class that *declares* a method — so such a subclass had no
129
+ registry entry at all and `describe()` threw a `TypeError` on it.
130
+
131
+ The failure was silent and total: `processRequest()` calls `describe()` on
132
+ every request and the constructor's `.catch` sends the rejection to the logger,
133
+ so the service returned no error response and no rejection. Callers hung until
134
+ their own `callTimeout`, which is unset by default.
135
+
136
+ Guarding the lookup alone would have traded the hang for a different wrong
137
+ answer — the walk follows the registry's `inherits` links, so it would have
138
+ stopped at the gap and lost every ancestor's exposed methods, denying all calls
139
+ with `IMQ_RPC_NO_ACCESS`. The function now walks the runtime prototype chain,
140
+ which has no gaps, applying each link root-first so a subclass method still
141
+ overrides a same-named parent one. `getClassMethods` is module-private, so the
142
+ signature change is not an API change.
143
+
144
+ - **The metrics endpoint advertised `plain/text`**, which is not a valid MIME
145
+ type, so scrapers keying on content type saw an unknown one. It is now
146
+ `text/plain`.
147
+
9
148
  ## [3.4.4] - 2026-07-26
10
149
 
11
150
  ### Changed
package/README.md CHANGED
@@ -1,6 +1,8 @@
1
1
  # I Message Queue RPC (@imqueue/rpc)
2
2
 
3
- [![License](https://img.shields.io/badge/license-GPL-blue.svg)](https://rawgit.com/imqueue/rpc/master/LICENSE)
3
+ [![Build Status](https://img.shields.io/github/actions/workflow/status/imqueue/rpc/build.yml)](https://github.com/imqueue/rpc/actions/workflows/build.yml)
4
+ [![npm version](https://img.shields.io/npm/v/@imqueue/rpc)](https://www.npmjs.com/package/@imqueue/rpc)
5
+ [![License](https://img.shields.io/badge/license-GPL-blue.svg)](https://github.com/imqueue/rpc/blob/master/LICENSE)
4
6
 
5
7
  RPC-like client-service implementation over messaging queue. This module
6
8
  provides base set of abstract classes and decorators to build services and
@@ -14,7 +16,9 @@ on) and [@imqueue/cli](https://github.com/imqueue/cli) (scaffolding & client
14
16
  generation).
15
17
 
16
18
  **Using an AI assistant?** Point it at [imqueue.org/llms.txt](https://imqueue.org/llms.txt)
17
- for a machine-readable index of the docs, or see [AGENTS.md](./AGENTS.md).
19
+ for a machine-readable index of the docs, or see [AGENTS.md](./AGENTS.md). Current
20
+ version, licence and Node floor for every package:
21
+ [imqueue.org/status.json](https://imqueue.org/status.json).
18
22
 
19
23
  ## Why?
20
24
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@imqueue/rpc",
3
- "version": "3.6.1",
3
+ "version": "3.7.1",
4
4
  "description": "Type-safe RPC framework for Node.js & TypeScript microservices over a Redis message queue — self-describing services generate their own strongly-typed clients (@imqueue framework)",
5
5
  "keywords": [
6
6
  "redis",
@@ -41,7 +41,7 @@
41
41
  },
42
42
  "repository": {
43
43
  "type": "git",
44
- "url": "git@github.com/imqueue/rpc.git"
44
+ "url": "git+https://github.com/imqueue/rpc.git"
45
45
  },
46
46
  "bugs": {
47
47
  "url": "https://github.com/imqueue/rpc/issues"
@@ -51,7 +51,7 @@
51
51
  "author": "imqueue.com <support@imqueue.com> (https://imqueue.com)",
52
52
  "license": "GPL-3.0-only",
53
53
  "dependencies": {
54
- "@imqueue/core": "^3.3.3",
54
+ "@imqueue/core": "^3.4.2",
55
55
  "acorn": "^8.17.0",
56
56
  "typescript": "^7.0.2"
57
57
  },
@@ -1,3 +1,20 @@
1
1
  {
2
- "signedContributors": []
2
+ "signedContributors": [
3
+ {
4
+ "name": "creomobile",
5
+ "id": 25711804,
6
+ "comment_id": 5346985474,
7
+ "created_at": "2026-08-19T19:27:27Z",
8
+ "repoId": 124483013,
9
+ "pullRequestNo": 34
10
+ },
11
+ {
12
+ "name": "creomobile",
13
+ "id": 25711804,
14
+ "comment_id": 5347025718,
15
+ "created_at": "2026-08-19T19:31:25Z",
16
+ "repoId": 124483013,
17
+ "pullRequestNo": 34
18
+ }
19
+ ]
3
20
  }
package/src/IMQClient.js CHANGED
@@ -57,7 +57,7 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
57
57
  */
58
58
  import IMQ, { IMQ_SHUTDOWN_TIMEOUT, } from '@imqueue/core';
59
59
  import { DEFAULT_IMQ_CLIENT_OPTIONS, IMQDelay, IMQError, remote, Description, IMQMetadata, BEFORE_HOOK_ERROR, AFTER_HOOK_ERROR, } from './index.js';
60
- import { pid, forgetPid, osUuid, fileExists, mkdir, writeFile, SIGNALS, } from './helpers/index.js';
60
+ import { pid, forgetPid, osUuid, fileExists, mkdir, writeFile, logSafe, SIGNALS, } from './helpers/index.js';
61
61
  import { EventEmitter } from 'node:events';
62
62
  import { Script } from 'node:vm';
63
63
  import { spawnSync } from 'node:child_process';
@@ -349,6 +349,8 @@ let IMQClient = (() => {
349
349
  // extends the budget accordingly
350
350
  timer = setTimeout(() => {
351
351
  delete this.resolvers[id];
352
+ // not logged here: the caller receives the
353
+ // rejection below and decides how to report it
352
354
  doReject(IMQError('IMQ_RPC_CALL_TIMEOUT', `Call to ${to}.${method}() timed out after ${callTimeout} ms.`, new Error().stack, method, args));
353
355
  }, callTimeout + delay);
354
356
  timer.unref?.();
@@ -416,6 +418,11 @@ let IMQClient = (() => {
416
418
  // current redis mock, BTW it was tested manually on real
417
419
  // redis run
418
420
  if (!this.resolvers[message.to]) {
421
+ // a response nobody is waiting for any more: either it came
422
+ // after the call had been given up on, or the call was made
423
+ // by a process which is gone. Neither the response nor its
424
+ // error is logged - the response echoes the request back
425
+ logSafe(this.logger, 'warn', `${this.serviceName}: response to request ${message?.to} has no pending call, method ${message?.request?.method}`);
419
426
  // when there is no resolvers it means
420
427
  // we have message in queue which was initiated
421
428
  // by some process which is broken. So we provide an
@@ -61,12 +61,14 @@ export interface LoggedDecoratorOptions {
61
61
  }
62
62
  /**
63
63
  * Creates a `@logged()` method decorator that wraps the decorated method in a
64
- * try/catch and logs any error it throws. The logger is resolved in this
65
- * order: an explicitly passed logger, then a `logger` defined on the instance
66
- * or on the class, and finally the global `console`. By default the error is
67
- * re-thrown after being logged; pass `{ doNotThrow: true }` to swallow it. The
68
- * returned decorator is dual-mode: it works both as a standard (TC39) and as a
69
- * legacy method decorator.
64
+ * try/catch and logs any error it throws. The logged line names the class, the
65
+ * method and an allow-listed failure code — never the error object itself,
66
+ * whose message, stack and properties may carry application data. The logger
67
+ * is resolved in this order: an explicitly passed logger, then a `logger`
68
+ * defined on the instance or on the class, and finally the global `console`.
69
+ * By default the error is re-thrown after being logged; pass
70
+ * `{ doNotThrow: true }` to swallow it. The returned decorator is dual-mode:
71
+ * it works both as a standard (TC39) and as a legacy method decorator.
70
72
  *
71
73
  * @param options - a logger to use, or the
72
74
  * logged-decorator options
@@ -22,14 +22,37 @@
22
22
  * <support@imqueue.com> to get commercial licensing options.
23
23
  */
24
24
  import {} from '@imqueue/core';
25
+ import { errorCode } from '../helpers/index.js';
26
+ /**
27
+ * Name of the class a decorated method was called on, or `unknown` when it
28
+ * cannot be told.
29
+ *
30
+ * @param self - the `this` of the decorated call
31
+ * @returns the class name
32
+ *
33
+ * @remarks
34
+ * On a static method `this` is the class itself, so its own name is the answer
35
+ * there — going through the constructor would report `Function`.
36
+ */
37
+ function className(self) {
38
+ try {
39
+ const name = typeof self === 'function' ? self.name : self?.constructor?.name;
40
+ return typeof name === 'string' && name ? name : 'unknown';
41
+ }
42
+ catch {
43
+ return 'unknown';
44
+ }
45
+ }
25
46
  /**
26
47
  * Creates a `@logged()` method decorator that wraps the decorated method in a
27
- * try/catch and logs any error it throws. The logger is resolved in this
28
- * order: an explicitly passed logger, then a `logger` defined on the instance
29
- * or on the class, and finally the global `console`. By default the error is
30
- * re-thrown after being logged; pass `{ doNotThrow: true }` to swallow it. The
31
- * returned decorator is dual-mode: it works both as a standard (TC39) and as a
32
- * legacy method decorator.
48
+ * try/catch and logs any error it throws. The logged line names the class, the
49
+ * method and an allow-listed failure code — never the error object itself,
50
+ * whose message, stack and properties may carry application data. The logger
51
+ * is resolved in this order: an explicitly passed logger, then a `logger`
52
+ * defined on the instance or on the class, and finally the global `console`.
53
+ * By default the error is re-thrown after being logged; pass
54
+ * `{ doNotThrow: true }` to swallow it. The returned decorator is dual-mode:
55
+ * it works both as a standard (TC39) and as a legacy method decorator.
33
56
  *
34
57
  * @param options - a logger to use, or the
35
58
  * logged-decorator options
@@ -40,7 +63,7 @@ export function logged(options) {
40
63
  ? options.level
41
64
  : 'error';
42
65
  const doThrow = !options || !options.doNotThrow;
43
- const wrap = (original) => async function (...args) {
66
+ const wrap = (original, method) => async function (...args) {
44
67
  try {
45
68
  if (original) {
46
69
  return await original.apply(this, args);
@@ -59,7 +82,24 @@ export function logged(options) {
59
82
  this.constructor.logger
60
83
  ? this.constructor.logger
61
84
  : console;
62
- logger[level](err);
85
+ // the caught value itself is never printed: an application
86
+ // error may carry personal data, and an imq error carries the
87
+ // call arguments in its own properties. Only the class, the
88
+ // method and the failure code go out
89
+ let where = 'unknown.unknown()';
90
+ let code = 'unknown';
91
+ try {
92
+ where = `${className(this)}.${method || 'unknown'}()`;
93
+ code = errorCode(err);
94
+ }
95
+ catch {
96
+ // extraction must never replace the original error, so
97
+ // the fallbacks above stand
98
+ }
99
+ // deliberately not contained: a throwing logger replaces the
100
+ // original error today, and changing that would be a change
101
+ // of behaviour rather than of logging
102
+ logger[level](`${where} failed, code ${code}`);
63
103
  if (doThrow) {
64
104
  throw err;
65
105
  }
@@ -71,9 +111,9 @@ export function logged(options) {
71
111
  // (target, propertyKey, descriptor).
72
112
  return function (target, context, descriptor) {
73
113
  if (context && typeof context === 'object' && 'kind' in context) {
74
- return wrap(target);
114
+ return wrap(target, context.name && String(context.name));
75
115
  }
76
- descriptor.value = wrap(descriptor.value);
116
+ descriptor.value = wrap(descriptor.value, context && String(context));
77
117
  return descriptor;
78
118
  };
79
119
  }
@@ -24,3 +24,4 @@ export * from './signature.js';
24
24
  export * from './os-uuid.js';
25
25
  export * from './pid.js';
26
26
  export * from './fs.js';
27
+ export * from './logging.js';
@@ -24,4 +24,5 @@ export * from './signature.js';
24
24
  export * from './os-uuid.js';
25
25
  export * from './pid.js';
26
26
  export * from './fs.js';
27
+ export * from './logging.js';
27
28
  //# sourceMappingURL=index.js.map
@@ -0,0 +1,51 @@
1
+ /*!
2
+ * I'm Queue Software Project
3
+ * Copyright (C) 2025 imqueue.com <support@imqueue.com>
4
+ *
5
+ * This program is free software: you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation, either version 3 of the License, or
8
+ * (at your option) any later version.
9
+ *
10
+ * This program is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ * GNU General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License
16
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ *
18
+ * If you want to use this code in a closed source (commercial) project, you can
19
+ * purchase a proprietary commercial license. Please contact us at
20
+ * <support@imqueue.com> to get commercial licensing options.
21
+ */
22
+ import { type ILogger } from '@imqueue/core';
23
+ /**
24
+ * Writes the given line through the given logger, containing any logger
25
+ * failure.
26
+ *
27
+ * @param logger - logger to write the line with
28
+ * @param level - logger method to use
29
+ * @param message - the line, which must never carry call arguments, request
30
+ * or response objects or an error text
31
+ *
32
+ * @remarks
33
+ * Never throws: a broken logger must not be able to change what the caller
34
+ * does.
35
+ */
36
+ export declare function logSafe(logger: ILogger, level: 'info' | 'warn' | 'error', message: string): void;
37
+ /**
38
+ * Extracts a loggable failure code from an unknown thrown value.
39
+ *
40
+ * @param err - the caught value, of any shape
41
+ * @returns the code, or `unknown` when none can be told safely
42
+ *
43
+ * @remarks
44
+ * Deliberately conservative: only an allow-listed code can come out of here,
45
+ * because an application error reaches this helper too and anything of its own
46
+ * may carry personal data. Recognised are a framework or system `code`, a
47
+ * small numeric `code`, the leading token of a known Redis error reply and a
48
+ * known redis-client failure message. Everything else — including the error's
49
+ * message, its stack and its class name — yields `unknown`. Never throws.
50
+ */
51
+ export declare function errorCode(err: unknown): string;
@@ -0,0 +1,140 @@
1
+ /*!
2
+ * I'm Queue Software Project
3
+ * Copyright (C) 2025 imqueue.com <support@imqueue.com>
4
+ *
5
+ * This program is free software: you can redistribute it and/or modify
6
+ * it under the terms of the GNU General Public License as published by
7
+ * the Free Software Foundation, either version 3 of the License, or
8
+ * (at your option) any later version.
9
+ *
10
+ * This program is distributed in the hope that it will be useful,
11
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
12
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13
+ * GNU General Public License for more details.
14
+ *
15
+ * You should have received a copy of the GNU General Public License
16
+ * along with this program. If not, see <https://www.gnu.org/licenses/>.
17
+ *
18
+ * If you want to use this code in a closed source (commercial) project, you can
19
+ * purchase a proprietary commercial license. Please contact us at
20
+ * <support@imqueue.com> to get commercial licensing options.
21
+ */
22
+ import {} from '@imqueue/core';
23
+ /**
24
+ * Writes the given line through the given logger, containing any logger
25
+ * failure.
26
+ *
27
+ * @param logger - logger to write the line with
28
+ * @param level - logger method to use
29
+ * @param message - the line, which must never carry call arguments, request
30
+ * or response objects or an error text
31
+ *
32
+ * @remarks
33
+ * Never throws: a broken logger must not be able to change what the caller
34
+ * does.
35
+ */
36
+ export function logSafe(logger, level, message) {
37
+ try {
38
+ logger[level](message);
39
+ }
40
+ catch {
41
+ // a failing logger must never influence behaviour
42
+ }
43
+ }
44
+ /**
45
+ * Redis error replies this helper is allowed to quote. The leading token of a
46
+ * Redis error reply is a protocol constant, never data — but only these are
47
+ * recognised, so an arbitrary upper-case first word of some other error's
48
+ * message can never reach the log.
49
+ */
50
+ const REDIS_REPLY_CODES = new Set([
51
+ 'ASK',
52
+ 'BUSY',
53
+ 'BUSYGROUP',
54
+ 'CLUSTERDOWN',
55
+ 'CROSSSLOT',
56
+ 'ERR',
57
+ 'EXECABORT',
58
+ 'LOADING',
59
+ 'MASTERDOWN',
60
+ 'MISCONF',
61
+ 'MOVED',
62
+ 'NOAUTH',
63
+ 'NOGROUP',
64
+ 'NOPERM',
65
+ 'NOPROTO',
66
+ 'NOREPLICAS',
67
+ 'NOSCRIPT',
68
+ 'NOTBUSY',
69
+ 'OOM',
70
+ 'READONLY',
71
+ 'TRYAGAIN',
72
+ 'UNBLOCKED',
73
+ 'UNKILLABLE',
74
+ 'WRONGPASS',
75
+ 'WRONGTYPE',
76
+ ]);
77
+ /**
78
+ * Transport failures the redis client reports by message only, mapped to a
79
+ * code of our own. The patterns are fixed library strings, so nothing from an
80
+ * application error can match them.
81
+ */
82
+ const CLIENT_MESSAGE_CODES = [
83
+ [/^Connection is closed/i, 'CONNECTION_CLOSED'],
84
+ [/^Stream connection ended/i, 'STREAM_ENDED'],
85
+ [/^Reached the max retries per request limit/i, 'MAX_RETRIES'],
86
+ [/^Command timed out/i, 'COMMAND_TIMEOUT'],
87
+ ];
88
+ /**
89
+ * Shape of an `err.code` this helper accepts: an `IMQ_`-prefixed code of the
90
+ * framework itself, or a system errno such as `ECONNREFUSED`.
91
+ */
92
+ const SAFE_CODE = /^(IMQ_[A-Z0-9_]{1,48}|E[A-Z]{2,15})$/;
93
+ /** Upper bound of a numeric `err.code`, so that no long number can pass */
94
+ const MAX_NUMERIC_CODE = 65535;
95
+ /**
96
+ * Extracts a loggable failure code from an unknown thrown value.
97
+ *
98
+ * @param err - the caught value, of any shape
99
+ * @returns the code, or `unknown` when none can be told safely
100
+ *
101
+ * @remarks
102
+ * Deliberately conservative: only an allow-listed code can come out of here,
103
+ * because an application error reaches this helper too and anything of its own
104
+ * may carry personal data. Recognised are a framework or system `code`, a
105
+ * small numeric `code`, the leading token of a known Redis error reply and a
106
+ * known redis-client failure message. Everything else — including the error's
107
+ * message, its stack and its class name — yields `unknown`. Never throws.
108
+ */
109
+ export function errorCode(err) {
110
+ try {
111
+ const code = err?.code;
112
+ if (typeof code === 'number' &&
113
+ Number.isInteger(code) &&
114
+ code >= 0 &&
115
+ code <= MAX_NUMERIC_CODE) {
116
+ return String(code);
117
+ }
118
+ if (typeof code === 'string' &&
119
+ (SAFE_CODE.test(code) || REDIS_REPLY_CODES.has(code))) {
120
+ return code;
121
+ }
122
+ const message = err?.message;
123
+ if (typeof message === 'string') {
124
+ const reply = message.split(' ', 1)[0];
125
+ if (REDIS_REPLY_CODES.has(reply)) {
126
+ return reply;
127
+ }
128
+ for (const [pattern, mapped] of CLIENT_MESSAGE_CODES) {
129
+ if (pattern.test(message)) {
130
+ return mapped;
131
+ }
132
+ }
133
+ }
134
+ return 'unknown';
135
+ }
136
+ catch {
137
+ return 'unknown';
138
+ }
139
+ }
140
+ //# sourceMappingURL=logging.js.map