chore: v4.0.0
[poolifier.git] / src / pools / worker-node.ts
index 59c4de7a388e81434c373f1835b144c1b3c88f57..64400d9eb1426be9ffe546b45855b606bfec05c0 100644 (file)
@@ -1,19 +1,27 @@
-import { MessageChannel } from 'node:worker_threads'
 import { EventEmitter } from 'node:events'
-import { CircularArray } from '../circular-array'
-import type { Task } from '../utility-types'
-import { DEFAULT_TASK_NAME, getWorkerId, getWorkerType } from '../utils'
-import { Deque } from '../deque'
+import { MessageChannel } from 'node:worker_threads'
+
+import { CircularArray } from '../circular-array.js'
+import { PriorityQueue } from '../priority-queue.js'
+import type { Task } from '../utility-types.js'
+import { DEFAULT_TASK_NAME } from '../utils.js'
 import {
+  checkWorkerNodeArguments,
+  createWorker,
+  getWorkerId,
+  getWorkerType
+} from './utils.js'
+import {
+  type EventHandler,
   type IWorker,
   type IWorkerNode,
   type StrategyData,
   type WorkerInfo,
+  type WorkerNodeOptions,
   type WorkerType,
   WorkerTypes,
   type WorkerUsage
-} from './worker'
-import { checkWorkerNodeArguments } from './utils'
+} from './worker.js'
 
 /**
  * Worker node.
@@ -36,27 +44,32 @@ export class WorkerNode<Worker extends IWorker, Data = unknown>
   public messageChannel?: MessageChannel
   /** @inheritdoc */
   public tasksQueueBackPressureSize: number
-  private readonly tasksQueue: Deque<Task<Data>>
+  private readonly tasksQueue: PriorityQueue<Task<Data>>
   private onBackPressureStarted: boolean
   private readonly taskFunctionsUsage: Map<string, WorkerUsage>
 
   /**
    * Constructs a new worker node.
    *
-   * @param worker - The worker.
-   * @param tasksQueueBackPressureSize - The tasks queue back pressure size.
+   * @param type - The worker type.
+   * @param filePath - Path to the worker file.
+   * @param opts - The worker node options.
    */
