messageworks
Version:
MessageWorks is a flexible framework for task orchestration, messaging, and workflow management across distributed systems. Simplify your processes with seamless communication and coordination.
238 lines (230 loc) • 10.2 kB
TypeScript
declare enum MessageType {
GENERAL = "general",
REQUEST = "request",
RESPONSE = "response"
}
type Messenger = string[] | string;
/**
* Represents a general message in the messaging system.
* This class can be extended to create more specific types of messages (e.g., start, stop, status).
*
* @template T The type of data that this message may contain. Can be any type or undefined if no data is provided.
*/
declare class GeneralMessage<T> {
/**
* The unique identifier for this message. This will be set automatically in MessagingService.sendMessage().
* @type {any}
*/
id: any;
/**
* The name of the message, typically used to identify the message type or purpose (e.g. start-process, stop-process).
* @type {string}
*/
name: string;
/**
* The type of the message (e.g., GENERAL, REQUEST, RESPONSE). Default is GENERAL.
* @type {MessageType}
*/
type: MessageType;
/**
* A flag indicating whether the message is a broadcast message.
* @type {boolean}
*/
broadcast: boolean;
/**
* The source of the message, usually represented as a path or address. This will be set automatically by MessagingService.sendMessage().
* @type {Messenger}
*/
source: Messenger;
/**
* The destination of the message. This can be in '/system/middleware/destination' or ['system', 'middleware', 'destination'] format.
* @type {Messenger}
*/
destination: Messenger;
/**
* Optional data associated with the message.
* @type {T | undefined}
*/
data?: T;
/**
* Creates an instance of the GeneralMessage.
*
* @param name The name of the message.
* @param destination The destination of the message (can be in string or string[] format).
* @param data Optional data that the message may contain.
*/
constructor(name: string, destination: Messenger, data?: T);
}
/**
* Represents a request message in the messaging system.
* This class extends the GeneralMessage class and overrides the message type to `REQUEST`.
*
* @template T The type of data this request message may contain. This is typically used for passing data in the request.
*/
declare abstract class RequestMessage<T> extends GeneralMessage<T> {
/**
* Creates an instance of the RequestMessage.
*
* This constructor sets the message type to `REQUEST` and passes the name, destination, and optional data
* to the parent class `GeneralMessage` constructor.
*
* @param name The name of the request message, typically identifying the purpose of the request.
* @param destination The destination(s) for the request, typically an address or a set of addresses.
* @param data Optional data that the request message may contain.
*/
constructor(name: string, destination: Messenger, data?: T);
}
/**
* Represents a response message in the messaging system.
* This class extends the GeneralMessage class and overrides the message type to `RESPONSE`.
*
* It is typically used as a reply to a `RequestMessage`, containing the result or information
* in response to the request. This class includes a `requestId` that references the original
* request message to correlate the response.
*
* @template T The type of data this response message may contain. This is typically used for passing data
* related to the response (such as success, failure, or result data).
*/
declare abstract class ResponseMessage<T> extends GeneralMessage<T> {
/**
* The ID of the original request this response is related to.
* This property is used to link the response back to the originating request message.
*
* @protected
*/
requestId: any;
/**
* Creates an instance of the ResponseMessage.
*
* This constructor sets the message type to `RESPONSE`, assigns the `requestId` from the incoming request,
* and passes the source of the request (to be used as the destination in the response) and optional data
* to the parent class `GeneralMessage`.
*
* @param name The name of the response message, typically identifying the purpose of the response.
* @param request The original request message to which this is responding. The `requestId` and `source`
* are extracted from this request.
* @param data Optional data that the response message may contain (e.g., result, success/failure data).
*/
constructor(name: string, request: RequestMessage<any>, data?: T);
}
/**
* A service for handling messaging between different workers and instances.
* It provides functionality to send messages, handle responses, and manage workers.
*/
declare class MessagingService {
private static instance;
private static instancePromise;
private workerThreads;
private messenger;
messageReceivedCallback: (message: GeneralMessage<any>) => void;
private workers;
private workerListeners;
private responseHandlers;
/**
* Creates an instance of the MessagingService.
* @param {Messenger} messenger The messenger identifier for this instance.
* @param {Function} messageReceivedCallback Callback function to handle received messages.
*/
private constructor();
static getInstance(): Promise<MessagingService>;
private setupWorkerThreadListener;
private setupWebWorkerListener;
/**
* Adds a worker to the service, associating it with the given messenger.
* @param {Messenger} messenger The messenger identifier for the worker.
* @param {Worker} worker The worker to be added.
*/
addWorker(name: string, worker: any): void;
/**
* Removes a worker from the service and cleans up associated resources.
* @param {Worker} worker The worker to be removed.
*/
removeWorker(name: string): void;
/**
* Cleans up all workers, listeners, and response handlers.
*/
cleanUp(): void;
/**
* Sends a message to one or more destinations (workers or upstream).
* @param {GeneralMessage<T>} message The message to be sent.
* @param {Worker} [worker] Optionally specify a specific worker to send the message to.
* @returns {Promise<ResponseMessage<T> | null>} A promise that resolves with the response message, or null if no response is expected.
*/
sendMessage<T, V>(message: GeneralMessage<T>, worker?: any): Promise<ResponseMessage<V> | null>;
/**
* Handles an incoming message.
* @param {GeneralMessage<any>} message The message to handle.
*/
private handleMessage;
/**
* Forwards a message to its correct destination (upstream or downstream).
* @param {GeneralMessage<any>} message The message to forward.
*/
private forwardMessage;
/**
* Forwards a message upstream (to the parent or higher level).
* @param {GeneralMessage<any>} message The message to forward upstream.
*/
private forwardUpstream;
/**
* Forwards a message downstream (to the worker or lower level).
* @param {GeneralMessage<any>} message The message to forward downstream.
*/
private forwardDownstream;
private getWorkerKey;
private getName;
}
/**
* Convert a Messenger object into an array of strings.
* If the Messenger is already an array, return it as is.
* If it's a string, split it into an array of strings using '/' as the separator.
* @param messenger The Messenger object
* @returns An array of strings
*/
declare function messengerAsArray(messenger: Messenger): string[];
/**
* Convert a Messenger object into a string.
* If the Messenger is already a string, return it as is.
* If it's an array, join the elements into a single string using '/' as the separator.
* @param messenger The Messenger object
* @returns A string representation of the Messenger object
*/
declare function messengerAsString(messenger: Messenger): string;
/**
* Normalize a Messenger object by applying path normalization techniques:
* - Trim leading/trailing slashes
* - Remove redundant slashes (multiple consecutive slashes)
* - Remove empty segments
* @param messenger The Messenger object (string or array)
* @returns A normalized Messenger object (string or array)
*/
declare function normalizeMessenger(messenger: Messenger): Messenger;
/**
* Compares two Messenger objects to check if they are equivalent.
* This function ensures both `messenger1` and `messenger2` are valid (not null or undefined)
* and compares them as arrays.
*
* @param {Messenger} messenger1 The first Messenger to compare.
* @param {Messenger} messenger2 The second Messenger to compare.
* @returns {boolean} Returns `true` if both messengers are equal after converting them to strings,
* otherwise returns `false`.
*/
declare function messengersAreEqual(messenger1: Messenger, messenger2: Messenger): boolean;
/**
* Determines if one Messenger (`there`) is upstream from another (`here`), based on their relative levels
* in a hierarchical messenger structure.
*
* This function compares two Messenger objects and returns `true` if the second Messenger (`there`)
* is upstream from the first Messenger (`here`), according to their hierarchical levels and names.
* The comparison is made based on the level and name of the destination in each Messenger.
*
* A "higher" or "upstream" Messenger is considered to be a "parent" or "ancestor"
* in the hierarchical structure, whereas a "lower" or "downstream" Messenger is a "child"
* or "descendant".
*
* @param {Messenger} here The first Messenger to compare (the one that is the starting point).
* @param {Messenger} there The second Messenger to compare (the one being checked to see if it is upstream or downstream).
* @returns {boolean} Returns `true` if `there` is upstream from `here`, otherwise returns `false`.
*/
declare function messengerIsUpstream(here: Messenger, there: Messenger): boolean;
export { GeneralMessage, MessageType, MessagingService, type Messenger, RequestMessage, ResponseMessage, messengerAsArray, messengerAsString, messengerIsUpstream, messengersAreEqual, normalizeMessenger };