Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@ raised `@imqueue/core` floor is how most fixes in the transport reach a service.

This project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]

### Added

- **A service served in process.** `local: true` on a service registers it,
once started, with every client in its own process, and those clients call
it directly — the same checks, hooks and method, with no trip through the
queue. The request and the answer are each copied through JSON, as the queue
copies them, so values arrive exactly as they would have. The queue is still
served, so other processes, delayed calls and `publish()` are unaffected. A
client's `local: false` keeps it on the queue. `localService()`,
`localServiceNames()` and `wireCopy()` are exported for a host.

## [3.10.0] - 2026-11-12

### Added
Expand Down
52 changes: 52 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,58 @@ Delivery remains **at-least-once** either way. A drain narrows the window in
which in-flight work is lost; `SIGKILL`, an OOM kill or a lost node still take
it, so handlers must stay idempotent.

## Serving a service in process

A service may also run inside the process of its caller. Start it with
`local: true` and every client in that process calls it directly, through the
same `@expose()`d methods and the same generated client, with no trip through
the queue:

~~~typescript
const service = new UserService({ local: true });

await service.start();

const client = new userService.UserClient();

await client.start();
await client.get('42'); // answered in this process
~~~

Which services share a process is a deployment choice: nothing in the service
or the client changes, and the same service runs standalone where `local` is
off.

What stays the same:

- **The queue is still served.** A client in another process, a call made with
an `IMQDelay` (the queue holds it until it is due) and `publish()` work as
before.
- **Values travel as the queue carries them.** The request and the answer are
each copied through JSON, so a `Date` arrives as its ISO string, a class
instance as a plain object, `undefined` properties are dropped and
`undefined` array items become `null`, and neither side can change an object
the other holds.
- **Errors are the same plain `{ code, message, … }` objects**, hooks run as
they do (`beforeCall`, `wrapCall` and `afterCall` on both sides), `callTimeout`
applies, and `callTiming()` splits the call, its `transit` now being the two
copies and the wait for the event loop.

What differs:

- An answer that cannot be written as JSON (a `BigInt`, a cycle) rejects at once
with `IMQ_RPC_CALL_ERROR`, where through the queue the service failed to send
it and the call timed out.
- A service served in process belongs to its host: it installs no signal
handlers, does not drain, starts no metrics server and cannot fork workers
(`multiProcess`). Destroy it from the host's own shutdown.
- A client with `local: false` sends every call through the queue regardless.

The service and the client need not share one copy of this package — a host
that loads a service from its own directory loads that service's own
`@imqueue/rpc` beside its own — so long as both are 3.11 or later.
`localServiceNames()` lists what a process serves itself.

## Notes

For image containers builds assign machine UUID in `/etc/machine-id` and
Expand Down
130 changes: 130 additions & 0 deletions src/IMQClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ import {
removeTrackedSignalHandler,
isProcessDrainEnabled,
} from './helpers/index.js';
import { type IMQLocalService, localService, wireCopy } from './IMQLocal.js';
import { EventEmitter } from 'node:events';
import { Script } from 'node:vm';
import { spawnSync } from 'node:child_process';
Expand Down Expand Up @@ -368,6 +369,14 @@ export abstract class IMQClient extends EventEmitter {
}

const callTimeout = this.options.callTimeout;
const local =
!delayed && this.options.local !== false
? localService(to)
: undefined;

if (local) {
return this.localCall<T>(local, request, callTimeout);
}

return new Promise<T>((resolve, reject) => {
let timer: NodeJS.Timeout | null = null;
Expand Down Expand Up @@ -431,6 +440,127 @@ export abstract class IMQClient extends EventEmitter {
}) as Promise<T>;
}

/**
* Calls a service this process serves itself, as {@link remoteCall} would
* through the queue.
*
* @param local - the service's in-process endpoint
* @param request - the request, after `beforeCall` ran
* @param callTimeout - as {@link IMQClientOptions.callTimeout}
*
* @remarks
* The request and the answer are each copied through JSON, as the queue
* copies them, so neither side holds an object of the other's and the
* values arrive as they would have. Where the queue would have failed
* silently and left the call to time out — an answer that cannot be
* written as JSON — this rejects at once with `IMQ_RPC_CALL_ERROR`.
*/
private localCall<T>(
local: IMQLocalService,
request: IMQRPCRequest,
callTimeout?: number,
): Promise<T> {
const { method, args } = request;
const to = this.serviceName;

return new Promise<T>((resolve, reject) => {
let timer: NodeJS.Timeout | null = null;
let settled = false;
const settle =
<V>(done: (value: V) => void) =>
(value: V): void => {
settled = true;

if (timer) {
clearTimeout(timer);
timer = null;
}

done(value);
};
const doResolve = settle(resolve);
const doReject = settle(reject);

if (callTimeout && callTimeout > 0) {
timer = setTimeout(() => {
doReject(
IMQError(
'IMQ_RPC_CALL_TIMEOUT',
`Call to ${to}.${method}() timed out after ${
callTimeout
} ms.`,
new Error().stack,
method,
args,
),
);
}, callTimeout);
timer.unref?.();
}

void (async () => {
try {
request.sentAt = Date.now();

const answered = await local.call(wireCopy(request));
let response: IMQRPCResponse;

try {
response = {
...answered,
...wireCopy({
data: answered.data,
error: answered.error,
}),
};
} catch (err: any) {
response = {
...answered,
data: null,
error: IMQError(
'IMQ_RPC_CALL_ERROR',
`${to}.${method}() answered with a value ` +
`that cannot be sent: ${err?.message}`,
err?.stack,
method,
args,
),
};
}

if (settled) {
logSafe(
this.logger,
'warn',
`${to}: in-process answer to ${method}() came ` +
'after the call had timed out',
);

return;
}

if (response.error) {
return imqCallRejector(
doReject,
request,
this,
)(response.error, response);
}

imqCallResolver(
doResolve,
request,
this,
)(response.data, response);
} catch (err) {
if (!settled) {
imqCallRejector(doReject, request, this)(err);
}
}
})();
});
}

