refactor: cleanup type definition
[poolifier.git] / src / pools / worker-node.ts
index 812d14448f6fc4c7b221a74a23958920627f94ac..f3ec3be3d83f4541da3713cbd46406d19be41ac0 100644 (file)
@@ -1,8 +1,13 @@
 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 {
+  DEFAULT_TASK_NAME,
+  EMPTY_FUNCTION,
+  exponentialDelay,
+  sleep
+} from '../utils'
+import { Deque } from '../deque'
 import {
   type IWorker,
   type IWorkerNode,
@@ -12,6 +17,9 @@ import {
   type WorkerUsage
 } from './worker'
 
+type EmptyQueueCallback = (workerId: number) => void
+type BackPressureCallback = EmptyQueueCallback
+
 /**
  * Worker node.
  *
@@ -25,30 +33,59 @@ implements IWorkerNode<Worker, Data> {
   /** @inheritdoc */
   public readonly info: WorkerInfo
   /** @inheritdoc */
+  public usage: WorkerUsage
+  /** @inheritdoc */
   public messageChannel?: MessageChannel
   /** @inheritdoc */
-  public usage: WorkerUsage
-  private readonly tasksUsage: Map<string, WorkerUsage>
-  private readonly tasksQueue: Queue<Task<Data>>
-  private readonly tasksQueueBackPressureSize: number
+  public tasksQueueBackPressureSize: number
+  /** @inheritdoc */
+  public onBackPressure?: BackPressureCallback
+  /** @inheritdoc */
+  public onEmptyQueue?: EmptyQueueCallback
+  private readonly tasksQueue: Deque<Task<Data>>
+  private onEmptyQueueCount: number
+  private readonly taskFunctionsUsage: Map<string, WorkerUsage>
 
   /**
    * Constructs a new worker node.
    *
    * @param worker - The worker.
    * @param workerType - The worker type.
-   * @param poolMaxSize - The pool maximum size.
+   * @param tasksQueueBackPressureSize - The tasks queue back pressure size.
    */
-  constructor (worker: Worker, workerType: WorkerType, poolMaxSize: number) {
+  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'
+      )
+    }
     this.worker = worker
     this.info = this.initWorkerInfo(worker, workerType)
+    this.usage = this.initWorkerUsage()
     if (workerType === WorkerTypes.thread) {
       this.messageChannel = new MessageChannel()
     }
-    this.usage = this.initWorkerUsage()
-    this.tasksUsage = new Map<string, WorkerUsage>()
-    this.tasksQueue = new Queue<Task<Data>>()
-    this.tasksQueueBackPressureSize = Math.pow(poolMaxSize, 2)
+    this.tasksQueueBackPressureSize = tasksQueueBackPressureSize
+    this.tasksQueue = new Deque<Task<Data>>()
+    this.onEmptyQueueCount = 0
+    this.taskFunctionsUsage = new Map<string, WorkerUsage>()
   }
 
   /** @inheritdoc */
@@ -56,23 +93,40 @@ implements IWorkerNode<Worker, Data> {
     return this.tasksQueue.size
   }
 
