chore: v2.6.31
[poolifier.git] / src / pools / worker-node.ts
index fcc091378565a4b78c7f9085619c9017169474d3..82e276886c08f56bc4051bc537df88b222600af0 100644 (file)
@@ -2,6 +2,7 @@ import { MessageChannel } from 'node:worker_threads'
 import { CircularArray } from '../circular-array'
 import { Queue } from '../queue'
 import type { Task } from '../utility-types'
+import { DEFAULT_TASK_NAME } from '../utils'
 import {
   type IWorker,
   type IWorkerNode,
@@ -19,24 +20,53 @@ import {
  */
 export class WorkerNode<Worker extends IWorker, Data = unknown>
 implements IWorkerNode<Worker, Data> {
+  /** @inheritdoc */
   public readonly worker: Worker
+  /** @inheritdoc */
   public readonly info: WorkerInfo
+  /** @inheritdoc */
+  public messageChannel?: MessageChannel
+  /** @inheritdoc */
   public usage: WorkerUsage
-  private readonly tasksUsage: Map<string, WorkerUsage>
+  private readonly taskFunctionsUsage: Map<string, WorkerUsage>
   private readonly tasksQueue: Queue<Task<Data>>
+  private readonly tasksQueueBackPressureSize: number
 
   /**
    * Constructs a new worker node.
    *
    * @param worker - The worker.
    * @param workerType - The worker type.
+   * @param poolMaxSize - The pool maximum size.
    */
-  constructor (worker: Worker, workerType: WorkerType) {
+  constructor (worker: Worker, workerType: WorkerType, poolMaxSize: number) {
+    if (worker == null) {
+      throw new TypeError('Cannot construct a worker node without a worker')
+    }
+    if (workerType == null) {
+      throw new TypeError(
+        'Cannot construct a worker node without a worker type'
+      )
+    }
+    if (poolMaxSize == null) {
+      throw new TypeError(
+        'Cannot construct a worker node without a pool maximum size'
+      )
+    }
+    if (!Number.isSafeInteger(poolMaxSize)) {
+      throw new TypeError(
+        'Cannot construct a worker node with a pool maximum size that is not an integer'
+      )
+    }
     this.worker = worker
     this.info = this.initWorkerInfo(worker, workerType)
+    if (workerType === WorkerTypes.thread) {
+      this.messageChannel = new MessageChannel()
+    }
     this.usage = this.initWorkerUsage()
-    this.tasksUsage = new Map<string, WorkerUsage>()
+    this.taskFunctionsUsage = new Map<string, WorkerUsage>()
     this.tasksQueue = new Queue<Task<Data>>()
+    this.tasksQueueBackPressureSize = Math.pow(poolMaxSize, 2)
   }
 
   /** @inheritdoc */
@@ -68,27 +98,50 @@ implements IWorkerNode<Worker, Data> {
     this.tasksQueue.clear()
   }
 
+  /** @inheritdoc */
+  public hasBackPressure (): boolean {
+    return this.tasksQueue.size >= this.tasksQueueBackPressureSize
+  }
+
   /** @inheritdoc */
   public resetUsage (): void {
     this.usage = this.initWorkerUsage()
-    this.tasksUsage.clear()
+    this.taskFunctionsUsage.clear()
   }
 
   /** @inheritdoc */
   public closeChannel (): void {
-    if (this.info.messageChannel != null) {
-      this.info.messageChannel?.port1.close()
-      this.info.messageChannel?.port2.close()
-      delete this.info.messageChannel
+    if (this.messageChannel != null) {
+      this.messageChannel?.port1.unref()
+      this.messageChannel?.port2.unref()
+      this.messageChannel?.port1.close()
+      this.messageChannel?.port2.close()
+      delete this.messageChannel
     }
   }
 
   /** @inheritdoc */
-  public getTaskWorkerUsage (name: string): WorkerUsage | undefined {
-    if (!this.tasksUsage.has(name)) {
-      this.tasksUsage.set(name, this.initTaskWorkerUsage(name))
+  public getTaskFunctionWorkerUsage (name: string): WorkerUsage | undefined {
+    if (!Array.isArray(this.info.taskFunctions)) {
+      throw new Error(
+        `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
+      )
+    }
+    if (
+      Array.isArray(this.info.taskFunctions) &&
+      this.info.taskFunctions.length < 3
+    ) {
+      throw new Error(
+        `Cannot get task function worker usage for task function name '${name}' when task function names list has less than 3 elements`
+      )
+    }
+    if (name === DEFAULT_TASK_NAME) {
+      name = this.info.taskFunctions[1]
+    }
+    if (!this.taskFunctionsUsage.has(name)) {
+      this.taskFunctionsUsage.set(name, this.initTaskFunctionWorkerUsage(name))
     }
-    return this.tasksUsage.get(name)
+    return this.taskFunctionsUsage.get(name)
   }
 
   private initWorkerInfo (worker: Worker, workerType: WorkerType): WorkerInfo {
@@ -96,10 +149,7 @@ implements IWorkerNode<Worker, Data> {
       id: this.getWorkerId(worker, workerType),
       type: workerType,
       dynamic: false,
-      ready: false,
-      ...(workerType === WorkerTypes.thread && {
-        messageChannel: new MessageChannel()
-      })
+      ready: false
     }
   }
 
@@ -139,22 +189,26 @@ implements IWorkerNode<Worker, Data> {
     }
   }
 
-  private initTaskWorkerUsage (name: string): WorkerUsage {
-    const getTaskQueueSize = (): number => {
-      let taskQueueSize = 0
+  private initTaskFunctionWorkerUsage (name: string): WorkerUsage {
+    const getTaskFunctionQueueSize = (): number => {
+      let taskFunctionQueueSize = 0
       for (const task of this.tasksQueue) {
-        if (task.name === name) {
-          ++taskQueueSize
+        if (
+          (task.name === DEFAULT_TASK_NAME &&
+            name === (this.info.taskFunctions as string[])[1]) ||
+          (task.name !== DEFAULT_TASK_NAME && name === task.name)
+        ) {
+          ++taskFunctionQueueSize
         }
       }
-      return taskQueueSize
+      return taskFunctionQueueSize
     }
     return {
       tasks: {
         executed: 0,
         executing: 0,
         get queued (): number {
-          return getTaskQueueSize()
+          return getTaskFunctionQueueSize()
         },
         failed: 0
       },