fix: ensure worker node cannot be instantiaed without proper arguments
[poolifier.git] / src / pools / worker-node.ts
index c2acd65b26290f576a1deb64630ceca5cb580466..09e4a7b5cd8831360365a7a88e338e3b921eaf91 100644 (file)
@@ -1,9 +1,11 @@
+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,
-  type Task,
   type WorkerInfo,
   type WorkerType,
   WorkerTypes,
@@ -18,23 +20,51 @@ 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 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.
-   * @internal
+   * @param poolMaxSize - The pool maximum size.
    */
-  constructor (worker: Worker, workerType: WorkerType) {
+  constructor (worker: Worker, workerType: WorkerType, poolMaxSize: number) {
+    if (worker == null) {
+      throw new Error('Cannot construct a worker node without a worker')
+    }
+    if (workerType == null) {
+      throw new Error('Cannot construct a worker node without a worker type')
+    }
+    if (poolMaxSize == null) {
+      throw new Error(
+        'Cannot construct a worker node without a pool maximum size'
+      )
+    }
+    if (isNaN(poolMaxSize)) {
+      throw new Error(
+        'Cannot construct a worker node with a NaN pool maximum size'
+      )
+    }
     this.worker = worker
     this.info = this.initWorkerInfo(worker, workerType)
+    if (workerType === WorkerTypes.thread) {
+      this.messageChannel = new MessageChannel()
+    }
     this.usage = this.initWorkerUsage()
+    this.taskFunctionsUsage = new Map<string, WorkerUsage>()
     this.tasksQueue = new Queue<Task<Data>>()
+    this.tasksQueueBackPressureSize = Math.pow(poolMaxSize, 2)
   }
 
   /** @inheritdoc */
@@ -43,7 +73,7 @@ implements IWorkerNode<Worker, Data> {
   }
 
   /**
-   * Worker node tasks queue maximum size.
+   * Tasks queue maximum size.
    *
    * @returns The tasks queue maximum size.
    */
@@ -66,8 +96,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.taskFunctionsUsage.clear()
+  }
+
+  /** @inheritdoc */
+  public closeChannel (): void {
+    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 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.taskFunctionsUsage.get(name)
   }
 
   private initWorkerInfo (worker: Worker, workerType: WorkerType): WorkerInfo {
@@ -75,7 +147,7 @@ implements IWorkerNode<Worker, Data> {
       id: this.getWorkerId(worker, workerType),
       type: workerType,
       dynamic: false,
-      started: true
+      ready: false
     }
   }
 
@@ -115,6 +187,42 @@ implements IWorkerNode<Worker, Data> {
     }
   }
 
+  private initTaskFunctionWorkerUsage (name: string): WorkerUsage {
+    const getTaskQueueSize = (): number => {
+      let taskQueueSize = 0
+      for (const task of this.tasksQueue) {
+        if (task.name === name) {
+          ++taskQueueSize
+        }
+      }
+      return taskQueueSize
+    }
+    return {
+      tasks: {
+        executed: 0,
+        executing: 0,
+        get queued (): number {
+          return getTaskQueueSize()
+        },
+        failed: 0
+      },
+      runTime: {
+        history: new CircularArray()
+      },
+      waitTime: {
+        history: new CircularArray()
+      },
+      elu: {
+        idle: {
+          history: new CircularArray()
+        },
+        active: {
+          history: new CircularArray()
+        }
+      }
+    }
+  }
+
   /**
    * Gets the worker id.
    *