+import crypto from 'node:crypto'
import type {
MessageValue,
PromiseWorkerResponseWrapper
import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
import type { PoolOptions } from './pool'
import { PoolEmitter } from './pool'
-import type { IPoolInternal, TasksUsage } from './pool-internal'
+import type { IPoolInternal, TasksUsage, WorkerType } from './pool-internal'
import { PoolType } from './pool-internal'
import type { IPoolWorker } from './pool-worker'
import {
Response = unknown
> implements IPoolInternal<Worker, Data, Response> {
/** {@inheritDoc} */
- public readonly workers: Worker[] = []
-
- /** {@inheritDoc} */
- public readonly workersTasksUsage: Map<Worker, TasksUsage> = new Map<
- Worker,
- TasksUsage
+ public readonly workers: Map<number, WorkerType<Worker>> = new Map<
+ number,
+ WorkerType<Worker>
>()
/** {@inheritDoc} */
public readonly emitter?: PoolEmitter
+ /**
+ * Id of the next worker.
+ */
+ protected nextWorkerId: number = 0
+
/**
* The promise map.
*
- * - `key`: This is the message Id of each submitted task.
+ * - `key`: This is the message id of each submitted task.
* - `value`: An object that contains the worker, the resolve function and the reject function.
*
* When we receive a message from the worker we get a map entry and resolve/reject the promise based on the message.
*/
protected promiseMap: Map<
- number,
+ string,
PromiseWorkerResponseWrapper<Worker, Response>
- > = new Map<number, PromiseWorkerResponseWrapper<Worker, Response>>()
-
- /**
- * Id of the next message.
- */
- protected nextMessageId: number = 0
+ > = new Map<string, PromiseWorkerResponseWrapper<Worker, Response>>()
/**
* Worker choice strategy instance implementing the worker choice algorithm.
this.registerWorkerMessageListener(workerCreated, message => {
if (
isKillBehavior(KillBehaviors.HARD, message.kill) ||
- this.getWorkerRunningTasks(workerCreated) === 0
+ this.getWorkerTasksUsage(workerCreated)?.running === 0
) {
// Kill received from the worker, means that no new tasks are submitted to that worker for a while ( > maxInactiveTime)
- void (this.destroyWorker(workerCreated) as Promise<void>)
+ void this.destroyWorker(workerCreated)
}
})
return workerCreated
}
private checkFilePath (filePath: string): void {
- if (filePath == null || filePath.length === 0) {
+ if (
+ filePath == null ||
+ (typeof filePath === 'string' && filePath.trim().length === 0)
+ ) {
throw new Error('Please specify a file with a worker implementation')
}
}
return this.promiseMap.size
}
- /** {@inheritDoc} */
- public getWorkerIndex (worker: Worker): number {
- return this.workers.indexOf(worker)
- }
-
- /** {@inheritDoc} */
- public getWorkerRunningTasks (worker: Worker): number | undefined {
- return this.workersTasksUsage.get(worker)?.running
- }
-
- /** {@inheritDoc} */
- public getWorkerAverageTasksRunTime (worker: Worker): number | undefined {
- return this.workersTasksUsage.get(worker)?.avgRunTime
+ /**
+ * Gets the given worker key.
+ *
+ * @param worker - The worker.
+ * @returns The worker key.
+ */
+ private getWorkerKey (worker: Worker): number | undefined {
+ return [...this.workers].find(([, value]) => value.worker === worker)?.[0]
}
/** {@inheritDoc} */
workerChoiceStrategy: WorkerChoiceStrategy
): void {
this.opts.workerChoiceStrategy = workerChoiceStrategy
- for (const worker of this.workers) {
- this.resetWorkerTasksUsage(worker)
+ for (const [key, value] of this.workers) {
+ this.setWorker(key, value.worker, {
+ run: 0,
+ running: 0,
+ runTime: 0,
+ avgRunTime: 0
+ })
}
this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
workerChoiceStrategy
/** {@inheritDoc} */
public findFreeWorker (): Worker | false {
- for (const worker of this.workers) {
- if (this.getWorkerRunningTasks(worker) === 0) {
+ for (const value of this.workers.values()) {
+ if (value.tasksUsage.running === 0) {
// A worker is free, return the matching worker
- return worker
+ return value.worker
}
}
return false
/** {@inheritDoc} */
public async execute (data: Data): Promise<Response> {
- // Configure worker to handle message with the specified task
const worker = this.chooseWorker()
- const res = this.internalExecute(worker, this.nextMessageId)
+ const messageId = crypto.randomUUID()
+ const res = this.internalExecute(worker, messageId)
this.checkAndEmitBusy()
this.sendToWorker(worker, {
- data,
- id: this.nextMessageId
+ // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
+ data: data ?? ({} as Data),
+ id: messageId
})
- ++this.nextMessageId
// eslint-disable-next-line @typescript-eslint/return-await
return res
}
/** {@inheritDoc} */
public async destroy (): Promise<void> {
await Promise.all(
- this.workers.map(async worker => {
- await this.destroyWorker(worker)
+ [...this.workers].map(async ([, value]) => {
+ await this.destroyWorker(value.worker)
})
)
}
* @param worker - The worker.
*/
protected beforePromiseWorkerResponseHook (worker: Worker): void {
- this.increaseWorkerRunningTasks(worker)
+ ++(this.getWorkerTasksUsage(worker) as TasksUsage).running
}
/**
message: MessageValue<Response>,
promise: PromiseWorkerResponseWrapper<Worker, Response>
): void {
- this.decreaseWorkerRunningTasks(promise.worker)
- this.stepWorkerRunTasks(promise.worker, 1)
- this.updateWorkerTasksRunTime(promise.worker, message.taskRunTime)
+ const workerTasksUsage = this.getWorkerTasksUsage(
+ promise.worker
+ ) as TasksUsage
+ --workerTasksUsage.running
+ ++workerTasksUsage.run
+ if (
+ this.workerChoiceStrategyContext.getWorkerChoiceStrategy()
+ .requiredStatistics.runTime
+ ) {
+ workerTasksUsage.runTime += message.taskRunTime ?? 0
+ if (workerTasksUsage.run !== 0) {
+ workerTasksUsage.avgRunTime =
+ workerTasksUsage.runTime / workerTasksUsage.run
+ }
+ }
}
/**
* @param worker - The worker that will be removed.
*/
protected removeWorker (worker: Worker): void {
- // Clean worker from data structure
- this.workers.splice(this.getWorkerIndex(worker), 1)
- this.removeWorkerTasksUsage(worker)
+ this.workers.delete(this.getWorkerKey(worker) as number)
+ --this.nextWorkerId
}
/**
this.removeWorker(worker)
})
- this.workers.push(worker)
-
- // Init worker tasks usage map
- this.initWorkerTasksUsage(worker)
+ this.setWorker(this.nextWorkerId, worker, {
+ run: 0,
+ running: 0,
+ runTime: 0,
+ avgRunTime: 0
+ })
+ ++this.nextWorkerId
this.afterWorkerSetup(worker)
private async internalExecute (
worker: Worker,
- messageId: number
+ messageId: string
): Promise<Response> {
this.beforePromiseWorkerResponseHook(worker)
return await new Promise<Response>((resolve, reject) => {
}
}
- /**
- * Increases the number of tasks that the given worker has applied.
- *
- * @param worker - Worker which running tasks is increased.
- */
- private increaseWorkerRunningTasks (worker: Worker): void {
- this.stepWorkerRunningTasks(worker, 1)
- }
-
- /**
- * Decreases the number of tasks that the given worker has applied.
- *
- * @param worker - Worker which running tasks is decreased.
- */
- private decreaseWorkerRunningTasks (worker: Worker): void {
- this.stepWorkerRunningTasks(worker, -1)
- }
-
- /**
- * Steps the number of tasks that the given worker has applied.
- *
- * @param worker - Worker which running tasks are stepped.
- * @param step - Number of running tasks step.
- */
- private stepWorkerRunningTasks (worker: Worker, step: number): void {
- if (this.checkWorkerTasksUsage(worker)) {
- const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
- tasksUsage.running = tasksUsage.running + step
- this.workersTasksUsage.set(worker, tasksUsage)
- }
- }
-
- /**
- * Steps the number of tasks that the given worker has run.
- *
- * @param worker - Worker which has run tasks.
- * @param step - Number of run tasks step.
- */
- private stepWorkerRunTasks (worker: Worker, step: number): void {
- if (this.checkWorkerTasksUsage(worker)) {
- const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
- tasksUsage.run = tasksUsage.run + step
- this.workersTasksUsage.set(worker, tasksUsage)
+ /** {@inheritDoc} */
+ public getWorkerTasksUsage (worker: Worker): TasksUsage | undefined {
+ const workerKey = this.getWorkerKey(worker)
+ if (workerKey !== undefined) {
+ return (this.workers.get(workerKey) as WorkerType<Worker>).tasksUsage
}
+ throw new Error('Worker could not be found in the pool')
}
/**
- * Updates tasks runtime for the given worker.
+ * Sets the given worker.
*
- * @param worker - Worker which run the task.
- * @param taskRunTime - Worker task runtime.
+ * @param workerKey - The worker key.
+ * @param worker - The worker.
+ * @param tasksUsage - The worker tasks usage.
*/
- private updateWorkerTasksRunTime (
+ private setWorker (
+ workerKey: number,
worker: Worker,
- taskRunTime: number | undefined
+ tasksUsage: TasksUsage
): void {
- if (
- this.workerChoiceStrategyContext.getWorkerChoiceStrategy()
- .requiredStatistics.runTime &&
- this.checkWorkerTasksUsage(worker)
- ) {
- const tasksUsage = this.workersTasksUsage.get(worker) as TasksUsage
- tasksUsage.runTime += taskRunTime ?? 0
- if (tasksUsage.run !== 0) {
- tasksUsage.avgRunTime = tasksUsage.runTime / tasksUsage.run
- }
- this.workersTasksUsage.set(worker, tasksUsage)
- }
- }
-
- /**
- * Checks if the given worker is registered in the workers tasks usage map.
- *
- * @param worker - Worker to check.
- * @returns `true` if the worker is registered in the workers tasks usage map. `false` otherwise.
- */
- private checkWorkerTasksUsage (worker: Worker): boolean {
- const hasTasksUsage = this.workersTasksUsage.has(worker)
- if (!hasTasksUsage) {
- throw new Error('Worker could not be found in workers tasks usage map')
- }
- return hasTasksUsage
- }
-
- /**
- * Initializes tasks usage statistics.
- *
- * @param worker - The worker.
- */
- private initWorkerTasksUsage (worker: Worker): void {
- this.workersTasksUsage.set(worker, {
- run: 0,
- running: 0,
- runTime: 0,
- avgRunTime: 0
+ this.workers.set(workerKey, {
+ worker,
+ tasksUsage
})
}
-
- /**
- * Removes worker tasks usage statistics.
- *
- * @param worker - The worker.
- */
- private removeWorkerTasksUsage (worker: Worker): void {
- this.workersTasksUsage.delete(worker)
- }
-
- /**
- * Resets worker tasks usage statistics.
- *
- * @param worker - The worker.
- */
- private resetWorkerTasksUsage (worker: Worker): void {
- this.removeWorkerTasksUsage(worker)
- this.initWorkerTasksUsage(worker)
- }
}