@imqueue/rpc 3.9.5 → 3.11.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 CHANGED
@@ -10,10 +10,39 @@ 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]
13
+ ## [3.11.0] - 2026-11-12
14
14
 
15
15
  ### Added
16
16
 
17
+ - **A service served in process.** `local: true` on a service registers it,
18
+ once started, with every client in its own process, and those clients call
19
+ it directly — the same checks, hooks and method, with no trip through the
20
+ queue. The request and the answer are each copied through JSON, as the queue
21
+ copies them, so values arrive exactly as they would have. The queue is still
22
+ served, so other processes, delayed calls and `publish()` are unaffected. A
23
+ client's `local: false` keeps it on the queue. `localService()`,
24
+ `localServiceNames()` and `wireCopy()` are exported for a host.
25
+
26
+ ## [3.10.0] - 2026-11-12
27
+
28
+ ### Added
29
+
30
+ - **Where a call spent its time.** A service now stamps every response with
31
+ `timing` — when it took the request off the queue, entered the method and
32
+ left it, by its own clock — and a client stamps every request with `sentAt`
33
+ just before sending it. `callTiming(request, response)` turns the pair into
34
+ `total`, `handled`, `waited` (in the service, before the method ran) and
35
+ `transit` (both trips through the queue and the caller's own wait to read
36
+ the answer). Each figure is a difference of two readings of one clock, so
37
+ hosts whose clocks disagree move none of them. Call it from an `afterCall`
38
+ hook. Both fields are optional on the wire: an older client ignores
39
+ `timing`, an older service ignores `sentAt`, and `callTiming` answers `null`
40
+ where either half is missing.
41
+
42
+ Measured on a production-like fleet, a call's round trip minus its handler
43
+ was 4 ms typical, 33 ms at p95 and 152 ms at p99, and nothing said which part
44
+ of the trip it was.
45
+
17
46
  - **TLS on the cache connection.** `RedisCache.init()` now honours `tls`, which
18
47
  it inherited from the queue option shape and silently ignored. `true`
19
48
  connects with Node's defaults, an object is handed to `tls.connect()` as
package/README.md CHANGED
@@ -330,6 +330,58 @@ 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
+ ## Serving a service in process
334
+
335
+ A service may also run inside the process of its caller. Start it with
336
+ `local: true` and every client in that process calls it directly, through the
337
+ same `@expose()`d methods and the same generated client, with no trip through
338
+ the queue:
339
+
340
+ ~~~typescript
341
+ const service = new UserService({ local: true });
342
+
343
+ await service.start();
344
+
345
+ const client = new userService.UserClient();
346
+
347
+ await client.start();
348
+ await client.get('42'); // answered in this process
349
+ ~~~
350
+
351
+ Which services share a process is a deployment choice: nothing in the service
352
+ or the client changes, and the same service runs standalone where `local` is
353
+ off.
354
+
355
+ What stays the same:
356
+
357
+ - **The queue is still served.** A client in another process, a call made with
358
+ an `IMQDelay` (the queue holds it until it is due) and `publish()` work as
359
+ before.
360
+ - **Values travel as the queue carries them.** The request and the answer are
361
+ each copied through JSON, so a `Date` arrives as its ISO string, a class
362
+ instance as a plain object, `undefined` properties are dropped and
363
+ `undefined` array items become `null`, and neither side can change an object
364
+ the other holds.
365
+ - **Errors are the same plain `{ code, message, … }` objects**, hooks run as
366
+ they do (`beforeCall`, `wrapCall` and `afterCall` on both sides), `callTimeout`
367
+ applies, and `callTiming()` splits the call, its `transit` now being the two
368
+ copies and the wait for the event loop.
369
+
370
+ What differs:
371
+
372
+ - An answer that cannot be written as JSON (a `BigInt`, a cycle) rejects at once
373
+ with `IMQ_RPC_CALL_ERROR`, where through the queue the service failed to send
374
+ it and the call timed out.
375
+ - A service served in process belongs to its host: it installs no signal
376
+ handlers, does not drain, starts no metrics server and cannot fork workers
377
+ (`multiProcess`). Destroy it from the host's own shutdown.
378
+ - A client with `local: false` sends every call through the queue regardless.
379
+
380
+ The service and the client need not share one copy of this package — a host
381
+ that loads a service from its own directory loads that service's own
382
+ `@imqueue/rpc` beside its own — so long as both are 3.11 or later.
383
+ `localServiceNames()` lists what a process serves itself.
384
+
333
385
  ## Notes