/**
* Subscribes to the service's event channel, named after
* {@link IMQClient.serviceName} — the same channel a service's `publish()`
Expand Down
121 changes: 121 additions & 0 deletions src/IMQLocal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
/*!
* IMQLocal implementation
*
* I'm Queue Software Project
* Copyright (C) 2025 imqueue.com <support@imqueue.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
* If you want to use this code in a closed source (commercial) project, you can
* purchase a proprietary commercial license. Please contact us at
* <support@imqueue.com> to get commercial licensing options.
*/
import type { IMQRPCRequest } from './IMQRPCRequest.js';
import type { IMQRPCResponse } from './IMQRPCResponse.js';

/**
* A service this process serves itself, as a client in the same process
* reaches it.
*
* @remarks
* Registered by a service started with {@link IMQServiceOptions.local}, and
* found by name by every client in the process. The contract is this object
* and nothing else, because the service and its client need not share one
* copy of this package: a host that loads a service from its own directory
* loads that service's own `@imqueue/rpc` beside the host's, and both see one
* registry.
*/
export interface IMQLocalService {
/**
* The service name, which is also its queue name.
*/
readonly name: string;
/**
* Answers one request as the service would through its queue.
*
* @param request - the request as it would arrive off the queue: already
* a copy the caller no longer holds
* @returns the response the service would have sent, before it is copied
* back to the caller
*/
call(request: IMQRPCRequest): Promise<IMQRPCResponse>;
}

const registry = (() => {
const anchor = globalThis as unknown as Record<
symbol,
Map<string, IMQLocalService> | undefined
>;
const symbol = Symbol.for('@imqueue/rpc:IMQ_LOCAL_SERVICES');

return (anchor[symbol] ??= new Map<string, IMQLocalService>());
})();

/**
* Makes a service reachable in process under its name.
*
* @param service - the service's local endpoint
*
* @remarks
* A second service under the same name replaces the first, so that a service
* started again after it was destroyed is the one called.
*/
export function registerLocalService(service: IMQLocalService): void {
registry.set(service.name, service);
}

/**
* Stops reaching a service in process. Its clients go back to the queue.
*
* @param service - the endpoint that was registered; another one registered
* since under the same name is left in place
*/
export function unregisterLocalService(service: IMQLocalService): void {
if (registry.get(service.name) === service) {
registry.delete(service.name);
}
}

/**
* The service this process serves under the given name, if it serves one.
*
* @param name - the service (queue) name
*/
export function localService(name: string): IMQLocalService | undefined {
return registry.get(name);
}

/**
* The name of every service this process serves itself, sorted.
*/
export function localServiceNames(): string[] {
return [...registry.keys()].sort();
}

/**
* Copies a value the way the queue does: through JSON and back.
*
* @param value - an object to copy
* @returns the copy, which shares nothing with the value
*
* @remarks
* This is what keeps an in-process call's semantics those of a queued one: a
* `Date` arrives as its ISO string, a class instance as a plain object,
* `undefined` properties are gone and `undefined` array items are `null`, and
* neither side can change an object the other still holds. It throws where
* the queue would fail to send, on a `BigInt` or a cycle.
*/
export function wireCopy<T extends object>(value: T): T {
return JSON.parse(JSON.stringify(value));
}
34 changes: 34 additions & 0 deletions src/IMQRPCOptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,26 @@ export interface IMQServiceOptions extends IMQOptions {
* abandoned, logged, and the process exits `0` regardless.
*/
drainTimeout?: number;
/**
* Serve this service in process as well: a client in the same process
* calls it directly, with no trip through the queue.
*
* @defaultValue false
*
* @remarks
* The queue is still served, so a client in another process, a delayed
* call and `publish()` work as before, and turning this off again changes
* nothing a caller sees. An in-process call copies its request and its
* answer through JSON exactly as the queue does, so dates, class instances
* and `undefined` arrive as they would have; see {@link wireCopy}.
*
* A service served in process belongs to the process that hosts it: it
* installs no signal handlers and does not drain (the host's shutdown
* decides when it is destroyed), its queue installs none either, and it
* starts no metrics server. It cannot be combined with
* {@link IMQServiceOptions.multiProcess}.
*/
local?: boolean;
}

/**
Expand Down Expand Up @@ -333,6 +353,20 @@ export interface IMQClientOptions extends IMQOptions {
* Use it to bound Redis connections when a process instantiates many clients.
*/
singleQueue?: boolean;
/**
* Call a service this process serves itself directly, rather than through
* the queue.
*
* @defaultValue true
*
* @remarks
* It matters only where a service in the same process was started with
* {@link IMQServiceOptions.local}; otherwise every call goes through the
* queue regardless. `false` sends every call through the queue. A call
* made with an {@link IMQDelay} always goes through the queue, which is
* what holds it until it is due.
*/
local?: boolean;
}

/**
Expand Down
Loading
Loading