refactor: move helpers to utils.ts file
[poolifier.git] / src / pools / abstract-pool.ts
index 2e769fc9c2660305bbbb84ab370468e7d4326da0..24e8a5b0c670f275a91a93dec22227fa12659d25 100644 (file)
@@ -1,24 +1,38 @@
 import crypto from 'node:crypto'
+import { performance } from 'node:perf_hooks'
 import type { MessageValue, PromiseResponseWrapper } from '../utility-types'
 import {
   DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS,
   EMPTY_FUNCTION,
+  isKillBehavior,
   isPlainObject,
-  median
+  median,
+  round
 } from '../utils'
-import { KillBehaviors, isKillBehavior } from '../worker/worker-options'
+import { KillBehaviors } from '../worker/worker-options'
 import { CircularArray } from '../circular-array'
 import { Queue } from '../queue'
 import {
   type IPool,
   PoolEmitter,
   PoolEvents,
+  type PoolInfo,
   type PoolOptions,
-  PoolType,
-  type TasksQueueOptions
+  type PoolType,
+  PoolTypes,
+  type TasksQueueOptions,
+  type WorkerType,
+  WorkerTypes
 } from './pool'
-import type { IWorker, Task, TasksUsage, WorkerNode } from './worker'
+import type {
+  IWorker,
+  MessageHandler,
+  Task,
+  WorkerNode,
+  WorkerUsage
+} from './worker'
 import {
+  Measurements,
   WorkerChoiceStrategies,
   type WorkerChoiceStrategy,
   type WorkerChoiceStrategyOptions
@@ -29,8 +43,8 @@ import { WorkerChoiceStrategyContext } from './selection-strategies/worker-choic
  * 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 serializable data.
- * @typeParam Response - Type of execution response. This can only be serializable data.
+ * @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 abstract class AbstractPool<
   Worker extends IWorker,
@@ -58,8 +72,6 @@ export abstract class AbstractPool<
 
   /**
    * Worker choice strategy context referencing a worker choice algorithm implementation.
-   *
-   * Default to a round robin algorithm.
    */
   protected workerChoiceStrategyContext: WorkerChoiceStrategyContext<
   Worker,
@@ -67,6 +79,11 @@ export abstract class AbstractPool<
   Response
   >
 
+  /**
+   * The start timestamp of the pool.
+   */
+  private readonly startTimestamp
+
   /**
    * Constructs a new poolifier pool.
    *
@@ -75,9 +92,9 @@ export abstract class AbstractPool<
    * @param opts - Options for the pool.
    */
   public constructor (
-    public readonly numberOfWorkers: number,
-    public readonly filePath: string,
-    public readonly opts: PoolOptions<Worker>
+    protected readonly numberOfWorkers: number,
+    protected readonly filePath: string,
+    protected readonly opts: PoolOptions<Worker>
   ) {
     if (!this.isMain()) {
       throw new Error('Cannot start a pool from a worker!')
@@ -91,12 +108,6 @@ export abstract class AbstractPool<
     this.enqueueTask = this.enqueueTask.bind(this)
     this.checkAndEmitEvents = this.checkAndEmitEvents.bind(this)
 
-    this.setupHook()
-
-    for (let i = 1; i <= this.numberOfWorkers; i++) {
-      this.createAndSetupWorker()
-    }
-
     if (this.opts.enableEvents === true) {
       this.emitter = new PoolEmitter()
     }
@@ -109,6 +120,14 @@ export abstract class AbstractPool<
       this.opts.workerChoiceStrategy,
       this.opts.workerChoiceStrategyOptions
     )
+
+    this.setupHook()
+
+    while (this.workerNodes.length < this.numberOfWorkers) {
+      this.createAndSetupWorker()
+    }
+
+    this.startTimestamp = performance.now()
   }
 
   private checkFilePath (filePath: string): void {
@@ -133,7 +152,7 @@ export abstract class AbstractPool<
       throw new RangeError(
         'Cannot instantiate a pool with a negative number of workers'
       )
-    } else if (this.type === PoolType.FIXED && numberOfWorkers === 0) {
+    } else if (this.type === PoolTypes.fixed && numberOfWorkers === 0) {
       throw new Error('Cannot instantiate a fixed pool with no worker')
     }
   }
@@ -149,6 +168,7 @@ export abstract class AbstractPool<
       this.checkValidWorkerChoiceStrategyOptions(
         this.opts.workerChoiceStrategyOptions
       )
