// Generated by dts-bundle-generator v9.5.1 /** * Circular buffer designed for numbers. * * @internal */ export declare class CircularBuffer { private readIdx; private writeIdx; private readonly items; private readonly maxArrayIdx; size: number; /** * CircularBuffer constructor. * * @param size - Buffer size. * @defaultValue defaultBufferSize * @returns CircularBuffer. */ constructor(size?: number); /** * Clears the buffer. */ clear(): void; /** * Checks whether the buffer is empty. * * @returns Whether the buffer is empty. */ empty(): boolean; /** * Checks whether the buffer is full. * * @returns Whether the buffer is full. */ full(): boolean; /** * Puts number into buffer. * * @param number - Number to put into buffer. */ put(number: number): void; /** * Gets number from buffer. * * @returns Number from buffer. */ get(): number | undefined; /** * Returns buffer as numbers' array. * * @returns Numbers' array. */ toArray(): number[]; /** * Checks the buffer size. * * @param size - Buffer size. */ private checkSize; } /** * Enumeration of worker choice strategies. */ export declare const WorkerChoiceStrategies: Readonly<{ ROUND_ROBIN: "ROUND_ROBIN"; LEAST_USED: "LEAST_USED"; LEAST_BUSY: "LEAST_BUSY"; FAIR_SHARE: "FAIR_SHARE"; WEIGHTED_ROUND_ROBIN: "WEIGHTED_ROUND_ROBIN"; INTERLEAVED_WEIGHTED_ROUND_ROBIN: "INTERLEAVED_WEIGHTED_ROUND_ROBIN"; }>; /** * Worker choice strategy. */ export type WorkerChoiceStrategy = keyof typeof WorkerChoiceStrategies; /** * Enumeration of measurements. */ export declare const Measurements: Readonly<{ runTime: "runTime"; waitTime: "waitTime"; }>; /** * Measurement. */ export type Measurement = keyof typeof Measurements; /** * Measurement options. */ export interface MeasurementOptions { /** * Set measurement median. */ readonly median: boolean; } /** * Worker choice strategy options. */ export interface WorkerChoiceStrategyOptions { /** * Measurement to use in worker choice strategy supporting it. */ readonly measurement?: Measurement; /** * Runtime options. * * @defaultValue \{ median: false \} */ readonly runTime?: MeasurementOptions; /** * Wait time options. * * @defaultValue \{ median: false \} */ readonly waitTime?: MeasurementOptions; /** * Event loop utilization options. * * @defaultValue \{ median: false \} */ readonly elu?: MeasurementOptions; /** * Worker weights to use for weighted round robin worker selection strategies. * A weight is tasks maximum execution time in milliseconds for a worker node. * * @defaultValue Weights computed automatically given the CPU performance. */ weights?: Record; } /** * Measurement statistics requirements. * * @internal */ export interface MeasurementStatisticsRequirements { /** * Requires measurement aggregate. */ aggregate: boolean; /** * Requires measurement average. */ average: boolean; /** * Requires measurement median. */ median: boolean; } /** * Pool worker node worker usage statistics requirements. * * @internal */ export interface TaskStatisticsRequirements { /** * Tasks runtime requirements. */ readonly runTime: MeasurementStatisticsRequirements; /** * Tasks wait time requirements. */ readonly waitTime: MeasurementStatisticsRequirements; /** * Tasks event loop utilization requirements. */ readonly elu: MeasurementStatisticsRequirements; } /** * Strategy policy. * * @internal */ export interface StrategyPolicy { /** * Expects tasks execution on the newly created dynamic worker. */ readonly dynamicWorkerUsage: boolean; /** * Expects the newly created dynamic worker to be flagged as ready. */ readonly dynamicWorkerReady: boolean; } /** * Worker choice strategy interface. * * @internal */ export interface IWorkerChoiceStrategy { /** * The worker choice strategy name. */ readonly name: WorkerChoiceStrategy; /** * Strategy policy. */ readonly strategyPolicy: StrategyPolicy; /** * Tasks statistics requirements. */ readonly taskStatisticsRequirements: TaskStatisticsRequirements; /** * Resets strategy internals. * * @returns `true` if the reset is successful, `false` otherwise. */ readonly reset: () => boolean; /** * The worker choice strategy execution retries count. */ retriesCount: number; /** * Updates the worker node key strategy internals. * This is called after a task has been executed on a worker node. * * @returns `true` if the update is successful, `false` otherwise. */ readonly update: (workerNodeKey: number) => boolean; /** * Chooses a worker node in the pool and returns its key. * If no worker nodes are eligible, `undefined` is returned and the caller retries. * * @param workerNodeKeysSet - The worker node keys affinity set. If undefined, all workers are eligible. * @returns The worker node key or `undefined`. */ readonly choose: (workerNodeKeysSet?: ReadonlySet) => number | undefined; /** * Removes the worker node key from strategy internals. * * @param workerNodeKey - The worker node key. * @returns `true` if the worker node key is removed, `false` otherwise. */ readonly remove: (workerNodeKey: number) => boolean; /** * Sets the worker choice strategy options. * * @param opts - The worker choice strategy options. */ readonly setOptions: (opts: WorkerChoiceStrategyOptions | undefined) => void; } /** * Enumeration of kill behaviors. */ export declare const KillBehaviors: Readonly<{ SOFT: "SOFT"; HARD: "HARD"; }>; /** * Kill behavior. */ export type KillBehavior = keyof typeof KillBehaviors; /** * Handler called when a worker is killed. */ export type KillHandler = () => void | Promise; /** * Options for workers. */ interface WorkerOptions$1 { /** * `killBehavior` dictates if your worker will be deleted in case a task is active on it. * * - SOFT: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but the worker is stealing tasks or a task is executing or queued, then the worker **won't** be deleted. * - HARD: If `currentTime - lastActiveTime` is greater than `maxInactiveTime` but the worker is stealing tasks or a task is executing or queued, then the worker will be deleted. * * This option only apply to the newly created workers. * * @defaultValue KillBehaviors.SOFT */ killBehavior?: KillBehavior; /** * Maximum waiting time in milliseconds for tasks on newly created workers. It must be greater or equal than 5. * * After this time, newly created workers will be terminated. * The last active time of your worker will be updated when it terminates a task. * * - If `killBehavior` is set to `KillBehaviors.HARD` this value represents also the timeout for the tasks that you submit to the pool, * when this timeout expires your tasks is interrupted before completion and removed. The worker is killed if is not part of the minimum size of the pool. * - If `killBehavior` is set to `KillBehaviors.SOFT` your tasks have no timeout and your workers will not be terminated until your task is completed. * * @defaultValue 60000 */ maxInactiveTime?: number; /** * The function to call when a worker is killed. * * @defaultValue `() => {}` */ killHandler?: KillHandler; } /** * Worker error. * * @typeParam Data - Type of data sent to the worker triggering an error. This can only be structured-cloneable data. */ export interface WorkerError { /** * Whether the error is an abort error or not. */ readonly aborted: boolean; /** * Data triggering the error. */ readonly data?: Data; /** * Error object. */ readonly error: Error; /** * Task function name triggering the error. */ readonly name?: string; } /** * Event loop utilization. */ export interface EventLoopUtilization { idle: number; active: number; utilization: number; } /** * Task performance. * * @internal */ export interface TaskPerformance { /** * Task name. */ readonly name: string; /** * Task performance timestamp. */ readonly timestamp: number; /** * Task runtime. */ readonly runTime?: number; /** * Task event loop utilization. */ readonly elu?: EventLoopUtilization; } /** * Worker task performance statistics computation settings. * * @internal */ export interface WorkerStatistics { /** * Whether the worker computes the task runtime or not. */ readonly runTime: boolean; } /** * Task function properties. */ export interface TaskFunctionProperties { /** * Task function name. */ readonly name: string; /** * Task function priority. Lower values have higher priority. */ readonly priority?: number; /** * Task function worker choice strategy. */ readonly strategy?: WorkerChoiceStrategy; /** * Task function worker node keys affinity. * Restricts task execution to specified worker nodes by their indices. * Must contain valid indices within [0, pool max size - 1]. * If undefined, task can execute on any worker node. */ readonly workerNodeKeys?: number[]; } /** * Message object that is passed as a task between main worker and worker. * * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @internal */ export interface Task { /** * Whether the task is abortable or not. */ readonly abortable?: boolean; /** * Task name. */ readonly name?: string; /** * Task input data that will be passed to the worker. */ readonly data?: Data; /** * Task priority. Lower values have higher priority. * * @defaultValue 0 */ readonly priority?: number; /** * Task worker choice strategy. */ readonly strategy?: WorkerChoiceStrategy; /** * Array of transferable objects. */ readonly transferList?: readonly Transferable[]; /** * Timestamp. */ readonly timestamp?: number; /** * Task UUID. */ readonly taskId?: `${string}-${string}-${string}-${string}-${string}`; } /** * Message object that is passed between main worker and worker. * * @typeParam Data - Type of data sent to the worker or execution response. This can only be structured-cloneable data. * @typeParam ErrorData - Type of data sent to the worker triggering an error. This can only be structured-cloneable data. * @internal */ export interface MessageValue extends Task { /** * Worker id. */ readonly workerId?: `${string}-${string}-${string}-${string}-${string}`; /** * Kill code. */ readonly kill?: KillBehavior | true | "success" | "failure"; /** * Worker error. */ readonly workerError?: WorkerError; /** * Task performance. */ readonly taskPerformance?: TaskPerformance; /** * Task function operation: * - `'add'` - Add a task function. * - `'remove'` - Remove a task function. * - `'default'` - Set a task function as default. */ readonly taskFunctionOperation?: "add" | "remove" | "default"; /** * Whether the task function operation is successful or not. */ readonly taskFunctionOperationStatus?: boolean; /** * Task function properties. */ readonly taskFunctionProperties?: TaskFunctionProperties; /** * Task function serialized to string. */ readonly taskFunction?: string; /** * Task function properties. */ readonly taskFunctionsProperties?: TaskFunctionProperties[]; /** * Task operation: * - `'abort'` - Abort a task. */ readonly taskOperation?: "abort"; /** * Whether the worker computes the given statistics or not. */ readonly statistics?: WorkerStatistics; /** * Whether the worker is ready or not. */ readonly ready?: boolean; /** * Whether the worker starts or stops its activity check. */ readonly checkActive?: boolean; /** * Message port. */ readonly port?: MessagePort; } /** * An object holding the task execution response promise resolve/reject callbacks. * * @typeParam Response - Type of execution response. This can only be structured-cloneable data. * @internal */ export interface PromiseResponseWrapper { /** * The task abort signal. */ readonly abortSignal?: AbortSignal; /** * Resolve callback to fulfill the promise. */ readonly resolve: (value: Response | PromiseLike) => void; /** * Reject callback to reject the promise. */ readonly reject: (reason?: unknown) => void; /** * The worker node key executing the task. */ readonly workerNodeKey: number; } /** * Remove readonly modifier from all properties of T. * @typeParam T - Type to remove readonly modifier. * @internal */ export type Writable = { -readonly [P in keyof T]: T[P]; }; /** * Task synchronous function that can be executed. * * @param data - Data sent to the worker. * @returns Execution response. * * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. */ export type TaskSyncFunction = (data?: Data) => Response; /** * Task asynchronous function that can be executed. * This function must return a promise. * * @param data - Data sent to the worker. * @returns Execution response promise. * * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. */ export type TaskAsyncFunction = (data?: Data) => Promise; /** * Task function that can be executed. * This function can be synchronous or asynchronous. * * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. */ export type TaskFunction = TaskSyncFunction | TaskAsyncFunction; /** * Task function object. * * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. */ export interface TaskFunctionObject { /** * Task function. */ taskFunction: TaskFunction; /** * Task function priority. Lower values have higher priority. */ priority?: number; /** * Task function worker choice strategy. */ strategy?: WorkerChoiceStrategy; /** * Task function worker node keys affinity. * Restricts task execution to specified worker nodes by their indices. * Must contain valid indices within [0, pool max size - 1]. * If undefined, task can execute on any worker node. */ workerNodeKeys?: number[]; } /** * Tasks functions that can be executed. * The key is the name of the task function or task function object. * The value is the task function or task function object. * * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. */ export type TaskFunctions = Record | TaskFunctionObject>; /** * Task function operation result. */ export interface TaskFunctionOperationResult { status: boolean; error?: Error; } /** * Priority queue. * * @typeParam T - Type of priority queue data. * @internal */ export declare class PriorityQueue { private head; private tail; private readonly bucketSize; private priorityEnabled; private readonly agingFactor; private readonly loadExponent; /** The priority queue size. */ size: number; /** The priority queue maximum size. */ maxSize: number; /** * Constructs a priority queue. * * @param bucketSize - Prioritized bucket size. * @defaultValue defaultBucketSize * @param enablePriority - Whether to enable priority. * @defaultValue false * @param agingFactor - Aging factor for priority boosting (priority points per millisecond). * @defaultValue defaultAgingFactor * @param loadExponent - Load exponent for aging adjustment based on queue fill ratio. * @defaultValue defaultLoadExponent * @returns PriorityQueue. */ constructor(bucketSize?: number, enablePriority?: boolean, agingFactor?: number, loadExponent?: number); /** * Whether priority is enabled. * * @returns Whether priority is enabled. */ get enablePriority(): boolean; /** * Enables/disables priority. * * @param enablePriority - Whether to enable priority. */ set enablePriority(enablePriority: boolean); /** * The number of filled prioritized buckets. * * @returns The number of filled prioritized buckets. */ get buckets(): number; /** * Enqueue data into the priority queue. * * @param data - Data to enqueue. * @param priority - Priority of the data. Lower values have higher priority. * @returns The new size of the priority queue. */ enqueue(data: T, priority?: number): number; /** * Deletes the given data from the priority queue. * @param data - Data to delete. * @returns `true` if the data was deleted, `false` otherwise. */ delete(data: T): boolean; /** * Dequeue data from the priority queue. * * @param bucket - The prioritized bucket to dequeue from. * @returns The dequeued data or `undefined` if the priority queue is empty. */ dequeue(bucket?: number): T | undefined; /** * Clears the priority queue. */ clear(): void; /** * Returns an iterator for the priority queue. * * @returns An iterator for the priority queue. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols */ [Symbol.iterator](): Iterator; private getPriorityQueueNode; private removePriorityQueueNode; } /** * Callback invoked if the worker has received a message event. */ export type MessageEventHandler = ((ev: MessageEvent) => any) | null; /** * Callback invoked if the worker raised an error at processing a message event. */ export type MessageEventErrorHandler = ((ev: MessageEvent) => any) | null; /** * Callback invoked if the worker raised an error event. */ export type ErrorEventHandler = ((ev: ErrorEvent) => any) | null; /** * Measurement statistics. * * @internal */ export interface MeasurementStatistics { /** * Measurement aggregate. */ aggregate?: number; /** * Measurement minimum. */ minimum?: number; /** * Measurement maximum. */ maximum?: number; /** * Measurement average. */ average?: number; /** * Measurement median. */ median?: number; /** * Measurement history. */ readonly history: CircularBuffer; } /** * Event loop utilization measurement statistics. * * @internal */ export interface EventLoopUtilizationMeasurementStatistics { readonly active: MeasurementStatistics; count?: number; readonly idle: MeasurementStatistics; utilization?: number; } /** * Task statistics. * * @internal */ export interface TaskStatistics { /** * Number of executed tasks. */ executed: number; /** * Number of executing tasks. */ executing: number; /** * Number of queued tasks. */ readonly queued: number; /** * Maximum number of queued tasks. */ readonly maxQueued?: number; /** * Number of sequentially stolen tasks. */ sequentiallyStolen: number; /** * Number of stolen tasks. */ stolen: number; /** * Number of failed tasks. */ failed: number; } /** * Enumeration of worker types. */ export declare const WorkerTypes: Readonly<{ web: "web"; }>; /** * Worker type. */ type WorkerType$1 = keyof typeof WorkerTypes; /** * Worker information. * * @internal */ export interface WorkerInfo { /** * Worker id. */ readonly id: `${string}-${string}-${string}-${string}-${string}` | undefined; /** * Worker type. */ readonly type: WorkerType$1; /** * Dynamic flag. */ dynamic: boolean; /** * Queued task abortion flag. * This flag is set to `true` when worker node is aborting a queued task. */ queuedTaskAbortion: boolean; /** * Ready flag. */ ready: boolean; /** * Stealing flag. * This flag is set to `true` when worker node is stealing one task from another worker node. */ stealing: boolean; /** * Stolen flag. * This flag is set to `true` when worker node has one task stolen from another worker node. */ stolen: boolean; /** * Continuous stealing flag. * This flag is set to `true` when worker node is continuously stealing tasks from other worker nodes. */ continuousStealing: boolean; /** * Back pressure stealing flag. * This flag is set to `true` when worker node is stealing one task from another back pressured worker node. */ backPressureStealing: boolean; /** * Back pressure flag. * This flag is set to `true` when worker node tasks queue is back pressured. */ backPressure: boolean; /** * Task functions properties. */ taskFunctionsProperties?: TaskFunctionProperties[]; } /** * Worker usage statistics. * * @internal */ export interface WorkerUsage { /** * Tasks statistics. */ readonly tasks: TaskStatistics; /** * Tasks runtime statistics. */ readonly runTime: MeasurementStatistics; /** * Tasks wait time statistics. */ readonly waitTime: MeasurementStatistics; /** * Tasks event loop utilization statistics. */ readonly elu: EventLoopUtilizationMeasurementStatistics; } /** * Worker choice strategy data. * * @internal */ export interface StrategyData { virtualTaskEndTimestamp?: number; } /** * Worker interface. */ export interface IWorker extends EventTarget { /** * Worker `message` event handler. */ onmessage: MessageEventHandler; /** * Worker `messageerror` event handler. */ onmessageerror: MessageEventErrorHandler; /** * Worker `error` event handler. */ onerror: ErrorEventHandler; /** * Clones message and transmits it to worker's global environment. transfer can be passed as a list of objects that are to be transferred rather than cloned. * * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Worker/postMessage) */ postMessage(message: any, transfer: Transferable[]): void; postMessage(message: any, options?: StructuredSerializeOptions): void; /** * Terminates the worker. */ terminate: () => void; addEventListener(type: K, listener: (this: this, ev: WorkerEventMap[K]) => any, options?: boolean | AddEventListenerOptions): void; addEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | AddEventListenerOptions): void; removeEventListener(type: K, listener: (this: this, ev: WorkerEventMap[K]) => any, options?: boolean | EventListenerOptions): void; removeEventListener(type: string, listener: EventListenerOrEventListenerObject, options?: boolean | EventListenerOptions): void; } /** * Worker node options. * * @internal */ export interface WorkerNodeOptions { workerOptions?: WorkerOptions; tasksQueueBackPressureSize: number | undefined; tasksQueueBucketSize: number | undefined; tasksQueuePriority: boolean | undefined; tasksQueueAgingFactor: number | undefined; tasksQueueLoadExponent: number | undefined; } /** * Worker node interface. * * @typeParam Worker - Type of worker. * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @internal */ export interface IWorkerNode extends EventTarget { /** * Worker. */ readonly worker: Worker; /** * Worker info. */ readonly info: WorkerInfo; /** * Worker usage statistics. */ readonly usage: WorkerUsage; /** * Worker choice strategy data. * This is used to store data that are specific to the worker choice strategy. */ strategyData?: StrategyData; /** * Tasks queue. */ readonly tasksQueue: PriorityQueue>; /** * Message channel (worker thread only). */ readonly messageChannel?: MessageChannel; /** * Tasks queue back pressure size. * This is the number of tasks that can be enqueued before the worker node has back pressure. */ tasksQueueBackPressureSize: number; /** * Sets tasks queue priority. * * @param enablePriority - Whether to enable tasks queue priority. */ readonly setTasksQueuePriority: (enablePriority: boolean) => void; /** * Tasks queue size. * * @returns The tasks queue size. */ readonly tasksQueueSize: () => number; /** * Enqueue task. * * @param task - The task to queue. * @returns The tasks queue size. */ readonly enqueueTask: (task: Task) => number; /** * Dequeue task. * * @returns The dequeued task. */ readonly dequeueTask: (bucket?: number) => Task | undefined; /** * Dequeue last prioritized task. * * @returns The dequeued task. */ readonly dequeueLastPrioritizedTask: () => Task | undefined; /** * Clears tasks queue. */ readonly clearTasksQueue: () => void; /** * Deletes a task from the tasks queue. * @param task - The task to delete. * @returns `true` if the task was deleted, `false` otherwise. */ readonly deleteTask: (task: Task) => boolean; /** * Terminates the worker node. */ readonly terminate: () => void; /** * Gets task function worker usage statistics. * * @param name - The task function name. * @returns The task function worker usage statistics if the task function worker usage statistics are initialized, `undefined` otherwise. */ readonly getTaskFunctionWorkerUsage: (name: string) => WorkerUsage | undefined; /** * Deletes task function worker usage statistics. * * @param name - The task function name. * @returns `true` if the task function worker usage statistics were deleted, `false` otherwise. */ readonly deleteTaskFunctionWorkerUsage: (name: string) => boolean; } /** * Worker node event detail. * * @internal */ export interface WorkerNodeEventDetail { taskId?: `${string}-${string}-${string}-${string}-${string}`; workerId?: `${string}-${string}-${string}-${string}-${string}`; workerNodeKey?: number; } /** * Enumeration of pool types. */ export declare const PoolTypes: Readonly<{ fixed: "fixed"; dynamic: "dynamic"; }>; /** * Pool type. */ export type PoolType = keyof typeof PoolTypes; /** * Enumeration of pool events. */ export declare const PoolEvents: Readonly<{ ready: "ready"; busy: "busy"; busyEnd: "busyEnd"; full: "full"; fullEnd: "fullEnd"; empty: "empty"; destroy: "destroy"; error: "error"; messageerror: "messageerror"; taskError: "taskError"; backPressure: "backPressure"; backPressureEnd: "backPressureEnd"; }>; /** * Pool event. */ export type PoolEvent = keyof typeof PoolEvents; /** * Pool information. */ export interface PoolInfo { readonly version: string; readonly type: PoolType; readonly worker: WorkerType$1; readonly started: boolean; readonly ready: boolean; readonly defaultStrategy: WorkerChoiceStrategy; readonly strategyRetries: number; readonly minSize: number; readonly maxSize: number; /** Pool utilization. */ readonly utilization?: number; /** Pool total worker nodes. */ readonly workerNodes: number; /** Pool dynamic worker nodes. */ readonly dynamicWorkerNodes?: number; /** Pool idle worker nodes. */ readonly idleWorkerNodes: number; /** Pool busy worker nodes. */ readonly busyWorkerNodes: number; /** Pool tasks stealing worker nodes. */ readonly stealingWorkerNodes?: number; /** Pool tasks back pressure worker nodes. */ readonly backPressureWorkerNodes?: number; readonly executedTasks: number; readonly executingTasks: number; readonly queuedTasks?: number; readonly maxQueuedTasks?: number; readonly backPressure?: boolean; readonly stolenTasks?: number; readonly failedTasks: number; readonly runTime?: { readonly minimum: number; readonly maximum: number; readonly average?: number; readonly median?: number; }; readonly waitTime?: { readonly minimum: number; readonly maximum: number; readonly average?: number; readonly median?: number; }; } /** * Worker node tasks queue options. */ export interface TasksQueueOptions { /** * Controls the priority queue anti-starvation aging rate. * @defaultValue 0.001 */ readonly agingFactor?: number; /** * Maximum number of tasks that can be executed concurrently on a worker node. * @defaultValue 1 */ readonly concurrency?: number; /** * Controls load-based aging adjustment exponent. * @defaultValue 0.667 */ readonly loadExponent?: number; /** * Maximum tasks queue size per worker node flagging it as back pressured. * * @defaultValue (pool maximum size)^2 */ readonly size?: number; /** * Whether to enable task stealing on idle. * * @defaultValue true */ readonly taskStealing?: boolean; /** * Queued tasks finished timeout in milliseconds at worker node termination. * * @defaultValue 2000 */ readonly tasksFinishedTimeout?: number; /** * Whether to enable tasks stealing under back pressure. * * @defaultValue true */ readonly tasksStealingOnBackPressure?: boolean; /** * Ratio of worker nodes that can steal tasks from another worker node. * * @defaultValue 0.6 */ readonly tasksStealingRatio?: number; } /** * Options for a poolifier pool. */ export interface PoolOptions { /** * A function that will listen for message event on each worker. * * @defaultValue `() => {}` */ messageEventHandler?: MessageEventHandler; /** * A function that will listen for message event processing error on each worker. * * @defaultValue `() => {}` */ messageEventErrorHandler?: MessageEventErrorHandler; /** * A function that will listen for error event on each worker. * * @defaultValue `() => {}` */ errorEventHandler?: ErrorEventHandler; /** * Whether to start the minimum number of workers at pool initialization. * * @defaultValue true */ startWorkers?: boolean; /** * The default worker choice strategy to use in this pool. * * @defaultValue WorkerChoiceStrategies.LEAST_USED */ workerChoiceStrategy?: WorkerChoiceStrategy; /** * The worker choice strategy options. */ workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions; /** * Restart worker on error. */ restartWorkerOnError?: boolean; /** * Pool events emission. * * @defaultValue true */ enableEvents?: boolean; /** * Pool worker node tasks queue. * * @defaultValue false */ enableTasksQueue?: boolean; /** * Pool worker node tasks queue options. */ tasksQueueOptions?: TasksQueueOptions; /** * Worker options. * * @see https://developer.mozilla.org/en-US/docs/Web/API/Worker/Worker#options */ workerOptions?: WorkerOptions; } /** * Contract definition for a poolifier pool. * * @typeParam Worker - Type of worker which manages this pool. * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. */ export interface IPool { /** * Pool information. */ readonly info: PoolInfo; /** * Pool worker nodes. * * @internal */ readonly workerNodes: IWorkerNode[]; /** * Pool event target. * * Events that can currently be listened to: * * - `'ready'`: Emitted when the number of workers created in the pool has reached the minimum size expected and are ready. If the pool is dynamic with a minimum number of workers set to zero, this event is emitted when the pool is started. * - `'busy'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are executing concurrently their tasks quota. * - `'busyEnd'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are no longer executing concurrently their tasks quota. * - `'full'`: Emitted when the pool is dynamic and the number of workers created has reached the maximum size expected. * - `'fullEnd'`: Emitted when the pool is dynamic and the number of workers created has no longer reached the maximum size expected. * - `'empty'`: Emitted when the pool is dynamic with a minimum number of workers set to zero and the number of workers has reached the minimum size expected. * - `'destroy'`: Emitted when the pool is destroyed. * - `'error'`: Emitted when an uncaught error occurs. * - `'messageerror'`: Emitted when an error occurs while processing a message event. * - `'taskError'`: Emitted when an error occurs while executing a task. * - `'backPressure'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are back pressured (i.e. their tasks queue is full: queue size \>= maximum queue size). * - `'backPressureEnd'`: Emitted when the number of workers created in the pool has reached the maximum size expected and are no longer back pressured (i.e. their tasks queue is no longer full: queue size \< maximum queue size). */ readonly eventTarget?: EventTarget; /** * Executes the specified function in the worker constructor with the task data input parameter. * * @param data - The optional task input data for the specified task function. This can only be structured-cloneable data. * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed. * @param abortSignal - The optional AbortSignal to abort the task. * @param transferList - The optional array of transferable objects to transfer ownership of. Ownership of the transferred objects is given to the chosen pool's web worker and they should not be used in the main thread afterwards. * @returns Promise with a task function response that will be fulfilled when the task is completed. */ readonly execute: (data?: Data, name?: string, abortSignal?: AbortSignal, transferList?: readonly Transferable[]) => Promise; /** * Executes the specified function in the worker constructor with the tasks data iterable input parameter. * * @param data - The tasks iterable input data for the specified task function. This can only be an iterable of structured-cloneable data. * @param name - The optional name of the task function to execute. If not specified, the default task function will be executed. * @param abortSignals - The optional iterable of AbortSignal to abort the tasks iterable. * @param transferList - The optional array of transferable objects to transfer ownership of. Ownership of the transferred objects is given to the chosen pool's worker_threads worker and they should not be used in the main thread afterwards. * @returns Promise with an array of task function responses that will be fulfilled when the tasks are completed. */ readonly mapExecute: (data: Iterable, name?: string, abortSignals?: Iterable, transferList?: readonly Transferable[]) => Promise; /** * Starts the minimum number of workers in this pool. */ readonly start: () => void; /** * Terminates all workers in this pool. */ readonly destroy: () => Promise; /** * Whether the specified task function exists in this pool. * * @param name - The name of the task function. * @returns `true` if the task function exists, `false` otherwise. */ readonly hasTaskFunction: (name: string) => boolean; /** * Adds a task function to this pool. * If a task function with the same name already exists, it will be overwritten. * * @param name - The name of the task function. * @param fn - The task function. * @returns `true` if the task function was added, `false` otherwise. * @throws {TypeError} If the `name` parameter is not a string or an empty string. * @throws {TypeError} If the `fn` parameter is not a function or task function object. */ readonly addTaskFunction: (name: string, fn: TaskFunction | TaskFunctionObject) => Promise; /** * Removes a task function from this pool. * * @param name - The name of the task function. * @returns `true` if the task function was removed, `false` otherwise. */ readonly removeTaskFunction: (name: string) => Promise; /** * Lists the properties of task functions available in this pool. * * @returns The properties of task functions available in this pool. */ readonly listTaskFunctionsProperties: () => TaskFunctionProperties[]; /** * Sets the default task function in this pool. * * @param name - The name of the task function. * @returns `true` if the default task function was set, `false` otherwise. */ readonly setDefaultTaskFunction: (name: string) => Promise; /** * Sets the default worker choice strategy in this pool. * * @param workerChoiceStrategy - The default worker choice strategy. * @param workerChoiceStrategyOptions - The worker choice strategy options. */ readonly setWorkerChoiceStrategy: (workerChoiceStrategy: WorkerChoiceStrategy, workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions) => void; /** * Sets the worker choice strategy options in this pool. * * @param workerChoiceStrategyOptions - The worker choice strategy options. * @returns `true` if the worker choice strategy options were set, `false` otherwise. */ readonly setWorkerChoiceStrategyOptions: (workerChoiceStrategyOptions: WorkerChoiceStrategyOptions) => boolean; /** * Enables/disables the worker node tasks queue in this pool. * * @param enable - Whether to enable or disable the worker node tasks queue. * @param tasksQueueOptions - The worker node tasks queue options. */ readonly enableTasksQueue: (enable: boolean, tasksQueueOptions?: TasksQueueOptions) => void; /** * Sets the worker node tasks queue options in this pool. * * @param tasksQueueOptions - The worker node tasks queue options. */ readonly setTasksQueueOptions: (tasksQueueOptions: TasksQueueOptions) => void; } /** * The worker choice strategies context. * * @typeParam Worker - Type of worker. * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. * @internal */ export declare class WorkerChoiceStrategiesContext { private readonly pool; /** * The default worker choice strategy in the context. */ private defaultWorkerChoiceStrategy; /** * The worker choice strategies registered in the context. */ private readonly workerChoiceStrategies; /** * The active worker choice strategies in the context policy. */ private workerChoiceStrategiesPolicy; /** * The active worker choice strategies in the context task statistics requirements. */ private workerChoiceStrategiesTaskStatisticsRequirements; /** * The maximum number of worker choice strategy execution retries. */ private readonly retries; /** * Worker choice strategies context constructor. * * @param pool - The pool instance. * @param workerChoiceStrategies - The worker choice strategies. * @defaultValue [WorkerChoiceStrategies.LEAST_USED] * @param opts - The worker choice strategy options. */ constructor(pool: IPool, workerChoiceStrategies?: WorkerChoiceStrategy[], opts?: WorkerChoiceStrategyOptions); /** * Gets the active worker choice strategies in the context policy. * * @returns The strategies policy. */ getPolicy(): StrategyPolicy; /** * Gets the number of worker choice strategies execution retries. * @returns The number of retries. */ getStrategyRetries(): number; /** * Gets the active worker choice strategies in the context task statistics requirements. * * @returns The strategies task statistics requirements. */ getTaskStatisticsRequirements(): TaskStatisticsRequirements; /** * Sets the default worker choice strategy to use in the context. * * @param workerChoiceStrategy - The default worker choice strategy to set. * @param opts - The worker choice strategy options. */ setDefaultWorkerChoiceStrategy(workerChoiceStrategy: WorkerChoiceStrategy, opts?: WorkerChoiceStrategyOptions): void; /** * Updates the worker node key in the active worker choice strategies in the context internals. * * @param workerNodeKey - The worker node key. * @returns `true` if the update is successful, `false` otherwise. */ update(workerNodeKey: number): boolean; /** * Executes the given worker choice strategy in the context algorithm. * * @param workerChoiceStrategy - The worker choice strategy algorithm to execute. * @defaultValue this.defaultWorkerChoiceStrategy * @param workerNodeKeysSet - The worker node keys set to choose from. * @returns The key of the worker node. * @throws {Error} If after computed retries the worker node key is null or undefined. */ execute(workerChoiceStrategy?: WorkerChoiceStrategy, workerNodeKeysSet?: ReadonlySet): number; /** * Executes the given worker choice strategy. * * @param workerChoiceStrategy - The worker choice strategy. * @param workerNodeKeysSet - The worker node keys set to choose from. * @returns The key of the worker node. * @throws {Error} If after computed retries the worker node key is null or undefined. */ private executeStrategy; /** * Removes the worker node key from the active worker choice strategies in the context. * * @param workerNodeKey - The worker node key. * @returns `true` if the removal is successful, `false` otherwise. */ remove(workerNodeKey: number): boolean; /** * Sets the active worker choice strategies in the context options. * * @param opts - The worker choice strategy options. */ setOptions(opts: WorkerChoiceStrategyOptions | undefined): void; /** * Synchronizes the active worker choice strategies in the context with the given worker choice strategies. * * @param workerChoiceStrategies - The worker choice strategies to synchronize. * @param opts - The worker choice strategy options. */ syncWorkerChoiceStrategies(workerChoiceStrategies: Set, opts?: WorkerChoiceStrategyOptions): void; /** * Adds a worker choice strategy to the context. * * @param workerChoiceStrategy - The worker choice strategy to add. * @param opts - The worker choice strategy options. * @param pool - The pool instance. * @returns The worker choice strategies. */ private addWorkerChoiceStrategy; /** * Removes a worker choice strategy from the context. * * @param workerChoiceStrategy - The worker choice strategy to remove. * @returns `true` if the worker choice strategy is removed, `false` otherwise. */ private removeWorkerChoiceStrategy; } /** * Base class that implements some shared logic for all poolifier pools. * * @typeParam Worker - Type of worker which manages this pool. * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. */ export declare abstract class AbstractPool implements IPool { protected readonly minimumNumberOfWorkers: number; protected readonly specifier: URL | string; protected readonly opts: PoolOptions; protected readonly maximumNumberOfWorkers?: number | undefined; /** @inheritDoc */ readonly workerNodes: IWorkerNode[]; /** @inheritDoc */ eventTarget?: EventTarget; /** * The task execution response promise map: * - `key`: The message id of each submitted task. * - `value`: An object that contains task's worker node key, execution response promise resolve and reject callbacks. * * When we receive a message from the worker, we get a map entry with the promise resolve/reject bound to the message id. */ protected promiseResponseMap: Map<`${string}-${string}-${string}-${string}-${string}`, PromiseResponseWrapper>; /** * Worker choice strategies context referencing worker choice algorithms implementation. */ protected workerChoiceStrategiesContext?: WorkerChoiceStrategiesContext; /** * Whether the pool is started or not. */ protected started: boolean; /** * Whether the pool is starting or not. */ protected starting: boolean; /** * Whether the pool is destroying or not. */ protected destroying: boolean; /** * The task functions added at runtime map: * - `key`: The task function name. * - `value`: The task function object. */ private readonly taskFunctions; /** * Whether the minimum number of workers is starting or not. */ private startingMinimumNumberOfWorkers; /** * Whether the pool ready event has been emitted or not. */ private readyEventEmitted; /** * Whether the pool back pressure event has been emitted or not. */ private backPressureEventEmitted; /** * Whether the pool busy event has been emitted or not. */ private busyEventEmitted; /** * The start timestamp of the pool. */ private startTimestamp?; /** * Constructs a new poolifier pool. * * @param minimumNumberOfWorkers - Minimum number of workers that this pool manages. * @param specifier - Specifier to the worker file. * @param opts - Options for the pool. * @param maximumNumberOfWorkers - Maximum number of workers that this pool manages. */ constructor(minimumNumberOfWorkers: number, specifier: URL | string, opts: PoolOptions, maximumNumberOfWorkers?: number | undefined); private checkPoolType; private checkMinimumNumberOfWorkers; private checkPoolOptions; private checkValidWorkerChoiceStrategyOptions; private initEventTarget; /** @inheritDoc */ get info(): PoolInfo; /** * Whether the pool is ready or not. * * @returns The pool readiness boolean status. */ private get ready(); /** * The approximate pool utilization. * * @returns The pool utilization. */ private get utilization(); /** * The pool type. * * If it is `'dynamic'`, it provides the `max` property. */ protected abstract get type(): PoolType; /** * The worker type. */ protected abstract get worker(): WorkerType$1; /** * Checks if the worker id sent in the received message from a worker is valid. * * @param message - The received message. * @throws {Error} If the worker id is invalid. */ private checkMessageWorkerId; /** * Gets the worker node key given its worker id. * * @param workerId - The worker id. * @returns The worker node key if the worker id is found in the pool worker nodes, `-1` otherwise. */ private getWorkerNodeKeyByWorkerId; /** @inheritDoc */ setWorkerChoiceStrategy(workerChoiceStrategy: WorkerChoiceStrategy, workerChoiceStrategyOptions?: WorkerChoiceStrategyOptions): void; /** @inheritDoc */ setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions: WorkerChoiceStrategyOptions | undefined): boolean; /** @inheritDoc */ enableTasksQueue(enable: boolean, tasksQueueOptions?: TasksQueueOptions): void; /** @inheritDoc */ setTasksQueueOptions(tasksQueueOptions: TasksQueueOptions | undefined): void; private buildTasksQueueOptions; private setTasksQueueSize; private setTaskStealing; private unsetTaskStealing; private setTasksStealingOnBackPressure; private unsetTasksStealingOnBackPressure; /** * Whether the pool is back pressured or not. * * @returns The pool back pressure boolean status. */ protected abstract get backPressure(): boolean; /** * Whether the pool is busy or not. * * @returns The pool busyness boolean status. */ protected abstract get busy(): boolean; /** * Whether worker nodes are executing concurrently their tasks quota or not. * * @returns Worker nodes busyness boolean status. */ protected internalBusy(): boolean; private isWorkerNodeBackPressured; private isWorkerNodeBusy; private isWorkerNodeIdle; private isWorkerNodeStealing; private sendTaskFunctionOperationToWorker; private sendTaskFunctionOperationToWorkers; /** @inheritDoc */ hasTaskFunction(name: string): boolean; /** @inheritDoc */ addTaskFunction(name: string, fn: TaskFunction | TaskFunctionObject): Promise; /** @inheritDoc */ removeTaskFunction(name: string): Promise; /** @inheritDoc */ listTaskFunctionsProperties(): TaskFunctionProperties[]; private readonly getAbortError; private getQueuedTasks; private getStealingWorkerNodes; /** * Gets task function worker choice strategy, if any. * * @param name - The task function name. * @returns The task function worker choice strategy if the task function worker choice strategy is defined, `undefined` otherwise. */ private readonly getTaskFunctionWorkerChoiceStrategy; /** * Gets worker node task function worker choice strategy, if any. * * @param workerNodeKey - The worker node key. * @param name - The task function name. * @returns The worker node task function worker choice strategy if the worker node task function worker choice strategy is defined, `undefined` otherwise. */ private readonly getWorkerNodeTaskFunctionWorkerChoiceStrategy; /** * Gets task function worker node keys affinity set, if any. * @param name - The task function name. * @returns The task function worker node keys affinity set, or `undefined` if not defined. */ private readonly getTaskFunctionWorkerNodeKeysSet; /** * Gets worker node task function priority, if any. * * @param workerNodeKey - The worker node key. * @param name - The task function name. * @returns The worker node task function priority if the worker node task function priority is defined, `undefined` otherwise. */ private readonly getWorkerNodeTaskFunctionPriority; /** * Gets the worker choice strategies registered in this pool. * * @returns The worker choice strategies. */ private readonly getWorkerChoiceStrategies; /** @inheritDoc */ setDefaultTaskFunction(name: string): Promise; private shallExecuteTask; internalExecute(data?: Data, name?: string, abortSignal?: AbortSignal, transferList?: readonly Transferable[]): Promise; /** @inheritDoc */ execute(data?: Data, name?: string, abortSignal?: AbortSignal, transferList?: readonly Transferable[]): Promise; /** @inheritDoc */ mapExecute(data: Iterable, name?: string, abortSignals?: Iterable, transferList?: readonly Transferable[]): Promise; /** * Starts the minimum number of workers. * * @param initWorkerNodeUsage - Whether to initialize the worker node usage or not. * @defaultValue false */ private startMinimumNumberOfWorkers; /** @inheritdoc */ start(): void; /** @inheritDoc */ destroy(): Promise; private sendKillMessageToWorker; /** * Terminates the worker node given its worker node key. * * @param workerNodeKey - The worker node key. */ protected destroyWorkerNode(workerNodeKey: number): Promise; /** * Setup hook to execute code before worker nodes are created in the abstract constructor. * Can be overridden. * * @virtual */ protected setupHook(): void; /** * Returns whether the worker is the main worker or not. * * @returns `true` if the worker is the main worker, `false` otherwise. */ protected abstract isMain(): boolean; /** * Hook executed before the worker task execution. * Can be overridden. * * @param workerNodeKey - The worker node key. * @param task - The task to execute. */ protected beforeTaskExecutionHook(workerNodeKey: number, task: Task): void; /** * Hook executed after the worker task execution. * Can be overridden. * * @param workerNodeKey - The worker node key. * @param message - The received message. */ protected afterTaskExecutionHook(workerNodeKey: number, message: MessageValue): void; /** * Whether the worker node shall update its task function worker usage or not. * * @param workerNodeKey - The worker node key. * @returns `true` if the worker node shall update its task function worker usage, `false` otherwise. */ private shallUpdateTaskFunctionWorkerUsage; /** * Chooses a worker node for the next task. * * @param name - The task function name. * @returns The chosen worker node key. */ private chooseWorkerNode; /** * Conditions for dynamic worker creation. * * @returns Whether to create a dynamic worker or not. */ protected abstract shallCreateDynamicWorker(): boolean; /** * Sends a message to worker given its worker node key. * * @param workerNodeKey - The worker node key. * @param message - The message. * @param transferList - The optional array of transferable objects. */ protected abstract sendToWorker(workerNodeKey: number, message: MessageValue, transferList?: readonly Transferable[]): void; /** * Initializes the worker node usage with sensible default values gathered during runtime. * * @param workerNode - The worker node. */ private initWorkerNodeUsage; /** * Creates a new, completely set up worker node. * * @returns New, completely set up worker node key. */ protected createAndSetupWorkerNode(): number; /** * Creates a new, completely set up dynamic worker node. * * @returns New, completely set up dynamic worker node key. */ protected createAndSetupDynamicWorkerNode(): number; /** * Registers a listener callback on the worker given its worker node key. * * @param workerNodeKey - The worker node key. * @param listener - The message listener callback. */ protected abstract registerWorkerMessageListener(workerNodeKey: number, listener: (message: MessageValue) => void): void; /** * Registers once a listener callback on the worker given its worker node key. * * @param workerNodeKey - The worker node key. * @param listener - The message listener callback. */ protected abstract registerOnceWorkerMessageListener(workerNodeKey: number, listener: (message: MessageValue) => void): void; /** * Deregisters a listener callback on the worker given its worker node key. * * @param workerNodeKey - The worker node key. * @param listener - The message listener callback. */ protected abstract deregisterWorkerMessageListener(workerNodeKey: number, listener: (message: MessageValue) => void): void; /** * Method hooked up after a worker node has been newly created. * Can be overridden. * * @param workerNodeKey - The newly created worker node key. */ protected afterWorkerNodeSetup(workerNodeKey: number): void; /** * Sends the startup message to worker given its worker node key. * * @param workerNodeKey - The worker node key. */ protected abstract sendStartupMessageToWorker(workerNodeKey: number): void; /** * Sends the statistics message to worker given its worker node key. * * @param workerNodeKey - The worker node key. */ private sendStatisticsMessageToWorker; private cannotStealTask; private handleTask; private redistributeQueuedTasks; private updateTaskStolenStatisticsWorkerUsage; private updateTaskSequentiallyStolenStatisticsWorkerUsage; private resetTaskSequentiallyStolenStatisticsWorkerUsage; private readonly stealTask; private readonly isStealingRatioReached; private readonly handleWorkerNodeIdleEvent; private readonly workerNodeStealTask; private readonly handleWorkerNodeBackPressureEvent; private setTasksQueuePriority; /** * This method is the message listener registered on each worker. * * @param message - The message received from the worker. */ protected readonly workerMessageListener: (message: MessageValue) => void; private checkAndEmitReadyEvent; private handleWorkerReadyResponse; private handleTaskExecutionResponse; private checkAndEmitTaskExecutionEvents; private checkAndEmitTaskExecutionFinishedEvents; private checkAndEmitTaskQueuingEvents; private checkAndEmitTaskDequeuingEvents; /** * Emits dynamic worker creation events. */ protected abstract checkAndEmitDynamicWorkerCreationEvents(): void; /** * Emits dynamic worker destruction events. */ protected abstract checkAndEmitDynamicWorkerDestructionEvents(): void; /** * Gets the worker information given its worker node key. * * @param workerNodeKey - The worker node key. * @returns The worker information. */ protected getWorkerInfo(workerNodeKey: number): WorkerInfo | undefined; private getTasksQueuePriority; /** * Creates a worker node. * * @returns The created worker node. */ private createWorkerNode; private readonly abortTask; /** * Adds the given worker node in the pool worker nodes. * * @param workerNode - The worker node. * @returns The added worker node key. * @throws {Error} If the added worker node is not found. */ private addWorkerNode; /** * Removes the worker node from the pool worker nodes. * * @param workerNode - The worker node. */ protected removeWorkerNode(workerNode: IWorkerNode): void; protected flagWorkerNodeAsNotReady(workerNodeKey: number): void; /** * Whether the worker nodes are back pressured or not. * * @returns Worker nodes back pressure boolean status. */ protected internalBackPressure(): boolean; /** * Executes the given task on the worker given its worker node key. * * @param workerNodeKey - The worker node key. * @param task - The task to execute. */ private executeTask; private enqueueTask; private dequeueTask; private tasksQueueSize; protected flushTasksQueue(workerNodeKey: number): number; private flushTasksQueues; } /** * Options for a poolifier thread pool. */ export type ThreadPoolOptions = PoolOptions; /** * A thread pool with a fixed number of threads. * * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. * @author [Alessandro Pio Ardizio](https://github.com/pioardi) * @since 0.0.1 */ export declare class FixedThreadPool extends AbstractPool { /** * Constructs a new poolifier fixed thread pool. * * @param numberOfThreads - Number of threads for this pool. * @param specifier - Specifier to an implementation of a `ThreadWorker` file. * @param opts - Options for this fixed thread pool. */ constructor(numberOfThreads: number, specifier: URL | string, opts?: ThreadPoolOptions, maximumNumberOfThreads?: number); /** @inheritDoc */ protected isMain(): boolean; /** @inheritDoc */ protected sendToWorker(workerNodeKey: number, message: MessageValue, transferList?: readonly Transferable[]): void; /** @inheritDoc */ protected sendStartupMessageToWorker(workerNodeKey: number): void; /** @inheritDoc */ protected registerWorkerMessageListener(workerNodeKey: number, listener: (message: MessageValue) => void): void; /** @inheritDoc */ protected registerOnceWorkerMessageListener(workerNodeKey: number, listener: (message: MessageValue) => void): void; /** @inheritDoc */ protected deregisterWorkerMessageListener(workerNodeKey: number, listener: (message: MessageValue) => void): void; /** @inheritDoc */ protected shallCreateDynamicWorker(): boolean; /** @inheritDoc */ protected checkAndEmitDynamicWorkerCreationEvents(): void; /** @inheritDoc */ protected checkAndEmitDynamicWorkerDestructionEvents(): void; /** @inheritDoc */ protected get type(): PoolType; /** @inheritDoc */ protected get worker(): WorkerType$1; /** @inheritDoc */ protected get backPressure(): boolean; /** @inheritDoc */ protected get busy(): boolean; } /** * A thread pool with a dynamic number of threads, but a guaranteed minimum number of threads. * * This thread pool creates new threads when the others are busy, up to the maximum number of threads. * When the maximum number of threads is reached and workers are busy, an event is emitted. If you want to listen to this event, use the pool's `eventTarget`. * * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. * @typeParam Response - Type of execution response. This can only be structured-cloneable data. * @author [Alessandro Pio Ardizio](https://github.com/pioardi) * @since 0.0.1 */ export declare class DynamicThreadPool extends FixedThreadPool { /** * Whether the pool empty event has been emitted or not */ private emptyEventEmitted; /** * Whether the pool full event has been emitted or not. */ private fullEventEmitted; /** * Constructs a new poolifier dynamic thread pool. * * @param min - Minimum number of threads which are always active. * @param max - Maximum number of threads that can be created by this pool. * @param specifier - Specifier to an implementation of a `ThreadWorker` file. * @param opts - Options for this dynamic thread pool. */ constructor(min: number, max: number, specifier: URL | string, opts?: ThreadPoolOptions); /** @inheritDoc */ protected shallCreateDynamicWorker(): boolean; /** @inheritDoc */ protected checkAndEmitDynamicWorkerCreationEvents(): void; /** @inheritDoc */ protected checkAndEmitDynamicWorkerDestructionEvents(): void; /** * Whether the pool is empty or not. * * @returns The pool emptiness boolean status. */ private get empty(); /** * Whether the pool is full or not. * * @returns The pool fullness boolean status. */ private get full(); /** @inheritDoc */ protected get type(): PoolType; /** @inheritDoc */ protected get backPressure(): boolean; /** @inheritDoc */ protected get busy(): boolean; } /** * Fixed queue node. * @typeParam T - Type of fixed queue node data. * @internal */ export interface FixedQueueNode { data: T; priority: number; timestamp: number; } /** * Fixed queue. * @typeParam T - Type of fixed queue data. * @internal */ export interface IFixedQueue { /** The fixed queue capacity. */ readonly capacity: number; /** The fixed queue size. */ readonly size: number; /** The fixed queue node array. */ readonly nodeArray: (FixedQueueNode | undefined)[]; /** * Checks if the fixed queue is empty. * @returns `true` if the fixed queue is empty, `false` otherwise. */ empty: () => boolean; /** * Checks if the fixed queue is full. * @returns `true` if the fixed queue is full, `false` otherwise. */ full: () => boolean; /** * Enqueue data into the fixed queue. * @param data - Data to enqueue. * @param priority - Priority of the data. Lower values have higher priority. * @returns The new size of the fixed queue. * @throws If the fixed queue is full. */ enqueue: (data: T, priority?: number) => number; /** * Gets data from the fixed queue. * @param index - The index of the data to get. * @returns The data at the index or `undefined` if the fixed queue is empty or the index is out of bounds. */ get: (index: number) => T | undefined; /** * Dequeue data from the fixed queue. * @returns The dequeued data or `undefined` if the fixed queue is empty. */ dequeue: () => T | undefined; /** * Clears the fixed queue. */ clear: () => void; /** * Deletes the given data from the fixed priority queue. * @param data - Data to delete. * @returns `true` if the data was deleted, `false` otherwise. */ delete: (data: T) => boolean; /** * Returns an iterator for the fixed queue. * @returns An iterator for the fixed queue. * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols */ [Symbol.iterator]: () => Iterator; } /** * Returns safe host OS optimized estimate of the default amount of parallelism a pool should use. * Always returns a value greater than zero. * * @returns The host OS optimized maximum pool size. */ export declare const availableParallelism: () => number; /** * Base class that implements some shared logic for all poolifier workers. * * @typeParam MainWorker - Type of main worker. * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data. * @typeParam Response - Type of response the worker sends back to the main worker. This can only be structured-cloneable data. */ declare abstract class AbstractWorker$1 { private readonly isMain; private readonly mainWorker; protected opts: WorkerOptions$1; /** * Worker id. */ protected abstract readonly id?: `${string}-${string}-${string}-${string}-${string}`; /** * Task function(s) object processed by the worker when the pool's `execute` method is invoked. */ protected taskFunctions: Map>; /** * Timestamp of the last task processed by this worker. */ protected lastTaskTimestamp: number; /** * Performance statistics computation requirements. */ protected statistics?: WorkerStatistics; /** * Task abort functions processed by the worker when task operation 'abort' is received. */ protected taskAbortFunctions: Map<`${string}-${string}-${string}-${string}-${string}`, () => void>; /** * Handler id of the `activeInterval` worker activity check. */ protected activeInterval?: number; /** * Constructs a new poolifier worker. * @param isMain - Whether this is the main worker or not. * @param mainWorker - Reference to main worker. * @param taskFunctions - Task function(s) processed by the worker when the pool's `execute` method is invoked. The first function is the default function. * @param opts - Options for the worker. */ constructor(isMain: boolean | undefined, mainWorker: MainWorker | undefined, taskFunctions: TaskFunction | TaskFunctions, opts?: WorkerOptions$1); private checkWorkerOptions; /** * Checks if the `taskFunctions` parameter is passed to the constructor and valid. * * @param taskFunctions - The task function(s) parameter that should be checked. */ private checkTaskFunctions; /** * Checks if the worker has a task function with the given name. * * @param name - The name of the task function to check. * @returns Whether the worker has a task function with the given name or not. */ hasTaskFunction(name: string): TaskFunctionOperationResult; /** * Adds a task function to the worker. * If a task function with the same name already exists, it is replaced. * * @param name - The name of the task function to add. * @param fn - The task function to add. * @returns Whether the task function was added or not. */ addTaskFunction(name: string, fn: TaskFunction | TaskFunctionObject): TaskFunctionOperationResult; /** * Removes a task function from the worker. * * @param name - The name of the task function to remove. * @returns Whether the task function existed and was removed or not. */ removeTaskFunction(name: string): TaskFunctionOperationResult; /** * Lists the properties of the worker's task functions. * * @returns The properties of the worker's task functions. */ listTaskFunctionsProperties(): TaskFunctionProperties[]; /** * Sets the default task function to use in the worker. * * @param name - The name of the task function to use as default task function. * @returns Whether the default task function was set or not. */ setDefaultTaskFunction(name: string): TaskFunctionOperationResult; /** * Handles the ready message event sent by the main worker. * * @param messageEvent - The ready message event. */ protected abstract handleReadyMessageEvent(messageEvent: MessageEvent>): void; /** * Worker message event listener. * * @param messageEvent - The received message event. */ protected messageEventListener(messageEvent: MessageEvent>): void; protected handleTaskFunctionOperationMessage(message: MessageValue): void; /** * Handles a kill message sent by the main worker. * * @param _message - The kill message. */ protected handleKillMessage(_message: MessageValue): void; /** * Check if the message worker id is set and matches the worker id. * * @param message - The message to check. * @throws {Error} If the message worker id is not set or does not match the worker id. */ private checkMessageWorkerId; /** * Gets abortable task function. * An abortable promise is built to permit the task to be aborted. * @param name - The name of the task. * @param taskId - The task id. * @returns The abortable task function. */ private getAbortableTaskFunction; /** * Starts the worker check active interval. */ private startCheckActive; /** * Stops the worker check active interval. */ private stopCheckActive; /** * Checks if the worker should be terminated, because its living too long. */ private checkActive; /** * Returns the main worker. * * @returns Reference to the main worker. * @throws {Error} If the main worker is not set. */ protected getMainWorker(): MainWorker; /** * Sends a message to main worker. * * @param message - The response message. */ protected abstract sendToMainWorker(message: MessageValue): void; /** * Sends task functions properties to the main worker. */ protected sendTaskFunctionsPropertiesToMainWorker(): void; /** * Runs the given task. * * @param task - The task to execute. */ protected readonly run: (task: Task) => void; /** * Runs the given task function synchronously. * * @param fn - Task function that will be executed. * @param task - Input data for the task function. */ protected readonly runSync: (fn: TaskSyncFunction, task: Task) => void; /** * Runs the given task function asynchronously. * * @param fn - Task function that will be executed. * @param task - Input data for the task function. */ protected readonly runAsync: (fn: TaskAsyncFunction, task: Task) => void; private beginTaskPerformance; private endTaskPerformance; private updateLastTaskTimestamp; } /** * A thread worker used by a poolifier `ThreadPool`. * * When this worker is inactive for more than the given `maxInactiveTime`, * it will send a termination request to its main thread. * * If you use a `DynamicThreadPool` the extra workers that were created will be terminated, * but the minimum number of workers will be guaranteed. * * @typeParam Data - Type of data this worker receives from pool's execution. This can only be structured-cloneable data. * @typeParam Response - Type of response the worker sends back to the main thread. This can only be structured-cloneable data. * @author [Alessandro Pio Ardizio](https://github.com/pioardi) * @since 0.0.1 */ export declare class ThreadWorker extends AbstractWorker$1 { /** * Message port used to communicate with the main worker. */ private port?; /** @inheritdoc */ id?: `${string}-${string}-${string}-${string}-${string}`; /** * Constructs a new poolifier thread worker. * * @param taskFunctions - Task function(s) processed by the worker when the pool's `execute` method is invoked. * @param opts - Options for the worker. */ constructor(taskFunctions: TaskFunction | TaskFunctions, opts?: WorkerOptions$1); /** @inheritDoc */ protected handleReadyMessageEvent(messageEvent: MessageEvent>): void; /** @inheritDoc */ protected handleKillMessage(message: MessageValue): void; /** @inheritDoc */ protected readonly sendToMainWorker: (message: MessageValue) => void; } export { AbstractWorker$1 as AbstractWorker, WorkerOptions$1 as WorkerOptions, WorkerType$1 as WorkerType, }; export {};