@imqueue/rpc 3.10.0 → 3.12.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/CHANGELOG.md +44 -0
- package/README.md +123 -0
- package/package.json +1 -1
- package/src/IMQClient.d.ts +32 -2
- package/src/IMQClient.js +105 -3
- package/src/IMQLocal.d.ts +93 -0
- package/src/IMQLocal.js +59 -0
- package/src/IMQRPCOptions.d.ts +81 -0
- package/src/IMQService.d.ts +22 -0
- package/src/IMQService.js +90 -14
- package/src/index.d.ts +1 -0
- package/src/index.js +1 -0
- package/AGENTS.md +0 -161
- package/CONTRIBUTION-TERMS.md +0 -79
- package/signatures/version1/cla.json +0 -20
package/CHANGELOG.md
CHANGED
|
@@ -10,6 +10,50 @@ 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
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- **A client honours `handleSignals: false`.** `IMQClient` installed its own
|
|
18
|
+
`SIGTERM`/`SIGINT`/`SIGHUP`/`SIGQUIT` handlers regardless of the option, and
|
|
19
|
+
those destroy the client — abandoning the calls still pending — and exit the
|
|
20
|
+
process after `IMQ_SHUTDOWN_TIMEOUT`. The option only reached the queue
|
|
21
|
+
layer, so a process that owns its shutdown, such as an HTTP gateway holding
|
|
22
|
+
clients, could not finish one: measured on a gateway under 50 req/s of
|
|
23
|
+
300 ms calls, a `SIGTERM` cut 15 requests mid-flight with the gateway's own
|
|
24
|
+
close-then-destroy handler installed and `handleSignals: false` set. Now
|
|
25
|
+
`handleSignals: false` means neither the client nor its queue installs a
|
|
26
|
+
handler, and the same gateway stops with none cut. The default is unchanged.
|
|
27
|
+
- **A service honours it the same way.** `IMQService` with
|
|
28
|
+
`handleSignals: false` no longer installs its fixed-timer signal handlers
|
|
29
|
+
either. A drain is an opt-in of its own, so with draining on `SIGTERM` and
|
|
30
|
+
`SIGINT` still start it; `drain: false` hands those to the host too.
|
|
31
|
+
|
|
32
|
+
### Changed
|
|
33
|
+
|
|
34
|
+
- A service or client that passed `handleSignals: false` and relied on this
|
|
35
|
+
package's handlers to exit the process on a signal no longer gets them. With
|
|
36
|
+
no handler of the host's own, Node's default applies to `SIGTERM`, `SIGINT`
|
|
37
|
+
and `SIGHUP` — the process ends at once, without `destroy()`; install a
|
|
38
|
+
handler that calls `destroy()` and exits, or leave the option at its
|
|
39
|
+
default.
|
|
40
|
+
- With draining enabled in the process, a client still installs its own
|
|
41
|
+
handlers for the drain to take over, as before — unless the host passed
|
|
42
|
+
`handleSignals: false` itself, in which case it installs none.
|
|
43
|
+
|
|
44
|
+
## [3.11.0] - 2026-11-12
|
|
45
|
+
|
|
46
|
+
### Added
|
|
47
|
+
|
|
48
|
+
- **A service served in process.** `local: true` on a service registers it,
|
|
49
|
+
once started, with every client in its own process, and those clients call
|
|
50
|
+
it directly — the same checks, hooks and method, with no trip through the
|
|
51
|
+
queue. The request and the answer are each copied through JSON, as the queue
|
|
52
|
+
copies them, so values arrive exactly as they would have. The queue is still
|
|
53
|
+
served, so other processes, delayed calls and `publish()` are unaffected. A
|
|
54
|
+
client's `local: false` keeps it on the queue. `localService()`,
|
|
55
|
+
`localServiceNames()` and `wireCopy()` are exported for a host.
|
|
56
|
+
|
|
13
57
|
## [3.10.0] - 2026-11-12
|
|
14
58
|
|
|
15
59
|
### Added
|
package/README.md
CHANGED
|
@@ -330,6 +330,129 @@ Delivery remains **at-least-once** either way. A drain narrows the window in
|
|
|
330
330
|
which in-flight work is lost; `SIGKILL`, an OOM kill or a lost node still take
|
|
331
331
|
it, so handlers must stay idempotent.
|
|
332
332
|
|
|
333
|
+
### A host that owns shutdown
|
|
334
|
+
|
|
335
|
+
A client installs signal handlers too: on `SIGTERM`, `SIGINT`, `SIGHUP` or
|
|
336
|
+
`SIGQUIT` it destroys itself — abandoning the calls still waiting for an
|
|
337
|
+
answer — and exits the process after `IMQ_SHUTDOWN_TIMEOUT`. In a process whose
|
|
338
|
+
job is something else, such as an HTTP gateway holding clients, that exit cuts
|
|
339
|
+
the host's own shutdown short. Pass `handleSignals: false` and neither the
|
|
340
|
+
client nor its queue installs a handler; the host stops taking work, lets what
|
|
341
|
+
it accepted finish, and only then destroys the client:
|
|
342
|
+
|
|
343
|
+
~~~typescript
|
|
344
|
+
import express from 'express';
|
|
345
|
+
import { userService } from './clients/UserService.js';
|
|
346
|
+
|
|
347
|
+
const client = new userService.UserClient({
|
|
348
|
+
handleSignals: false, // this process's shutdown is the gateway's
|
|
349
|
+
callTimeout: 5000,
|
|
350
|
+
});
|
|
351
|
+
|
|
352
|
+
await client.start();
|
|
353
|
+
|
|
354
|
+
let stopping = false;
|
|
355
|
+
const app = express();
|
|
356
|
+
|
|
357
|
+
app.use((_req, res, next) => {
|
|
358
|
+
// once stopping, every answer closes its connection, so keep-alive
|
|
359
|
+
// callers reconnect to another instance instead of holding this one open
|
|
360
|
+
if (stopping) {
|
|
361
|
+
res.set('Connection', 'close');
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
next();
|
|
365
|
+
});
|
|
366
|
+
app.get('/ready', (_req, res) => res.status(stopping ? 503 : 200).end());
|
|
367
|
+
app.get('/users/:id', async (req, res) => {
|
|
368
|
+
res.json(await client.get(req.params.id));
|
|
369
|
+
});
|
|
370
|
+
|
|
371
|
+
const server = app.listen(8080);
|
|
372
|
+
|
|
373
|
+
async function shutdown(): Promise<void> {
|
|
374
|
+
stopping = true;
|
|
375
|
+
|
|
376
|
+
// accept no new connection; resolves once the last open one has ended
|
|
377
|
+
const closed = new Promise<void>(resolve => server.close(() => resolve()));
|
|
378
|
+
|
|
379
|
+
server.closeIdleConnections();
|
|
380
|
+
|
|
381
|
+
// stay inside the orchestrator's grace period whatever the callers do
|
|
382
|
+
const deadline = setTimeout(() => server.closeAllConnections(), 10_000);
|
|
383
|
+
|
|
384
|
+
await closed; // every request already accepted has been answered
|
|
385
|
+
clearTimeout(deadline);
|
|
386
|
+
await client.destroy(); // so no call is left in flight
|
|
387
|
+
process.exit(0);
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// `once`: a second signal finds no handler and ends the process at once
|
|
391
|
+
process.once('SIGTERM', shutdown);
|
|
392
|
+
process.once('SIGINT', shutdown);
|
|
393
|
+
~~~
|
|
394
|
+
|
|
395
|
+
`handleSignals: false` has to be on every client and service in the process:
|
|
396
|
+
the handlers are process-wide, so any one that leaves the default in place
|
|
397
|
+
still exits the process on a signal. On a service the option stops the
|
|
398
|
+
fixed-timer handlers the same way, except that a drain, when enabled, still
|
|
399
|
+
handles `SIGTERM`/`SIGINT` — add `drain: false` to own those as well.
|
|
400
|
+
|
|
401
|
+
## Serving a service in process
|
|
402
|
+
|
|
403
|
+
A service may also run inside the process of its caller. Start it with
|
|
404
|
+
`local: true` and every client in that process calls it directly, through the
|
|
405
|
+
same `@expose()`d methods and the same generated client, with no trip through
|
|
406
|
+
the queue:
|
|
407
|
+
|
|
408
|
+
~~~typescript
|
|
409
|
+
const service = new UserService({ local: true });
|
|
410
|
+
|
|
411
|
+
await service.start();
|
|
412
|
+
|
|
413
|
+
const client = new userService.UserClient();
|
|
414
|
+
|
|
415
|
+
await client.start();
|
|
416
|
+
await client.get('42'); // answered in this process
|
|
417
|
+
~~~
|
|
418
|
+
|
|
419
|
+
Which services share a process is a deployment choice: nothing in the service
|
|
420
|
+
or the client changes, and the same service runs standalone where `local` is
|
|
421
|
+
off.
|
|
422
|
+
|
|
423
|
+
What stays the same:
|
|
424
|
+
|
|
425
|
+
- **The queue is still served.** A client in another process, a call made with
|
|
426
|
+
an `IMQDelay` (the queue holds it until it is due) and `publish()` work as
|
|
427
|
+
before.
|
|
428
|
+
- **Values travel as the queue carries them.** The request and the answer are
|
|
429
|
+
each copied through JSON, so a `Date` arrives as its ISO string, a class
|
|
430
|
+
instance as a plain object, `undefined` properties are dropped and
|
|
431
|
+
`undefined` array items become `null`, and neither side can change an object
|
|
432
|
+
the other holds.
|
|
433
|
+
- **Errors are the same plain `{ code, message, … }` objects**, hooks run as
|
|
434
|
+
they do (`beforeCall`, `wrapCall` and `afterCall` on both sides), `callTimeout`
|
|
435
|
+
applies, and `callTiming()` splits the call, its `transit` now being the two
|
|
436
|
+
copies and the wait for the event loop.
|
|
437
|
+
|
|
438
|
+
What differs:
|
|
439
|
+
|
|
440
|
+
- An answer that cannot be written as JSON (a `BigInt`, a cycle) rejects at once
|
|
441
|
+
with `IMQ_RPC_CALL_ERROR`, where through the queue the service failed to send
|
|
442
|
+
it and the call timed out.
|
|
443
|
+
- A service served in process belongs to its host: it installs no signal
|
|
444
|
+
handlers, does not drain, starts no metrics server and cannot fork workers
|
|
445
|
+
(`multiProcess`). Destroy it from the host's own shutdown — and give the
|
|
446
|
+
host's clients `handleSignals: false` too (see
|
|
447
|
+
[A host that owns shutdown](#a-host-that-owns-shutdown)), or theirs still
|
|
448
|
+
exit the process first.
|
|
449
|
+
- A client with `local: false` sends every call through the queue regardless.
|
|
450
|
+
|
|
451
|
+
The service and the client need not share one copy of this package — a host
|
|
452
|
+
that loads a service from its own directory loads that service's own
|
|
453
|
+
`@imqueue/rpc` beside its own — so long as both are 3.11 or later.
|
|
454
|
+
`localServiceNames()` lists what a process serves itself.
|
|
455
|
+
|
|
333
456
|
## Notes
|
|
334
457
|
|
|
335
458
|
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.12.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",
|
package/src/IMQClient.d.ts
CHANGED
|
@@ -127,8 +127,22 @@ export declare abstract class IMQClient extends EventEmitter {
|
|
|
127
127
|
* file under `$TMPDIR/.imq-rpc`, opens its message queue (two in `singleQueue`
|
|
128
128
|
* mode), raises the process max-listener limit once per process, and installs
|
|
129
129
|
* `SIGTERM`/`SIGINT`/`SIGHUP`/`SIGQUIT` handlers that destroy the client and
|
|
130
|
-
* then exit the process after `IMQ_SHUTDOWN_TIMEOUT
|
|
131
|
-
* a client inherits that
|
|
130
|
+
* then exit the process after `IMQ_SHUTDOWN_TIMEOUT`, without waiting for
|
|
131
|
+
* calls still in flight. Any library embedding a client inherits that
|
|
132
|
+
* process-terminating behaviour.
|
|
133
|
+
*
|
|
134
|
+
* Pass `handleSignals: false` when the host owns the process's shutdown —
|
|
135
|
+
* an HTTP gateway holding clients, say. Then neither the client nor its
|
|
136
|
+
* queue installs a signal handler, and the host's own handler decides when
|
|
137
|
+
* to call {@link IMQClient.destroy}: typically after it has stopped taking
|
|
138
|
+
* new work and the calls already made have settled. The option is
|
|
139
|
+
* process-wide in effect, not per client — any client or service in the
|
|
140
|
+
* process that leaves it on still exits the process on a signal.
|
|
141
|
+
*
|
|
142
|
+
* With draining enabled in this process — a service's `drain` option or
|
|
143
|
+
* `IMQ_DRAIN_ENABLE=1` — the client's queue is kept from installing
|
|
144
|
+
* handlers, but the client still installs its own unless the host passed
|
|
145
|
+
* `handleSignals: false` itself; the drain takes those over.
|
|
132
146
|
*
|
|
133
147
|
* Only {@link IMQClient.destroy} releases the pid file and removes those
|
|
134
148
|
* handlers.
|
|
@@ -167,6 +181,22 @@ export declare abstract class IMQClient extends EventEmitter {
|
|
|
167
181
|
* otherwise ignored.
|
|
168
182
|
*/
|
|
169
183
|
protected remoteCall<T>(...args: any[]): Promise<T>;
|
|
184
|
+
/**
|
|
185
|
+
* Calls a service this process serves itself, as {@link remoteCall} would
|
|
186
|
+
* through the queue.
|
|
187
|
+
*
|
|
188
|
+
* @param local - the service's in-process endpoint
|
|
189
|
+
* @param request - the request, after `beforeCall` ran
|
|
190
|
+
* @param callTimeout - as {@link IMQClientOptions.callTimeout}
|
|
191
|
+
*
|
|
192
|
+
* @remarks
|
|
193
|
+
* The request and the answer are each copied through JSON, as the queue
|
|
194
|
+
* copies them, so neither side holds an object of the other's and the
|
|
195
|
+
* values arrive as they would have. Where the queue would have failed
|
|
196
|
+
* silently and left the call to time out — an answer that cannot be
|
|
197
|
+
* written as JSON — this rejects at once with `IMQ_RPC_CALL_ERROR`.
|
|
198
|
+
*/
|
|
199
|
+
private localCall;
|
|
170
200
|
/**
|
|
171
201
|
* Subscribes to the service's event channel, named after
|
|
172
202
|
* {@link IMQClient.serviceName} — the same channel a service's `publish()`
|
package/src/IMQClient.js
CHANGED
|
@@ -58,6 +58,7 @@ var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn,
|
|
|
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
60
|
import { pid, forgetPid, osUuid, fileExists, mkdir, writeFile, logSafe, SIGNALS, addTrackedSignalHandler, removeTrackedSignalHandler, isProcessDrainEnabled, } from './helpers/index.js';
|
|
61
|
+
import { localService, wireCopy } from './IMQLocal.js';
|
|
61
62
|
import { EventEmitter } from 'node:events';
|
|
62
63
|
import { Script } from 'node:vm';
|
|
63
64
|
import { spawnSync } from 'node:child_process';
|
|
@@ -186,8 +187,22 @@ let IMQClient = (() => {
|
|
|
186
187
|
* file under `$TMPDIR/.imq-rpc`, opens its message queue (two in `singleQueue`
|
|
187
188
|
* mode), raises the process max-listener limit once per process, and installs
|
|
188
189
|
* `SIGTERM`/`SIGINT`/`SIGHUP`/`SIGQUIT` handlers that destroy the client and
|
|
189
|
-
* then exit the process after `IMQ_SHUTDOWN_TIMEOUT
|
|
190
|
-
* a client inherits that
|
|
190
|
+
* then exit the process after `IMQ_SHUTDOWN_TIMEOUT`, without waiting for
|
|
191
|
+
* calls still in flight. Any library embedding a client inherits that
|
|
192
|
+
* process-terminating behaviour.
|
|
193
|
+
*
|
|
194
|
+
* Pass `handleSignals: false` when the host owns the process's shutdown —
|
|
195
|
+
* an HTTP gateway holding clients, say. Then neither the client nor its
|
|
196
|
+
* queue installs a signal handler, and the host's own handler decides when
|
|
197
|
+
* to call {@link IMQClient.destroy}: typically after it has stopped taking
|
|
198
|
+
* new work and the calls already made have settled. The option is
|
|
199
|
+
* process-wide in effect, not per client — any client or service in the
|
|
200
|
+
* process that leaves it on still exits the process on a signal.
|
|
201
|
+
*
|
|
202
|
+
* With draining enabled in this process — a service's `drain` option or
|
|
203
|
+
* `IMQ_DRAIN_ENABLE=1` — the client's queue is kept from installing
|
|
204
|
+
* handlers, but the client still installs its own unless the host passed
|
|
205
|
+
* `handleSignals: false` itself; the drain takes those over.
|
|
191
206
|
*
|
|
192
207
|
* Only {@link IMQClient.destroy} releases the pid file and removes those
|
|
193
208
|
* handlers.
|
|
@@ -201,6 +216,10 @@ let IMQClient = (() => {
|
|
|
201
216
|
'be instantiated directly!');
|
|
202
217
|
}
|
|
203
218
|
this.options = { ...DEFAULT_IMQ_CLIENT_OPTIONS, ...options };
|
|
219
|
+
// read before the drain below rewrites the option: only the host's
|
|
220
|
+
// own `false` means it owns shutdown. A drain forcing it off for the
|
|
221
|
+
// queue still wants these handlers here, to take them over.
|
|
222
|
+
const ownSignalHandlers = this.options.handleSignals !== false;
|
|
204
223
|
if (isProcessDrainEnabled()) {
|
|
205
224
|
// a client's queue would otherwise install the queue layer's own
|
|
206
225
|
// signal handlers, which exit the process without waiting — enough
|
|
@@ -224,7 +243,7 @@ let IMQClient = (() => {
|
|
|
224
243
|
IMQClient.maxListenersBumped = true;
|
|
225
244
|
process.setMaxListeners(10000);
|
|
226
245
|
}
|
|
227
|
-
SIGNALS.forEach((signal) => {
|
|
246
|
+
(ownSignalHandlers ? SIGNALS : []).forEach((signal) => {
|
|
228
247
|
const handler = () => {
|
|
229
248
|
this.destroy().catch(this.logger.error);
|
|
230
249
|
setTimeout(() => process.exit(0), IMQ_SHUTDOWN_TIMEOUT);
|
|
@@ -331,6 +350,12 @@ let IMQClient = (() => {
|
|
|
331
350
|
}
|
|
332
351
|
}
|
|
333
352
|
const callTimeout = this.options.callTimeout;
|
|
353
|
+
const local = !delayed && this.options.local !== false
|
|
354
|
+
? localService(to)
|
|
355
|
+
: undefined;
|
|
356
|
+
if (local) {
|
|
357
|
+
return this.localCall(local, request, callTimeout);
|
|
358
|
+
}
|
|
334
359
|
return new Promise((resolve, reject) => {
|
|
335
360
|
let timer = null;
|
|
336
361
|
const clearTimer = () => {
|
|
@@ -374,6 +399,83 @@ let IMQClient = (() => {
|
|
|
374
399
|
})();
|
|
375
400
|
});
|
|
376
401
|
}
|
|
402
|
+
/**
|
|
403
|
+
* Calls a service this process serves itself, as {@link remoteCall} would
|
|
404
|
+
* through the queue.
|
|
405
|
+
*
|
|
406
|
+
* @param local - the service's in-process endpoint
|
|
407
|
+
* @param request - the request, after `beforeCall` ran
|
|
408
|
+
* @param callTimeout - as {@link IMQClientOptions.callTimeout}
|
|
409
|
+
*
|
|
410
|
+
* @remarks
|
|
411
|
+
* The request and the answer are each copied through JSON, as the queue
|
|
412
|
+
* copies them, so neither side holds an object of the other's and the
|
|
413
|
+
* values arrive as they would have. Where the queue would have failed
|
|
414
|
+
* silently and left the call to time out — an answer that cannot be
|
|
415
|
+
* written as JSON — this rejects at once with `IMQ_RPC_CALL_ERROR`.
|
|
416
|
+
*/
|
|
417
|
+
localCall(local, request, callTimeout) {
|
|
418
|
+
const { method, args } = request;
|
|
419
|
+
const to = this.serviceName;
|
|
420
|
+
return new Promise((resolve, reject) => {
|
|
421
|
+
let timer = null;
|
|
422
|
+
let settled = false;
|
|
423
|
+
const settle = (done) => (value) => {
|
|
424
|
+
settled = true;
|
|
425
|
+
if (timer) {
|
|
426
|
+
clearTimeout(timer);
|
|
427
|
+
timer = null;
|
|
428
|
+
}
|
|
429
|
+
done(value);
|
|
430
|
+
};
|
|
431
|
+
const doResolve = settle(resolve);
|
|
432
|
+
const doReject = settle(reject);
|
|
433
|
+
if (callTimeout && callTimeout > 0) {
|
|
434
|
+
timer = setTimeout(() => {
|
|
435
|
+
doReject(IMQError('IMQ_RPC_CALL_TIMEOUT', `Call to ${to}.${method}() timed out after ${callTimeout} ms.`, new Error().stack, method, args));
|
|
436
|
+
}, callTimeout);
|
|
437
|
+
timer.unref?.();
|
|
438
|
+
}
|
|
439
|
+
void (async () => {
|
|
440
|
+
try {
|
|
441
|
+
request.sentAt = Date.now();
|
|
442
|
+
const answered = await local.call(wireCopy(request));
|
|
443
|
+
let response;
|
|
444
|
+
try {
|
|
445
|
+
response = {
|
|
446
|
+
...answered,
|
|
447
|
+
...wireCopy({
|
|
448
|
+
data: answered.data,
|
|
449
|
+
error: answered.error,
|
|
450
|
+
}),
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
catch (err) {
|
|
454
|
+
response = {
|
|
455
|
+
...answered,
|
|
456
|
+
data: null,
|
|
457
|
+
error: IMQError('IMQ_RPC_CALL_ERROR', `${to}.${method}() answered with a value ` +
|
|
458
|
+
`that cannot be sent: ${err?.message}`, err?.stack, method, args),
|
|
459
|
+
};
|
|
460
|
+
}
|
|
461
|
+
if (settled) {
|
|
462
|
+
logSafe(this.logger, 'warn', `${to}: in-process answer to ${method}() came ` +
|
|
463
|
+
'after the call had timed out');
|
|
464
|
+
return;
|
|
465
|
+
}
|
|
466
|
+
if (response.error) {
|
|
467
|
+
return imqCallRejector(doReject, request, this)(response.error, response);
|
|
468
|
+
}
|
|
469
|
+
imqCallResolver(doResolve, request, this)(response.data, response);
|
|
470
|
+
}
|
|
471
|
+
catch (err) {
|
|
472
|
+
if (!settled) {
|
|
473
|
+
imqCallRejector(doReject, request, this)(err);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
})();
|
|
477
|
+
});
|
|
478
|
+
}
|
|
377
479
|
/**
|
|
378
480
|
* Subscribes to the service's event channel, named after
|
|
379
481
|
* {@link IMQClient.serviceName} — the same channel a service's `publish()`
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
/*!
|
|
2
|
+
* IMQLocal implementation
|
|
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
|
+
import type { IMQRPCRequest } from './IMQRPCRequest.js';
|
|
25
|
+
import type { IMQRPCResponse } from './IMQRPCResponse.js';
|
|
26
|
+
/**
|
|
27
|
+
* A service this process serves itself, as a client in the same process
|
|
28
|
+
* reaches it.
|
|
29
|
+
*
|
|
30
|
+
* @remarks
|
|
31
|
+
* Registered by a service started with {@link IMQServiceOptions.local}, and
|
|
32
|
+
* found by name by every client in the process. The contract is this object
|
|
33
|
+
* and nothing else, because the service and its client need not share one
|
|
34
|
+
* copy of this package: a host that loads a service from its own directory
|
|
35
|
+
* loads that service's own `@imqueue/rpc` beside the host's, and both see one
|
|
36
|
+
* registry.
|
|
37
|
+
*/
|
|
38
|
+
export interface IMQLocalService {
|
|
39
|
+
/**
|
|
40
|
+
* The service name, which is also its queue name.
|
|
41
|
+
*/
|
|
42
|
+
readonly name: string;
|
|
43
|
+
/**
|
|
44
|
+
* Answers one request as the service would through its queue.
|
|
45
|
+
*
|
|
46
|
+
* @param request - the request as it would arrive off the queue: already
|
|
47
|
+
* a copy the caller no longer holds
|
|
48
|
+
* @returns the response the service would have sent, before it is copied
|
|
49
|
+
* back to the caller
|
|
50
|
+
*/
|
|
51
|
+
call(request: IMQRPCRequest): Promise<IMQRPCResponse>;
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Makes a service reachable in process under its name.
|
|
55
|
+
*
|
|
56
|
+
* @param service - the service's local endpoint
|
|
57
|
+
*
|
|
58
|
+
* @remarks
|
|
59
|
+
* A second service under the same name replaces the first, so that a service
|
|
60
|
+
* started again after it was destroyed is the one called.
|
|
61
|
+
*/
|
|
62
|
+
export declare function registerLocalService(service: IMQLocalService): void;
|
|
63
|
+
/**
|
|
64
|
+
* Stops reaching a service in process. Its clients go back to the queue.
|
|
65
|
+
*
|
|
66
|
+
* @param service - the endpoint that was registered; another one registered
|
|
67
|
+
* since under the same name is left in place
|
|
68
|
+
*/
|
|
69
|
+
export declare function unregisterLocalService(service: IMQLocalService): void;
|
|
70
|
+
/**
|
|
71
|
+
* The service this process serves under the given name, if it serves one.
|
|
72
|
+
*
|
|
73
|
+
* @param name - the service (queue) name
|
|
74
|
+
*/
|
|
75
|
+
export declare function localService(name: string): IMQLocalService | undefined;
|
|
76
|
+
/**
|
|
77
|
+
* The name of every service this process serves itself, sorted.
|
|
78
|
+
*/
|
|
79
|
+
export declare function localServiceNames(): string[];
|
|
80
|
+
/**
|
|
81
|
+
* Copies a value the way the queue does: through JSON and back.
|
|
82
|
+
*
|
|
83
|
+
* @param value - an object to copy
|
|
84
|
+
* @returns the copy, which shares nothing with the value
|
|
85
|
+
*
|
|
86
|
+
* @remarks
|
|
87
|
+
* This is what keeps an in-process call's semantics those of a queued one: a
|
|
88
|
+
* `Date` arrives as its ISO string, a class instance as a plain object,
|
|
89
|
+
* `undefined` properties are gone and `undefined` array items are `null`, and
|
|
90
|
+
* neither side can change an object the other still holds. It throws where
|
|
91
|
+
* the queue would fail to send, on a `BigInt` or a cycle.
|
|
92
|
+
*/
|
|
93
|
+
export declare function wireCopy<T extends object>(value: T): T;
|
package/src/IMQLocal.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const registry = (() => {
|
|
2
|
+
const anchor = globalThis;
|
|
3
|
+
const symbol = Symbol.for('@imqueue/rpc:IMQ_LOCAL_SERVICES');
|
|
4
|
+
return (anchor[symbol] ??= new Map());
|
|
5
|
+
})();
|
|
6
|
+
/**
|
|
7
|
+
* Makes a service reachable in process under its name.
|
|
8
|
+
*
|
|
9
|
+
* @param service - the service's local endpoint
|
|
10
|
+
*
|
|
11
|
+
* @remarks
|
|
12
|
+
* A second service under the same name replaces the first, so that a service
|
|
13
|
+
* started again after it was destroyed is the one called.
|
|
14
|
+
*/
|
|
15
|
+
export function registerLocalService(service) {
|
|
16
|
+
registry.set(service.name, service);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Stops reaching a service in process. Its clients go back to the queue.
|
|
20
|
+
*
|
|
21
|
+
* @param service - the endpoint that was registered; another one registered
|
|
22
|
+
* since under the same name is left in place
|
|
23
|
+
*/
|
|
24
|
+
export function unregisterLocalService(service) {
|
|
25
|
+
if (registry.get(service.name) === service) {
|
|
26
|
+
registry.delete(service.name);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* The service this process serves under the given name, if it serves one.
|
|
31
|
+
*
|
|
32
|
+
* @param name - the service (queue) name
|
|
33
|
+
*/
|
|
34
|
+
export function localService(name) {
|
|
35
|
+
return registry.get(name);
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* The name of every service this process serves itself, sorted.
|
|
39
|
+
*/
|
|
40
|
+
export function localServiceNames() {
|
|
41
|
+
return [...registry.keys()].sort();
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Copies a value the way the queue does: through JSON and back.
|
|
45
|
+
*
|
|
46
|
+
* @param value - an object to copy
|
|
47
|
+
* @returns the copy, which shares nothing with the value
|
|
48
|
+
*
|
|
49
|
+
* @remarks
|
|
50
|
+
* This is what keeps an in-process call's semantics those of a queued one: a
|
|
51
|
+
* `Date` arrives as its ISO string, a class instance as a plain object,
|
|
52
|
+
* `undefined` properties are gone and `undefined` array items are `null`, and
|
|
53
|
+
* neither side can change an object the other still holds. It throws where
|
|
54
|
+
* the queue would fail to send, on a `BigInt` or a cycle.
|
|
55
|
+
*/
|
|
56
|
+
export function wireCopy(value) {
|
|
57
|
+
return JSON.parse(JSON.stringify(value));
|
|
58
|
+
}
|
|
59
|
+
//# sourceMappingURL=IMQLocal.js.map
|
package/src/IMQRPCOptions.d.ts
CHANGED
|
@@ -231,6 +231,47 @@ export interface IMQServiceOptions extends IMQOptions {
|
|
|
231
231
|
* abandoned, logged, and the process exits `0` regardless.
|
|
232
232
|
*/
|
|
233
233
|
drainTimeout?: number;
|
|
234
|
+
/**
|
|
235
|
+
* Let this package handle `SIGTERM`, `SIGINT`, `SIGHUP` and `SIGQUIT` for
|
|
236
|
+
* the process. Set it to `false` when the host owns shutdown.
|
|
237
|
+
*
|
|
238
|
+
* @defaultValue true
|
|
239
|
+
*
|
|
240
|
+
* @remarks
|
|
241
|
+
* Left on, the service installs handlers that tear it down and exit the
|
|
242
|
+
* process after `IMQ_SHUTDOWN_TIMEOUT`, and its queue installs its own
|
|
243
|
+
* (see the core `IMQOptions.handleSignals`).
|
|
244
|
+
*
|
|
245
|
+
* `false` stops both: the service installs no such handler and its queue
|
|
246
|
+
* none either, so the host's own handler decides when to call
|
|
247
|
+
* `destroy()`. With {@link IMQServiceOptions.drain} on, `SIGTERM` and
|
|
248
|
+
* `SIGINT` still start the drain — that is an opt-in of its own — so a
|
|
249
|
+
* host that owns those signals too leaves the drain off.
|
|
250
|
+
*
|
|
251
|
+
* Handlers are process-wide: any other service or client in the process
|
|
252
|
+
* that leaves this on still exits the process on a signal.
|
|
253
|
+
*/
|
|
254
|
+
handleSignals?: boolean;
|
|
255
|
+
/**
|
|
256
|
+
* Serve this service in process as well: a client in the same process
|
|
257
|
+
* calls it directly, with no trip through the queue.
|
|
258
|
+
*
|
|
259
|
+
* @defaultValue false
|
|
260
|
+
*
|
|
261
|
+
* @remarks
|
|
262
|
+
* The queue is still served, so a client in another process, a delayed
|
|
263
|
+
* call and `publish()` work as before, and turning this off again changes
|
|
264
|
+
* nothing a caller sees. An in-process call copies its request and its
|
|
265
|
+
* answer through JSON exactly as the queue does, so dates, class instances
|
|
266
|
+
* and `undefined` arrive as they would have; see {@link wireCopy}.
|
|
267
|
+
*
|
|
268
|
+
* A service served in process belongs to the process that hosts it: it
|
|
269
|
+
* installs no signal handlers and does not drain (the host's shutdown
|
|
270
|
+
* decides when it is destroyed), its queue installs none either, and it
|
|
271
|
+
* starts no metrics server. It cannot be combined with
|
|
272
|
+
* {@link IMQServiceOptions.multiProcess}.
|
|
273
|
+
*/
|
|
274
|
+
local?: boolean;
|
|
234
275
|
}
|
|
235
276
|
/**
|
|
236
277
|
* Options accepted by a generated IMQ client.
|
|
@@ -323,6 +364,46 @@ export interface IMQClientOptions extends IMQOptions {
|
|
|
323
364
|
* Use it to bound Redis connections when a process instantiates many clients.
|
|
324
365
|
*/
|
|
325
366
|
singleQueue?: boolean;
|
|
367
|
+
/**
|
|
368
|
+
* Let this package handle `SIGTERM`, `SIGINT`, `SIGHUP` and `SIGQUIT` for
|
|
369
|
+
* the process. Set it to `false` when the host owns shutdown — an HTTP
|
|
370
|
+
* gateway holding clients, for one.
|
|
371
|
+
*
|
|
372
|
+
* @defaultValue true
|
|
373
|
+
*
|
|
374
|
+
* @remarks
|
|
375
|
+
* Left on, the client installs handlers that destroy it — abandoning the
|
|
376
|
+
* calls still waiting for an answer — and exit the process after
|
|
377
|
+
* `IMQ_SHUTDOWN_TIMEOUT`, and its queue installs its own (see the core
|
|
378
|
+
* `IMQOptions.handleSignals`). A host's own shutdown handler cannot finish
|
|
379
|
+
* its work before that exit.
|
|
380
|
+
*
|
|
381
|
+
* `false` stops both, so the host decides: stop taking new work, let the
|
|
382
|
+
* calls already made settle, then call `destroy()`.
|
|
383
|
+
*
|
|
384
|
+
* With draining enabled in the process (`IMQ_DRAIN_ENABLE=1`, or a service
|
|
385
|
+
* constructed with `drain`), the queue's handlers are suppressed anyway and
|
|
386
|
+
* the client's own are left for the drain to take over — unless this is
|
|
387
|
+
* `false`, in which case the client installs none.
|
|
388
|
+
*
|
|
389
|
+
* Handlers are process-wide: any other client or service in the process
|
|
390
|
+
* that leaves this on still exits the process on a signal.
|
|
391
|
+
*/
|
|
392
|
+
handleSignals?: boolean;
|
|
393
|
+
/**
|
|
394
|
+
* Call a service this process serves itself directly, rather than through
|
|
395
|
+
* the queue.
|
|
396
|
+
*
|
|
397
|
+
* @defaultValue true
|
|
398
|
+
*
|
|
399
|
+
* @remarks
|
|
400
|
+
* It matters only where a service in the same process was started with
|
|
401
|
+
* {@link IMQServiceOptions.local}; otherwise every call goes through the
|
|
402
|
+
* queue regardless. `false` sends every call through the queue. A call
|
|
403
|
+
* made with an {@link IMQDelay} always goes through the queue, which is
|
|
404
|
+
* what holds it until it is due.
|
|
405
|
+
*/
|
|
406
|
+
local?: boolean;
|
|
326
407
|
}
|
|
327
408
|
/**
|
|
328
409
|
* Default options applied to every IMQ service: the core queue defaults, plus
|
package/src/IMQService.d.ts
CHANGED
|
@@ -128,6 +128,11 @@ export declare abstract class IMQService {
|
|
|
128
128
|
* the first and force an immediate exit.
|
|
129
129
|
*/
|
|
130
130
|
private draining;
|
|
131
|
+
/**
|
|
132
|
+
* How a client in this process reaches this service, present only with
|
|
133
|
+
* {@link IMQServiceOptions.local} on, and registered while it serves.
|
|
134
|
+
*/
|
|
135
|
+
private readonly localEndpoint?;
|
|
131
136
|
/**
|
|
132
137
|
* This service's name, which is also its queue name and the key its description
|
|
133
138
|
* is cached under.
|
|
@@ -168,6 +173,14 @@ export declare abstract class IMQService {
|
|
|
168
173
|
* queue layer does not exit mid-drain. Handlers registered by anything
|
|
169
174
|
* other than this package are never touched.
|
|
170
175
|
*
|
|
176
|
+
* Pass `handleSignals: false` when the host owns the process's shutdown:
|
|
177
|
+
* then neither the service nor its queue installs a handler for the
|
|
178
|
+
* fixed-timer shutdown above, and the host calls
|
|
179
|
+
* {@link IMQService.destroy} when it is ready. A drain is the exception —
|
|
180
|
+
* an explicit opt-in to this package handling shutdown gracefully — so with
|
|
181
|
+
* draining on, `SIGTERM` and `SIGINT` still start it; pass `drain: false`
|
|
182
|
+
* as well to own those too.
|
|
183
|
+
*
|
|
171
184
|
* The merged options are passed straight to the queue factory, so `vendor` and
|
|
172
185
|
* `cluster`/`clusterManagers` select the transport implementation.
|
|
173
186
|
*/
|
|
@@ -230,6 +243,15 @@ export declare abstract class IMQService {
|
|
|
230
243
|
*/
|
|
231
244
|
private handleRequest;
|
|
232
245
|
private processRequest;
|
|
246
|
+
/**
|
|
247
|
+
* Answers a request a client in this process made, with no trip through
|
|
248
|
+
* the queue: the same checks, hooks and method as a queued request, and
|
|
249
|
+
* the response handed back rather than sent.
|
|
250
|
+
*
|
|
251
|
+
* @param request - the request, already copied the way the queue copies it
|
|
252
|
+
*/
|
|
253
|
+
private answerLocally;
|
|
254
|
+
private respond;
|
|
233
255
|
/**
|
|
234
256
|
* Initializes this instance of service and starts handling request
|
|
235
257
|
* messages.
|
package/src/IMQService.js
CHANGED
|
@@ -63,7 +63,9 @@ import cluster, {} from 'node:cluster';
|
|
|
63
63
|
import {} from './IMQRPCDescription.js';
|
|
64
64
|
import {} from './IMQRPCOptions.js';
|
|
65
65
|
import { runWithRequest } from './IMQRequestContext.js';
|
|
66
|
+
import { registerLocalService, unregisterLocalService, } from './IMQLocal.js';
|
|
66
67
|
import { createServer } from 'node:http';
|
|
68
|
+
import { randomUUID } from 'node:crypto';
|
|
67
69
|
/**
|
|
68
70
|
* The self-description a service serves to its clients, and the input to client
|
|
69
71
|
* generation.
|
|
@@ -211,6 +213,11 @@ let IMQService = (() => {
|
|
|
211
213
|
* the first and force an immediate exit.
|
|
212
214
|
*/
|
|
213
215
|
draining = false;
|
|
216
|
+
/**
|
|
217
|
+
* How a client in this process reaches this service, present only with
|
|
218
|
+
* {@link IMQServiceOptions.local} on, and registered while it serves.
|
|
219
|
+
*/
|
|
220
|
+
localEndpoint;
|
|
214
221
|
/**
|
|
215
222
|
* This service's name, which is also its queue name and the key its description
|
|
216
223
|
* is cached under.
|
|
@@ -251,6 +258,14 @@ let IMQService = (() => {
|
|
|
251
258
|
* queue layer does not exit mid-drain. Handlers registered by anything
|
|
252
259
|
* other than this package are never touched.
|
|
253
260
|
*
|
|
261
|
+
* Pass `handleSignals: false` when the host owns the process's shutdown:
|
|
262
|
+
* then neither the service nor its queue installs a handler for the
|
|
263
|
+
* fixed-timer shutdown above, and the host calls
|
|
264
|
+
* {@link IMQService.destroy} when it is ready. A drain is the exception —
|
|
265
|
+
* an explicit opt-in to this package handling shutdown gracefully — so with
|
|
266
|
+
* draining on, `SIGTERM` and `SIGINT` still start it; pass `drain: false`
|
|
267
|
+
* as well to own those too.
|
|
268
|
+
*
|
|
254
269
|
* The merged options are passed straight to the queue factory, so `vendor` and
|
|
255
270
|
* `cluster`/`clusterManagers` select the transport implementation.
|
|
256
271
|
*/
|
|
@@ -269,6 +284,23 @@ let IMQService = (() => {
|
|
|
269
284
|
},
|
|
270
285
|
};
|
|
271
286
|
this.logger = this.options.logger || /* istanbul ignore next */ console;
|
|
287
|
+
// read before `local` and the drain below rewrite the option: only the
|
|
288
|
+
// host's own `false` means it owns shutdown
|
|
289
|
+
const ownSignalHandlers = this.options.handleSignals !== false;
|
|
290
|
+
if (this.options.local) {
|
|
291
|
+
if (this.options.multiProcess) {
|
|
292
|
+
throw new TypeError(`${this.name}: a service served in process cannot ` +
|
|
293
|
+
'also fork workers (local with multiProcess)');
|
|
294
|
+
}
|
|
295
|
+
// the host owns this process's shutdown, so neither this service
|
|
296
|
+
// nor its queue may exit it from a signal of their own
|
|
297
|
+
this.options.handleSignals = false;
|
|
298
|
+
this.options.drain = false;
|
|
299
|
+
this.localEndpoint = {
|
|
300
|
+
name: this.name,
|
|
301
|
+
call: request => this.answerLocally(request),
|
|
302
|
+
};
|
|
303
|
+
}
|
|
272
304
|
this.drainEnabled = this.options.drain ?? drainEnabledFromEnv();
|
|
273
305
|
this.drainTimeout = this.options.drainTimeout ?? drainTimeoutFromEnv();
|
|
274
306
|
if (this.drainEnabled) {
|
|
@@ -283,7 +315,7 @@ let IMQService = (() => {
|
|
|
283
315
|
}
|
|
284
316
|
this.imq = IMQ.create(this.name, this.options);
|
|
285
317
|
this.handleRequest = this.handleRequest.bind(this);
|
|
286
|
-
SIGNALS.forEach((signal) => {
|
|
318
|
+
(this.localEndpoint ? [] : SIGNALS).forEach((signal) => {
|
|
287
319
|
if (this.drainEnabled && DRAIN_SIGNALS.includes(signal)) {
|
|
288
320
|
const handler = () => {
|
|
289
321
|
// a drain that throws must not leave the process hanging
|
|
@@ -300,6 +332,9 @@ let IMQService = (() => {
|
|
|
300
332
|
process.on(signal, handler);
|
|
301
333
|
return;
|
|
302
334
|
}
|
|
335
|
+
if (!ownSignalHandlers) {
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
303
338
|
const handler = () => {
|
|
304
339
|
this.destroy().catch(this.logger.error);
|
|
305
340
|
if (this.metricsServer) {
|
|
@@ -436,6 +471,23 @@ let IMQService = (() => {
|
|
|
436
471
|
return runWithRequest(request, () => this.processRequest(request, id, received));
|
|
437
472
|
}
|
|
438
473
|
async processRequest(request, id, received) {
|
|
474
|
+
const response = await this.respond(request, id, received);
|
|
475
|
+
return await send(request, response, this);
|
|
476
|
+
}
|
|
477
|
+
/**
|
|
478
|
+
* Answers a request a client in this process made, with no trip through
|
|
479
|
+
* the queue: the same checks, hooks and method as a queued request, and
|
|
480
|
+
* the response handed back rather than sent.
|
|
481
|
+
*
|
|
482
|
+
* @param request - the request, already copied the way the queue copies it
|
|
483
|
+
*/
|
|
484
|
+
async answerLocally(request) {
|
|
485
|
+
const received = Date.now();
|
|
486
|
+
const response = await runWithRequest(request, () => this.respond(request, randomUUID(), received));
|
|
487
|
+
await afterCall(request, response, this);
|
|
488
|
+
return response;
|
|
489
|
+
}
|
|
490
|
+
async respond(request, id, received) {
|
|
439
491
|
const logger = this.options.logger || console;
|
|
440
492
|
const method = request.method;
|
|
441
493
|
const description = await this.describe();
|
|
@@ -479,7 +531,7 @@ let IMQService = (() => {
|
|
|
479
531
|
this.logger.warn(response.error);
|
|
480
532
|
const now = Date.now();
|
|
481
533
|
response.timing = { received, started: now, finished: now };
|
|
482
|
-
return
|
|
534
|
+
return response;
|
|
483
535
|
}
|
|
484
536
|
const started = Date.now();
|
|
485
537
|
try {
|
|
@@ -501,7 +553,7 @@ let IMQService = (() => {
|
|
|
501
553
|
response.error = IMQError(err.code || 'IMQ_RPC_CALL_ERROR', err.message, err.stack, method, args, err);
|
|
502
554
|
}
|
|
503
555
|
response.timing = { received, started, finished: Date.now() };
|
|
504
|
-
return
|
|
556
|
+
return response;
|
|
505
557
|
}
|
|
506
558
|
/**
|
|
507
559
|
* Initializes this instance of service and starts handling request
|
|
@@ -525,7 +577,16 @@ let IMQService = (() => {
|
|
|
525
577
|
if (!this.options.multiProcess) {
|
|
526
578
|
this.logger.info('%s: starting single-worker, pid %s', this.name, process.pid);
|
|
527
579
|
this.describe();
|
|
528
|
-
|
|
580
|
+
if (!this.localEndpoint) {
|
|
581
|
+
return this.startWithMetricsServer();
|
|
582
|
+
}
|
|
583
|
+
// in process the metrics port is the host's, and a second listener
|
|
584
|
+
// on it would fail; the queue still starts first, so a method can
|
|
585
|
+
// publish from the first in-process call
|
|
586
|
+
const started = await this.imq.start();
|
|
587
|
+
registerLocalService(this.localEndpoint);
|
|
588
|
+
this.logger.info('%s: serving in process too', this.name);
|
|
589
|
+
return started;
|
|
529
590
|
}
|
|
530
591
|
if (cluster.isMaster) {
|
|
531
592
|
const numCpus = cpus().length;
|
|
@@ -593,6 +654,9 @@ let IMQService = (() => {
|
|
|
593
654
|
* {@link IMQServiceOptions.drain}.
|
|
594
655
|
*/
|
|
595
656
|
async destroy() {
|
|
657
|
+
if (this.localEndpoint) {
|
|
658
|
+
unregisterLocalService(this.localEndpoint);
|
|
659
|
+
}
|
|
596
660
|
// unregister this instance's process signal handlers so destroyed
|
|
597
661
|
// services do not leak process-level listeners
|
|
598
662
|
for (const [signal, handler] of this.signalHandlers) {
|
|
@@ -672,17 +736,29 @@ export { IMQService };
|
|
|
672
736
|
* @returns send result message identifier
|
|
673
737
|
*/
|
|
674
738
|
export async function send(request, response, service) {
|
|
675
|
-
const logger = service.options.logger || console;
|
|
676
739
|
const id = await service.imq.send(request.from, response);
|
|
677
|
-
|
|
678
|
-
const afterCall = service.options.afterCall.bind(service);
|
|
679
|
-
try {
|
|
680
|
-
await afterCall(request, response);
|
|
681
|
-
}
|
|
682
|
-
catch (err) {
|
|
683
|
-
logger.warn(AFTER_HOOK_ERROR, err);
|
|
684
|
-
}
|
|
685
|
-
}
|
|
740
|
+
await afterCall(request, response, service);
|
|
686
741
|
return id;
|
|
687
742
|
}
|
|
743
|
+
/**
|
|
744
|
+
* Runs the service's optional after-call hook on an answered request, logging
|
|
745
|
+
* rather than propagating its failure.
|
|
746
|
+
*
|
|
747
|
+
* @param request - the request answered
|
|
748
|
+
* @param response - the response it was answered with
|
|
749
|
+
* @param service - imq service to bind
|
|
750
|
+
*/
|
|
751
|
+
async function afterCall(request, response, service) {
|
|
752
|
+
if (typeof service.options.afterCall !== 'function') {
|
|
753
|
+
return;
|
|
754
|
+
}
|
|
755
|
+
const logger = service.options.logger || console;
|
|
756
|
+
const hook = service.options.afterCall.bind(service);
|
|
757
|
+
try {
|
|
758
|
+
await hook(request, response);
|
|
759
|
+
}
|
|
760
|
+
catch (err) {
|
|
761
|
+
logger.warn(AFTER_HOOK_ERROR, err);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
688
764
|
//# sourceMappingURL=IMQService.js.map
|
package/src/index.d.ts
CHANGED
|
@@ -29,6 +29,7 @@ export * from './IMQRPCError.js';
|
|
|
29
29
|
export * from './IMQRPCRequest.js';
|
|
30
30
|
export * from './IMQRPCResponse.js';
|
|
31
31
|
export * from './IMQCallTiming.js';
|
|
32
|
+
export * from './IMQLocal.js';
|
|
32
33
|
export * from './IMQLock.js';
|
|
33
34
|
export * from './IMQService.js';
|
|
34
35
|
export * from './IMQClient.js';
|
package/src/index.js
CHANGED
|
@@ -29,6 +29,7 @@ export * from './IMQRPCError.js';
|
|
|
29
29
|
export * from './IMQRPCRequest.js';
|
|
30
30
|
export * from './IMQRPCResponse.js';
|
|
31
31
|
export * from './IMQCallTiming.js';
|
|
32
|
+
export * from './IMQLocal.js';
|
|
32
33
|
export * from './IMQLock.js';
|
|
33
34
|
export * from './IMQService.js';
|
|
34
35
|
export * from './IMQClient.js';
|
package/AGENTS.md
DELETED
|
@@ -1,161 +0,0 @@
|
|
|
1
|
-
# AGENTS.md — orientation for coding agents
|
|
2
|
-
|
|
3
|
-
This file is for AI coding agents (and humans who like density) working on
|
|
4
|
-
`@imqueue/rpc`. It captures how the codebase is built, tested and structured,
|
|
5
|
-
plus the invariants that are easy to get wrong. Read it before making changes.
|
|
6
|
-
For contribution *process/terms* see [CONTRIBUTING.md](./CONTRIBUTING.md); for
|
|
7
|
-
end-user docs see the [README](./README.md) and https://imqueue.org/.
|
|
8
|
-
|
|
9
|
-
## What this is
|
|
10
|
-
|
|
11
|
-
`@imqueue/rpc` is the typed RPC layer of the @imqueue framework. It provides the
|
|
12
|
-
abstract base classes and decorators to build **self-describing services** and
|
|
13
|
-
the machinery to **generate strongly-typed clients** from them — all over the
|
|
14
|
-
Redis-backed message queue in [`@imqueue/core`](https://github.com/imqueue/core).
|
|
15
|
-
No service discovery, no load balancer, no hand-written HTTP layer: a service
|
|
16
|
-
describes itself and its client is generated from that description.
|
|
17
|
-
|
|
18
|
-
## Toolchain & invariants (do not fight these)
|
|
19
|
-
|
|
20
|
-
- **ESM only**, `"type": "module"`. Use `import`, not `require()`. Import
|
|
21
|
-
sibling modules with the **`.js`** extension (NodeNext resolves it to the
|
|
22
|
-
`.ts` source).
|
|
23
|
-
- **TypeScript, `module`/`moduleResolution: nodenext`**, `target: es2024`,
|
|
24
|
-
`verbatimModuleSyntax: true`, `isolatedModules: true`, `strict: true`
|
|
25
|
-
(`strictPropertyInitialization: false`). Use `import type` for type-only
|
|
26
|
-
imports.
|
|
27
|
-
- **Standard (TC39) decorators** — `experimentalDecorators` is **false** and the
|
|
28
|
-
`esnext.decorators` lib is enabled. There is **no `emitDecoratorMetadata`**,
|
|
29
|
-
so there is **no runtime type reflection**.
|
|
30
|
-
- **Types are derived from JSDoc.** Because decorators carry no type metadata,
|
|
31
|
-
the RPC layer parses JSDoc `@param`/`@returns` tags (via `acorn`) to build a
|
|
32
|
-
service's description and its generated client's types. Consequences:
|
|
33
|
-
`removeComments` MUST stay **`false`**, and every exposed method MUST carry
|
|
34
|
-
accurate JSDoc — undocumented params fall back to `any` in generated clients.
|
|
35
|
-
- **Node ≥ 22.12.**
|
|
36
|
-
- Runtime deps: `@imqueue/core`, `acorn` (JSDoc/source parsing for client
|
|
37
|
-
generation), `typescript` (compiling generated clients on the fly).
|
|
38
|
-
- **Lint/format:** `oxlint` + `oxfmt`. Run `npm run format` before committing;
|
|
39
|
-
CI checks `npm run format:check`.
|
|
40
|
-
- Build **emits `.js`/`.d.ts`/`.js.map` next to sources**; **gitignored, not
|
|
41
|
-
committed**. `build` runs `build:deps` (builds `../core` if present) then
|
|
42
|
-
`clean-compiled` then `tsc`.
|
|
43
|
-
|
|
44
|
-
## Commands
|
|
45
|
-
|
|
46
|
-
```bash
|
|
47
|
-
npm install
|
|
48
|
-
npm run build # build ../core (if present) + clean + tsc
|
|
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)
|
|
51
|
-
npm run lint # oxlint
|
|
52
|
-
npm run format # oxfmt (write) | npm run format:check (verify)
|
|
53
|
-
npm run test-coverage # tests + experimental coverage
|
|
54
|
-
```
|
|
55
|
-
|
|
56
|
-
Tests use the native `node:test` runner with
|
|
57
|
-
`--experimental-test-module-mocks` and preload `./test/warmup.mjs`; timeout is
|
|
58
|
-
15s. A local Redis on `localhost:6379` is expected for the integration-style
|
|
59
|
-
specs.
|
|
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
|
-
|
|
79
|
-
## Layout
|
|
80
|
-
|
|
81
|
-
| Path | Role |
|
|
82
|
-
|---|---|
|
|
83
|
-
| `index.ts` | `export * from './src/index.js'` **and** `export * from '@imqueue/core'` — consumers get core's queue API re-exported. |
|
|
84
|
-
| `src/IMQService.ts` | `IMQService` abstract base — extend it and decorate methods with `@expose()`. |
|
|
85
|
-
| `src/IMQClient.ts` | `IMQClient` base + `IMQClient.create()` — generates/compiles/loads a client from a running service's description. |
|
|
86
|
-
| `src/decorators/expose.ts` | `@expose()` — marks a service method remotely callable. |
|
|
87
|
-
| `src/decorators/remote.ts` | `@remote()` — marks a hand-written client method. |
|
|
88
|
-
| `src/decorators/classType.ts`, `property.ts`, `indexed.ts` | Complex-type registration: `@classType()` on the class, `@property('type', optional?)` on fields. |
|
|
89
|
-
| `src/decorators/cache.ts`, `lock.ts`, `logged.ts`, `metadata.ts` | Cross-cutting method decorators. |
|
|
90
|
-
| `src/cache/` (`ICache`, `RedisCache`) | Caching layer for RPC results. |
|
|
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. |
|
|
93
|
-
| `src/IMQRPCDescription.ts`, `IMQRPCRequest.ts`, `IMQRPCResponse.ts`, `IMQRPCError.ts`, `IMQDelay.ts`, `IMQLock.ts`, `IMQMetadata.ts`, `IMQRequestContext.ts` | RPC wire types & context. |
|
|
94
|
-
|
|
95
|
-
## Authoring rules (behavioural invariants that generated clients depend on)
|
|
96
|
-
|
|
97
|
-
- **Only `@expose()`-decorated methods are remotely callable.** Non-exposed
|
|
98
|
-
methods stay private to the service.
|
|
99
|
-
- **Arguments and return values must be JSON-serializable.**
|
|
100
|
-
- **No spread/rest params on exposed methods** — the generated client will not
|
|
101
|
-
compile. Pass an array instead: `foo(args: any[])`, not `foo(...args: any[])`.
|
|
102
|
-
- **Complex types need `@classType()` on the class** *and* `@property()` on each
|
|
103
|
-
field, or they will not appear in generated clients. `@indexed()` registers
|
|
104
|
-
`@property` fields too.
|
|
105
|
-
- **JSDoc is load-bearing**, not documentation-only (see toolchain note). Keep
|
|
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.
|
|
114
|
-
|
|
115
|
-
## Using this package correctly (for consumer-facing code an agent writes)
|
|
116
|
-
|
|
117
|
-
```typescript
|
|
118
|
-
import { IMQService, expose } from '@imqueue/rpc';
|
|
119
|
-
|
|
120
|
-
export class UserService extends IMQService {
|
|
121
|
-
/**
|
|
122
|
-
* Returns a user by id
|
|
123
|
-
* @param {string} id - user identifier
|
|
124
|
-
* @return {Promise<{ id: string; name: string } | null>}
|
|
125
|
-
*/
|
|
126
|
-
@expose()
|
|
127
|
-
public async get(id: string): Promise<{ id: string; name: string } | null> {
|
|
128
|
-
return { id, name: 'Jane Doe' };
|
|
129
|
-
}
|
|
130
|
-
}
|
|
131
|
-
```
|
|
132
|
-
|
|
133
|
-
Generate the client with `@imqueue/cli`. The name is the service's **class**
|
|
134
|
-
name, because that is also its queue name:
|
|
135
|
-
|
|
136
|
-
```bash
|
|
137
|
-
imq client generate UserService ./src/clients
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
The generated module exports exactly one symbol: a namespace named after the
|
|
141
|
-
service with a lower-case first letter, holding a client class whose trailing
|
|
142
|
-
`Service` is replaced by `Client` (see `clientName`/`namespaceName` in
|
|
143
|
-
[`src/IMQClient.ts`](./src/IMQClient.ts)). The class itself has no top-level
|
|
144
|
-
export, so importing it by name does not resolve:
|
|
145
|
-
|
|
146
|
-
```typescript
|
|
147
|
-
import { userService } from './src/clients/UserService.js';
|
|
148
|
-
|
|
149
|
-
// callTimeout is unset by default, which means calls wait forever.
|
|
150
|
-
const client = new userService.UserClient({ callTimeout: 5000 });
|
|
151
|
-
|
|
152
|
-
await client.start();
|
|
153
|
-
await client.get('42');
|
|
154
|
-
```
|
|
155
|
-
|
|
156
|
-
`IMQClient.create('UserService')` does the same at runtime, and resolves to that
|
|
157
|
-
namespace object — not to a client instance.
|
|
158
|
-
|
|
159
|
-
## License
|
|
160
|
-
|
|
161
|
-
GPL-3.0. Commercial licensing for closed-source products: https://imqueue.com/.
|
package/CONTRIBUTION-TERMS.md
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
# @imqueue Contribution Terms (v1.0)
|
|
2
|
-
|
|
3
|
-
These terms apply to every contribution to any repository of the **@imqueue**
|
|
4
|
-
project — the packages published under the `@imqueue` npm scope and any repository
|
|
5
|
-
in the imqueue GitHub organisation.
|
|
6
|
-
|
|
7
|
-
**By submitting a contribution — opening a pull request, pushing a commit, sending
|
|
8
|
-
a patch, or otherwise offering work for inclusion — you accept these terms in
|
|
9
|
-
full. If you do not agree with them, do not contribute.**
|
|
10
|
-
|
|
11
|
-
In these terms, **"Owner"** means Mykhailo Stadnyk, together with his successors,
|
|
12
|
-
assigns and any entity he controls (including VaryLogic s.r.o.), and
|
|
13
|
-
**"Contribution"** means any work of authorship — code, documentation or other
|
|
14
|
-
material — you submit to an @imqueue repository.
|
|
15
|
-
|
|
16
|
-
## 1. What you grant
|
|
17
|
-
|
|
18
|
-
You grant the Owner a **perpetual, worldwide, irrevocable, royalty-free,
|
|
19
|
-
non-exclusive, transferable and sublicensable** license to use, reproduce,
|
|
20
|
-
modify, adapt, publish, distribute and otherwise exploit your Contribution and
|
|
21
|
-
derivative works of it, **and to license and sub-license it under any terms the
|
|
22
|
-
Owner chooses — including commercial and proprietary (closed-source) licenses,
|
|
23
|
-
without any obligation to release source code.**
|
|
24
|
-
|
|
25
|
-
In plain terms: the Owner may include your Contribution in @imqueue and **sell
|
|
26
|
-
commercial licenses that cover it**, alongside the open-source edition.
|
|
27
|
-
|
|
28
|
-
## 2. No royalties, fees or compensation
|
|
29
|
-
|
|
30
|
-
The rights above are granted **free of charge**. You **waive** any right to
|
|
31
|
-
royalties, license fees, revenue share or any other compensation arising from the
|
|
32
|
-
Owner's use or licensing of your Contribution, including its commercial licensing,
|
|
33
|
-
and you agree not to seek any such payment now or in the future.
|
|
34
|
-
|
|
35
|
-
## 3. You keep your copyright
|
|
36
|
-
|
|
37
|
-
You **retain ownership** of the copyright in your Contribution and may use it
|
|
38
|
-
elsewhere for your own purposes. You are granting the Owner the rights in Section
|
|
39
|
-
1 — you are not required to transfer ownership. Your Contribution also remains
|
|
40
|
-
available to the public under the repository's open-source license (GPL-3.0).
|
|
41
|
-
|
|
42
|
-
## 4. Patent license
|
|
43
|
-
|
|
44
|
-
You grant the Owner and all downstream recipients a perpetual, worldwide,
|
|
45
|
-
royalty-free, irrevocable (except as stated) patent license to make, use, sell,
|
|
46
|
-
offer to sell, import and transfer your Contribution, limited to the patent claims
|
|
47
|
-
you can license that are necessarily infringed by your Contribution alone or in
|
|
48
|
-
combination with the project. If you start patent litigation alleging the project
|
|
49
|
-
or your Contribution infringes your patents, the patent license you received
|
|
50
|
-
terminates.
|
|
51
|
-
|
|
52
|
-
## 5. Your promises
|
|
53
|
-
|
|
54
|
-
You confirm that: (a) the Contribution is your own original work, or you have the
|
|
55
|
-
right to submit it and to grant these rights; (b) if your employer has any rights
|
|
56
|
-
in your work, you have their permission to contribute, or they have waived those
|
|
57
|
-
rights; and (c) you have identified any third-party material in your Contribution
|
|
58
|
-
and its license.
|
|
59
|
-
|
|
60
|
-
## 6. Moral rights
|
|
61
|
-
|
|
62
|
-
To the maximum extent permitted by applicable law, you waive, or agree not to
|
|
63
|
-
exercise, any moral rights in your Contribution in a way that would prevent the
|
|
64
|
-
Owner from exercising the rights in Section 1. (Certain moral rights are
|
|
65
|
-
inalienable under Slovak/EU law; nothing here purports to transfer those.)
|
|
66
|
-
|
|
67
|
-
## 7. No obligation; "as is"
|
|
68
|
-
|
|
69
|
-
The Owner is under no obligation to use your Contribution. It is provided **"as
|
|
70
|
-
is"**, without warranty of any kind.
|
|
71
|
-
|
|
72
|
-
## 8. Governing law
|
|
73
|
-
|
|
74
|
-
These terms are governed by the laws of the Slovak Republic, without regard to its
|
|
75
|
-
conflict-of-laws rules.
|
|
76
|
-
|
|
77
|
-
---
|
|
78
|
-
|
|
79
|
-
**If you do not agree to all of the above, do not contribute to @imqueue.**
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
{
|
|
2
|
-
"signedContributors": [
|
|
3
|
-
{
|
|
4
|
-
"name": "creomobile",
|
|
5
|
-
"id": 25711804,
|
|
6
|
-
"comment_id": 5346985474,
|
|
7
|
-
"created_at": "2026-08-19T19:27:27Z",
|
|
8
|
-
"repoId": 124483013,
|
|
9
|
-
"pullRequestNo": 34
|
|
10
|
-
},
|
|
11
|
-
{
|
|
12
|
-
"name": "creomobile",
|
|
13
|
-
"id": 25711804,
|
|
14
|
-
"comment_id": 5347025718,
|
|
15
|
-
"created_at": "2026-08-19T19:31:25Z",
|
|
16
|
-
"repoId": 124483013,
|
|
17
|
-
"pullRequestNo": 34
|
|
18
|
-
}
|
|
19
|
-
]
|
|
20
|
-
}
|