334
386
 
335
387
  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.9.5",
3
+ "version": "3.11.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",
@@ -0,0 +1,59 @@
1
+ /*!
2
+ * IMQ-RPC: where a remote call spent its time
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
+ * One call's round trip, split into where it went, in milliseconds.
28
+ */
29
+ export interface IMQCallTiming {
30
+ /** From handing the call to the queue until its answer arrived. */
31
+ total: number;
32
+ /** Inside the service's method. */
33
+ handled: number;
34
+ /** In the service between leaving the queue and entering the method. */
35
+ waited: number;
36
+ /**
37
+ * Everything else: both trips through the queue, and the caller's own wait
38
+ * to read the answer.
39
+ */
40
+ transit: number;
41
+ }
42
+ /**
43
+ * Splits a call's round trip from the request a client sent and the response
44
+ * it was answered with.
45
+ *
46
+ * @param request - the request as the client sent it, carrying `sentAt`
47
+ * @param response - the response as it arrived, carrying `timing`
48
+ * @param answeredAt - when the answer arrived, by the caller's clock
49
+ * @returns the split, or `null` where either side did not record its half
50
+ *
51
+ * @remarks
52
+ * Each figure is a difference of two readings of one clock — `total` the
53
+ * caller's, `handled` and `waited` the service's — so clocks that disagree
54
+ * between hosts move no figure. `transit` is what is left, and is where a
55
+ * busy caller, a busy broker and the size of a message show.
56
+ *
57
+ * Call it from an `afterCall` hook, which runs as the answer arrives.
58
+ */
59
+ export declare function callTiming(request: Partial<IMQRPCRequest> | undefined, response: Partial<IMQRPCResponse> | undefined, answeredAt?: number): IMQCallTiming | null;
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Splits a call's round trip from the request a client sent and the response
3
+ * it was answered with.
4
+ *
5
+ * @param request - the request as the client sent it, carrying `sentAt`
6
+ * @param response - the response as it arrived, carrying `timing`
7
+ * @param answeredAt - when the answer arrived, by the caller's clock
8
+ * @returns the split, or `null` where either side did not record its half
9
+ *
10
+ * @remarks
11
+ * Each figure is a difference of two readings of one clock — `total` the
12
+ * caller's, `handled` and `waited` the service's — so clocks that disagree
13
+ * between hosts move no figure. `transit` is what is left, and is where a
14
+ * busy caller, a busy broker and the size of a message show.
15
+ *
16
+ * Call it from an `afterCall` hook, which runs as the answer arrives.
17
+ */
18
+ export function callTiming(request, response, answeredAt = Date.now()) {
19
+ const sentAt = request?.sentAt;
20
+ const timing = response?.timing;
21
+ if (typeof sentAt !== 'number' || !timing) {
22
+ return null;
23
+ }
24
+ const total = Math.max(0, answeredAt - sentAt);
25
+ const handled = Math.max(0, timing.finished - timing.started);
26
+ const waited = Math.max(0, timing.started - timing.received);
27
+ return {
28
+ total,
29
+ handled,
30
+ waited,
31
+ transit: Math.max(0, total - handled - waited),
32
+ };
33
+ }
34
+ //# sourceMappingURL=IMQCallTiming.js.map
@@ -167,6 +167,22 @@ export declare abstract class IMQClient extends EventEmitter {
167
167
  * otherwise ignored.
168
168
  */
169
169
  protected remoteCall<T>(...args: any[]): Promise<T>;
170
+ /**
171
+ * Calls a service this process serves itself, as {@link remoteCall} would
172
+ * through the queue.
173
+ *
174
+ * @param local - the service's in-process endpoint
175
+ * @param request - the request, after `beforeCall` ran
176
+ * @param callTimeout - as {@link IMQClientOptions.callTimeout}
177
+ *
178
+ * @remarks
179
+ * The request and the answer are each copied through JSON, as the queue
180
+ * copies them, so neither side holds an object of the other's and the
181
+ * values arrive as they would have. Where the queue would have failed
182
+ * silently and left the call to time out — an answer that cannot be
183
+ * written as JSON — this rejects at once with `IMQ_RPC_CALL_ERROR`.
184
+ */
185
+ private localCall;
170
186
  /**
171
187
  * Subscribes to the service's event channel, named after
172
188
  * {@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';
@@ -331,6 +332,12 @@ let IMQClient = (() => {
331
332
  }
332
333
  }
333
334
  const callTimeout = this.options.callTimeout;
335
+ const local = !delayed && this.options.local !== false
336
+ ? localService(to)
337
+ : undefined;
338
+ if (local) {
339
+ return this.localCall(local, request, callTimeout);
340
+ }
334
341
  return new Promise((resolve, reject) => {
335
342
  let timer = null;
336
343
  const clearTimer = () => {
@@ -349,6 +356,7 @@ let IMQClient = (() => {
349
356
  };
350
357
  void (async () => {
351
358
  try {
359
+ request.sentAt = Date.now();
352
360
  const id = await this.imq.send(to, request, delay, doReject);
353
361
  this.resolvers[id] = [
354
362
  imqCallResolver(doResolve, request, this),
@@ -373,6 +381,83 @@ let IMQClient = (() => {
373
381
  })();
374
382
  });
375
383
  }
384
+ /**
385
+ * Calls a service this process serves itself, as {@link remoteCall} would
386
+ * through the queue.
387
+ *
388
+ * @param local - the service's in-process endpoint
389
+ * @param request - the request, after `beforeCall` ran
390
+ * @param callTimeout - as {@link IMQClientOptions.callTimeout}
391
+ *
392
+ * @remarks
393
+ * The request and the answer are each copied through JSON, as the queue
394
+ * copies them, so neither side holds an object of the other's and the
395
+ * values arrive as they would have. Where the queue would have failed
396
+ * silently and left the call to time out — an answer that cannot be
397
+ * written as JSON — this rejects at once with `IMQ_RPC_CALL_ERROR`.
398
+ */
399
+ localCall(local, request, callTimeout) {
400
+ const { method, args } = request;
401
+ const to = this.serviceName;
402
+ return new Promise((resolve, reject) => {
403
+ let timer = null;
404
+ let settled = false;
405
+ const settle = (done) => (value) => {
406
+ settled = true;
407
+ if (timer) {
408
+ clearTimeout(timer);
409
+ timer = null;
410
+ }
411
+ done(value);
412
+ };
413
+ const doResolve = settle(resolve);
414
+ const doReject = settle(reject);
415
+ if (callTimeout && callTimeout > 0) {
416
+ timer = setTimeout(() => {
417
+ doReject(IMQError('IMQ_RPC_CALL_TIMEOUT', `Call to ${to}.${method}() timed out after ${callTimeout} ms.`, new Error().stack, method, args));
418
+ }, callTimeout);
419
+ timer.unref?.();
420
+ }
421
+ void (async () => {
422
+ try {
423
+ request.sentAt = Date.now();
424
+ const answered = await local.call(wireCopy(request));
425
+ let response;
426
+ try {
427
+ response = {
428
+ ...answered,
429
+ ...wireCopy({
430
+ data: answered.data,
431
+ error: answered.error,
432
+ }),
433
+ };
434
+ }
435
+ catch (err) {
436
+ response = {
437
+ ...answered,
438
+ data: null,
439
+ error: IMQError('IMQ_RPC_CALL_ERROR', `${to}.${method}() answered with a value ` +
440
+ `that cannot be sent: ${err?.message}`, err?.stack, method, args),
441
+ };
442
+ }
443
+ if (settled) {
444
+ logSafe(this.logger, 'warn', `${to}: in-process answer to ${method}() came ` +
445
+ 'after the call had timed out');
446
+ return;
447
+ }
448
+ if (response.error) {
449
+ return imqCallRejector(doReject, request, this)(response.error, response);
450
+ }
451
+ imqCallResolver(doResolve, request, this)(response.data, response);
452
+ }
453
+ catch (err) {
454
+ if (!settled) {
455
+ imqCallRejector(doReject, request, this)(err);
456
+ }
457
+ }
458
+ })();
459
+ });
460
+ }
376
461
  /**
377
462
  * Subscribes to the service's event channel, named after
378
463
  * {@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;
@@ -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
@@ -231,6 +231,26 @@ export interface IMQServiceOptions extends IMQOptions {
231
231
  * abandoned, logged, and the process exits `0` regardless.
232
232
  */
233
233
  drainTimeout?: number;
234
+ /**
235
+ * Serve this service in process as well: a client in the same process
236
+ * calls it directly, with no trip through the queue.
237
+ *
238
+ * @defaultValue false
239
+ *
240
+ * @remarks
241
+ * The queue is still served, so a client in another process, a delayed
242
+ * call and `publish()` work as before, and turning this off again changes
243
+ * nothing a caller sees. An in-process call copies its request and its
244
+ * answer through JSON exactly as the queue does, so dates, class instances
245
+ * and `undefined` arrive as they would have; see {@link wireCopy}.
246
+ *
247
+ * A service served in process belongs to the process that hosts it: it
248
+ * installs no signal handlers and does not drain (the host's shutdown
249
+ * decides when it is destroyed), its queue installs none either, and it
250
+ * starts no metrics server. It cannot be combined with
251
+ * {@link IMQServiceOptions.multiProcess}.
252
+ */
253
+ local?: boolean;
234
254
  }
