@imqueue/rpc 3.7.2 → 3.9.0
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/AGENTS.md +28 -1
- package/CHANGELOG.md +73 -0
- package/README.md +69 -0
- package/package.json +6 -5
- package/src/IMQClient.js +15 -4
- package/src/IMQRPCOptions.d.ts +42 -0
- package/src/IMQService.d.ts +92 -1
- package/src/IMQService.js +191 -6
- package/src/cache/RedisCache.d.ts +9 -2
- package/src/cache/RedisCache.js +53 -1
- package/src/helpers/drain.d.ts +141 -0
- package/src/helpers/drain.js +206 -0
- package/src/helpers/index.d.ts +1 -0
- package/src/helpers/index.js +1 -0
- package/src/index.d.ts +1 -0
- package/src/index.js +2 -0
- package/CLAUDE.md +0 -3
package/AGENTS.md
CHANGED
|
@@ -46,7 +46,8 @@ describes itself and its client is generated from that description.
|
|
|
46
46
|
```bash
|
|
47
47
|
npm install
|
|
48
48
|
npm run build # build ../core (if present) + clean + tsc
|
|
49
|
-
npm test # build + node:test over
|
|
49
|
+
npm test # build + node:test over test/**/*.spec.js, minus test/integration
|
|
50
|
+
npm run test-integration # build + test/integration/**/*.spec.js (real redis)
|
|
50
51
|
npm run lint # oxlint
|
|
51
52
|
npm run format # oxfmt (write) | npm run format:check (verify)
|
|
52
53
|
npm run test-coverage # tests + experimental coverage
|
|
@@ -57,6 +58,24 @@ Tests use the native `node:test` runner with
|
|
|
57
58
|
15s. A local Redis on `localhost:6379` is expected for the integration-style
|
|
58
59
|
specs.
|
|
59
60
|
|
|
61
|
+
**`test/integration/` is different, and must stay outside `npm test`.** Those
|
|
62
|
+
specs run *unmocked* — the preload replaces `ioredis` wholesale, which is fine
|
|
63
|
+
for every option except `tls`, whose whole point is a handshake a mock does not
|
|
64
|
+
perform. `test/integration/tlsBroker.ts` issues a throwaway CA and certificates
|
|
65
|
+
with `openssl`, then starts `redis-server` on a port picked at run time with
|
|
66
|
+
`--port 0 --tls-port <n>`: with no plaintext listener at all, a connection that
|
|
67
|
+
reaches it has demonstrably gone over TLS.
|
|
68
|
+
|
|
69
|
+
**They skip, never fail, when the machine cannot host a broker.**
|
|
70
|
+
`startTlsBroker()` returns a reason string instead of throwing when
|
|
71
|
+
`redis-server` or `openssl` is missing, or when redis will not start with TLS,
|
|
72
|
+
and that reason becomes the suite's `skip`. CI has no redis and must stay
|
|
73
|
+
green, so keep that contract: report a skip reason, do not throw, keep the
|
|
74
|
+
`npm test` glob excluding `test/integration`, and do not add these specs to a
|
|
75
|
+
runner CI invokes. The harness is a copy of the one in `@imqueue/core` — a
|
|
76
|
+
package's `test/` is not published, so there is nothing to import; keep the two
|
|
77
|
+
in step.
|
|
78
|
+
|
|
60
79
|
## Layout
|
|
61
80
|
|
|
62
81
|
| Path | Role |
|
|
@@ -70,6 +89,7 @@ specs.
|
|
|
70
89
|
| `src/decorators/cache.ts`, `lock.ts`, `logged.ts`, `metadata.ts` | Cross-cutting method decorators. |
|
|
71
90
|
| `src/cache/` (`ICache`, `RedisCache`) | Caching layer for RPC results. |
|
|
72
91
|
| `src/helpers/signature.ts` | JSDoc/source signature extraction (acorn). |
|
|
92
|
+
| `src/helpers/drain.ts` | Graceful-drain config (`IMQ_DRAIN_ENABLE`, `IMQ_DRAIN_TIMEOUT`) and the registry of signal handlers this package installed. |
|
|
73
93
|
| `src/IMQRPCDescription.ts`, `IMQRPCRequest.ts`, `IMQRPCResponse.ts`, `IMQRPCError.ts`, `IMQDelay.ts`, `IMQLock.ts`, `IMQMetadata.ts`, `IMQRequestContext.ts` | RPC wire types & context. |
|
|
74
94
|
|
|
75
95
|
## Authoring rules (behavioural invariants that generated clients depend on)
|
|
@@ -84,6 +104,13 @@ specs.
|
|
|
84
104
|
`@property` fields too.
|
|
85
105
|
- **JSDoc is load-bearing**, not documentation-only (see toolchain note). Keep
|
|
86
106
|
`@param`/`@returns` types accurate.
|
|
107
|
+
- **Graceful draining is opt-in and must stay that way.** `IMQ_DRAIN_ENABLE`
|
|
108
|
+
(or the `drain` option) defaults to off, and with it off the dispatch path,
|
|
109
|
+
the signal handlers and the shutdown timing must be exactly what they were —
|
|
110
|
+
there is a regression test that signals a real child process mid-handler to
|
|
111
|
+
hold that line. When on, `IMQService` drains: `stop()`, bounded wait,
|
|
112
|
+
`destroy()`, `exit(0)`, in that order, because `destroy()` closes the writer
|
|
113
|
+
the in-flight replies still need.
|
|
87
114
|
|
|
88
115
|
## Using this package correctly (for consumer-facing code an agent writes)
|
|
89
116
|
|
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,79 @@ raised `@imqueue/core` floor is how most fixes in the transport reach a service.
|
|
|
10
10
|
|
|
11
11
|
This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
|
12
12
|
|
|
13
|
+
## [Unreleased]
|
|
14
|
+
|
|
15
|
+
### Added
|
|
16
|
+
|
|
17
|
+
- **TLS on the cache connection.** `RedisCache.init()` now honours `tls`, which
|
|
18
|
+
it inherited from the queue option shape and silently ignored. `true`
|
|
19
|
+
connects with Node's defaults, an object is handed to `tls.connect()` as
|
|
20
|
+
given, so a private CA and mutual TLS both work — and with it unset the
|
|
21
|
+
`IMQ_REDIS_TLS*` environment variables are consulted, so one setting encrypts
|
|
22
|
+
a service's queues and its method cache together. Requires `@imqueue/core`
|
|
23
|
+
3.5.0, which is where the option became real.
|
|
24
|
+
|
|
25
|
+
Covered by integration specs in `test/integration/`, run by
|
|
26
|
+
`npm run test-integration`, which stand up a throwaway TLS-only redis and
|
|
27
|
+
assert what a mocked `ioredis` cannot: that the handshake completes and is
|
|
28
|
+
verified, that a cached value survives a round trip over it, and that
|
|
29
|
+
plaintext, an unverifiable certificate and a wrong server name are refused
|
|
30
|
+
rather than downgraded. They skip themselves, with a reason, wherever
|
|
31
|
+
`redis-server` and `openssl` are not both available, so a checkout without
|
|
32
|
+
redis still passes; `npm test` excludes them and is unchanged in what it runs.
|
|
33
|
+
|
|
34
|
+
The shared connection is still opened once per process and the first
|
|
35
|
+
initialization still decides its transport. What is new is that a later one
|
|
36
|
+
asking for a different transport is told so, rather than silently handed an
|
|
37
|
+
encrypted connection when it asked for plaintext or, worse, the reverse.
|
|
38
|
+
|
|
39
|
+
- **Opt-in graceful shutdown draining.** With `IMQ_DRAIN_ENABLE=1` — or the new
|
|
40
|
+
`drain` service option — `SIGTERM` and `SIGINT` now stop consuming, wait for
|
|
41
|
+
the requests already being handled, publish their replies, tear the transport
|
|
42
|
+
down and exit `0`, in that order. The order is the feature: `stop()` drops the
|
|
43
|
+
reader connection only, so the writer that in-flight replies need stays up
|
|
44
|
+
until `destroy()` runs *after* the wait. Previously the signal handler started
|
|
45
|
+
`destroy()` without awaiting it and force-exited on a fixed timer, so a
|
|
46
|
+
handler still running was abandoned, no reply was ever published, and its
|
|
47
|
+
caller was left holding a promise that never settled — silently, with exit
|
|
48
|
+
code 0.
|
|
49
|
+
- **`IMQ_DRAIN_TIMEOUT` / the `drainTimeout` option**, the drain budget in
|
|
50
|
+
milliseconds, default `4000`. The wait is always bounded: whatever has not
|
|
51
|
+
finished by then is abandoned and logged, and the process exits `0` anyway.
|
|
52
|
+
The default is set by the `imq stop` CLI, which signals the process group,
|
|
53
|
+
polls for about five seconds, then sends `SIGKILL` — a budget above that would
|
|
54
|
+
make the local CLI harsher than a Kubernetes deployment, whose
|
|
55
|
+
`terminationGracePeriodSeconds` defaults to 30 s.
|
|
56
|
+
|
|
57
|
+
Both variables are read numerically, consistent with the rest of the `IMQ_*`
|
|
58
|
+
family, but a non-numeric value throws at construction instead of falling back
|
|
59
|
+
to the default — `IMQ_DRAIN_ENABLE=true` coerces to `NaN` under that
|
|
60
|
+
convention, and a feature flag that quietly reads as *off* is the failure mode
|
|
61
|
+
worth being loud about.
|
|
62
|
+
|
|
63
|
+
### Changed
|
|
64
|
+
|
|
65
|
+
- With draining enabled, requests are tracked at the single point where an
|
|
66
|
+
incoming message is dispatched, so every `@expose()`d method is covered
|
|
67
|
+
automatically — no per-method wrapper to add and none to forget. Bookkeeping
|
|
68
|
+
attaches to a *derived* promise, leaving a handler's rejection its caller's to
|
|
69
|
+
handle and never producing an unhandled rejection of its own.
|
|
70
|
+
- With draining enabled, a service forces `handleSignals: false` on its queue
|
|
71
|
+
and its drain takes over the signal handlers this package registered —
|
|
72
|
+
`IMQService`'s own, and any `IMQClient`'s in the same process — each by the
|
|
73
|
+
exact function reference that was registered, so handlers belonging to
|
|
74
|
+
unrelated libraries are left in place. A second signal during a drain forces
|
|
75
|
+
an immediate exit.
|
|
76
|
+
- **Nothing changes with `IMQ_DRAIN_ENABLE` unset or `0`**, which is the
|
|
77
|
+
default: the signal handlers, the timing and the dispatch path are what they
|
|
78
|
+
were, down to the tracking set that is never allocated. Covered by a
|
|
79
|
+
regression test that signals a real process mid-handler and asserts the
|
|
80
|
+
handler is still abandoned.
|
|
81
|
+
|
|
82
|
+
Delivery remains at-least-once in every mode. A drain narrows the window in
|
|
83
|
+
which in-flight work is lost, it does not close it: `SIGKILL`, an OOM kill or
|
|
84
|
+
a lost node still take it, and handlers still need to be idempotent.
|
|
85
|
+
|
|
13
86
|
## [3.7.1] - 2026-08-22
|
|
14
87
|
|
|
15
88
|
### Changed
|
package/README.md
CHANGED
|
@@ -261,6 +261,75 @@ Because standard decorators provide no runtime type reflection (there is no
|
|
|
261
261
|
and `removeComments` must remain `false` so those comments survive compilation.
|
|
262
262
|
Undocumented parameters fall back to `any` in generated clients.
|
|
263
263
|
|
|
264
|
+
## Encrypting the method cache
|
|
265
|
+
|
|
266
|
+
`RedisCache` opens its own connection to Redis, separate from the queue's, and
|
|
267
|
+
it takes the same `tls` option:
|
|
268
|
+
|
|
269
|
+
```typescript
|
|
270
|
+
import { IMQCache, RedisCache } from '@imqueue/rpc';
|
|
271
|
+
import { readFileSync } from 'node:fs';
|
|
272
|
+
|
|
273
|
+
IMQCache.register(RedisCache, {
|
|
274
|
+
prefix: 'my-service',
|
|
275
|
+
tls: { ca: readFileSync('/etc/redis-tls/ca.crt') },
|
|
276
|
+
});
|
|
277
|
+
```
|
|
278
|
+
|
|
279
|
+
With `tls` unset the `IMQ_REDIS_TLS*` environment variables are consulted — the
|
|
280
|
+
same ones `@imqueue/core` reads — so one setting encrypts a service's queues
|
|
281
|
+
and its method cache together. Pass `false` to decline that fallback.
|
|
282
|
+
|
|
283
|
+
Two things to know about the connection itself. It is opened **once per
|
|
284
|
+
process** and shared by every `RedisCache` instance, so the first
|
|
285
|
+
initialization decides its transport; a later one asking for something
|
|
286
|
+
different is warned rather than silently given what already exists. And `conn`
|
|
287
|
+
still lets a service hand the cache a connection it already has — a running
|
|
288
|
+
queue's writer, for example — in which case the cache inherits whatever
|
|
289
|
+
transport that connection was opened with.
|
|
290
|
+
|
|
291
|
+
## Graceful shutdown
|
|
292
|
+
|
|
293
|
+
By default a service signalled mid-request abandons it: the signal handler
|
|
294
|
+
starts `destroy()` without awaiting it and force-exits after
|
|
295
|
+
`IMQ_SHUTDOWN_TIMEOUT`, so the handler never finishes, no reply is published,
|
|
296
|
+
and the caller waits on a promise that never settles.
|
|
297
|
+
|
|
298
|
+
Opt into draining and `SIGTERM`/`SIGINT` instead stop consuming, wait for the
|
|
299
|
+
requests already in flight, then tear down and exit `0`:
|
|
300
|
+
|
|
301
|
+
~~~bash
|
|
302
|
+
IMQ_DRAIN_ENABLE=1
|
|
303
|
+
~~~
|
|
304
|
+
|
|
305
|
+
| variable | option | default | meaning |
|
|
306
|
+
|---|---|---|---|
|
|
307
|
+
| `IMQ_DRAIN_ENABLE` | `drain` | `0` | run a drain on `SIGTERM`/`SIGINT` |
|
|
308
|
+
| `IMQ_DRAIN_TIMEOUT` | `drainTimeout` | `4000` | drain budget, milliseconds |
|
|
309
|
+
|
|
310
|
+
~~~typescript
|
|
311
|
+
const service = new UserService({ drain: true, drainTimeout: 4000 });
|
|
312
|
+
~~~
|
|
313
|
+
|
|
314
|
+
Both are read numerically, like the rest of the `IMQ_*` family — and a
|
|
315
|
+
non-numeric value throws at construction rather than silently reading as *off*.
|
|
316
|
+
Every `@expose()`d method is tracked automatically; there is nothing to wrap.
|
|
317
|
+
|
|
318
|
+
The 4000 ms default sits inside the `imq stop` CLI's five-second
|
|
319
|
+
`SIGTERM`-to-`SIGKILL` window, which is tighter than Kubernetes'
|
|
320
|
+
30-second `terminationGracePeriodSeconds` — raise it for a cluster deployment if
|
|
321
|
+
your handlers need longer.
|
|
322
|
+
|
|
323
|
+
Two things to know. Enabling the drain forces `handleSignals: false` on the
|
|
324
|
+
service's queue, because the queue layer's own handler exits without waiting;
|
|
325
|
+
and the drain takes over the signal handlers this framework registered — by
|
|
326
|
+
exact function reference, so handlers installed by other libraries are
|
|
327
|
+
untouched. A second signal during a drain exits immediately.
|
|
328
|
+
|
|
329
|
+
Delivery remains **at-least-once** either way. A drain narrows the window in
|
|
330
|
+
which in-flight work is lost; `SIGKILL`, an OOM kill or a lost node still take
|
|
331
|
+
it, so handlers must stay idempotent.
|
|
332
|
+
|
|
264
333
|
## Notes
|
|
265
334
|
|
|
266
335
|
For image containers builds assign machine UUID in `/etc/machine-id` and
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@imqueue/rpc",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.9.0",
|
|
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",
|
|
@@ -27,10 +27,11 @@
|
|
|
27
27
|
"lint": "oxlint",
|
|
28
28
|
"format": "oxfmt \"index.ts\" \"debug.ts\" \"src/**/*.ts\" \"test/**/*.ts\"",
|
|
29
29
|
"format:check": "oxfmt --check \"index.ts\" \"debug.ts\" \"src/**/*.ts\" \"test/**/*.ts\"",
|
|
30
|
-
"test": "npm run build && node --experimental-test-module-mocks --import ./test/warmup.mjs --test --test-timeout=15000 $(find test -name '*.spec.js')",
|
|
31
|
-
"test-coverage": "npm run build && node --experimental-test-module-mocks --enable-source-maps --import ./test/warmup.mjs --test --experimental-test-coverage --test-timeout=15000 $(find test -name '*.spec.js')",
|
|
32
|
-
"test-lcov": "npm run build && mkdir -p coverage && node --experimental-test-module-mocks --enable-source-maps --import ./test/warmup.mjs --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-timeout=15000 $(find test -name '*.spec.js'); node scripts/strip-comment-coverage.mjs coverage/lcov.info",
|
|
30
|
+
"test": "npm run build && node --experimental-test-module-mocks --import ./test/warmup.mjs --test --test-timeout=15000 $(find test -name '*.spec.js' -not -path 'test/integration/*')",
|
|
31
|
+
"test-coverage": "npm run build && node --experimental-test-module-mocks --enable-source-maps --import ./test/warmup.mjs --test --experimental-test-coverage --test-timeout=15000 $(find test -name '*.spec.js' -not -path 'test/integration/*')",
|
|
32
|
+
"test-lcov": "npm run build && mkdir -p coverage && node --experimental-test-module-mocks --enable-source-maps --import ./test/warmup.mjs --test --experimental-test-coverage --test-reporter=lcov --test-reporter-destination=coverage/lcov.info --test-timeout=15000 $(find test -name '*.spec.js' -not -path 'test/integration/*'); node scripts/strip-comment-coverage.mjs coverage/lcov.info",
|
|
33
33
|
"test-coverage-html": "npm run test-lcov; genhtml coverage/lcov.info --output-directory coverage/html --ignore-errors inconsistent,corrupt,format,mismatch && echo \"Coverage report: file://$(pwd)/coverage/html/index.html\"",
|
|
34
|
+
"test-integration": "npm run build && node --test --test-timeout=60000 $(find test/integration -name '*.spec.js')",
|
|
34
35
|
"test-dev": "npm run test && npm run clean-js && npm run clean-typedefs && npm run clean-maps",
|
|
35
36
|
"clean-typedefs": "find . -name '*.d.ts' -not -wholename '*node_modules*' -not -wholename '*generator*' -type f -delete",
|
|
36
37
|
"clean-maps": "find . -name '*.js.map' -not -wholename '*node_modules*' -not -wholename '*generator*' -type f -delete",
|
|
@@ -51,7 +52,7 @@
|
|
|
51
52
|
"author": "imqueue.com <support@imqueue.com> (https://imqueue.com)",
|
|
52
53
|
"license": "GPL-3.0-only",
|
|
53
54
|
"dependencies": {
|
|
54
|
-
"@imqueue/core": "^3.
|
|
55
|
+
"@imqueue/core": "^3.5.0",
|
|
55
56
|
"acorn": "^8.17.0",
|
|
56
57
|
"typescript": "^7.0.2"
|
|
57
58
|
},
|
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, logSafe, SIGNALS, } from './helpers/index.js';
|
|
60
|
+
import { pid, forgetPid, osUuid, fileExists, mkdir, writeFile, logSafe, SIGNALS, addTrackedSignalHandler, removeTrackedSignalHandler, isProcessDrainEnabled, } 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';
|
|
@@ -201,6 +201,14 @@ let IMQClient = (() => {
|
|
|
201
201
|
'be instantiated directly!');
|
|
202
202
|
}
|
|
203
203
|
this.options = { ...DEFAULT_IMQ_CLIENT_OPTIONS, ...options };
|
|
204
|
+
if (isProcessDrainEnabled()) {
|
|
205
|
+
// a client's queue would otherwise install the queue layer's own
|
|
206
|
+
// signal handlers, which exit the process without waiting — enough
|
|
207
|
+
// to cut short a drain running in the same process. Suppressing
|
|
208
|
+
// them uses the existing option and only ever happens when
|
|
209
|
+
// draining was explicitly opted into.
|
|
210
|
+
this.options.handleSignals = false;
|
|
211
|
+
}
|
|
204
212
|
this.id = pid(baseName);
|
|
205
213
|
this.logger = this.options.logger || /* istanbul ignore next */ console;
|
|
206
214
|
this.hostName =
|
|
@@ -221,9 +229,12 @@ let IMQClient = (() => {
|
|
|
221
229
|
this.destroy().catch(this.logger.error);
|
|
222
230
|
setTimeout(() => process.exit(0), IMQ_SHUTDOWN_TIMEOUT);
|
|
223
231
|
};
|
|
224
|
-
// tracked so destroy() can unregister them (see below)
|
|
232
|
+
// tracked so destroy() can unregister them (see below), and so a
|
|
233
|
+
// service draining in this process can take over from them: this
|
|
234
|
+
// handler exits on a fixed timer and would otherwise cut a drain
|
|
235
|
+
// short from the side
|
|
225
236
|
this.signalHandlers.push([signal, handler]);
|
|
226
|
-
|
|
237
|
+
addTrackedSignalHandler(signal, handler);
|
|
227
238
|
});
|
|
228
239
|
}
|
|
229
240
|
createImq() {
|
|
@@ -459,7 +470,7 @@ let IMQClient = (() => {
|
|
|
459
470
|
// unregister this instance's process signal handlers so destroyed
|
|
460
471
|
// clients do not leak process-level listeners
|
|
461
472
|
for (const [signal, handler] of this.signalHandlers) {
|
|
462
|
-
|
|
473
|
+
removeTrackedSignalHandler(signal, handler);
|
|
463
474
|
}
|
|
464
475
|
this.signalHandlers.length = 0;
|
|
465
476
|
await this.subscriptionImq.unsubscribe();
|
package/src/IMQRPCOptions.d.ts
CHANGED
|
@@ -189,6 +189,48 @@ export interface IMQServiceOptions extends IMQOptions {
|
|
|
189
189
|
* Around hook wrapping the method invocation. See {@link IMQWrapCall}.
|
|
190
190
|
*/
|
|
191
191
|
wrapCall?: IMQWrapCall<IMQService>;
|
|
192
|
+
/**
|
|
193
|
+
* Drain in-flight requests before shutting down on `SIGTERM`/`SIGINT`
|
|
194
|
+
* instead of exiting on a fixed timer.
|
|
195
|
+
*
|
|
196
|
+
* @defaultValue the `IMQ_DRAIN_ENABLE` environment variable, itself
|
|
197
|
+
* defaulting to `false`
|
|
198
|
+
*
|
|
199
|
+
* @remarks
|
|
200
|
+
* Opt-in. Left off, a service behaves exactly as it always has: the signal
|
|
201
|
+
* handler starts `destroy()` without awaiting it and force-exits after
|
|
202
|
+
* `IMQ_SHUTDOWN_TIMEOUT`, so a handler still running is abandoned and its
|
|
203
|
+
* caller never receives a reply.
|
|
204
|
+
*
|
|
205
|
+
* Turned on, the service stops consuming, waits up to
|
|
206
|
+
* {@link IMQServiceOptions.drainTimeout} for the handlers already running
|
|
207
|
+
* to finish and publish their replies, then tears the transport down and
|
|
208
|
+
* exits `0`. Because the queue layer's own signal handlers would exit the
|
|
209
|
+
* process mid-drain, enabling this also forces
|
|
210
|
+
* {@link IMQOptions.handleSignals} to `false` on the service's queue.
|
|
211
|
+
*
|
|
212
|
+
* Delivery stays at-least-once either way — a drain narrows the window in
|
|
213
|
+
* which work is lost, it does not close it.
|
|
214
|
+
*
|
|
215
|
+
* Each process drains its own in-flight work, so under
|
|
216
|
+
* {@link IMQServiceOptions.multiProcess} every forked worker drains
|
|
217
|
+
* separately — and the cluster primary, which runs a consumer of its own,
|
|
218
|
+
* drains only what that consumer was handling.
|
|
219
|
+
*/
|
|
220
|
+
drain?: boolean;
|
|
221
|
+
/**
|
|
222
|
+
* Milliseconds a drain waits for in-flight requests before giving up on
|
|
223
|
+
* them and exiting anyway. Ignored unless
|
|
224
|
+
* {@link IMQServiceOptions.drain} is on.
|
|
225
|
+
*
|
|
226
|
+
* @defaultValue the `IMQ_DRAIN_TIMEOUT` environment variable, itself
|
|
227
|
+
* defaulting to {@link DEFAULT_IMQ_DRAIN_TIMEOUT} (4000)
|
|
228
|
+
*
|
|
229
|
+
* @remarks
|
|
230
|
+
* The wait is always bounded: whatever has not finished by then is
|
|
231
|
+
* abandoned, logged, and the process exits `0` regardless.
|
|
232
|
+
*/
|
|
233
|
+
drainTimeout?: number;
|
|
192
234
|
}
|
|
193
235
|
/**
|
|
194
236
|
* Options accepted by a generated IMQ client.
|
package/src/IMQService.d.ts
CHANGED
|
@@ -102,6 +102,32 @@ export declare abstract class IMQService {
|
|
|
102
102
|
*/
|
|
103
103
|
protected metricsServer?: Server<any, any>;
|
|
104
104
|
private readonly signalHandlers;
|
|
105
|
+
/**
|
|
106
|
+
* Whether this service drains in-flight requests before shutting down.
|
|
107
|
+
* Resolved once, at construction, from `options.drain` falling back to the
|
|
108
|
+
* `IMQ_DRAIN_ENABLE` environment variable.
|
|
109
|
+
*/
|
|
110
|
+
private readonly drainEnabled;
|
|
111
|
+
/**
|
|
112
|
+
* Milliseconds a drain waits for in-flight requests. Resolved once, at
|
|
113
|
+
* construction, from `options.drainTimeout` falling back to the
|
|
114
|
+
* `IMQ_DRAIN_TIMEOUT` environment variable.
|
|
115
|
+
*/
|
|
116
|
+
private readonly drainTimeout;
|
|
117
|
+
/**
|
|
118
|
+
* Requests currently being handled, as promises that never reject.
|
|
119
|
+
*
|
|
120
|
+
* @remarks
|
|
121
|
+
* Allocated only while {@link IMQService.drainEnabled} is on — with
|
|
122
|
+
* draining off there is nothing to track and nothing to allocate, so the
|
|
123
|
+
* dispatch path is byte-for-byte what it always was.
|
|
124
|
+
*/
|
|
125
|
+
private readonly inFlight?;
|
|
126
|
+
/**
|
|
127
|
+
* Set once a drain has begun, so a second signal can be told apart from
|
|
128
|
+
* the first and force an immediate exit.
|
|
129
|
+
*/
|
|
130
|
+
private draining;
|
|
105
131
|
/**
|
|
106
132
|
* This service's name, which is also its queue name and the key its description
|
|
107
133
|
* is cached under.
|
|
@@ -132,10 +158,69 @@ export declare abstract class IMQService {
|
|
|
132
158
|
* `IMQ_SHUTDOWN_TIMEOUT` — a fixed timer, not a drain: requests still being
|
|
133
159
|
* processed are not awaited.
|
|
134
160
|
*
|
|
161
|
+
* With {@link IMQServiceOptions.drain} on — or `IMQ_DRAIN_ENABLE=1` —
|
|
162
|
+
* `SIGTERM` and `SIGINT` instead start a graceful drain: stop consuming,
|
|
163
|
+
* await the requests already in flight for at most
|
|
164
|
+
* {@link IMQServiceOptions.drainTimeout}, then tear down and exit `0`. That
|
|
165
|
+
* drain takes over from every signal handler this package registered,
|
|
166
|
+
* including this service's own for `SIGHUP`/`SIGQUIT` and any client's in
|
|
167
|
+
* the same process, and forces `handleSignals: false` on the queue so the
|
|
168
|
+
* queue layer does not exit mid-drain. Handlers registered by anything
|
|
169
|
+
* other than this package are never touched.
|
|
170
|
+
*
|
|
135
171
|
* The merged options are passed straight to the queue factory, so `vendor` and
|
|
136
172
|
* `cluster`/`clusterManagers` select the transport implementation.
|
|
137
173
|
*/
|
|
138
174
|
constructor(options?: Partial<IMQServiceOptions>, name?: string);
|
|
175
|
+
/**
|
|
176
|
+
* Records a dispatched request as in-flight until it settles, and hands the
|
|
177
|
+
* original promise straight back.
|
|
178
|
+
*
|
|
179
|
+
* @param handled - the dispatch promise for one incoming message
|
|
180
|
+
* @returns `handled`, unchanged
|
|
181
|
+
*
|
|
182
|
+
* @remarks
|
|
183
|
+
* Bookkeeping observes a *derived* promise, never `handled` itself: a
|
|
184
|
+
* rejection therefore stays the original caller's to handle, and the
|
|
185
|
+
* tracking cannot manufacture an unhandled rejection of its own. The
|
|
186
|
+
* derived promise is what the drain waits on, so it is settled — not
|
|
187
|
+
* fulfilled — that matters.
|
|
188
|
+
*/
|
|
189
|
+
private track;
|
|
190
|
+
/**
|
|
191
|
+
* Drains in-flight requests and shuts the service down, in the one order
|
|
192
|
+
* that works.
|
|
193
|
+
*
|
|
194
|
+
* @param signal - the signal that started the drain
|
|
195
|
+
*
|
|
196
|
+
* @remarks
|
|
197
|
+
* `stop()` before the wait, `destroy()` after it. `stop()` drops the reader
|
|
198
|
+
* connection only, so the writer stays up and handlers still running can
|
|
199
|
+
* publish their replies; `destroy()` closes that writer, so calling it
|
|
200
|
+
* before the wait would strand exactly the replies the drain exists to
|
|
201
|
+
* deliver.
|
|
202
|
+
*
|
|
203
|
+
* The wait is bounded by {@link IMQService.drainTimeout} — never
|
|
204
|
+
* open-ended — and the process exits `0` either way.
|
|
205
|
+
*
|
|
206
|
+
* A second signal arriving mid-drain exits immediately, the familiar
|
|
207
|
+
* double-interrupt convention.
|
|
208
|
+
*/
|
|
209
|
+
private runDrain;
|
|
210
|
+
/**
|
|
211
|
+
* Awaits every tracked request, bounded by {@link IMQService.drainTimeout}.
|
|
212
|
+
*
|
|
213
|
+
* @param inFlight - the tracked requests
|
|
214
|
+
*/
|
|
215
|
+
private awaitInFlight;
|
|
216
|
+
/**
|
|
217
|
+
* Runs one teardown step of a drain, logging rather than propagating a
|
|
218
|
+
* failure — a broken step must not leave the process hanging half-drained.
|
|
219
|
+
*
|
|
220
|
+
* @param name - step name, for the log message
|
|
221
|
+
* @param step - the step to run
|
|
222
|
+
*/
|
|
223
|
+
private drainStep;
|
|
139
224
|
/**
|
|
140
225
|
* Handles incoming request and produces corresponding response
|
|
141
226
|
*
|
|
@@ -183,6 +268,10 @@ export declare abstract class IMQService {
|
|
|
183
268
|
* Connections, signal handlers and the metrics server are all left in place —
|
|
184
269
|
* use {@link IMQService.destroy} for full teardown. Calling this first is not a
|
|
185
270
|
* prerequisite for `destroy()`.
|
|
271
|
+
*
|
|
272
|
+
* Only the reader connection is dropped; the writer stays up, which is what
|
|
273
|
+
* lets a drain publish the replies of requests that were already running
|
|
274
|
+
* when the shutdown signal arrived.
|
|
186
275
|
*/
|
|
187
276
|
stop(): Promise<void>;
|
|
188
277
|
/**
|
|
@@ -193,7 +282,9 @@ export declare abstract class IMQService {
|
|
|
193
282
|
* It does not close the metrics server — if
|
|
194
283
|
* {@link IMQMetricsServerOptions.enabled} was set, close
|
|
195
284
|
* `service.metricsServer` yourself, otherwise the open listener keeps the
|
|
196
|
-
* process alive. In-flight requests are not awaited
|
|
285
|
+
* process alive. In-flight requests are not awaited — a graceful drain
|
|
286
|
+
* awaits them *before* reaching here, see
|
|
287
|
+
* {@link IMQServiceOptions.drain}.
|
|
197
288
|
*/
|
|
198
289
|
destroy(): Promise<void>;
|
|
199
290
|
/**
|
package/src/IMQService.js
CHANGED
|
@@ -57,7 +57,7 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
|
|
|
57
57
|
*/
|
|
58
58
|
import IMQ, { profile, IMQ_SHUTDOWN_TIMEOUT, } from '@imqueue/core';
|
|
59
59
|
import { IMQRPCDescription, IMQError, expose, DEFAULT_IMQ_SERVICE_OPTIONS, AFTER_HOOK_ERROR, BEFORE_HOOK_ERROR, DEFAULT_IMQ_METRICS_SERVER_OPTIONS, } from './index.js';
|
|
60
|
-
import { SIGNALS } from './helpers/index.js';
|
|
60
|
+
import { SIGNALS, DRAIN_SIGNALS, addTrackedSignalHandler, removeTrackedSignalHandler, removeTrackedSignalHandlers, drainEnabledFromEnv, drainTimeoutFromEnv, setProcessDrainEnabled, } from './helpers/index.js';
|
|
61
61
|
import { cpus } from 'node:os';
|
|
62
62
|
import cluster, {} from 'node:cluster';
|
|
63
63
|
import {} from './IMQRPCDescription.js';
|
|
@@ -91,6 +91,12 @@ export class Description {
|
|
|
91
91
|
*/
|
|
92
92
|
types;
|
|
93
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* No-op used to derive a never-rejecting promise from a tracked request.
|
|
96
|
+
*/
|
|
97
|
+
function ignore() {
|
|
98
|
+
/* deliberately empty */
|
|
99
|
+
}
|
|
94
100
|
const serviceDescriptions = new Map();
|
|
95
101
|
/**
|
|
96
102
|
* Returns collection of class methods metadata even those are inherited
|
|
@@ -179,6 +185,32 @@ let IMQService = (() => {
|
|
|
179
185
|
*/
|
|
180
186
|
metricsServer;
|
|
181
187
|
signalHandlers = [];
|
|
188
|
+
/**
|
|
189
|
+
* Whether this service drains in-flight requests before shutting down.
|
|
190
|
+
* Resolved once, at construction, from `options.drain` falling back to the
|
|
191
|
+
* `IMQ_DRAIN_ENABLE` environment variable.
|
|
192
|
+
*/
|
|
193
|
+
drainEnabled;
|
|
194
|
+
/**
|
|
195
|
+
* Milliseconds a drain waits for in-flight requests. Resolved once, at
|
|
196
|
+
* construction, from `options.drainTimeout` falling back to the
|
|
197
|
+
* `IMQ_DRAIN_TIMEOUT` environment variable.
|
|
198
|
+
*/
|
|
199
|
+
drainTimeout;
|
|
200
|
+
/**
|
|
201
|
+
* Requests currently being handled, as promises that never reject.
|
|
202
|
+
*
|
|
203
|
+
* @remarks
|
|
204
|
+
* Allocated only while {@link IMQService.drainEnabled} is on — with
|
|
205
|
+
* draining off there is nothing to track and nothing to allocate, so the
|
|
206
|
+
* dispatch path is byte-for-byte what it always was.
|
|
207
|
+
*/
|
|
208
|
+
inFlight;
|
|
209
|
+
/**
|
|
210
|
+
* Set once a drain has begun, so a second signal can be told apart from
|
|
211
|
+
* the first and force an immediate exit.
|
|
212
|
+
*/
|
|
213
|
+
draining = false;
|
|
182
214
|
/**
|
|
183
215
|
* This service's name, which is also its queue name and the key its description
|
|
184
216
|
* is cached under.
|
|
@@ -209,6 +241,16 @@ let IMQService = (() => {
|
|
|
209
241
|
* `IMQ_SHUTDOWN_TIMEOUT` — a fixed timer, not a drain: requests still being
|
|
210
242
|
* processed are not awaited.
|
|
211
243
|
*
|
|
244
|
+
* With {@link IMQServiceOptions.drain} on — or `IMQ_DRAIN_ENABLE=1` —
|
|
245
|
+
* `SIGTERM` and `SIGINT` instead start a graceful drain: stop consuming,
|
|
246
|
+
* await the requests already in flight for at most
|
|
247
|
+
* {@link IMQServiceOptions.drainTimeout}, then tear down and exit `0`. That
|
|
248
|
+
* drain takes over from every signal handler this package registered,
|
|
249
|
+
* including this service's own for `SIGHUP`/`SIGQUIT` and any client's in
|
|
250
|
+
* the same process, and forces `handleSignals: false` on the queue so the
|
|
251
|
+
* queue layer does not exit mid-drain. Handlers registered by anything
|
|
252
|
+
* other than this package are never touched.
|
|
253
|
+
*
|
|
212
254
|
* The merged options are passed straight to the queue factory, so `vendor` and
|
|
213
255
|
* `cluster`/`clusterManagers` select the transport implementation.
|
|
214
256
|
*/
|
|
@@ -227,9 +269,37 @@ let IMQService = (() => {
|
|
|
227
269
|
},
|
|
228
270
|
};
|
|
229
271
|
this.logger = this.options.logger || /* istanbul ignore next */ console;
|
|
272
|
+
this.drainEnabled = this.options.drain ?? drainEnabledFromEnv();
|
|
273
|
+
this.drainTimeout = this.options.drainTimeout ?? drainTimeoutFromEnv();
|
|
274
|
+
if (this.drainEnabled) {
|
|
275
|
+
this.inFlight = new Set();
|
|
276
|
+
// the queue layer installs its own SIGTERM/SIGINT handlers, which
|
|
277
|
+
// exit the process without waiting for in-flight work and would
|
|
278
|
+
// therefore cut a drain short. Suppressing them is what the
|
|
279
|
+
// existing `handleSignals` option is for, so no queue-side change
|
|
280
|
+
// is needed — but it does mean the drain now owns shutdown.
|
|
281
|
+
this.options.handleSignals = false;
|
|
282
|
+
setProcessDrainEnabled(true);
|
|
283
|
+
}
|
|
230
284
|
this.imq = IMQ.create(this.name, this.options);
|
|
231
285
|
this.handleRequest = this.handleRequest.bind(this);
|
|
232
286
|
SIGNALS.forEach((signal) => {
|
|
287
|
+
if (this.drainEnabled && DRAIN_SIGNALS.includes(signal)) {
|
|
288
|
+
const handler = () => {
|
|
289
|
+
// a drain that throws must not leave the process hanging
|
|
290
|
+
// on an unhandled rejection with no handlers left
|
|
291
|
+
this.runDrain(signal).catch(err => {
|
|
292
|
+
this.logger.error(`${this.name}: drain failed:`, err);
|
|
293
|
+
process.exit(1);
|
|
294
|
+
});
|
|
295
|
+
};
|
|
296
|
+
// deliberately NOT put in the shared registry: a drain removes
|
|
297
|
+
// everything registered there, and this handler has to outlive
|
|
298
|
+
// that so a second signal can still force an immediate exit
|
|
299
|
+
this.signalHandlers.push([signal, handler]);
|
|
300
|
+
process.on(signal, handler);
|
|
301
|
+
return;
|
|
302
|
+
}
|
|
233
303
|
const handler = () => {
|
|
234
304
|
this.destroy().catch(this.logger.error);
|
|
235
305
|
if (this.metricsServer) {
|
|
@@ -237,14 +307,123 @@ let IMQService = (() => {
|
|
|
237
307
|
}
|
|
238
308
|
setTimeout(() => process.exit(0), IMQ_SHUTDOWN_TIMEOUT);
|
|
239
309
|
};
|
|
240
|
-
// tracked so destroy() can unregister them (see below)
|
|
310
|
+
// tracked so destroy() can unregister them (see below), and so a
|
|
311
|
+
// drain elsewhere in this process can take over from them
|
|
241
312
|
this.signalHandlers.push([signal, handler]);
|
|
242
|
-
|
|
313
|
+
addTrackedSignalHandler(signal, handler);
|
|
243
314
|
});
|
|
244
315
|
// guard the async handler: a failure while processing or publishing
|
|
245
316
|
// the response (e.g. the broker went away mid-reply) must be logged,
|
|
246
317
|
// not surface as an unhandled rejection and crash the process
|
|
247
|
-
this.imq.on('message', ((request, id) =>
|
|
318
|
+
this.imq.on('message', ((request, id) => {
|
|
319
|
+
const handled = this.handleRequest(request, id).catch(err => this.logger.error(`${this.name}: error handling request:`, err));
|
|
320
|
+
// fast path with draining off: no set, no tracking, no
|
|
321
|
+
// allocation beyond what this dispatch already did
|
|
322
|
+
return this.inFlight ? this.track(handled) : handled;
|
|
323
|
+
}));
|
|
324
|
+
}
|
|
325
|
+
/**
|
|
326
|
+
* Records a dispatched request as in-flight until it settles, and hands the
|
|
327
|
+
* original promise straight back.
|
|
328
|
+
*
|
|
329
|
+
* @param handled - the dispatch promise for one incoming message
|
|
330
|
+
* @returns `handled`, unchanged
|
|
331
|
+
*
|
|
332
|
+
* @remarks
|
|
333
|
+
* Bookkeeping observes a *derived* promise, never `handled` itself: a
|
|
334
|
+
* rejection therefore stays the original caller's to handle, and the
|
|
335
|
+
* tracking cannot manufacture an unhandled rejection of its own. The
|
|
336
|
+
* derived promise is what the drain waits on, so it is settled — not
|
|
337
|
+
* fulfilled — that matters.
|
|
338
|
+
*/
|
|
339
|
+
track(handled) {
|
|
340
|
+
const inFlight = this.inFlight;
|
|
341
|
+
const settled = handled.then(ignore, ignore);
|
|
342
|
+
inFlight.add(settled);
|
|
343
|
+
void settled.then(() => {
|
|
344
|
+
inFlight.delete(settled);
|
|
345
|
+
});
|
|
346
|
+
return handled;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Drains in-flight requests and shuts the service down, in the one order
|
|
350
|
+
* that works.
|
|
351
|
+
*
|
|
352
|
+
* @param signal - the signal that started the drain
|
|
353
|
+
*
|
|
354
|
+
* @remarks
|
|
355
|
+
* `stop()` before the wait, `destroy()` after it. `stop()` drops the reader
|
|
356
|
+
* connection only, so the writer stays up and handlers still running can
|
|
357
|
+
* publish their replies; `destroy()` closes that writer, so calling it
|
|
358
|
+
* before the wait would strand exactly the replies the drain exists to
|
|
359
|
+
* deliver.
|
|
360
|
+
*
|
|
361
|
+
* The wait is bounded by {@link IMQService.drainTimeout} — never
|
|
362
|
+
* open-ended — and the process exits `0` either way.
|
|
363
|
+
*
|
|
364
|
+
* A second signal arriving mid-drain exits immediately, the familiar
|
|
365
|
+
* double-interrupt convention.
|
|
366
|
+
*/
|
|
367
|
+
async runDrain(signal) {
|
|
368
|
+
if (this.draining) {
|
|
369
|
+
this.logger.warn('%s: %s received during drain, exiting immediately', this.name, signal);
|
|
370
|
+
process.exit(0);
|
|
371
|
+
}
|
|
372
|
+
this.draining = true;
|
|
373
|
+
// take over from the framework's fixed-timer handlers — this service's
|
|
374
|
+
// own for the other signals, any other service's, and any client's in
|
|
375
|
+
// this process — every one of which exits without awaiting in-flight
|
|
376
|
+
// work. Only references this package registered are removed, so
|
|
377
|
+
// handlers belonging to unrelated libraries are left alone.
|
|
378
|
+
removeTrackedSignalHandlers();
|
|
379
|
+
const inFlight = this.inFlight;
|
|
380
|
+
this.logger.info('%s: draining on %s, %s request(s) in flight, budget %sms', this.name, signal, inFlight.size, this.drainTimeout);
|
|
381
|
+
await this.drainStep('stop', () => this.stop());
|
|
382
|
+
if (this.metricsServer) {
|
|
383
|
+
this.metricsServer.close();
|
|
384
|
+
}
|
|
385
|
+
await this.awaitInFlight(inFlight);
|
|
386
|
+
await this.drainStep('destroy', () => this.destroy());
|
|
387
|
+
process.exit(0);
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Awaits every tracked request, bounded by {@link IMQService.drainTimeout}.
|
|
391
|
+
*
|
|
392
|
+
* @param inFlight - the tracked requests
|
|
393
|
+
*/
|
|
394
|
+
async awaitInFlight(inFlight) {
|
|
395
|
+
if (!inFlight.size) {
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
let timer;
|
|
399
|
+
const expired = new Promise(resolve => {
|
|
400
|
+
timer = setTimeout(resolve, this.drainTimeout);
|
|
401
|
+
});
|
|
402
|
+
// every tracked promise is derived and never rejects, so this race
|
|
403
|
+
// settles on completion or on the budget running out, never on an error
|
|
404
|
+
// Promise.all drains the iterable synchronously, so the deletions the
|
|
405
|
+
// tracked promises perform as they settle cannot disturb it
|
|
406
|
+
await Promise.race([Promise.all(inFlight), expired]);
|
|
407
|
+
clearTimeout(timer);
|
|
408
|
+
if (inFlight.size) {
|
|
409
|
+
this.logger.warn('%s: drain budget of %sms expired, abandoning %s in-flight ' +
|
|
410
|
+
'request(s)', this.name, this.drainTimeout, inFlight.size);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
/**
|
|
414
|
+
* Runs one teardown step of a drain, logging rather than propagating a
|
|
415
|
+
* failure — a broken step must not leave the process hanging half-drained.
|
|
416
|
+
*
|
|
417
|
+
* @param name - step name, for the log message
|
|
418
|
+
* @param step - the step to run
|
|
419
|
+
*/
|
|
420
|
+
async drainStep(name, step) {
|
|
421
|
+
try {
|
|
422
|
+
await step();
|
|
423
|
+
}
|
|
424
|
+
catch (err) {
|
|
425
|
+
this.logger.error(`${this.name}: drain ${name}() failed:`, err);
|
|
426
|
+
}
|
|
248
427
|
}
|
|
249
428
|
/**
|
|
250
429
|
* Handles incoming request and produces corresponding response
|
|
@@ -388,6 +567,10 @@ let IMQService = (() => {
|
|
|
388
567
|
* Connections, signal handlers and the metrics server are all left in place —
|
|
389
568
|
* use {@link IMQService.destroy} for full teardown. Calling this first is not a
|
|
390
569
|
* prerequisite for `destroy()`.
|
|
570
|
+
*
|
|
571
|
+
* Only the reader connection is dropped; the writer stays up, which is what
|
|
572
|
+
* lets a drain publish the replies of requests that were already running
|
|
573
|
+
* when the shutdown signal arrived.
|
|
391
574
|
*/
|
|
392
575
|
async stop() {
|
|
393
576
|
await this.imq.stop();
|
|
@@ -400,13 +583,15 @@ let IMQService = (() => {
|
|
|
400
583
|
* It does not close the metrics server — if
|
|
401
584
|
* {@link IMQMetricsServerOptions.enabled} was set, close
|
|
402
585
|
* `service.metricsServer` yourself, otherwise the open listener keeps the
|
|
403
|
-
* process alive. In-flight requests are not awaited
|
|
586
|
+
* process alive. In-flight requests are not awaited — a graceful drain
|
|
587
|
+
* awaits them *before* reaching here, see
|
|
588
|
+
* {@link IMQServiceOptions.drain}.
|
|
404
589
|
*/
|
|
405
590
|
async destroy() {
|
|
406
591
|
// unregister this instance's process signal handlers so destroyed
|
|
407
592
|
// services do not leak process-level listeners
|
|
408
593
|
for (const [signal, handler] of this.signalHandlers) {
|
|
409
|
-
|
|
594
|
+
removeTrackedSignalHandler(signal, handler);
|
|
410
595
|
}
|
|
411
596
|
this.signalHandlers.length = 0;
|
|
412
597
|
await this.imq.unsubscribe();
|
|
@@ -28,8 +28,14 @@ import { type ICache } from './index.js';
|
|
|
28
28
|
*
|
|
29
29
|
* @remarks
|
|
30
30
|
* This inherits the queue option shape, but the adapter only honours `host`,
|
|
31
|
-
* `port`, `username`, `password`, `prefix`, `logger` and `conn`. All
|
|
32
|
-
* inherited queue options are accepted by the type and silently ignored.
|
|
31
|
+
* `port`, `username`, `password`, `tls`, `prefix`, `logger` and `conn`. All
|
|
32
|
+
* other inherited queue options are accepted by the type and silently ignored.
|
|
33
|
+
*
|
|
34
|
+
* `tls` encrypts the cache connection exactly as it encrypts a queue's: `true`
|
|
35
|
+
* for Node's defaults, an object handed to `tls.connect()` as given, and when
|
|
36
|
+
* omitted the `IMQ_REDIS_TLS*` environment variables are consulted, so a
|
|
37
|
+
* deployment can encrypt its caches and its queues with one setting. Pass
|
|
38
|
+
* `false` to decline that fallback.
|
|
33
39
|
*/
|
|
34
40
|
export interface IRedisCacheOptions extends Partial<IMQOptions> {
|
|
35
41
|
/**
|
|
@@ -61,6 +67,7 @@ export declare const REDIS_CLIENT_INIT_ERROR = "Redis client is not initialized!
|
|
|
61
67
|
*/
|
|
62
68
|
export declare class RedisCache implements ICache {
|
|
63
69
|
private static redis?;
|
|
70
|
+
private static tlsPrint?;
|
|
64
71
|
private static initPromise?;
|
|
65
72
|
private logger;
|
|
66
73
|
/**
|
package/src/cache/RedisCache.js
CHANGED
|
@@ -21,7 +21,7 @@
|
|
|
21
21
|
* purchase a proprietary commercial license. Please contact us at
|
|
22
22
|
* <support@imqueue.com> to get commercial licensing options.
|
|
23
23
|
*/
|
|
24
|
-
import { DEFAULT_IMQ_OPTIONS, Redis, } from '@imqueue/core';
|
|
24
|
+
import { DEFAULT_IMQ_OPTIONS, envTls, Redis, tlsFingerprint, } from '@imqueue/core';
|
|
25
25
|
import { hostname } from 'node:os';
|
|
26
26
|
import {} from './index.js';
|
|
27
27
|
/**
|
|
@@ -47,6 +47,11 @@ export const REDIS_CLIENT_INIT_ERROR = 'Redis client is not initialized!';
|
|
|
47
47
|
*/
|
|
48
48
|
export class RedisCache {
|
|
49
49
|
static redis;
|
|
50
|
+
// fingerprint of the TLS configuration the shared connection was opened
|
|
51
|
+
// with, so a later init() asking for a different one can be told that it
|
|
52
|
+
// is getting the existing connection rather than the transport it asked
|
|
53
|
+
// for. Absent when the shared connection is plaintext.
|
|
54
|
+
static tlsPrint;
|
|
50
55
|
// pending shared connection attempt; concurrent init() calls await this
|
|
51
56
|
// single promise instead of opening one connection each
|
|
52
57
|
static initPromise;
|
|
@@ -87,12 +92,50 @@ export class RedisCache {
|
|
|
87
92
|
...options,
|
|
88
93
|
};
|
|
89
94
|
this.logger = this.options.logger || console;
|
|
95
|
+
if (this.options.tls === undefined) {
|
|
96
|
+
// an unreadable CA or client key throws out of here rather than
|
|
97
|
+
// yielding a cache that would quietly talk to redis in the clear
|
|
98
|
+
const fromEnv = envTls();
|
|
99
|
+
if (fromEnv !== undefined) {
|
|
100
|
+
// assigned only when the environment actually asks for TLS, so
|
|
101
|
+
// that a cache nobody configured for it carries no `tls` key at
|
|
102
|
+
// all and `options` keeps exactly the shape it always had
|
|
103
|
+
this.options.tls = fromEnv;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
const tlsPrint = this.options.tls
|
|
107
|
+
? tlsFingerprint(this.options.tls)
|
|
108
|
+
: undefined;
|
|
109
|
+
if (this.options.tls &&
|
|
110
|
+
this.options.tls !== true &&
|
|
111
|
+
this.options.tls.rejectUnauthorized === false) {
|
|
112
|
+
this.logger.warn('%s: TLS certificate verification is disabled for the cache' +
|
|
113
|
+
' connection to %s:%s — it is encrypted but the server is' +
|
|
114
|
+
' not authenticated, so it is open to interception', this.name, this.options.host, this.options.port);
|
|
115
|
+
}
|
|
90
116
|
if (RedisCache.redis && !RedisCache.initPromise) {
|
|
117
|
+
// the connection is process-wide and the first caller's transport
|
|
118
|
+
// is what every later one gets. Silently handing a caller that
|
|
119
|
+
// asked for TLS a plaintext connection - or the reverse - is the
|
|
120
|
+
// one case where that is worth saying out loud
|
|
121
|
+
if (tlsPrint !== RedisCache.tlsPrint) {
|
|
122
|
+
this.logger.warn('%s: re-using the existing %s cache connection, which is' +
|
|
123
|
+
' not the transport these options asked for — the' +
|
|
124
|
+
' first initialization in a process decides it', this.name, RedisCache.tlsPrint ? 'encrypted' : 'plaintext');
|
|
125
|
+
}
|
|
91
126
|
this.ready = true;
|
|
92
127
|
return this;
|
|
93
128
|
}
|
|
94
129
|
if (this.options.conn && !RedisCache.initPromise) {
|
|
95
130
|
this.logger.info('Re-using given connection for cache.');
|
|
131
|
+
// the caller's own connection brings its transport with it, so
|
|
132
|
+
// read the fingerprint off the client rather than off the options
|
|
133
|
+
// this adapter was handed - otherwise a reused TLS connection
|
|
134
|
+
// would be reported as plaintext to whoever initializes next. It
|
|
135
|
+
// comes from outside this package and need not be a full client,
|
|
136
|
+
// so read through it rather than assume the option bag is there.
|
|
137
|
+
const given = this.options.conn.options?.tls;
|
|
138
|
+
RedisCache.tlsPrint = given ? tlsFingerprint(given) : undefined;
|
|
96
139
|
RedisCache.redis = this.options.conn;
|
|
97
140
|
this.ready = true;
|
|
98
141
|
return this;
|
|
@@ -100,11 +143,19 @@ export class RedisCache {
|
|
|
100
143
|
if (!RedisCache.initPromise) {
|
|
101
144
|
RedisCache.initPromise = new Promise((resolve, reject) => {
|
|
102
145
|
const connectionName = `${this.options.prefix}:${this.name}:pid:${process.pid}:host:${hostname()}`;
|
|
146
|
+
RedisCache.tlsPrint = tlsPrint;
|
|
103
147
|
RedisCache.redis = new Redis({
|
|
104
148
|
port: Number(this.options.port),
|
|
105
149
|
host: String(this.options.host),
|
|
106
150
|
username: this.options.username,
|
|
107
151
|
password: this.options.password,
|
|
152
|
+
...(this.options.tls
|
|
153
|
+
? {
|
|
154
|
+
tls: this.options.tls === true
|
|
155
|
+
? {}
|
|
156
|
+
: this.options.tls,
|
|
157
|
+
}
|
|
158
|
+
: {}),
|
|
108
159
|
connectionName,
|
|
109
160
|
});
|
|
110
161
|
RedisCache.redis.on('ready', () => {
|
|
@@ -215,6 +266,7 @@ export class RedisCache {
|
|
|
215
266
|
*/
|
|
216
267
|
static async destroy() {
|
|
217
268
|
RedisCache.initPromise = undefined;
|
|
269
|
+
RedisCache.tlsPrint = undefined;
|
|
218
270
|
try {
|
|
219
271
|
if (RedisCache.redis) {
|
|
220
272
|
RedisCache.redis.removeAllListeners();
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* IMQ-RPC helpers: graceful drain configuration and signal-handler registry
|
|
3
|
+
*
|
|
4
|
+
* I'm Queue Software Project
|
|
5
|
+
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
|
|
6
|
+
*
|
|
7
|
+
* This program is free software: you can redistribute it and/or modify
|
|
8
|
+
* it under the terms of the GNU General Public License as published by
|
|
9
|
+
* the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
* (at your option) any later version.
|
|
11
|
+
*
|
|
12
|
+
* This program is distributed in the hope that it will be useful,
|
|
13
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
* GNU General Public License for more details.
|
|
16
|
+
*
|
|
17
|
+
* You should have received a copy of the GNU General Public License
|
|
18
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
19
|
+
*
|
|
20
|
+
* If you want to use this code in a closed source (commercial) project, you can
|
|
21
|
+
* purchase a proprietary commercial license. Please contact us at
|
|
22
|
+
* <support@imqueue.com> to get commercial licensing options.
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Default drain budget in milliseconds, used when neither
|
|
26
|
+
* {@link IMQServiceOptions.drainTimeout} nor the `IMQ_DRAIN_TIMEOUT`
|
|
27
|
+
* environment variable is set.
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* Chosen to sit below the `imq stop` CLI's escalation window: the CLI signals
|
|
31
|
+
* the process group, then polls liveness 20 times at 250 ms (~5 s) before
|
|
32
|
+
* sending `SIGKILL`. A budget above that would let the local CLI kill a
|
|
33
|
+
* draining service harder than a cluster would, which is backwards. 4000 ms
|
|
34
|
+
* leaves roughly a second of headroom for `stop()`, `destroy()` and process
|
|
35
|
+
* teardown inside that window.
|
|
36
|
+
*
|
|
37
|
+
* Kubernetes is not the binding constraint here — its
|
|
38
|
+
* `terminationGracePeriodSeconds` defaults to 30 s — so raise this (and the
|
|
39
|
+
* CLI is then the odd one out) only for deployments that never use `imq stop`.
|
|
40
|
+
*/
|
|
41
|
+
export declare const DEFAULT_IMQ_DRAIN_TIMEOUT = 4000;
|
|
42
|
+
/**
|
|
43
|
+
* Signals that trigger a graceful drain when draining is enabled.
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* A deliberate subset of {@link SIGNALS}: `SIGHUP` and `SIGQUIT` keep the
|
|
47
|
+
* framework's pre-existing immediate-shutdown behaviour.
|
|
48
|
+
*/
|
|
49
|
+
export declare const DRAIN_SIGNALS: readonly string[];
|
|
50
|
+
/**
|
|
51
|
+
* A process signal handler registered by this framework.
|
|
52
|
+
*/
|
|
53
|
+
export type SignalHandler = (...args: any[]) => void;
|
|
54
|
+
/**
|
|
55
|
+
* Installs a process signal handler and records it, so
|
|
56
|
+
* {@link removeTrackedSignalHandlers} can take it back off again.
|
|
57
|
+
*
|
|
58
|
+
* @param signal - the signal to listen for
|
|
59
|
+
* @param handler - the handler to install
|
|
60
|
+
*/
|
|
61
|
+
export declare function addTrackedSignalHandler(signal: string, handler: SignalHandler): void;
|
|
62
|
+
/**
|
|
63
|
+
* Removes a previously tracked signal handler from the process and from the
|
|
64
|
+
* registry.
|
|
65
|
+
*
|
|
66
|
+
* @param signal - the signal the handler was installed for
|
|
67
|
+
* @param handler - the exact handler reference that was installed
|
|
68
|
+
*/
|
|
69
|
+
export declare function removeTrackedSignalHandler(signal: string, handler: SignalHandler): void;
|
|
70
|
+
/**
|
|
71
|
+
* Removes every signal handler this package has installed, leaving handlers
|
|
72
|
+
* installed by anything else untouched.
|
|
73
|
+
*
|
|
74
|
+
* @remarks
|
|
75
|
+
* Used at the start of a drain: the framework's pre-existing handlers exit the
|
|
76
|
+
* process on a fixed timer without waiting for in-flight work, which is exactly
|
|
77
|
+
* what a drain must prevent. Drain handlers themselves are never registered
|
|
78
|
+
* here, so they survive this and can still force an immediate exit on a second
|
|
79
|
+
* signal.
|
|
80
|
+
*/
|
|
81
|
+
export declare function removeTrackedSignalHandlers(): void;
|
|
82
|
+
/**
|
|
83
|
+
* Marks this process as running with draining enabled.
|
|
84
|
+
*
|
|
85
|
+
* @param enabled - whether a drain-enabled service exists in this process
|
|
86
|
+
*/
|
|
87
|
+
export declare function setProcessDrainEnabled(enabled: boolean): void;
|
|
88
|
+
/**
|
|
89
|
+
* Whether draining is enabled anywhere in this process, either through the
|
|
90
|
+
* `IMQ_DRAIN_ENABLE` environment variable or through a service constructed
|
|
91
|
+
* with the `drain` option.
|
|
92
|
+
*/
|
|
93
|
+
export declare function isProcessDrainEnabled(): boolean;
|
|
94
|
+
/**
|
|
95
|
+
* Reads a boolean `IMQ_*` environment variable.
|
|
96
|
+
*
|
|
97
|
+
* @param name - environment variable name
|
|
98
|
+
* @param defaultValue - value to use when the variable is unset or empty
|
|
99
|
+
* @returns the parsed flag
|
|
100
|
+
* @throws TypeError when the variable is set to something non-numeric
|
|
101
|
+
*
|
|
102
|
+
* @remarks
|
|
103
|
+
* Numeric coercion matches the rest of the framework's boolean `IMQ_*`
|
|
104
|
+
* variables, which are read as `!!+(process.env.X || 0)`. Under that
|
|
105
|
+
* convention a well-meant `IMQ_DRAIN_ENABLE=true` coerces to `NaN` and reads
|
|
106
|
+
* as *disabled* — a feature silently not doing anything. So anything that is
|
|
107
|
+
* not a number throws instead.
|
|
108
|
+
*/
|
|
109
|
+
export declare function envFlag(name: string, defaultValue: boolean): boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Reads a millisecond-valued `IMQ_*` environment variable.
|
|
112
|
+
*
|
|
113
|
+
* @param name - environment variable name
|
|
114
|
+
* @param defaultValue - value to use when the variable is unset or empty
|
|
115
|
+
* @returns the parsed duration in milliseconds
|
|
116
|
+
* @throws TypeError when the variable is set to something that is not a finite
|
|
117
|
+
* number greater than zero
|
|
118
|
+
*/
|
|
119
|
+
export declare function envMs(name: string, defaultValue: number): number;
|
|
120
|
+
/**
|
|
121
|
+
* Whether `IMQ_DRAIN_ENABLE` turns draining on.
|
|
122
|
+
*
|
|
123
|
+
* @returns `true` only when the variable is set to a non-zero number
|
|
124
|
+
* @throws TypeError when the variable is set to a non-numeric value
|
|
125
|
+
*
|
|
126
|
+
* @remarks
|
|
127
|
+
* Read on every call rather than memoized at import time, unlike core's
|
|
128
|
+
* `IMQ_SHUTDOWN_TIMEOUT`. Services resolve it once, at construction, so an
|
|
129
|
+
* environment loaded after this module is imported — a `.env` file, a test
|
|
130
|
+
* harness — still takes effect.
|
|
131
|
+
*/
|
|
132
|
+
export declare function drainEnabledFromEnv(): boolean;
|
|
133
|
+
/**
|
|
134
|
+
* The drain budget in milliseconds from `IMQ_DRAIN_TIMEOUT`, falling back to
|
|
135
|
+
* {@link DEFAULT_IMQ_DRAIN_TIMEOUT}.
|
|
136
|
+
*
|
|
137
|
+
* @returns the drain budget in milliseconds
|
|
138
|
+
* @throws TypeError when the variable is set to a non-positive or non-numeric
|
|
139
|
+
* value
|
|
140
|
+
*/
|
|
141
|
+
export declare function drainTimeoutFromEnv(): number;
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* IMQ-RPC helpers: graceful drain configuration and signal-handler registry
|
|
3
|
+
*
|
|
4
|
+
* I'm Queue Software Project
|
|
5
|
+
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
|
|
6
|
+
*
|
|
7
|
+
* This program is free software: you can redistribute it and/or modify
|
|
8
|
+
* it under the terms of the GNU General Public License as published by
|
|
9
|
+
* the Free Software Foundation, either version 3 of the License, or
|
|
10
|
+
* (at your option) any later version.
|
|
11
|
+
*
|
|
12
|
+
* This program is distributed in the hope that it will be useful,
|
|
13
|
+
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
14
|
+
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
15
|
+
* GNU General Public License for more details.
|
|
16
|
+
*
|
|
17
|
+
* You should have received a copy of the GNU General Public License
|
|
18
|
+
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
|
19
|
+
*
|
|
20
|
+
* If you want to use this code in a closed source (commercial) project, you can
|
|
21
|
+
* purchase a proprietary commercial license. Please contact us at
|
|
22
|
+
* <support@imqueue.com> to get commercial licensing options.
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Default drain budget in milliseconds, used when neither
|
|
26
|
+
* {@link IMQServiceOptions.drainTimeout} nor the `IMQ_DRAIN_TIMEOUT`
|
|
27
|
+
* environment variable is set.
|
|
28
|
+
*
|
|
29
|
+
* @remarks
|
|
30
|
+
* Chosen to sit below the `imq stop` CLI's escalation window: the CLI signals
|
|
31
|
+
* the process group, then polls liveness 20 times at 250 ms (~5 s) before
|
|
32
|
+
* sending `SIGKILL`. A budget above that would let the local CLI kill a
|
|
33
|
+
* draining service harder than a cluster would, which is backwards. 4000 ms
|
|
34
|
+
* leaves roughly a second of headroom for `stop()`, `destroy()` and process
|
|
35
|
+
* teardown inside that window.
|
|
36
|
+
*
|
|
37
|
+
* Kubernetes is not the binding constraint here — its
|
|
38
|
+
* `terminationGracePeriodSeconds` defaults to 30 s — so raise this (and the
|
|
39
|
+
* CLI is then the odd one out) only for deployments that never use `imq stop`.
|
|
40
|
+
*/
|
|
41
|
+
export const DEFAULT_IMQ_DRAIN_TIMEOUT = 4000;
|
|
42
|
+
/**
|
|
43
|
+
* Signals that trigger a graceful drain when draining is enabled.
|
|
44
|
+
*
|
|
45
|
+
* @remarks
|
|
46
|
+
* A deliberate subset of {@link SIGNALS}: `SIGHUP` and `SIGQUIT` keep the
|
|
47
|
+
* framework's pre-existing immediate-shutdown behaviour.
|
|
48
|
+
*/
|
|
49
|
+
export const DRAIN_SIGNALS = ['SIGTERM', 'SIGINT'];
|
|
50
|
+
/**
|
|
51
|
+
* Every signal handler this package has installed on the process, by the exact
|
|
52
|
+
* function reference, so a drain can take over from them without disturbing
|
|
53
|
+
* handlers installed by unrelated libraries.
|
|
54
|
+
*
|
|
55
|
+
* @remarks
|
|
56
|
+
* `process.removeAllListeners(signal)` would also drop those foreign handlers,
|
|
57
|
+
* which is why registration is tracked explicitly instead.
|
|
58
|
+
*/
|
|
59
|
+
const registry = new Map();
|
|
60
|
+
/**
|
|
61
|
+
* Set once any service in this process is constructed with draining enabled.
|
|
62
|
+
*
|
|
63
|
+
* @remarks
|
|
64
|
+
* Read by {@link IMQClient} so that clients living in a draining service's
|
|
65
|
+
* process do not let the queue layer's own signal handlers cut the drain
|
|
66
|
+
* short. It is only consulted when draining was enabled through constructor
|
|
67
|
+
* options; the environment variable is visible to every component directly.
|
|
68
|
+
*/
|
|
69
|
+
let processDrainEnabled = false;
|
|
70
|
+
/**
|
|
71
|
+
* Installs a process signal handler and records it, so
|
|
72
|
+
* {@link removeTrackedSignalHandlers} can take it back off again.
|
|
73
|
+
*
|
|
74
|
+
* @param signal - the signal to listen for
|
|
75
|
+
* @param handler - the handler to install
|
|
76
|
+
*/
|
|
77
|
+
export function addTrackedSignalHandler(signal, handler) {
|
|
78
|
+
let handlers = registry.get(signal);
|
|
79
|
+
if (!handlers) {
|
|
80
|
+
handlers = new Set();
|
|
81
|
+
registry.set(signal, handlers);
|
|
82
|
+
}
|
|
83
|
+
handlers.add(handler);
|
|
84
|
+
process.on(signal, handler);
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* Removes a previously tracked signal handler from the process and from the
|
|
88
|
+
* registry.
|
|
89
|
+
*
|
|
90
|
+
* @param signal - the signal the handler was installed for
|
|
91
|
+
* @param handler - the exact handler reference that was installed
|
|
92
|
+
*/
|
|
93
|
+
export function removeTrackedSignalHandler(signal, handler) {
|
|
94
|
+
registry.get(signal)?.delete(handler);
|
|
95
|
+
process.removeListener(signal, handler);
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Removes every signal handler this package has installed, leaving handlers
|
|
99
|
+
* installed by anything else untouched.
|
|
100
|
+
*
|
|
101
|
+
* @remarks
|
|
102
|
+
* Used at the start of a drain: the framework's pre-existing handlers exit the
|
|
103
|
+
* process on a fixed timer without waiting for in-flight work, which is exactly
|
|
104
|
+
* what a drain must prevent. Drain handlers themselves are never registered
|
|
105
|
+
* here, so they survive this and can still force an immediate exit on a second
|
|
106
|
+
* signal.
|
|
107
|
+
*/
|
|
108
|
+
export function removeTrackedSignalHandlers() {
|
|
109
|
+
for (const [signal, handlers] of registry) {
|
|
110
|
+
for (const handler of handlers) {
|
|
111
|
+
process.removeListener(signal, handler);
|
|
112
|
+
}
|
|
113
|
+
handlers.clear();
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
/**
|
|
117
|
+
* Marks this process as running with draining enabled.
|
|
118
|
+
*
|
|
119
|
+
* @param enabled - whether a drain-enabled service exists in this process
|
|
120
|
+
*/
|
|
121
|
+
export function setProcessDrainEnabled(enabled) {
|
|
122
|
+
processDrainEnabled = processDrainEnabled || enabled;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Whether draining is enabled anywhere in this process, either through the
|
|
126
|
+
* `IMQ_DRAIN_ENABLE` environment variable or through a service constructed
|
|
127
|
+
* with the `drain` option.
|
|
128
|
+
*/
|
|
129
|
+
export function isProcessDrainEnabled() {
|
|
130
|
+
return processDrainEnabled || drainEnabledFromEnv();
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Reads a boolean `IMQ_*` environment variable.
|
|
134
|
+
*
|
|
135
|
+
* @param name - environment variable name
|
|
136
|
+
* @param defaultValue - value to use when the variable is unset or empty
|
|
137
|
+
* @returns the parsed flag
|
|
138
|
+
* @throws TypeError when the variable is set to something non-numeric
|
|
139
|
+
*
|
|
140
|
+
* @remarks
|
|
141
|
+
* Numeric coercion matches the rest of the framework's boolean `IMQ_*`
|
|
142
|
+
* variables, which are read as `!!+(process.env.X || 0)`. Under that
|
|
143
|
+
* convention a well-meant `IMQ_DRAIN_ENABLE=true` coerces to `NaN` and reads
|
|
144
|
+
* as *disabled* — a feature silently not doing anything. So anything that is
|
|
145
|
+
* not a number throws instead.
|
|
146
|
+
*/
|
|
147
|
+
export function envFlag(name, defaultValue) {
|
|
148
|
+
const raw = process.env[name];
|
|
149
|
+
if (raw === undefined || raw === '') {
|
|
150
|
+
return defaultValue;
|
|
151
|
+
}
|
|
152
|
+
const value = Number(raw);
|
|
153
|
+
if (!Number.isFinite(value)) {
|
|
154
|
+
throw new TypeError(`${name} must be 0 or 1, got ${JSON.stringify(raw)}. ` +
|
|
155
|
+
'Boolean IMQ_* variables are read numerically.');
|
|
156
|
+
}
|
|
157
|
+
return !!value;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Reads a millisecond-valued `IMQ_*` environment variable.
|
|
161
|
+
*
|
|
162
|
+
* @param name - environment variable name
|
|
163
|
+
* @param defaultValue - value to use when the variable is unset or empty
|
|
164
|
+
* @returns the parsed duration in milliseconds
|
|
165
|
+
* @throws TypeError when the variable is set to something that is not a finite
|
|
166
|
+
* number greater than zero
|
|
167
|
+
*/
|
|
168
|
+
export function envMs(name, defaultValue) {
|
|
169
|
+
const raw = process.env[name];
|
|
170
|
+
if (raw === undefined || raw === '') {
|
|
171
|
+
return defaultValue;
|
|
172
|
+
}
|
|
173
|
+
const value = Number(raw);
|
|
174
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
175
|
+
throw new TypeError(`${name} must be a positive number of milliseconds, ` +
|
|
176
|
+
`got ${JSON.stringify(raw)}.`);
|
|
177
|
+
}
|
|
178
|
+
return value;
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Whether `IMQ_DRAIN_ENABLE` turns draining on.
|
|
182
|
+
*
|
|
183
|
+
* @returns `true` only when the variable is set to a non-zero number
|
|
184
|
+
* @throws TypeError when the variable is set to a non-numeric value
|
|
185
|
+
*
|
|
186
|
+
* @remarks
|
|
187
|
+
* Read on every call rather than memoized at import time, unlike core's
|
|
188
|
+
* `IMQ_SHUTDOWN_TIMEOUT`. Services resolve it once, at construction, so an
|
|
189
|
+
* environment loaded after this module is imported — a `.env` file, a test
|
|
190
|
+
* harness — still takes effect.
|
|
191
|
+
*/
|
|
192
|
+
export function drainEnabledFromEnv() {
|
|
193
|
+
return envFlag('IMQ_DRAIN_ENABLE', false);
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* The drain budget in milliseconds from `IMQ_DRAIN_TIMEOUT`, falling back to
|
|
197
|
+
* {@link DEFAULT_IMQ_DRAIN_TIMEOUT}.
|
|
198
|
+
*
|
|
199
|
+
* @returns the drain budget in milliseconds
|
|
200
|
+
* @throws TypeError when the variable is set to a non-positive or non-numeric
|
|
201
|
+
* value
|
|
202
|
+
*/
|
|
203
|
+
export function drainTimeoutFromEnv() {
|
|
204
|
+
return envMs('IMQ_DRAIN_TIMEOUT', DEFAULT_IMQ_DRAIN_TIMEOUT);
|
|
205
|
+
}
|
|
206
|
+
//# sourceMappingURL=drain.js.map
|
package/src/helpers/index.d.ts
CHANGED
package/src/helpers/index.js
CHANGED
package/src/index.d.ts
CHANGED
package/src/index.js
CHANGED
|
@@ -33,4 +33,6 @@ export * from './IMQService.js';
|
|
|
33
33
|
export * from './IMQClient.js';
|
|
34
34
|
export * from './IMQMetadata.js';
|
|
35
35
|
export * from './IMQRequestContext.js';
|
|
36
|
+
// graceful-drain configuration surface; the remaining helpers stay internal
|
|
37
|
+
export { DEFAULT_IMQ_DRAIN_TIMEOUT, DRAIN_SIGNALS } from './helpers/drain.js';
|
|
36
38
|
//# sourceMappingURL=index.js.map
|
package/CLAUDE.md
DELETED