WRR: Fix worker choice initial runtime value on each round
[poolifier.git] / src / worker / abstract-worker.ts
index 0883b03eb0b5e6587892b5e6456745e8ce53cdd6..52143fe3099c36c284cf56c3a8c6746b6c76c1dc 100644 (file)
@@ -6,11 +6,11 @@ import { EMPTY_FUNCTION } from '../utils'
 import type { KillBehavior, WorkerOptions } from './worker-options'
 import { KillBehaviors } from './worker-options'
 
-const DEFAULT_MAX_INACTIVE_TIME = 1000 * 60
+const DEFAULT_MAX_INACTIVE_TIME = 60000
 const DEFAULT_KILL_BEHAVIOR: KillBehavior = KillBehaviors.SOFT
 
 /**
- * Base class containing some shared logic for all poolifier workers.
+ * Base class that implements some shared logic for all poolifier workers.
  *
  * @template MainWorker Type of main worker.
  * @template Data Type of data this worker receives from pool's execution. This can only be serializable data.
@@ -29,7 +29,10 @@ export abstract class AbstractWorker<
    * Handler Id of the `aliveInterval` worker alive check.
    */
   protected readonly aliveInterval?: NodeJS.Timeout
-
+  /**
+   * Options for the worker.
+   */
+  public readonly opts: WorkerOptions
   /**
    * Constructs a new poolifier worker.
    *
@@ -44,7 +47,7 @@ export abstract class AbstractWorker<
     isMain: boolean,
     fn: (data: Data) => Response,
     protected mainWorker: MainWorker | undefined | null,
-    public readonly opts: WorkerOptions = {
+    opts: WorkerOptions = {
       /**
        * The kill behavior option on this Worker or its default value.
        */
@@ -57,11 +60,12 @@ export abstract class AbstractWorker<
     }
   ) {
     super(type)
+    this.opts = opts
     this.checkFunctionInput(fn)
     this.checkWorkerOptions(this.opts)
     this.lastTaskTimestamp = Date.now()
     // Keep the worker active
-    if (!isMain) {
+    if (isMain === false) {
       this.aliveInterval = setInterval(
         this.checkAlive.bind(this),
         (this.opts.maxInactiveTime ?? DEFAULT_MAX_INACTIVE_TIME) / 2
@@ -70,25 +74,32 @@ export abstract class AbstractWorker<
     }
 
     this.mainWorker?.on('message', (value: MessageValue<Data, MainWorker>) => {
-      if (value?.data && value.id) {
-        // Here you will receive messages
-        if (this.opts.async) {
-          this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
-        } else {
-          this.runInAsyncScope(this.run.bind(this), this, fn, value)
-        }
-      } else if (value.parent) {
-        // Save a reference of the main worker to communicate with it
-        // This will be received once
-        this.mainWorker = value.parent
-      } else if (value.kill) {
-        // Here is time to kill this worker, just clearing the interval
-        if (this.aliveInterval) clearInterval(this.aliveInterval)
-        this.emitDestroy()
-      }
+      this.messageListener(value, fn)
     })
   }
 
+  protected messageListener (
+    value: MessageValue<Data, MainWorker>,
+    fn: (data: Data) => Response
+  ): void {
+    if (value.data !== undefined && value.id !== undefined) {
+      // Here you will receive messages
+      if (this.opts.async) {
+        this.runInAsyncScope(this.runAsync.bind(this), this, fn, value)
+      } else {
+        this.runInAsyncScope(this.run.bind(this), this, fn, value)
+      }
+    } else if (value.parent !== undefined) {
+      // Save a reference of the main worker to communicate with it
+      // This will be received once
+      this.mainWorker = value.parent
+    } else if (value.kill !== undefined) {
+      // Here is time to kill this worker, just clearing the interval
+      if (this.aliveInterval) clearInterval(this.aliveInterval)
+      this.emitDestroy()
+    }
+  }
+
   private checkWorkerOptions (opts: WorkerOptions) {
     this.opts.killBehavior = opts.killBehavior ?? DEFAULT_KILL_BEHAVIOR
     this.opts.maxInactiveTime =
@@ -160,8 +171,10 @@ export abstract class AbstractWorker<
     value: MessageValue<Data>
   ): void {
     try {
+      const startTaskTimestamp = Date.now()
       const res = fn(value.data)
-      this.sendToMainWorker({ data: res, id: value.id })
+      const taskRunTime = Date.now() - startTaskTimestamp
+      this.sendToMainWorker({ data: res, id: value.id, taskRunTime })
     } catch (e) {
       const err = this.handleError(e as Error)
       this.sendToMainWorker({ error: err, id: value.id })
@@ -180,13 +193,15 @@ export abstract class AbstractWorker<
     fn: (data?: Data) => Promise<Response>,
     value: MessageValue<Data>
   ): void {
+    const startTaskTimestamp = Date.now()
     fn(value.data)
       .then(res => {
-        this.sendToMainWorker({ data: res, id: value.id })
+        const taskRunTime = Date.now() - startTaskTimestamp
+        this.sendToMainWorker({ data: res, id: value.id, taskRunTime })
         return null
       })
       .catch(e => {
-        const err = this.handleError(e)
+        const err = this.handleError(e as Error)
         this.sendToMainWorker({ error: err, id: value.id })
       })
       .finally(() => {