@imqueue/rpc 3.7.2 → 3.8.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 +8 -0
- package/CHANGELOG.md +51 -0
- package/README.md +42 -0
- package/package.json +2 -2
- 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/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
|
@@ -70,6 +70,7 @@ specs.
|
|
|
70
70
|
| `src/decorators/cache.ts`, `lock.ts`, `logged.ts`, `metadata.ts` | Cross-cutting method decorators. |
|
|
71
71
|
| `src/cache/` (`ICache`, `RedisCache`) | Caching layer for RPC results. |
|
|
72
72
|
| `src/helpers/signature.ts` | JSDoc/source signature extraction (acorn). |
|
|
73
|
+
| `src/helpers/drain.ts` | Graceful-drain config (`IMQ_DRAIN_ENABLE`, `IMQ_DRAIN_TIMEOUT`) and the registry of signal handlers this package installed. |
|
|
73
74
|
| `src/IMQRPCDescription.ts`, `IMQRPCRequest.ts`, `IMQRPCResponse.ts`, `IMQRPCError.ts`, `IMQDelay.ts`, `IMQLock.ts`, `IMQMetadata.ts`, `IMQRequestContext.ts` | RPC wire types & context. |
|
|
74
75
|
|
|
75
76
|
## Authoring rules (behavioural invariants that generated clients depend on)
|
|
@@ -84,6 +85,13 @@ specs.
|
|
|
84
85
|
`@property` fields too.
|
|
85
86
|
- **JSDoc is load-bearing**, not documentation-only (see toolchain note). Keep
|
|
86
87
|
`@param`/`@returns` types accurate.
|
|
88
|
+
- **Graceful draining is opt-in and must stay that way.** `IMQ_DRAIN_ENABLE`
|
|
89
|
+
(or the `drain` option) defaults to off, and with it off the dispatch path,
|
|
90
|
+
the signal handlers and the shutdown timing must be exactly what they were —
|
|
91
|
+
there is a regression test that signals a real child process mid-handler to
|
|
92
|
+
hold that line. When on, `IMQService` drains: `stop()`, bounded wait,
|
|
93
|
+
`destroy()`, `exit(0)`, in that order, because `destroy()` closes the writer
|
|
94
|
+
the in-flight replies still need.
|
|
87
95
|
|
|
88
96
|
## Using this package correctly (for consumer-facing code an agent writes)
|
|
89
97
|
|
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,57 @@ 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
|
+
- **Opt-in graceful shutdown draining.** With `IMQ_DRAIN_ENABLE=1` — or the new
|
|
18
|
+
`drain` service option — `SIGTERM` and `SIGINT` now stop consuming, wait for
|
|
19
|
+
the requests already being handled, publish their replies, tear the transport
|
|
20
|
+
down and exit `0`, in that order. The order is the feature: `stop()` drops the
|
|
21
|
+
reader connection only, so the writer that in-flight replies need stays up
|
|
22
|
+
until `destroy()` runs *after* the wait. Previously the signal handler started
|
|
23
|
+
`destroy()` without awaiting it and force-exited on a fixed timer, so a
|
|
24
|
+
handler still running was abandoned, no reply was ever published, and its
|
|
25
|
+
caller was left holding a promise that never settled — silently, with exit
|
|
26
|
+
code 0.
|
|
27
|
+
- **`IMQ_DRAIN_TIMEOUT` / the `drainTimeout` option**, the drain budget in
|
|
28
|
+
milliseconds, default `4000`. The wait is always bounded: whatever has not
|
|
29
|
+
finished by then is abandoned and logged, and the process exits `0` anyway.
|
|
30
|
+
The default is set by the `imq stop` CLI, which signals the process group,
|
|
31
|
+
polls for about five seconds, then sends `SIGKILL` — a budget above that would
|
|
32
|
+
make the local CLI harsher than a Kubernetes deployment, whose
|
|
33
|
+
`terminationGracePeriodSeconds` defaults to 30 s.
|
|
34
|
+
|
|
35
|
+
Both variables are read numerically, consistent with the rest of the `IMQ_*`
|
|
36
|
+
family, but a non-numeric value throws at construction instead of falling back
|
|
37
|
+
to the default — `IMQ_DRAIN_ENABLE=true` coerces to `NaN` under that
|
|
38
|
+
convention, and a feature flag that quietly reads as *off* is the failure mode
|
|
39
|
+
worth being loud about.
|
|
40
|
+
|
|
41
|
+
### Changed
|
|
42
|
+
|
|
43
|
+
- With draining enabled, requests are tracked at the single point where an
|
|
44
|
+
incoming message is dispatched, so every `@expose()`d method is covered
|
|
45
|
+
automatically — no per-method wrapper to add and none to forget. Bookkeeping
|
|
46
|
+
attaches to a *derived* promise, leaving a handler's rejection its caller's to
|
|
47
|
+
handle and never producing an unhandled rejection of its own.
|
|
48
|
+
- With draining enabled, a service forces `handleSignals: false` on its queue
|
|
49
|
+
and its drain takes over the signal handlers this package registered —
|
|
50
|
+
`IMQService`'s own, and any `IMQClient`'s in the same process — each by the
|
|
51
|
+
exact function reference that was registered, so handlers belonging to
|
|
52
|
+
unrelated libraries are left in place. A second signal during a drain forces
|
|
53
|
+
an immediate exit.
|
|
54
|
+
- **Nothing changes with `IMQ_DRAIN_ENABLE` unset or `0`**, which is the
|
|
55
|
+
default: the signal handlers, the timing and the dispatch path are what they
|
|
56
|
+
were, down to the tracking set that is never allocated. Covered by a
|
|
57
|
+
regression test that signals a real process mid-handler and asserts the
|
|
58
|
+
handler is still abandoned.
|
|
59
|
+
|
|
60
|
+
Delivery remains at-least-once in every mode. A drain narrows the window in
|
|
61
|
+
which in-flight work is lost, it does not close it: `SIGKILL`, an OOM kill or
|
|
62
|
+
a lost node still take it, and handlers still need to be idempotent.
|
|
63
|
+
|
|
13
64
|
## [3.7.1] - 2026-08-22
|
|
14
65
|
|
|
15
66
|
### Changed
|
package/README.md
CHANGED
|
@@ -261,6 +261,48 @@ 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
|
+
## Graceful shutdown
|
|
265
|
+
|
|
266
|
+
By default a service signalled mid-request abandons it: the signal handler
|
|
267
|
+
starts `destroy()` without awaiting it and force-exits after
|
|
268
|
+
`IMQ_SHUTDOWN_TIMEOUT`, so the handler never finishes, no reply is published,
|
|
269
|
+
and the caller waits on a promise that never settles.
|
|
270
|
+
|
|
271
|
+
Opt into draining and `SIGTERM`/`SIGINT` instead stop consuming, wait for the
|
|
272
|
+
requests already in flight, then tear down and exit `0`:
|
|
273
|
+
|
|
274
|
+
~~~bash
|
|
275
|
+
IMQ_DRAIN_ENABLE=1
|
|
276
|
+
~~~
|
|
277
|
+
|
|
278
|
+
| variable | option | default | meaning |
|
|
279
|
+
|---|---|---|---|
|
|
280
|
+
| `IMQ_DRAIN_ENABLE` | `drain` | `0` | run a drain on `SIGTERM`/`SIGINT` |
|
|
281
|
+
| `IMQ_DRAIN_TIMEOUT` | `drainTimeout` | `4000` | drain budget, milliseconds |
|
|
282
|
+
|
|
283
|
+
~~~typescript
|
|
284
|
+
const service = new UserService({ drain: true, drainTimeout: 4000 });
|
|
285
|
+
~~~
|
|
286
|
+
|
|
287
|
+
Both are read numerically, like the rest of the `IMQ_*` family — and a
|
|
288
|
+
non-numeric value throws at construction rather than silently reading as *off*.
|
|
289
|
+
Every `@expose()`d method is tracked automatically; there is nothing to wrap.
|
|
290
|
+
|
|
291
|
+
The 4000 ms default sits inside the `imq stop` CLI's five-second
|
|
292
|
+
`SIGTERM`-to-`SIGKILL` window, which is tighter than Kubernetes'
|
|
293
|
+
30-second `terminationGracePeriodSeconds` — raise it for a cluster deployment if
|
|
294
|
+
your handlers need longer.
|
|
295
|
+
|
|
296
|
+
Two things to know. Enabling the drain forces `handleSignals: false` on the
|
|
297
|
+
service's queue, because the queue layer's own handler exits without waiting;
|
|
298
|
+
and the drain takes over the signal handlers this framework registered — by
|
|
299
|
+
exact function reference, so handlers installed by other libraries are
|
|
300
|
+
untouched. A second signal during a drain exits immediately.
|
|
301
|
+
|
|
302
|
+
Delivery remains **at-least-once** either way. A drain narrows the window in
|
|
303
|
+
which in-flight work is lost; `SIGKILL`, an OOM kill or a lost node still take
|
|
304
|
+
it, so handlers must stay idempotent.
|
|
305
|
+
|
|
264
306
|
## Notes
|
|
265
307
|
|
|
266
308
|
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.8.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",
|
|
@@ -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.4.
|
|
54
|
+
"@imqueue/core": "^3.4.3",
|
|
55
55
|
"acorn": "^8.17.0",
|
|
56
56
|
"typescript": "^7.0.2"
|
|
57
57
|
},
|
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();
|
|
@@ -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