import { InlineThread, Thread } from "./thread.js"; import type { WorkerThreadFn } from "../models"; import EventEmitter from "../internals/event-emitter.js"; /** Utility type for a value that may or may not be a Promise */ export type MaybePromise

= P | Promise

; /** Utility type for defining Worker Thread arguments */ export type ThreadArgs = T extends void | undefined ? [] : T extends [...args: infer A] ? A : [T]; /** * @internal * @ignore */ export type BaseThreadPoolParameters = { count: number; type?: "module" | undefined; maxConcurrency?: number; }; /** * Parameters for configuring a `ThreadPool`. * @template Arguments - The type of arguments that the worker thread function accepts. * @template Output - The type of value that the worker thread function returns. */ export type ThreadPoolParams = (BaseThreadPoolParameters & { task: WorkerThreadFn>; }) | (BaseThreadPoolParameters & { task: string | URL; }) | (BaseThreadPoolParameters & { task: WorkerThreadFn> | string | URL; }); /** * Parameters for configuring a `DynamicThreadPool`. * * @template Arguments - The type of arguments that the worker thread function accepts. * @template Output - The type of value that the worker thread function returns. */ export type DynamicThreadPoolParams = Omit, "count"> & { /** * The minimum number of threads to maintain in the pool. The pool will always keep at least this many threads alive, even if they are idle. */ minThreads: number; /** * The maximum number of threads to allow in the pool. The pool will not scale up beyond this number of threads, even if there are pending tasks. */ maxThreads: number; /** * The idle timeout in milliseconds. Threads that are idle for longer than this duration may be terminated if the pool needs to scale down. */ idleTimeout?: number; }; export type AnyThread = InlineThread | Thread; /** * Events emitted by `ThreadPool` instances. */ export type ThreadPoolEvents = { /** * `drained` is emitted when the internal task queue of the pool is fully processed and all workers are idle. * * **Note:** This does not necessarily mean that all tasks sent to the pool have completed, as some may still be in-flight on the workers. */ drained: (() => void)[]; }; /** * `AbstractThreadPool` is the base class for thread pool implementations, providing common logic for managing worker threads and task execution. * It defines the core interface and shared functionality, while concrete subclasses implement specific scaling strategies (e.g. static vs dynamic). * @class AbstractThreadPool * @abstract * * ```ts * import { EventEmitter, AbstractThreadPool, type EventMap } from 'nanothreads'; * * type MyEvents = EventMap<{ * 'data': (payload: string) => void; * 'error': (error: Error) => void; * }>; * * class MyThreadPool extends AbstractThreadPool { * protected eventBus: EventEmitter; * * constructor() { * super(/* ... *\/); * this.eventBus = new EventEmitter(); * } * * } * ``` */ export declare abstract class AbstractThreadPool { protected task: WorkerThreadFn> | string | URL; protected type: "module" | undefined; protected threads: Array>; protected abstract eventBus: EventEmitter; protected readonly count: number; constructor(task: WorkerThreadFn> | string | URL, count: number, type?: "module" | undefined); /** * Executes the task on a thread * @abstract * @param args - The arguments to pass to the worker thread function. Can be a single value or an array of values depending on the expected input of the worker function. * @returns A promise that resolves with the output of the worker thread function. * @throws If no workers are available to execute the task, the promise will be rejected. * */ abstract exec(...args: ThreadArgs): Promise; /** * Kills each thread in the pool, terminating it * @abstract * @return A promise that resolves when all threads have been terminated. * * @remarks After calling `terminate()`, the pool should not be used to execute new tasks. Any pending tasks that have not yet been assigned to a worker may be rejected or left unprocessed. * Implementations should ensure that all worker threads are properly cleaned up and resources are released when terminating the pool. */ abstract terminate(): Promise; /** * Helper method used internally by the ThreadPool to retrieve an available worker thread. * @abstract * @protected * @returns A worker thread from the pool, or `null` if no workers are available. */ protected abstract getWorker(): AnyThread | null; } /** * @internal * @ignore */ export type InternalThreadPoolTask = { args: ThreadArgs; resolve: (value: any) => void; reject: (reason?: any) => void; }; /** * A static thread pool that will execute a task/function on different threads. * * @class ThreadPool * @template Arguments - The type of arguments that the worker thread function accepts. * @template Output - The type of value that the worker thread function returns. * @example * import { ThreadPool } from 'nanothreads'; * * const pool = new ThreadPool({ * task: (name) => `Hello ${name}!`, * count: 4 * }); * * await pool.exec("Paul") // output: "Hello Paul!" */ export declare class ThreadPool extends AbstractThreadPool { protected readonly count: number; protected eventBus: EventEmitter; private readonly taskQueue; private idleWorkerQueue; constructor(params: ThreadPoolParams & { count: number; }); on(event: keyof ThreadPoolEvents, listener: ThreadPoolEvents[typeof event][number]): void; off(event: keyof ThreadPoolEvents, listener: ThreadPoolEvents[typeof event][number]): void; exec(...args: ThreadArgs): Promise; getWorker(): AnyThread | null; execAll(...args: ThreadArgs): Promise[]>; private executeTask; terminate(): Promise; }