Merge branch 'master' into feature/task-functions
[poolifier.git] / src / pools / worker-node.ts
index 03fc0df192f3ce6689306ba3f6eb38c12dabed40..ed6677027f810474aa9aa01e768fd5f483250679 100644 (file)
@@ -5,15 +5,17 @@ import {
   DEFAULT_TASK_NAME,
   EMPTY_FUNCTION,
   exponentialDelay,
+  getWorkerId,
+  getWorkerType,
   sleep
 } from '../utils'
 import { Deque } from '../deque'
 import {
-  type BackPressureCallback,
-  type EmptyQueueCallback,
   type IWorker,
   type IWorkerNode,
+  type StrategyData,
   type WorkerInfo,
+  type WorkerNodeEventCallback,
   type WorkerType,
   WorkerTypes,
   type WorkerUsage
@@ -34,14 +36,17 @@ implements IWorkerNode<Worker, Data> {
   /** @inheritdoc */
   public usage: WorkerUsage
   /** @inheritdoc */
+  public strategyData?: StrategyData
+  /** @inheritdoc */
   public messageChannel?: MessageChannel
   /** @inheritdoc */
   public tasksQueueBackPressureSize: number
   /** @inheritdoc */
-  public onBackPressure?: BackPressureCallback
+  public onBackPressure?: WorkerNodeEventCallback
   /** @inheritdoc */
-  public onEmptyQueue?: EmptyQueueCallback
+  public onEmptyQueue?: WorkerNodeEventCallback
   private readonly tasksQueue: Deque<Task<Data>>
+  private onBackPressureStarted: boolean
   private onEmptyQueueCount: number
   private readonly taskFunctionsUsage: Map<string, WorkerUsage>
 
@@ -49,40 +54,19 @@ implements IWorkerNode<Worker, Data> {
    * Constructs a new worker node.
    *
    * @param worker - The worker.
-   * @param workerType - The worker type.
    * @param tasksQueueBackPressureSize - The tasks queue back pressure size.
    */
-  constructor (
-    worker: Worker,
-    workerType: WorkerType,
-    tasksQueueBackPressureSize: 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 (tasksQueueBackPressureSize == null) {
-      throw new TypeError(
-        'Cannot construct a worker node without a tasks queue back pressure size'
-      )
-    }
-    if (!Number.isSafeInteger(tasksQueueBackPressureSize)) {
-      throw new TypeError(
-        'Cannot construct a worker node with a tasks queue back pressure size that is not an integer'
-      )
-    }
+  constructor (worker: Worker, tasksQueueBackPressureSize: number) {
+    this.checkWorkerNodeArguments(worker, tasksQueueBackPressureSize)
     this.worker = worker
-    this.info = this.initWorkerInfo(worker, workerType)
+    this.info = this.initWorkerInfo(worker)
     this.usage = this.initWorkerUsage()
-    if (workerType === WorkerTypes.thread) {
+    if (this.info.type === WorkerTypes.thread) {
       this.messageChannel = new MessageChannel()
     }
     this.tasksQueueBackPressureSize = tasksQueueBackPressureSize
     this.tasksQueue = new Deque<Task<Data>>()
+    this.onBackPressureStarted = false
     this.onEmptyQueueCount = 0
     this.taskFunctionsUsage = new Map<string, WorkerUsage>()
   }
@@ -95,8 +79,14 @@ implements IWorkerNode<Worker, Data> {
   /** @inheritdoc */
   public enqueueTask (task: Task<Data>): number {
     const tasksQueueSize = this.tasksQueue.push(task)
-    if (this.onBackPressure != null && this.hasBackPressure()) {
+    if (
+      this.onBackPressure != null &&
+      this.hasBackPressure() &&
+      !this.onBackPressureStarted
+    ) {
+      this.onBackPressureStarted = true
       this.onBackPressure(this.info.id as number)
+      this.onBackPressureStarted = false
     }
     return tasksQueueSize
   }
@@ -104,8 +94,14 @@ implements IWorkerNode<Worker, Data> {
   /** @inheritdoc */
   public unshiftTask (task: Task<Data>): number {
     const tasksQueueSize = this.tasksQueue.unshift(task)
-    if (this.onBackPressure != null && this.hasBackPressure()) {
+    if (
+      this.onBackPressure != null &&
+      this.hasBackPressure() &&
+      !this.onBackPressureStarted
+    ) {
+      this.onBackPressureStarted = true
       this.onBackPressure(this.info.id as number)
+      this.onBackPressureStarted = false
     }
     return tasksQueueSize
   }
@@ -113,7 +109,11 @@ implements IWorkerNode<Worker, Data> {
   /** @inheritdoc */
   public dequeueTask (): Task<Data> | undefined {
     const task = this.tasksQueue.shift()
-    if (this.onEmptyQueue != null && this.tasksQueue.size === 0) {
+    if (
+      this.onEmptyQueue != null &&
+      this.tasksQueue.size === 0 &&
+      this.onEmptyQueueCount === 0
+    ) {
       this.startOnEmptyQueue().catch(EMPTY_FUNCTION)
     }
     return task
@@ -122,7 +122,11 @@ implements IWorkerNode<Worker, Data> {
   /** @inheritdoc */
   public popTask (): Task<Data> | undefined {
     const task = this.tasksQueue.pop()
-    if (this.onEmptyQueue != null && this.tasksQueue.size === 0) {
+    if (
+      this.onEmptyQueue != null &&
+      this.tasksQueue.size === 0 &&
+      this.onEmptyQueueCount === 0
+    ) {
       this.startOnEmptyQueue().catch(EMPTY_FUNCTION)
     }
     return task
@@ -157,21 +161,21 @@ implements IWorkerNode<Worker, Data> {
 
   /** @inheritdoc */
   public getTaskFunctionWorkerUsage (name: string): WorkerUsage | undefined {
-    if (!Array.isArray(this.info.taskFunctions)) {
+    if (!Array.isArray(this.info.taskFunctionNames)) {
       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
+      Array.isArray(this.info.taskFunctionNames) &&
+      this.info.taskFunctionNames.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]
+      name = this.info.taskFunctionNames[1]
     }
     if (!this.taskFunctionsUsage.has(name)) {
       this.taskFunctionsUsage.set(name, this.initTaskFunctionWorkerUsage(name))
@@ -187,16 +191,16 @@ implements IWorkerNode<Worker, Data> {
       this.onEmptyQueueCount = 0
       return
     }
-    (this.onEmptyQueue as EmptyQueueCallback)(this.info.id as number)
     ++this.onEmptyQueueCount
+    this.onEmptyQueue?.(this.info.id as number)
     await sleep(exponentialDelay(this.onEmptyQueueCount))
     await this.startOnEmptyQueue()
   }
 
-  private initWorkerInfo (worker: Worker, workerType: WorkerType): WorkerInfo {
+  private initWorkerInfo (worker: Worker): WorkerInfo {
     return {
-      id: this.getWorkerId(worker, workerType),
-      type: workerType,
+      id: getWorkerId(worker),
+      type: getWorkerType(worker) as WorkerType,
       dynamic: false,
       ready: false
     }
@@ -245,7 +249,7 @@ implements IWorkerNode<Worker, Data> {
       for (const task of this.tasksQueue) {
         if (
           (task.name === DEFAULT_TASK_NAME &&
-            name === (this.info.taskFunctions as string[])[1]) ||
+            name === (this.info.taskFunctionNames as string[])[1]) ||
           (task.name !== DEFAULT_TASK_NAME && name === task.name)
         ) {
           ++taskFunctionQueueSize
@@ -280,21 +284,27 @@ implements IWorkerNode<Worker, Data> {
     }
   }
 
-  /**
-   * Gets the worker id.
-   *
-   * @param worker - The worker.
-   * @param workerType - The worker type.
-   * @returns The worker id.
-   */
-  private getWorkerId (
+  private checkWorkerNodeArguments (
     worker: Worker,
-    workerType: WorkerType
-  ): number | undefined {
-    if (workerType === WorkerTypes.thread) {
-      return worker.threadId
-    } else if (workerType === WorkerTypes.cluster) {
-      return worker.id
+    tasksQueueBackPressureSize: number
+  ): void {
+    if (worker == null) {
+      throw new TypeError('Cannot construct a worker node without a worker')
+    }
+    if (tasksQueueBackPressureSize == null) {
+      throw new TypeError(
+        'Cannot construct a worker node without a tasks queue back pressure size'
+      )
+    }
+    if (!Number.isSafeInteger(tasksQueueBackPressureSize)) {
+      throw new TypeError(
+        'Cannot construct a worker node with a tasks queue back pressure size that is not an integer'
+      )
+    }
+    if (tasksQueueBackPressureSize <= 0) {
+      throw new RangeError(
+        'Cannot construct a worker node with a tasks queue back pressure size that is not a positive integer'
+      )
     }
   }
 }