235
255
  /**
236
256
  * Options accepted by a generated IMQ client.
@@ -323,6 +343,20 @@ export interface IMQClientOptions extends IMQOptions {
323
343
  * Use it to bound Redis connections when a process instantiates many clients.
324
344
  */
325
345
  singleQueue?: boolean;
346
+ /**
347
+ * Call a service this process serves itself directly, rather than through
348
+ * the queue.
349
+ *
350
+ * @defaultValue true
351
+ *
352
+ * @remarks
353
+ * It matters only where a service in the same process was started with
354
+ * {@link IMQServiceOptions.local}; otherwise every call goes through the
355
+ * queue regardless. `false` sends every call through the queue. A call
356
+ * made with an {@link IMQDelay} always goes through the queue, which is
357
+ * what holds it until it is due.
358
+ */
359
+ local?: boolean;
326
360
  }
327
361
  /**
328
362
  * Default options applied to every IMQ service: the core queue defaults, plus
@@ -69,4 +69,14 @@ export interface IMQRPCRequest extends JsonObject {
69
69
  * caller's bag, so it is a plain object, not an {@link IMQMetadata} instance.
70
70
  */
71
71
  metadata?: IMQMetadata;
72
+ /**
73
+ * When the client handed the call to the queue, in milliseconds since the
74
+ * epoch by the caller's clock.
75
+ *
76
+ * @remarks
77
+ * Set by the client immediately before sending, after `beforeCall` ran.
78
+ * Read back on the client only, so the service's clock never meets it;
79
+ * see {@link callTiming}.
80
+ */
81
+ sentAt?: number;
72
82
  }