+      this.opts.restartWorkerOnError = opts.restartWorkerOnError ?? true
       this.opts.enableEvents = opts.enableEvents ?? true
       this.opts.enableTasksQueue = opts.enableTasksQueue ?? false
       if (this.opts.enableTasksQueue) {
@@ -184,12 +204,22 @@ export abstract class AbstractPool<
     }
     if (
       workerChoiceStrategyOptions.weights != null &&
-      Object.keys(workerChoiceStrategyOptions.weights).length !== this.size
+      Object.keys(workerChoiceStrategyOptions.weights).length !== this.maxSize
     ) {
       throw new Error(
         'Invalid worker choice strategy options: must have a weight for each worker node'
       )
     }
+    if (
+      workerChoiceStrategyOptions.measurement != null &&
+      !Object.values(Measurements).includes(
+        workerChoiceStrategyOptions.measurement
+      )
+    ) {
+      throw new Error(
+        `Invalid worker choice strategy options: invalid measurement '${workerChoiceStrategyOptions.measurement}'`
+      )
+    }
   }
 
   private checkValidTasksQueueOptions (
@@ -198,49 +228,140 @@ export abstract class AbstractPool<
     if (tasksQueueOptions != null && !isPlainObject(tasksQueueOptions)) {
       throw new TypeError('Invalid tasks queue options: must be a plain object')
     }
-    if ((tasksQueueOptions?.concurrency as number) <= 0) {
+    if (
+      tasksQueueOptions?.concurrency != null &&
+      !Number.isSafeInteger(tasksQueueOptions.concurrency)
+    ) {
+      throw new TypeError(
+        'Invalid worker tasks concurrency: must be an integer'
+      )
+    }
+    if (
+      tasksQueueOptions?.concurrency != null &&
+      tasksQueueOptions.concurrency <= 0
+    ) {
       throw new Error(
-        `Invalid worker tasks concurrency '${
-          tasksQueueOptions.concurrency as number
-        }'`
+        `Invalid worker tasks concurrency '${tasksQueueOptions.concurrency}'`
       )
     }
   }
 
   /** @inheritDoc */
-  public abstract get type (): PoolType
+  public get info (): PoolInfo {
+    return {
+      type: this.type,
+      worker: this.worker,
+      minSize: this.minSize,
+      maxSize: this.maxSize,
+      utilization: round(this.utilization),
+      workerNodes: this.workerNodes.length,
+      idleWorkerNodes: this.workerNodes.reduce(
+        (accumulator, workerNode) =>
+          workerNode.usage.tasks.executing === 0
+            ? accumulator + 1
+            : accumulator,
+        0
+      ),
+      busyWorkerNodes: this.workerNodes.reduce(
+        (accumulator, workerNode) =>
+          workerNode.usage.tasks.executing > 0 ? accumulator + 1 : accumulator,
+        0
+      ),
+      executedTasks: this.workerNodes.reduce(
+        (accumulator, workerNode) =>
+          accumulator + workerNode.usage.tasks.executed,
+        0
+      ),
+      executingTasks: this.workerNodes.reduce(
+        (accumulator, workerNode) =>
+          accumulator + workerNode.usage.tasks.executing,
+        0
+      ),
+      queuedTasks: this.workerNodes.reduce(
+        (accumulator, workerNode) =>
+          accumulator + workerNode.usage.tasks.queued,
+        0
+      ),
+      maxQueuedTasks: this.workerNodes.reduce(
+        (accumulator, workerNode) =>
+          accumulator + workerNode.usage.tasks.maxQueued,
+        0
+      ),
+      failedTasks: this.workerNodes.reduce(
+        (accumulator, workerNode) =>
+          accumulator + workerNode.usage.tasks.failed,
+        0
+      )
+    }
+  }
 
-  /** @inheritDoc */
-  public abstract get size (): number
+  /**
+   * Gets the pool run time.
+   *
+   * @returns The pool run time in milliseconds.
+   */
+  private get runTime (): number {
+    return performance.now() - this.startTimestamp
+  }
 
   /**
-   * Number of tasks running in the pool.
+   * Gets the approximate pool utilization.
+   *
+   * @returns The pool utilization.
    */
-  private get numberOfRunningTasks (): number {
-    return this.workerNodes.reduce(
-      (accumulator, workerNode) => accumulator + workerNode.tasksUsage.running,
+  private get utilization (): number {
+    const poolRunTimeCapacity = this.runTime * this.maxSize
+    const totalTasksRunTime = this.workerNodes.reduce(
+      (accumulator, workerNode) =>
+        accumulator + workerNode.usage.runTime.aggregate,
+      0
+    )
+    const totalTasksWaitTime = this.workerNodes.reduce(
+      (accumulator, workerNode) =>
+        accumulator + workerNode.usage.waitTime.aggregate,
       0
     )
+    return (totalTasksRunTime + totalTasksWaitTime) / poolRunTimeCapacity
   }
 
   /**
-   * Number of tasks queued in the pool.
+   * Pool type.
+   *
+   * If it is `'dynamic'`, it provides the `max` property.
    */
-  private get numberOfQueuedTasks (): number {
-    if (this.opts.enableTasksQueue === false) {
-      return 0
-    }
-    return this.workerNodes.reduce(
-      (accumulator, workerNode) => accumulator + workerNode.tasksQueue.size,
-      0
-    )
+  protected abstract get type (): PoolType
+
+  /**
+   * Gets the worker type.
+   */
+  protected abstract get worker (): WorkerType
+
+  /**
+   * Pool minimum size.
+   */
+  protected abstract get minSize (): number
+
+  /**
+   * Pool maximum size.
+   */
+  protected abstract get maxSize (): number
+
+  /**
+   * Get the worker given its id.
+   *
+   * @param workerId - The worker id.
+   * @returns The worker if found in the pool worker nodes, `undefined` otherwise.
+   */
+  private getWorkerById (workerId: number): Worker | undefined {
+    return this.workerNodes.find(workerNode => workerNode.info.id === workerId)
+      ?.worker
   }
 
   /**
    * Gets the given worker its worker node key.
    *
    * @param worker - The worker.
-   * @returns The worker node key if the worker is found in the pool worker nodes, `-1` otherwise.
+   * @returns The worker node key if found in the pool worker nodes, `-1` otherwise.
    */
   private getWorkerNodeKey (worker: Worker): number {
     return this.workerNodes.findIndex(
@@ -255,27 +376,19 @@ export abstract class AbstractPool<
   ): void {
     this.checkValidWorkerChoiceStrategy(workerChoiceStrategy)
     this.opts.workerChoiceStrategy = workerChoiceStrategy
-    for (const workerNode of this.workerNodes) {
-      this.setWorkerNodeTasksUsage(workerNode, {
-        run: 0,
-        running: 0,
-        runTime: 0,
-        runTimeHistory: new CircularArray(),
-        avgRunTime: 0,
-        medRunTime: 0,
-        waitTime: 0,
-        waitTimeHistory: new CircularArray(),
-        avgWaitTime: 0,
-        medWaitTime: 0,
-        error: 0
-      })
-    }
     this.workerChoiceStrategyContext.setWorkerChoiceStrategy(
       this.opts.workerChoiceStrategy
     )
     if (workerChoiceStrategyOptions != null) {
       this.setWorkerChoiceStrategyOptions(workerChoiceStrategyOptions)
     }
+    for (const [workerNodeKey, workerNode] of this.workerNodes.entries()) {
+      this.setWorkerNodeTasksUsage(
+        workerNode,
+        this.getWorkerUsage(workerNodeKey)
+      )
+      this.setWorkerStatistics(workerNode.worker)
+    }
   }
 
   /** @inheritDoc */
@@ -307,7 +420,7 @@ export abstract class AbstractPool<
       this.checkValidTasksQueueOptions(tasksQueueOptions)
       this.opts.tasksQueueOptions =
         this.buildTasksQueueOptions(tasksQueueOptions)
-    } else {
+    } else if (this.opts.tasksQueueOptions != null) {
       delete this.opts.tasksQueueOptions
     }
   }
@@ -325,7 +438,9 @@ export abstract class AbstractPool<
    *
    * The pool filling boolean status.
    */
-  protected abstract get full (): boolean
+  protected get full (): boolean {
+    return this.workerNodes.length >= this.maxSize
+  }
 
   /**
    * Whether the pool is busy or not.
@@ -334,23 +449,28 @@ export abstract class AbstractPool<
    */
   protected abstract get busy (): boolean
 
+  /**
+   * Whether worker nodes are executing at least one task.
+   *
+   * @returns Worker nodes busyness boolean status.
+   */
   protected internalBusy (): boolean {
     return (
       this.workerNodes.findIndex(workerNode => {
-        return workerNode.tasksUsage.running === 0
+        return workerNode.usage.tasks.executing === 0
       }) === -1
     )
   }
 
   /** @inheritDoc */
   public async execute (data?: Data, name?: string): Promise<Response> {
-    const submissionTimestamp = performance.now()
+    const timestamp = performance.now()
     const workerNodeKey = this.chooseWorkerNode()
     const submittedTask: Task<Data> = {
       name,
       // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
       data: data ?? ({} as Data),
-      submissionTimestamp,
+      timestamp,
       id: crypto.randomUUID()
     }
     const res = new Promise<Response>((resolve, reject) => {
@@ -363,7 +483,7 @@ export abstract class AbstractPool<
     if (
       this.opts.enableTasksQueue === true &&
       (this.busy ||
-        this.workerNodes[workerNodeKey].tasksUsage.running >=
+        this.workerNodes[workerNodeKey].usage.tasks.executing >=
           ((this.opts.tasksQueueOptions as TasksQueueOptions)
             .concurrency as number))
     ) {
@@ -371,7 +491,6 @@ export abstract class AbstractPool<
     } else {
       this.executeTask(workerNodeKey, submittedTask)
     }
-    this.workerChoiceStrategyContext.update(workerNodeKey)
     this.checkAndEmitEvents()
     // eslint-disable-next-line @typescript-eslint/return-await
     return res
@@ -382,21 +501,22 @@ export abstract class AbstractPool<
     await Promise.all(
       this.workerNodes.map(async (workerNode, workerNodeKey) => {
         this.flushTasksQueue(workerNodeKey)
+        // FIXME: wait for tasks to be finished
         await this.destroyWorker(workerNode.worker)
       })
     )
   }
 
   /**
-   * Shutdowns the given worker.
+   * Terminates the given worker.
    *
    * @param worker - A worker within `workerNodes`.
    */
   protected abstract destroyWorker (worker: Worker): void | Promise<void>
 
   /**
-   * Setup hook to execute code before worker node are created in the abstract constructor.
-   * Can be overridden
+   * Setup hook to execute code before worker nodes are created in the abstract constructor.
+   * Can be overridden.
    *
    * @virtual
    */
@@ -414,9 +534,15 @@ export abstract class AbstractPool<
    * Can be overridden.
    *
    * @param workerNodeKey - The worker node key.
+   * @param task - The task to execute.
    */
-  protected beforeTaskExecutionHook (workerNodeKey: number): void {
-    ++this.workerNodes[workerNodeKey].tasksUsage.running
+  protected beforeTaskExecutionHook (
+    workerNodeKey: number,
+    task: Task<Data>
+  ): void {
+    const workerUsage = this.workerNodes[workerNodeKey].usage
+    ++workerUsage.tasks.executing
+    this.updateWaitTimeWorkerUsage(workerUsage, task)
   }
 
   /**
@@ -430,45 +556,125 @@ export abstract class AbstractPool<
     worker: Worker,
     message: MessageValue<Response>
   ): void {
-    const workerNodeKey = this.getWorkerNodeKey(worker)
-    const workerTasksUsage = this.workerNodes[workerNodeKey].tasksUsage
-    --workerTasksUsage.running
-    ++workerTasksUsage.run
-    if (message.error != null) {
-      ++workerTasksUsage.error
-    }
-    if (this.workerChoiceStrategyContext.getRequiredStatistics().runTime) {
-      workerTasksUsage.runTime += message.runTime ?? 0
+    const workerUsage = this.workerNodes[this.getWorkerNodeKey(worker)].usage
+    this.updateTaskStatisticsWorkerUsage(workerUsage, message)
+    this.updateRunTimeWorkerUsage(workerUsage, message)
+    this.updateEluWorkerUsage(workerUsage, message)
+  }
+
+  private updateTaskStatisticsWorkerUsage (
+    workerUsage: WorkerUsage,
+    message: MessageValue<Response>
+  ): void {
+    const workerTaskStatistics = workerUsage.tasks
+    --workerTaskStatistics.executing
+    ++workerTaskStatistics.executed
+    if (message.taskError != null) {
+      ++workerTaskStatistics.failed
+    }
+  }
+
+  private updateRunTimeWorkerUsage (
+    workerUsage: WorkerUsage,
+    message: MessageValue<Response>
+  ): void {
+    if (
+      this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
+        .aggregate
+    ) {
+      workerUsage.runTime.aggregate += message.taskPerformance?.runTime ?? 0
+      if (
+        this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
+          .average &&
+        workerUsage.tasks.executed !== 0
+      ) {
+        workerUsage.runTime.average =
+          workerUsage.runTime.aggregate /
+          (workerUsage.tasks.executed - workerUsage.tasks.failed)
+      }
+      if (
+        this.workerChoiceStrategyContext.getTaskStatisticsRequirements().runTime
+          .median &&
+        message.taskPerformance?.runTime != null
+      ) {
+        workerUsage.runTime.history.push(message.taskPerformance.runTime)
+        workerUsage.runTime.median = median(workerUsage.runTime.history)
+      }
+    }
+  }
+
+  private updateWaitTimeWorkerUsage (
+    workerUsage: WorkerUsage,
+    task: Task<Data>
+  ): void {
+    const timestamp = performance.now()
+    const taskWaitTime = timestamp - (task.timestamp ?? timestamp)
+    if (
+      this.workerChoiceStrategyContext.getTaskStatisticsRequirements().waitTime
+        .aggregate
+    ) {
+      workerUsage.waitTime.aggregate += taskWaitTime ?? 0
       if (
-        this.workerChoiceStrategyContext.getRequiredStatistics().avgRunTime &&
-        workerTasksUsage.run !== 0
+        this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
+          .waitTime.average &&
+        workerUsage.tasks.executed !== 0
       ) {
-        workerTasksUsage.avgRunTime =
-          workerTasksUsage.runTime / workerTasksUsage.run
+        workerUsage.waitTime.average =
+          workerUsage.waitTime.aggregate /
+          (workerUsage.tasks.executed - workerUsage.tasks.failed)
       }
       if (
-        this.workerChoiceStrategyContext.getRequiredStatistics().medRunTime &&
-        message.runTime != null
+        this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
+          .waitTime.median &&
+        taskWaitTime != null
       ) {
-        workerTasksUsage.runTimeHistory.push(message.runTime)
-        workerTasksUsage.medRunTime = median(workerTasksUsage.runTimeHistory)
+        workerUsage.waitTime.history.push(taskWaitTime)
+        workerUsage.waitTime.median = median(workerUsage.waitTime.history)
       }
     }
-    if (this.workerChoiceStrategyContext.getRequiredStatistics().waitTime) {
-      workerTasksUsage.waitTime += message.waitTime ?? 0
+  }
+
+  private updateEluWorkerUsage (
+    workerUsage: WorkerUsage,
+    message: MessageValue<Response>
+  ): void {
+    if (
+      this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
+        .aggregate
+    ) {
+      if (workerUsage.elu != null && message.taskPerformance?.elu != null) {
+        workerUsage.elu.idle.aggregate += message.taskPerformance.elu.idle
+        workerUsage.elu.active.aggregate += message.taskPerformance.elu.active
+        workerUsage.elu.utilization =
+          (workerUsage.elu.utilization +
+            message.taskPerformance.elu.utilization) /
+          2
+      } else if (message.taskPerformance?.elu != null) {
+        workerUsage.elu.idle.aggregate = message.taskPerformance.elu.idle
+        workerUsage.elu.active.aggregate = message.taskPerformance.elu.active
+        workerUsage.elu.utilization = message.taskPerformance.elu.utilization
+      }
       if (
-        this.workerChoiceStrategyContext.getRequiredStatistics().avgWaitTime &&
-        workerTasksUsage.run !== 0
+        this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
+          .average &&
+        workerUsage.tasks.executed !== 0
       ) {
-        workerTasksUsage.avgWaitTime =
-          workerTasksUsage.waitTime / workerTasksUsage.run
+        const executedTasks =
+          workerUsage.tasks.executed - workerUsage.tasks.failed
+        workerUsage.elu.idle.average =
+          workerUsage.elu.idle.aggregate / executedTasks
+        workerUsage.elu.active.average =
+          workerUsage.elu.active.aggregate / executedTasks
       }
       if (
-        this.workerChoiceStrategyContext.getRequiredStatistics().medWaitTime &&
-        message.waitTime != null
+        this.workerChoiceStrategyContext.getTaskStatisticsRequirements().elu
+          .median &&
+        message.taskPerformance?.elu != null
       ) {
-        workerTasksUsage.waitTimeHistory.push(message.waitTime)
-        workerTasksUsage.medWaitTime = median(workerTasksUsage.waitTimeHistory)
+        workerUsage.elu.idle.history.push(message.taskPerformance.elu.idle)
+        workerUsage.elu.active.history.push(message.taskPerformance.elu.active)
+        workerUsage.elu.idle.median = median(workerUsage.elu.idle.history)
+        workerUsage.elu.active.median = median(workerUsage.elu.active.history)
       }
     }
   }
@@ -476,31 +682,29 @@ export abstract class AbstractPool<
   /**
    * Chooses a worker node for the next task.
    *
-   * The default worker choice strategy uses a round robin algorithm to distribute the load.
+   * The default worker choice strategy uses a round robin algorithm to distribute the tasks.
    *
    * @returns The worker node key
    */
-  protected chooseWorkerNode (): number {
-    let workerNodeKey: number
-    if (this.type === PoolType.DYNAMIC && !this.full && this.internalBusy()) {
-      const workerCreated = this.createAndSetupWorker()
-      this.registerWorkerMessageListener(workerCreated, message => {
-        const currentWorkerNodeKey = this.getWorkerNodeKey(workerCreated)
-        if (
-          isKillBehavior(KillBehaviors.HARD, message.kill) ||
-          (message.kill != null &&
-            this.workerNodes[currentWorkerNodeKey].tasksUsage.running === 0)
-        ) {
-          // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
-          this.flushTasksQueue(currentWorkerNodeKey)
-          void (this.destroyWorker(workerCreated) as Promise<void>)
-        }
-      })
-      workerNodeKey = this.getWorkerNodeKey(workerCreated)
-    } else {
-      workerNodeKey = this.workerChoiceStrategyContext.execute()
+  private chooseWorkerNode (): number {
+    if (this.shallCreateDynamicWorker()) {
+      const worker = this.createAndSetupDynamicWorker()
+      if (
+        this.workerChoiceStrategyContext.getStrategyPolicy().useDynamicWorker
+      ) {
+        return this.getWorkerNodeKey(worker)
+      }
     }
-    return workerNodeKey
+    return this.workerChoiceStrategyContext.execute()
+  }
+
+  /**
+   * Conditions for dynamic worker creation.
+   *
+   * @returns Whether to create a dynamic worker or not.
+   */
+  private shallCreateDynamicWorker (): boolean {
+    return this.type === PoolTypes.dynamic && !this.full && this.internalBusy()
   }
 
   /**
@@ -520,23 +724,30 @@ export abstract class AbstractPool<
    * @param worker - The worker which should register a listener.
    * @param listener - The message listener callback.
    */
-  protected abstract registerWorkerMessageListener<
-    Message extends Data | Response
-  >(worker: Worker, listener: (message: MessageValue<Message>) => void): void
+  private registerWorkerMessageListener<Message extends Data | Response>(
+    worker: Worker,
+    listener: (message: MessageValue<Message>) => void
+  ): void {
+    worker.on('message', listener as MessageHandler<Worker>)
+  }
 
   /**
-   * Returns a newly created worker.
+   * Creates a new worker.
+   *
+   * @returns Newly created worker.
    */
   protected abstract createWorker (): Worker
 
   /**
    * Function that can be hooked up when a worker has been newly created and moved to the pool worker nodes.
-   *
-   * Can be used to update the `maxListeners` or binding the `main-worker`\<-\>`worker` connection if not bind by default.
+   * Can be overridden.
    *
    * @param worker - The newly created worker.
    */
-  protected abstract afterWorkerSetup (worker: Worker): void
+  protected afterWorkerSetup (worker: Worker): void {
+    // Listen to worker messages.
+    this.registerWorkerMessageListener(worker, this.workerListener())
+  }
 
   /**
    * Creates a new worker and sets it up completely in the pool worker nodes.
@@ -548,6 +759,14 @@ export abstract class AbstractPool<
 
     worker.on('message', this.opts.messageHandler ?? EMPTY_FUNCTION)
     worker.on('error', this.opts.errorHandler ?? EMPTY_FUNCTION)
+    worker.on('error', error => {
+      if (this.emitter != null) {
+        this.emitter.emit(PoolEvents.error, error)
+      }
+      if (this.opts.restartWorkerOnError === true) {
+        this.createAndSetupWorker()
+      }
+    })
     worker.on('online', this.opts.onlineHandler ?? EMPTY_FUNCTION)
     worker.on('exit', this.opts.exitHandler ?? EMPTY_FUNCTION)
     worker.once('exit', () => {
@@ -556,11 +775,38 @@ export abstract class AbstractPool<
 
     this.pushWorkerNode(worker)
 
+    this.setWorkerStatistics(worker)
+
     this.afterWorkerSetup(worker)
 
     return worker
   }
 
+  /**
+   * Creates a new dynamic worker and sets it up completely in the pool worker nodes.
+   *
+   * @returns New, completely set up dynamic worker.
+   */
+  protected createAndSetupDynamicWorker (): Worker {
+    const worker = this.createAndSetupWorker()
+    this.registerWorkerMessageListener(worker, message => {
+      const workerNodeKey = this.getWorkerNodeKey(worker)
+      if (
+        isKillBehavior(KillBehaviors.HARD, message.kill) ||
+        (message.kill != null &&
+          ((this.opts.enableTasksQueue === false &&
+            this.workerNodes[workerNodeKey].usage.tasks.executing === 0) ||
+            (this.opts.enableTasksQueue === true &&
+              this.workerNodes[workerNodeKey].usage.tasks.executing === 0 &&
+              this.tasksQueueSize(workerNodeKey) === 0)))
+      ) {
+        // Kill message received from the worker: no new tasks are submitted to that worker for a while ( > maxInactiveTime)
+        void (this.destroyWorker(worker) as Promise<void>)
+      }
+    })
+    return worker
+  }
+
   /**
    * This function is the listener registered for each worker message.
    *
@@ -568,12 +814,26 @@ export abstract class AbstractPool<
    */
   protected workerListener (): (message: MessageValue<Response>) => void {
     return message => {
-      if (message.id != null) {
+      if (message.workerId != null && message.started != null) {
+        // Worker started message received
+        const worker = this.getWorkerById(message.workerId)
+        if (worker != null) {
+          this.workerNodes[this.getWorkerNodeKey(worker)].info.started =
+            message.started
+        } else {
+          throw new Error(
+            `Worker started message received from unknown worker '${message.workerId}'`
+          )
+        }
+      } else if (message.id != null) {
         // Task execution response received
         const promiseResponse = this.promiseResponseMap.get(message.id)
         if (promiseResponse != null) {
-          if (message.error != null) {
-            promiseResponse.reject(message.error)
+          if (message.taskError != null) {
+            if (this.emitter != null) {
+              this.emitter.emit(PoolEvents.taskError, message.taskError)
+            }
+            promiseResponse.reject(message.taskError.message)
           } else {
             promiseResponse.resolve(message.data as Response)
           }
@@ -589,18 +849,19 @@ export abstract class AbstractPool<
               this.dequeueTask(workerNodeKey) as Task<Data>
             )
           }
+          this.workerChoiceStrategyContext.update(workerNodeKey)
         }
       }
     }
   }
 
   private checkAndEmitEvents (): void {
-    if (this.opts.enableEvents === true) {
+    if (this.emitter != null) {
       if (this.busy) {
-        this.emitter?.emit(PoolEvents.busy)
+        this.emitter?.emit(PoolEvents.busy, this.info)
       }
-      if (this.type === PoolType.DYNAMIC && this.full) {
-        this.emitter?.emit(PoolEvents.full)
+      if (this.type === PoolTypes.dynamic && this.full) {
+        this.emitter?.emit(PoolEvents.full, this.info)
       }
     }
   }
@@ -609,13 +870,13 @@ export abstract class AbstractPool<
    * Sets the given worker node its tasks usage in the pool.
    *
    * @param workerNode - The worker node.
-   * @param tasksUsage - The worker node tasks usage.
+   * @param workerUsage - The worker usage.
    */
   private setWorkerNodeTasksUsage (
     workerNode: WorkerNode<Worker, Data>,
-    tasksUsage: TasksUsage
+    workerUsage: WorkerUsage
   ): void {
-    workerNode.tasksUsage = tasksUsage
+    workerNode.usage = workerUsage
   }
 
   /**
@@ -625,46 +886,58 @@ export abstract class AbstractPool<
    * @returns The worker nodes length.
    */
   private pushWorkerNode (worker: Worker): number {
-    return this.workerNodes.push({
+    this.workerNodes.push({
       worker,
-      tasksUsage: {
-        run: 0,
-        running: 0,
-        runTime: 0,
-        runTimeHistory: new CircularArray(),
-        avgRunTime: 0,
-        medRunTime: 0,
-        waitTime: 0,
-        waitTimeHistory: new CircularArray(),
-        avgWaitTime: 0,
-        medWaitTime: 0,
-        error: 0
-      },
+      info: { id: this.getWorkerId(worker), started: true },
+      usage: this.getWorkerUsage(),
       tasksQueue: new Queue<Task<Data>>()
     })
+    const workerNodeKey = this.getWorkerNodeKey(worker)
+    this.setWorkerNodeTasksUsage(
+      this.workerNodes[workerNodeKey],
+      this.getWorkerUsage(workerNodeKey)
+    )
+    return this.workerNodes.length
   }
 
   /**
-   * Sets the given worker in the pool worker nodes.
+   * Gets the worker id.
    *
-   * @param workerNodeKey - The worker node key.
    * @param worker - The worker.
-   * @param tasksUsage - The worker tasks usage.
-   * @param tasksQueue - The worker task queue.
+   * @returns The worker id.
    */
-  private setWorkerNode (
-    workerNodeKey: number,
-    worker: Worker,
-    tasksUsage: TasksUsage,
-    tasksQueue: Queue<Task<Data>>
-  ): void {
-    this.workerNodes[workerNodeKey] = {
-      worker,
-      tasksUsage,
-      tasksQueue
+  private getWorkerId (worker: Worker): number | undefined {
+    if (this.worker === WorkerTypes.thread) {
+      return worker.threadId
+    } else if (this.worker === WorkerTypes.cluster) {
+      return worker.id
     }
   }
 
+  // /**
+  //  * Sets the given worker in the pool worker nodes.
+  //  *
+  //  * @param workerNodeKey - The worker node key.
+  //  * @param worker - The worker.
+  //  * @param workerInfo - The worker info.
+  //  * @param workerUsage - The worker usage.
+  //  * @param tasksQueue - The worker task queue.
+  //  */
+  // private setWorkerNode (
+  //   workerNodeKey: number,
+  //   worker: Worker,
+  //   workerInfo: WorkerInfo,
+  //   workerUsage: WorkerUsage,
+  //   tasksQueue: Queue<Task<Data>>
+  // ): void {
+  //   this.workerNodes[workerNodeKey] = {
+  //     worker,
+  //     info: workerInfo,
+  //     usage: workerUsage,
+  //     tasksQueue
+  //   }
+  // }
+
   /**
    * Removes the given worker from the pool worker nodes.
    *
@@ -672,12 +945,14 @@ export abstract class AbstractPool<
    */
   private removeWorkerNode (worker: Worker): void {
     const workerNodeKey = this.getWorkerNodeKey(worker)
-    this.workerNodes.splice(workerNodeKey, 1)
-    this.workerChoiceStrategyContext.remove(workerNodeKey)
+    if (workerNodeKey !== -1) {
+      this.workerNodes.splice(workerNodeKey, 1)
+      this.workerChoiceStrategyContext.remove(workerNodeKey)
+    }
   }
 
   private executeTask (workerNodeKey: number, task: Task<Data>): void {
-    this.beforeTaskExecutionHook(workerNodeKey)
+    this.beforeTaskExecutionHook(workerNodeKey, task)
     this.sendToWorker(this.workerNodes[workerNodeKey].worker, task)
   }
 
@@ -693,6 +968,10 @@ export abstract class AbstractPool<
     return this.workerNodes[workerNodeKey].tasksQueue.size
   }
 
+  private tasksMaxQueueSize (workerNodeKey: number): number {
+    return this.workerNodes[workerNodeKey].tasksQueue.maxSize
+  }
+
   private flushTasksQueue (workerNodeKey: number): void {
     if (this.tasksQueueSize(workerNodeKey) > 0) {
       for (let i = 0; i < this.tasksQueueSize(workerNodeKey); i++) {
@@ -702,6 +981,7 @@ export abstract class AbstractPool<
         )
       }
     }
+    this.workerNodes[workerNodeKey].tasksQueue.clear()
   }
 
   private flushTasksQueues (): void {
@@ -709,4 +989,65 @@ export abstract class AbstractPool<
       this.flushTasksQueue(workerNodeKey)
     }
   }
+
+  private setWorkerStatistics (worker: Worker): void {
+    this.sendToWorker(worker, {
+      statistics: {
+        runTime:
+          this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
+            .runTime.aggregate,
+        elu: this.workerChoiceStrategyContext.getTaskStatisticsRequirements()
+          .elu.aggregate
+      }
+    })
+  }
+
+  private getWorkerUsage (workerNodeKey?: number): WorkerUsage {
+    const getTasksQueueSize = (workerNodeKey?: number): number => {
+      return workerNodeKey != null ? this.tasksQueueSize(workerNodeKey) : 0
+    }
+    const getTasksMaxQueueSize = (workerNodeKey?: number): number => {
+      return workerNodeKey != null ? this.tasksMaxQueueSize(workerNodeKey) : 0
+    }
+    return {
+      tasks: {
+        executed: 0,
+        executing: 0,
+        get queued (): number {
+          return getTasksQueueSize(workerNodeKey)
+        },
+        get maxQueued (): number {
+          return getTasksMaxQueueSize(workerNodeKey)
+        },
+        failed: 0
+      },
+      runTime: {
+        aggregate: 0,
+        average: 0,
+        median: 0,
+        history: new CircularArray()
+      },
+      waitTime: {
+        aggregate: 0,
+        average: 0,
+        median: 0,
+        history: new CircularArray()
+      },
+      elu: {
+        idle: {
+          aggregate: 0,
+          average: 0,
+          median: 0,
+          history: new CircularArray()
+        },
+        active: {
+          aggregate: 0,
+          average: 0,
+          median: 0,
+          history: new CircularArray()
+        },
+        utilization: 0
+      }
+    }
+  }
 }