async-multi-worker
Version:
Use worker as simple asynchronous function
104 lines (98 loc) • 4.26 kB
TypeScript
type FunctionsRecord = Record<string, any>;
interface WorkerProxy<T extends FunctionsRecord> {
func<K extends keyof T>(funcName: K): (...args: Parameters<T[K]>) => Promise<ReturnType<T[K]>>;
terminate(): void;
}
interface HostInterface {
postMessage: (message: any) => void;
onmessage: (data: any) => void;
}
/**
*
* @param obj Object containing functions to be called in the worker.
* @returns The host instance for the worker. it was returns for testing purpose only
* do not use it in production code.
*/
declare const initWorker: <T extends FunctionsRecord>(obj: T) => HostInterface;
/**
* A generic handler for making asynchronous function calls to a Worker.
*
* This class manages communication between the main thread and a worker, allowing you to call worker-exposed functions as Promises.
* It handles message passing, result/error propagation, timeouts, and worker cleanup.
*
* @template T - The type describing the functions exposed by the worker (should extend FunctionsRecord).
*
* @see func for calling worker functions
* @see terminate for cleanup
*/
declare class ElasticWorker<T extends FunctionsRecord> implements WorkerProxy<T> {
private readonly workerManager;
constructor(workerURL: URL, maxIdleWorkers?: number);
private messageListener;
/**
* Returns a function that calls a method in the worker asynchronously with optional timeout.
*
* @template K - The key of the function in the worker object.
* @param funcName - The name of the function to call in the worker.
* @param timeoutMs - Optional timeout in milliseconds (default: 5000ms).
* @returns A function that, when called with arguments, returns a Promise resolving to the result of the worker function.
*
* @example
* const add = workerProxy.func('add');
* const result = await add(1, 2);
*/
func: <K extends keyof T>(funcName: K, timeoutMs?: number) => (...args: Parameters<T[K]>) => Promise<ReturnType<T[K]>>;
private onWorkerExit;
private onWorkerError;
/**
* Terminates the worker and cleans up all pending calls.
* This method removes all event listeners and clears the calls map.
* It should be called when the worker is no longer needed to prevent memory leaks.
*
* ! Keep in mind that this will stop all workers including the workers with ongoing calls.
*/
terminate: () => void;
}
/**
* A generic handler for making asynchronous function calls to a Worker.
*
* This class manages communication between the main thread and a worker, allowing you to call worker-exposed functions as Promises.
* It handles message passing, result/error propagation, timeouts, and worker cleanup.
*
* @template T - The type describing the functions exposed by the worker .
*
* @see func for calling worker functions
* @see terminate for cleanup
*/
declare class DedicatedWorker<T extends FunctionsRecord> implements WorkerProxy<T> {
private readonly calls;
private readonly worker;
private readonly workerURL;
constructor(workerURL: URL);
private spawnWorker;
private cleanup;
/**
* Returns a function that calls a method in the worker asynchronously with optional timeout.
*
* @template K - The key of the function in the worker object.
* @param funcName - The name of the function to call in the worker.
* @param timeoutMs - Optional timeout in milliseconds (default: 5000ms).
* @returns A function that, when called with arguments, returns a Promise resolving to the result of the worker function.
*
* @example
* const add = workerProxy.func('add');
* const result = await add(1, 2);
*/
func: <K extends keyof T>(funcName: K) => (...args: Parameters<T[K]>) => Promise<ReturnType<T[K]>>;
get busy(): boolean;
/**
* Terminates the worker and cleans up all pending calls.
* This method removes all event listeners and clears the calls map.
* It should be called when the worker is no longer needed to prevent memory leaks.
*/
terminate: () => void;
}
declare class TimeoutError extends Error {
constructor(timeoutMs: number);
}
export { DedicatedWorker, ElasticWorker, TimeoutError, initWorker };