@@ -66,4 +66,26 @@ export interface IMQRPCResponse extends JsonObject {
66
66
  * this round-trips every argument value back to the caller.
67
67
  */
68
68
  request: IMQRPCRequest;
69
+ /**
70
+ * When the service took the request off the queue, started the method and
71
+ * finished it, in milliseconds since the epoch by the service's clock.
72
+ *
73
+ * @remarks
74
+ * Absent on a response from a service older than this field. Only the
75
+ * differences between its own values mean anything to a caller, because
76
+ * the two clocks are not the same clock; {@link callTiming} combines them
77
+ * with the caller's own round trip without comparing one with the other.
78
+ */
79
+ timing?: IMQRPCTiming;
80
+ }
81
+ /**
82
+ * Where a service spent a call, by its own clock.
83
+ */
84
+ export interface IMQRPCTiming extends JsonObject {
85
+ /** When the message was taken off the queue. */
86
+ received: number;
87
+ /** When the method was entered, after the service's `beforeCall` ran. */
88
+ started: number;
89
+ /** When the method returned or threw. */
90
+ finished: number;
69
91
  }
@@ -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.
@@ -226,9 +231,19 @@ export declare abstract class IMQService {
226
231
  *
227
232
  * @param request - request message
228
233
  * @param id - message unique identifier
234
+ * @param received - when the message was taken off the queue
229
235
  */
230
236
  private handleRequest;
231
237
  private processRequest;
238
+ /**
239
+ * Answers a request a client in this process made, with no trip through
240
+ * the queue: the same checks, hooks and method as a queued request, and
241
+ * the response handed back rather than sent.
242
+ *
243
+ * @param request - the request, already copied the way the queue copies it
244
+ */
245
+ private answerLocally;
246
+ private respond;
232
247
  /**
233
248
  * Initializes this instance of service and starts handling request
234
249
  * 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.
@@ -269,6 +276,20 @@ let IMQService = (() => {
269
276
  },
270
277
  };
271
278
  this.logger = this.options.logger || /* istanbul ignore next */ console;
279
+ if (this.options.local) {
280
+ if (this.options.multiProcess) {
281
+ throw new TypeError(`${this.name}: a service served in process cannot ` +
282
+ 'also fork workers (local with multiProcess)');
283
+ }
284
+ // the host owns this process's shutdown, so neither this service
285
+ // nor its queue may exit it from a signal of their own
286
+ this.options.handleSignals = false;
287
+ this.options.drain = false;
288
+ this.localEndpoint = {
289
+ name: this.name,
290
+ call: request => this.answerLocally(request),
291
+ };
292
+ }
272
293
  this.drainEnabled = this.options.drain ?? drainEnabledFromEnv();
273
294
  this.drainTimeout = this.options.drainTimeout ?? drainTimeoutFromEnv();
274
295
  if (this.drainEnabled) {
@@ -283,7 +304,7 @@ let IMQService = (() => {
283
304
  }
284
305
  this.imq = IMQ.create(this.name, this.options);
285
306
  this.handleRequest = this.handleRequest.bind(this);
286
- SIGNALS.forEach((signal) => {
307
+ (this.localEndpoint ? [] : SIGNALS).forEach((signal) => {
287
308
  if (this.drainEnabled && DRAIN_SIGNALS.includes(signal)) {
288
309
  const handler = () => {
289
310
  // a drain that throws must not leave the process hanging
@@ -316,7 +337,7 @@ let IMQService = (() => {
316
337
  // the response (e.g. the broker went away mid-reply) must be logged,
317
338
  // not surface as an unhandled rejection and crash the process
318
339
  this.imq.on('message', ((request, id) => {
319
- const handled = this.handleRequest(request, id).catch(err => this.logger.error(`${this.name}: error handling request:`, err));
340
+ const handled = this.handleRequest(request, id, Date.now()).catch(err => this.logger.error(`${this.name}: error handling request:`, err));
320
341
  // fast path with draining off: no set, no tracking, no
321
342
  // allocation beyond what this dispatch already did
322
343
  return this.inFlight ? this.track(handled) : handled;
@@ -430,11 +451,29 @@ let IMQService = (() => {
430
451
  *
431
452
  * @param request - request message
432
453
  * @param id - message unique identifier
454
+ * @param received - when the message was taken off the queue
433
455
  */
434
- async handleRequest(request, id) {
435
- return runWithRequest(request, () => this.processRequest(request, id));
456
+ async handleRequest(request, id, received = Date.now()) {
457
+ return runWithRequest(request, () => this.processRequest(request, id, received));
458
+ }
459
+ async processRequest(request, id, received) {
460
+ const response = await this.respond(request, id, received);
461
+ return await send(request, response, this);
436
462
  }
437
- async processRequest(request, id) {
463
+ /**
464
+ * Answers a request a client in this process made, with no trip through
465
+ * the queue: the same checks, hooks and method as a queued request, and
466
+ * the response handed back rather than sent.
467
+ *
468
+ * @param request - the request, already copied the way the queue copies it
469
+ */
470
+ async answerLocally(request) {
471
+ const received = Date.now();
472
+ const response = await runWithRequest(request, () => this.respond(request, randomUUID(), received));
473
+ await afterCall(request, response, this);
474
+ return response;
475
+ }
476
+ async respond(request, id, received) {
438
477
  const logger = this.options.logger || console;
439
478
  const method = request.method;
440
479
  const description = await this.describe();
@@ -476,8 +515,11 @@ let IMQService = (() => {
476
515
  }
477
516
  if (response.error) {
478
517
  this.logger.warn(response.error);
479
- return await send(request, response, this);
518
+ const now = Date.now();
519
+ response.timing = { received, started: now, finished: now };
520
+ return response;
480
521
  }
522
+ const started = Date.now();
481
523
  try {
482
524
  // Run the method through the optional `wrapCall` around-hook so a
483
525
  // hook can execute it within its own scope (e.g. an OpenTelemetry
@@ -496,7 +538,8 @@ let IMQService = (() => {
496
538
  catch (err) {
497
539
  response.error = IMQError(err.code || 'IMQ_RPC_CALL_ERROR', err.message, err.stack, method, args, err);
498
540
  }
499
- return await send(request, response, this);
541
+ response.timing = { received, started, finished: Date.now() };
542
+ return response;
500
543
  }
501
544
  /**
502
545
  * Initializes this instance of service and starts handling request
@@ -520,7 +563,16 @@ let IMQService = (() => {
520
563
  if (!this.options.multiProcess) {
521
564
  this.logger.info('%s: starting single-worker, pid %s', this.name, process.pid);
522
565
  this.describe();
523
- return this.startWithMetricsServer();
566
+ if (!this.localEndpoint) {
567
+ return this.startWithMetricsServer();
568
+ }
569
+ // in process the metrics port is the host's, and a second listener
570
+ // on it would fail; the queue still starts first, so a method can
571
+ // publish from the first in-process call
572
+ const started = await this.imq.start();
573
+ registerLocalService(this.localEndpoint);
574
+ this.logger.info('%s: serving in process too', this.name);
575
+ return started;
524
576
  }
525
577
  if (cluster.isMaster) {
526
578
  const numCpus = cpus().length;
@@ -588,6 +640,9 @@ let IMQService = (() => {
588
640
  * {@link IMQServiceOptions.drain}.
589
641
  */
590
642
  async destroy() {
643
+ if (this.localEndpoint) {
644
+ unregisterLocalService(this.localEndpoint);
645
+ }
591
646
  // unregister this instance's process signal handlers so destroyed
592
647
  // services do not leak process-level listeners
593
648
  for (const [signal, handler] of this.signalHandlers) {
@@ -667,17 +722,29 @@ export { IMQService };
667
722
  * @returns send result message identifier
668
723
  */
669
724
  export async function send(request, response, service) {
670
- const logger = service.options.logger || console;
671
725
  const id = await service.imq.send(request.from, response);
672
- if (typeof service.options.afterCall === 'function') {
673
- const afterCall = service.options.afterCall.bind(service);
674
- try {
675
- await afterCall(request, response);
676
- }
677
- catch (err) {
678
- logger.warn(AFTER_HOOK_ERROR, err);
679
- }
680
- }
726
+ await afterCall(request, response, service);
681
727
  return id;
682
728
  }
729
+ /**
730
+ * Runs the service's optional after-call hook on an answered request, logging
731
+ * rather than propagating its failure.
732
+ *
733
+ * @param request - the request answered
734
+ * @param response - the response it was answered with
735
+ * @param service - imq service to bind
736
+ */
737
+ async function afterCall(request, response, service) {
738
+ if (typeof service.options.afterCall !== 'function') {
739
+ return;
740
+ }
741
+ const logger = service.options.logger || console;
742
+ const hook = service.options.afterCall.bind(service);
743
+ try {
744
+ await hook(request, response);
745
+ }
746
+ catch (err) {
747
+ logger.warn(AFTER_HOOK_ERROR, err);
748
+ }
749
+ }
683
750
  //# sourceMappingURL=IMQService.js.map
package/src/index.d.ts CHANGED
@@ -28,6 +28,8 @@ export * from './IMQRPCDescription.js';
28
28
  export * from './IMQRPCError.js';
29
29
  export * from './IMQRPCRequest.js';
30
30
  export * from './IMQRPCResponse.js';
31
+ export * from './IMQCallTiming.js';
32
+ export * from './IMQLocal.js';
31
33
  export * from './IMQLock.js';
32
34
  export * from './IMQService.js';
33
35
  export * from './IMQClient.js';
package/src/index.js CHANGED
@@ -28,6 +28,8 @@ export * from './IMQRPCDescription.js';
28
28
  export * from './IMQRPCError.js';
29
29
  export * from './IMQRPCRequest.js';
30
30
  export * from './IMQRPCResponse.js';
31
+ export * from './IMQCallTiming.js';
32
+ export * from './IMQLocal.js';
31
33
  export * from './IMQLock.js';
32
34
  export * from './IMQService.js';
33
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/.
@@ -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
- }