-  /**
-   * Tasks queue maximum size.
-   *
-   * @returns The tasks queue maximum size.
-   */
-  private tasksQueueMaxSize (): number {
-    return this.tasksQueue.maxSize
+  /** @inheritdoc */
+  public enqueueTask (task: Task<Data>): number {
+    const tasksQueueSize = this.tasksQueue.push(task)
+    if (this.onBackPressure != null && this.hasBackPressure()) {
+      this.onBackPressure(this.info.id as number)
+    }
+    return tasksQueueSize
   }
 
   /** @inheritdoc */
-  public enqueueTask (task: Task<Data>): number {
-    return this.tasksQueue.enqueue(task)
+  public unshiftTask (task: Task<Data>): number {
+    const tasksQueueSize = this.tasksQueue.unshift(task)
+    if (this.onBackPressure != null && this.hasBackPressure()) {
+      this.onBackPressure(this.info.id as number)
+    }
+    return tasksQueueSize
   }
 
   /** @inheritdoc */
   public dequeueTask (): Task<Data> | undefined {
-    return this.tasksQueue.dequeue()
+    const task = this.tasksQueue.shift()
+    if (this.onEmptyQueue != null && this.tasksQueue.size === 0) {
+      this.startOnEmptyQueue().catch(EMPTY_FUNCTION)
+    }
+    return task
+  }
+
+  /** @inheritdoc */
+  public popTask (): Task<Data> | undefined {
+    const task = this.tasksQueue.pop()
+    if (this.onEmptyQueue != null && this.tasksQueue.size === 0) {
+      this.startOnEmptyQueue().catch(EMPTY_FUNCTION)
+    }
+    return task
   }
 
   /** @inheritdoc */
@@ -82,13 +136,13 @@ implements IWorkerNode<Worker, Data> {
 
   /** @inheritdoc */
   public hasBackPressure (): boolean {
-    return this.tasksQueueSize() >= this.tasksQueueBackPressureSize
+    return this.tasksQueue.size >= this.tasksQueueBackPressureSize
   }
 
   /** @inheritdoc */
   public resetUsage (): void {
     this.usage = this.initWorkerUsage()
-    this.tasksUsage.clear()
+    this.taskFunctionsUsage.clear()
   }
 
   /** @inheritdoc */
@@ -103,23 +157,41 @@ implements IWorkerNode<Worker, Data> {
   }
 
   /** @inheritdoc */
-  public getTaskWorkerUsage (name: string): WorkerUsage | undefined {
+  public getTaskFunctionWorkerUsage (name: string): WorkerUsage | undefined {
     if (!Array.isArray(this.info.taskFunctions)) {
       throw new Error(
-        `Cannot get task worker usage for task function name '${name}' when task function names list is not yet defined`
+        `Cannot get task function worker usage for task function name '${name}' when task function names list is not yet defined`
       )
     }
     if (
-      name === DEFAULT_TASK_NAME &&
       Array.isArray(this.info.taskFunctions) &&
-      this.info.taskFunctions.length > 1
+      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.tasksUsage.has(name)) {
-      this.tasksUsage.set(name, this.initTaskWorkerUsage(name))
+    if (!this.taskFunctionsUsage.has(name)) {
+      this.taskFunctionsUsage.set(name, this.initTaskFunctionWorkerUsage(name))
+    }
+    return this.taskFunctionsUsage.get(name)
+  }
+
+  private async startOnEmptyQueue (): Promise<void> {
+    if (
+      this.onEmptyQueueCount > 0 &&
+      (this.usage.tasks.executing > 0 || this.tasksQueue.size > 0)
+    ) {
+      this.onEmptyQueueCount = 0
+      return
     }
-    return this.tasksUsage.get(name)
+    (this.onEmptyQueue as EmptyQueueCallback)(this.info.id as number)
+    ++this.onEmptyQueueCount
+    await sleep(exponentialDelay(this.onEmptyQueueCount))
+    await this.startOnEmptyQueue()
   }
 
   private initWorkerInfo (worker: Worker, workerType: WorkerType): WorkerInfo {
@@ -133,10 +205,10 @@ implements IWorkerNode<Worker, Data> {
 
   private initWorkerUsage (): WorkerUsage {
     const getTasksQueueSize = (): number => {
-      return this.tasksQueueSize()
+      return this.tasksQueue.size
     }
     const getTasksQueueMaxSize = (): number => {
-      return this.tasksQueueMaxSize()
+      return this.tasksQueue.maxSize
     }
     return {
       tasks: {
@@ -148,6 +220,7 @@ implements IWorkerNode<Worker, Data> {
         get maxQueued (): number {
           return getTasksQueueMaxSize()
         },
+        stolen: 0,
         failed: 0
       },
       runTime: {
@@ -167,23 +240,28 @@ 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()
         },
+        stolen: 0,
         failed: 0
       },
       runTime: {