feat: worker node readiness aware worker choice strategies
[poolifier.git] / src / pools / selection-strategies / least-busy-worker-choice-strategy.ts
index aafc07dd6f8ac8f8faa47742bdda2e096449fd55..b61bca1c8bdf450083474d8e2d8e78fef48ea2bc 100644 (file)
@@ -1,4 +1,7 @@
-import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
+import {
+  DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS,
+  DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
+} from '../../utils'
 import type { IPool } from '../pool'
 import type { IWorker } from '../worker'
 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
@@ -12,8 +15,8 @@ import type {
  * Selects the least busy worker.
  *
  * @typeParam Worker - Type of worker which manages the strategy.
- * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
- * @typeParam Response - Type of execution response. This can only be serializable data.
+ * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
+ * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
  */
 export class LeastBusyWorkerChoiceStrategy<
     Worker extends IWorker,
@@ -34,11 +37,7 @@ export class LeastBusyWorkerChoiceStrategy<
       average: false,
       median: false
     },
-    elu: {
-      aggregate: false,
-      average: false,
-      median: false
-    }
+    elu: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS
   }
 
   /** @inheritDoc */
@@ -57,24 +56,24 @@ export class LeastBusyWorkerChoiceStrategy<
 
   /** @inheritDoc */
   public update (): boolean {
+    return true
+  }
+
+  /** @inheritDoc */
+  public choose (): number {
     let minTime = Infinity
     for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
       const workerTime =
-        workerNode.workerUsage.runTime.aggregate +
-        workerNode.workerUsage.waitTime.aggregate
-      if (workerTime === 0) {
+        (workerNode.usage.runTime?.aggregate ?? 0) +
+        (workerNode.usage.waitTime?.aggregate ?? 0)
+      if (this.workerNodeReady(workerNodeKey) && workerTime === 0) {
         this.nextWorkerNodeId = workerNodeKey
         break
-      } else if (workerTime < minTime) {
+      } else if (this.workerNodeReady(workerNodeKey) && workerTime < minTime) {
         minTime = workerTime
         this.nextWorkerNodeId = workerNodeKey
       }
     }
-    return true
-  }
-
-  /** @inheritDoc */
-  public choose (): number {
     return this.nextWorkerNodeId
   }