@dudousxd/nestjs-diagnostics
Version:
A standard convention for @dudousxd/nestjs-* libs to emit observability events over node:diagnostics_channel.
170 lines • 6.44 kB
JavaScript
import { randomUUID } from 'node:crypto';
import { CHANNEL_PREFIX, channelName, getChannel } from './channel.js';
import { onChannelRegistered, registeredChannels } from './registry.js';
import { publishRelayed } from './relayed.js';
const DEFAULT_REDIS_CHANNEL = 'aviary:diagnostics:relay';
/** Strip the `aviary:` prefix and split on the FIRST colon — the event segment may contain dots
* (e.g. `durable:run.failed`), but the lib/event boundary is the first colon after the prefix. */
function parseChannelName(name) {
const prefix = `${CHANNEL_PREFIX}:`;
if (!name.startsWith(prefix))
return null;
const rest = name.slice(prefix.length);
const idx = rest.indexOf(':');
if (idx <= 0 || idx === rest.length - 1)
return null;
return { lib: rest.slice(0, idx), event: rest.slice(idx + 1) };
}
/**
* Relay diagnostics events across processes over Redis pub/sub. The envelope crosses as JSON with
* its `id` intact, and the re-emitted copy is marked as relayed (see {@link publishRelayed}). Forwards selected local
* `aviary:<lib>:<event>` channels to Redis and re-emits Redis-received events onto the local bus, so
* `@OnDiagnostic` handlers / `getChannel(...).subscribe(...)` fire cross-process. Loop-safe via nodeId
* echo suppression and a re-emit guard. Never throws into `emit()` or the Redis handler. Does NOT
* close the `pub`/`sub` connections — the caller owns them.
*
* Forwarding happens off the emitter's call stack: selected events are queued and, once per event
* loop turn, serialized and published in emit order (one Redis message per event, sent as a single
* pipeline when `pub` supports it).
*
* @returns a teardown that publishes any queued events, then removes all local subscriptions and
* the Redis message handler.
*/
export function createDiagnosticsRedisRelay(options) {
const { pub } = options;
const sub = options.receive === false ? undefined : options.sub;
if (options.receive !== false && sub === undefined) {
throw new Error('@dudousxd/nestjs-diagnostics: the Redis relay needs a `sub` connection, or `receive: false` for a publish-only relay');
}
const redisChannel = options.redisChannel ?? DEFAULT_REDIS_CHANNEL;
const nodeId = options.nodeId ?? randomUUID();
const forwardAll = options.all === true;
const libs = options.libs ?? [];
const exact = options.channels ?? [];
const subscriptions = [];
const subscribed = new Set();
const reEmitting = new WeakSet();
const pending = [];
let scheduled = null;
const publishOne = (message) => {
try {
pub.publish(redisChannel, message);
}
catch {
// a failing publish drops only its own event
}
};
const flush = () => {
if (scheduled !== null) {
clearImmediate(scheduled);
scheduled = null;
}
if (pending.length === 0)
return;
const messages = [];
for (const env of pending.splice(0)) {
try {
messages.push(JSON.stringify({ node: nodeId, env }));
}
catch {
// an unserializable event is dropped without affecting the rest of the batch
}
}
if (messages.length > 1 && typeof pub.pipeline === 'function') {
try {
const pipeline = pub.pipeline();
for (const message of messages)
pipeline.publish(redisChannel, message);
pipeline.exec();
}
catch {
// never throw out of the flush
}
return;
}
for (const message of messages)
publishOne(message);
};
const forward = (msg) => {
if (typeof msg !== 'object' || msg === null)
return;
if (reEmitting.has(msg))
return; // a re-emitted remote event — do not send it back
pending.push(msg);
scheduled ??= setImmediate(flush);
};
const subscribeRef = (ref) => {
const name = channelName(ref.lib, ref.event);
if (subscribed.has(name))
return;
getChannel(ref.lib, ref.event).subscribe(forward);
subscribed.add(name);
subscriptions.push({ ref, listener: forward });
};
const wildcardMatches = (name) => {
if (forwardAll)
return name.startsWith(`${CHANNEL_PREFIX}:`);
return libs.some((lib) => name.startsWith(`${CHANNEL_PREFIX}:${lib}:`));
};
for (const ref of exact)
subscribeRef(ref);
const hasWildcard = forwardAll || libs.length > 0;
if (hasWildcard) {
for (const name of registeredChannels()) {
if (wildcardMatches(name)) {
const ref = parseChannelName(name);
if (ref)
subscribeRef(ref);
}
}
}
const offRegistered = hasWildcard
? onChannelRegistered((name) => {
if (wildcardMatches(name)) {
const ref = parseChannelName(name);
if (ref)
subscribeRef(ref);
}
})
: null;
const onMessage = (channel, raw) => {
if (channel !== redisChannel)
return;
let parsed;
try {
parsed = JSON.parse(raw);
}
catch {
return; // ignore malformed
}
if (parsed.node === nodeId)
return; // our own echo
const env = parsed.env;
if (!env || typeof env.lib !== 'string' || typeof env.event !== 'string')
return;
reEmitting.add(env);
try {
publishRelayed(env, () => getChannel(env.lib, env.event).publish(env));
}
catch {
// a local subscriber threw — never propagate into the message handler
}
finally {
reEmitting.delete(env);
}
};
sub?.subscribe(redisChannel);
sub?.on('message', onMessage);
return () => {
flush();
for (const { ref, listener } of subscriptions) {
getChannel(ref.lib, ref.event).unsubscribe(listener);
}
subscriptions.length = 0;
subscribed.clear();
offRegistered?.();
sub?.removeListener('message', onMessage);
sub?.unsubscribe(redisChannel);
};
}
//# sourceMappingURL=redis-relay.js.map