-  constructor (worker: Worker, tasksQueueBackPressureSize: number) {
+  constructor (type: WorkerType, filePath: string, opts: WorkerNodeOptions) {
     super()
-    checkWorkerNodeArguments<Worker>(worker, tasksQueueBackPressureSize)
-    this.worker = worker
-    this.info = this.initWorkerInfo(worker)
+    checkWorkerNodeArguments(type, filePath, opts)
+    this.worker = createWorker<Worker>(type, filePath, {
+      env: opts.env,
+      workerOptions: opts.workerOptions
+    })
+    this.info = this.initWorkerInfo(this.worker)
     this.usage = this.initWorkerUsage()
     if (this.info.type === WorkerTypes.thread) {
       this.messageChannel = new MessageChannel()
     }
-    this.tasksQueueBackPressureSize = tasksQueueBackPressureSize
-    this.tasksQueue = new Deque<Task<Data>>()
+    // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+    this.tasksQueueBackPressureSize = opts.tasksQueueBackPressureSize!
+    this.tasksQueue = new PriorityQueue<Task<Data>>(opts.tasksQueueBucketSize)
     this.onBackPressureStarted = false
     this.taskFunctionsUsage = new Map<string, WorkerUsage>()
   }
@@ -68,34 +81,18 @@ export class WorkerNode<Worker extends IWorker, Data = unknown>
 
   /** @inheritdoc */
   public enqueueTask (task: Task<Data>): number {
-    const tasksQueueSize = this.tasksQueue.push(task)
-    if (this.hasBackPressure() && !this.onBackPressureStarted) {
-      this.onBackPressureStarted = true
-      this.emit('backPressure', { workerId: this.info.id as number })
-      this.onBackPressureStarted = false
-    }
-    return tasksQueueSize
-  }
-
-  /** @inheritdoc */
-  public unshiftTask (task: Task<Data>): number {
-    const tasksQueueSize = this.tasksQueue.unshift(task)
+    const tasksQueueSize = this.tasksQueue.enqueue(task, task.priority)
     if (this.hasBackPressure() && !this.onBackPressureStarted) {
       this.onBackPressureStarted = true
-      this.emit('backPressure', { workerId: this.info.id as number })
+      this.emit('backPressure', { workerId: this.info.id })
       this.onBackPressureStarted = false
     }
     return tasksQueueSize
   }
 
   /** @inheritdoc */
-  public dequeueTask (): Task<Data> | undefined {
-    return this.tasksQueue.shift()
-  }
-
-  /** @inheritdoc */
-  public popTask (): Task<Data> | undefined {
-    return this.tasksQueue.pop()
+  public dequeueTask (bucket?: number): Task<Data> | undefined {
+    return this.tasksQueue.dequeue(bucket)
   }
 
   /** @inheritdoc */
@@ -109,39 +106,62 @@ export class WorkerNode<Worker extends IWorker, Data = unknown>
   }
 
   /** @inheritdoc */
-  public resetUsage (): void {
-    this.usage = this.initWorkerUsage()
-    this.taskFunctionsUsage.clear()
+  public async terminate (): Promise<void> {
+    const waitWorkerExit = new Promise<void>(resolve => {
+      this.registerOnceWorkerEventHandler('exit', () => {
+        resolve()
+      })
+    })
+    this.closeMessageChannel()
+    this.removeAllListeners()
+    switch (this.info.type) {
+      case WorkerTypes.thread:
+        this.worker.unref?.()
+        await this.worker.terminate?.()
+        break
+      case WorkerTypes.cluster:
+        this.registerOnceWorkerEventHandler('disconnect', () => {
+          this.worker.kill?.()
+        })
+        this.worker.disconnect?.()
+        break
+    }
+    await waitWorkerExit
   }
 
   /** @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
-    }
+  public registerWorkerEventHandler (
+    event: string,
+    handler: EventHandler<Worker>
+  ): void {
+    this.worker.on(event, handler)
+  }
+
+  /** @inheritdoc */
+  public registerOnceWorkerEventHandler (
+    event: string,
+    handler: EventHandler<Worker>
+  ): void {
+    this.worker.once(event, handler)
   }
 
   /** @inheritdoc */
   public getTaskFunctionWorkerUsage (name: string): WorkerUsage | undefined {
-    if (!Array.isArray(this.info.taskFunctionNames)) {
+    if (!Array.isArray(this.info.taskFunctionsProperties)) {
       throw new Error(
-        `Cannot get task function 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 properties list is not yet defined`
       )
     }
     if (
-      Array.isArray(this.info.taskFunctionNames) &&
-      this.info.taskFunctionNames.length < 3
+      Array.isArray(this.info.taskFunctionsProperties) &&
+      this.info.taskFunctionsProperties.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`
+        `Cannot get task function worker usage for task function name '${name}' when task function properties list has less than 3 elements`
       )
     }
     if (name === DEFAULT_TASK_NAME) {
-      name = this.info.taskFunctionNames[1]
+      name = this.info.taskFunctionsProperties[1].name
     }
     if (!this.taskFunctionsUsage.has(name)) {
       this.taskFunctionsUsage.set(name, this.initTaskFunctionWorkerUsage(name))
@@ -154,12 +174,24 @@ export class WorkerNode<Worker extends IWorker, Data = unknown>
     return this.taskFunctionsUsage.delete(name)
   }
 
+  private closeMessageChannel (): void {
+    if (this.messageChannel != null) {
+      this.messageChannel.port1.unref()
+      this.messageChannel.port2.unref()
+      this.messageChannel.port1.close()
+      this.messageChannel.port2.close()
+      delete this.messageChannel
+    }
+  }
+
   private initWorkerInfo (worker: Worker): WorkerInfo {
     return {
       id: getWorkerId(worker),
-      type: getWorkerType(worker) as WorkerType,
+      // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+      type: getWorkerType(worker)!,
       dynamic: false,
-      ready: false
+      ready: false,
+      stealing: false
     }
   }
 
@@ -207,7 +239,8 @@ export class WorkerNode<Worker extends IWorker, Data = unknown>
       for (const task of this.tasksQueue) {
         if (
           (task.name === DEFAULT_TASK_NAME &&
-            name === (this.info.taskFunctionNames as string[])[1]) ||
+            // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
+            name === this.info.taskFunctionsProperties![1].name) ||
           (task.name !== DEFAULT_TASK_NAME && name === task.name)
         ) {
           ++taskFunctionQueueSize