/** * @file packages/thread/src/broadcastServer.ts * @description This file contains the BroadcastServer class. * @author Luca Liguori * @created 2025-10-05 * @version 2.0.3 * @license Apache-2.0 * * Copyright 2024, 2025, 2026 Luca Liguori. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import { EventEmitter } from 'node:events'; import { BroadcastChannel } from 'node:worker_threads'; import type { WorkerMessage, WorkerMessageRequest, WorkerMessageRequestAny, WorkerMessageResponse, WorkerMessageResponseSuccess, WorkerMessageTypes, WorkerSrcType, } from '@matterbridge/types'; import { hasAnyParameter } from '@matterbridge/utils/cli'; import { writeDiagnostic } from '@matterbridge/utils/diagnostic'; import { logError } from '@matterbridge/utils/error'; import { logModuleLoaded } from '@matterbridge/utils/loader'; import { type AnsiLogger, CYAN, db, debugStringify, er } from 'node-ansi-logger'; logModuleLoaded('BroadcastServer'); interface BroadcastServerEvents { broadcast_message: [msg: WorkerMessage]; } /** * The event received by the BroadcastChannel handlers, taken from the channel itself instead of the global MessageEvent. * When a project loads both @types/node and bun-types (the buntest typecheck), the global MessageEvent resolves to the * Node (undici) type while onmessage expects the Bun one, and their `source` properties are incompatible. * Deriving the type from onmessage keeps the handlers assignable under either set of types. It is a type-only alias. */ type BroadcastChannelEvent = Parameters>[0]; /** * A fetch waiting for its response, stored by request id. */ interface PendingFetch { /** Settles the fetch when the message is the response to its request, otherwise ignores it. */ handler: (msg: WorkerMessage) => void; /** Rejects the fetch with the given error and removes it from the pending fetches. */ cancel: (error: Error) => void; } /** * BroadcastServer class to handle broadcast messages between workers with BroadcastChannel. */ export class BroadcastServer extends EventEmitter { private readonly broadcastChannel: BroadcastChannel; private closed = false; // The fetches waiting for a response, by request id. A single map lookup per message replaces one event listener per fetch. private readonly pendingFetches = new Map(); private readonly debug = hasAnyParameter('debug', 'verbose', 'debug-broadcast', 'verbose-broadcast'); private readonly verbose = hasAnyParameter('verbose', 'verbose-broadcast'); private readonly diagnostic = hasAnyParameter('diagnostic', 'diagnostic-broadcast'); /** * Creates an instance of BroadcastServer. * * @param {string} name - The name of the broadcast server. * @param {AnsiLogger} log - The logger instance to use for logging. * @param {string} channel - The channel name for the broadcast. Default is 'broadcast-channel'. */ constructor( readonly name: WorkerSrcType, private readonly log: AnsiLogger, private readonly channel: string = 'broadcast-channel', ) { super(); // Create a BroadcastChannel for the specified channel name and set up message handlers. It must remain referenced to keep the process alive. this.broadcastChannel = new BroadcastChannel(this.channel); this.broadcastChannel.onmessage = this.broadcastMessageHandler.bind(this); this.broadcastChannel.onmessageerror = this.broadcastMessageErrorHandler.bind(this); } /** * Closes the broadcast channel and rejects the fetches still waiting for a response. * * @returns {void} */ close(): void { this.broadcastChannel.onmessage = null; this.broadcastChannel.onmessageerror = null; this.broadcastChannel.close(); this.closed = true; // Each cancel deletes its own entry: deleting from a Map while iterating it is safe for (const pending of this.pendingFetches.values()) pending.cancel(new Error('Broadcast channel is closed')); } /** * Handles incoming broadcast messages. * * @param {BroadcastChannelEvent} event - The message event containing the broadcast message. * @returns {void} */ private broadcastMessageHandler(event: BroadcastChannelEvent): void { const msg: WorkerMessage = event.data; if (msg.dst === this.name || msg.dst === 'all') { if (this.verbose) this.log.debug(`Server ${CYAN}${this.name}${db} received broadcast message: ${debugStringify(msg)}`); if (msg.id !== undefined) this.pendingFetches.get(msg.id)?.handler(msg); this.emit('broadcast_message', msg); } else { if (this.verbose) this.log.debug(`Server ${CYAN}${this.name}${db} received unrelated broadcast message: ${debugStringify(msg)}`); } } /** * Handles incoming broadcast error messages. * * @param {BroadcastChannelEvent} event - The message event containing the broadcast message. * @returns {void} */ private broadcastMessageErrorHandler(event: BroadcastChannelEvent): void { const msg: WorkerMessage = event.data; this.log.error(`Server ${CYAN}${this.name}${db} received message error: ${debugStringify(msg)}`); } /** * Generate a pseudo-random identifier between 100,000,000 and 999,999,999. * * @returns {number} A nine-digit identifier. */ getUniqueId(): number { return Math.floor(Math.random() * 900000000) + 100000000; } /** * Type guard to verify a value matches the WorkerMessageRequest structure. * * @param {unknown} value Value to test. * @returns {value is WorkerMessageRequest} True when the value looks like a request message. */ isWorkerRequest(value: unknown): value is WorkerMessageRequest { if (typeof value !== 'object' || value === null) { return false; } const message = value as Partial & { result?: unknown; error?: unknown }; if ( typeof message.type !== 'string' || typeof message.src !== 'string' || typeof message.dst !== 'string' || typeof message.id !== 'number' || typeof message.timestamp !== 'number' ) { return false; } return message.result === undefined && message.error === undefined; } /** * Type guard to verify a value matches a specific WorkerMessageRequest structure. * * @param {unknown} value Value to test. * @param {K} type Worker message type to match. * @returns {value is WorkerMessageRequest} True when the value looks like a request message of the requested type. */ isWorkerRequestOfType(value: unknown, type: K): value is WorkerMessageRequest { return this.isWorkerRequest(value) && value.type === type; } /** * Type guard to verify a value matches the WorkerMessageResponse structure. * * @param {unknown} value Value to test. * @returns {value is WorkerMessageResponse} True when the value looks like a response message. */ isWorkerResponse(value: unknown): value is WorkerMessageResponse { if (typeof value !== 'object' || value === null) { return false; } const message = value as Partial & { error?: unknown; result?: unknown }; if ( typeof message.type !== 'string' || typeof message.src !== 'string' || typeof message.dst !== 'string' || typeof message.id !== 'number' || typeof message.timestamp !== 'number' ) { return false; } const hasError = typeof message.error === 'string'; const hasResult = message.result !== undefined; return hasError !== hasResult; } /** * Type guard to verify a value matches a specific WorkerMessageResponse structure. * * @param {unknown} value Value to test. * @param {K} type Worker message type to match. * @returns {value is WorkerMessageResponse} True when the value looks like a response message of the requested type. */ isWorkerResponseOfType(value: unknown, type: K): value is WorkerMessageResponse { return this.isWorkerResponse(value) && value.type === type; } /** * Broadcast a message to all workers. * * @param {WorkerMessage} message - The message to broadcast. * @returns {void} * * @remarks No checks are performed on the message structure. */ broadcast(message: WorkerMessage): void { if (this.closed) { this.log.error('Broadcast channel is closed'); return; } const broadcastMessage = { ...message, id: message.id ?? this.getUniqueId(), timestamp: message.timestamp ?? Date.now(), src: this.name, }; if (this.verbose) this.log.debug(`Broadcasting message: ${debugStringify(broadcastMessage)}`); try { this.broadcastChannel.postMessage(broadcastMessage); } catch (error) { logError(this.log, `Failed to broadcast message ${debugStringify(broadcastMessage)}${er}`, error); } } /** * Send a request message from the worker implementation. * * @template K * @param {WorkerMessageRequest} message The request message to send. * @returns {void} */ request(message: WorkerMessageRequest): void { if (this.closed) { this.log.error('Broadcast channel is closed'); return; } const requestMessage = { ...message, id: message.id ?? this.getUniqueId(), timestamp: message.timestamp ?? Date.now(), src: this.name, }; if (!this.isWorkerRequest(requestMessage)) { this.log.error(`Invalid request message format: ${debugStringify(requestMessage)}`); return; } if (this.verbose) this.log.debug(`Broadcasting request message: ${debugStringify(requestMessage)}`); try { this.broadcastChannel.postMessage(requestMessage); } catch (error) { logError(this.log, `Failed to broadcast request message ${debugStringify(requestMessage)}${er}`, error); } } /** * Send a response message from the worker implementation. * It also calculates the elapsed time since the request was sent and swaps the source and destination fields. * * @template K * @param {WorkerMessageResponse} message The response message to send. * @returns {void} */ respond(message: WorkerMessageResponse): void { if (this.closed) { this.log.error('Broadcast channel is closed'); return; } const now = Date.now(); const responseMessage = { ...message, ...(typeof message.timestamp === 'number' ? { elapsed: now - message.timestamp } : {}), timestamp: message.timestamp ?? now, dst: message.dst === this.name ? message.src : message.dst, src: this.name, }; if (!this.isWorkerResponse(responseMessage)) { this.log.error(`Invalid response message format: ${debugStringify(responseMessage)}`); return; } if (this.verbose) this.log.debug(`Broadcasting response message: ${debugStringify(responseMessage)}`); try { this.broadcastChannel.postMessage(responseMessage); } catch (error) { logError(this.log, `Failed to broadcast response message ${debugStringify(responseMessage)}${er}`, error); } } /** * Fetch data from a worker. * It broadcasts a request message and waits for a valid response with the same id. * * @template K * @param {WorkerMessageRequest} message - The typed request message to fetch. * @param {number} timeout - The timeout in milliseconds to wait for a response. Default is 250ms. * @returns {Promise>} A promise that resolves with the successful response from the worker or rejects on timeout. * @throws {Error} If the fetch operation times out after the specified timeout (default 250ms) or if an error response is received or if the response is malformed * or if the channel is closed or if a fetch with the same provided id is already pending. */ async fetch>( message: T, timeout: number = 250, ): Promise> { if (this.closed) { return Promise.reject(new Error('Broadcast channel is closed')); } let id: number; if (message.id === undefined) { // Generate an id not used by any pending fetch do id = this.getUniqueId(); while (this.pendingFetches.has(id)); } else { if (this.pendingFetches.has(message.id)) { return Promise.reject(new Error(`Fetch id ${message.id} is already pending for message type ${message.type} from ${this.name} to ${message.dst}`)); } id = message.id; } let timeoutId: NodeJS.Timeout; const start = performance.now(); const requestMessage = { ...message, id, timestamp: message.timestamp ?? Date.now(), src: this.name, }; if (this.verbose) this.log.debug(`Fetching message: ${debugStringify(requestMessage)}`); return new Promise>((resolve, reject) => { const responseHandler = (msg: WorkerMessage): void => { // The id already matches: the handler is looked up by the message id if (this.isWorkerResponseOfType(msg, requestMessage.type)) { clearTimeout(timeoutId); this.pendingFetches.delete(requestMessage.id); if (this.verbose) this.log.debug(`Fetch response: ${debugStringify(msg)}`); if (this.diagnostic) writeDiagnostic( `Broadcast:${this.name}`, `fetch ${requestMessage.type} from ${requestMessage.src} to ${requestMessage.dst} took ${(performance.now() - start).toFixed(2)} ms`, ); if ('error' in msg && typeof msg.error === 'string') { reject( new Error( `Fetch received error response ${msg.error} to message type ${requestMessage.type} id ${requestMessage.id} from ${requestMessage.src} to ${requestMessage.dst}`, ), ); } else if ('result' in msg) { // oxlint-disable-next-line typescript/no-unsafe-type-assertion resolve(msg as WorkerMessageResponseSuccess); } else { reject( new Error(`Fetch received malformed response for message type ${requestMessage.type} id ${requestMessage.id} from ${requestMessage.src} to ${requestMessage.dst}`), ); } return; } }; const cancel = (error: Error): void => { clearTimeout(timeoutId); this.pendingFetches.delete(requestMessage.id); reject(error); }; this.pendingFetches.set(requestMessage.id, { handler: responseHandler, cancel }); this.request(requestMessage); timeoutId = setTimeout(() => { cancel(new Error(`Fetch timeout after ${timeout}ms for message type ${requestMessage.type} id ${requestMessage.id} from ${requestMessage.src} to ${requestMessage.dst}`)); }, timeout); }); } }