chore: switch from mitata to tatami-ng
[poolifier.git] / src / pools / selection-strategies / least-used-worker-choice-strategy.ts
index 5c266f282d229fd5c5647e3305237ac1ee33c865..e45d57549580b883c1f6a185dc7701b861004336 100644 (file)
@@ -1,11 +1,10 @@
-import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
-import type { IPool } from '../pool'
-import type { IWorker } from '../worker'
-import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
+import type { IPool } from '../pool.js'
+import type { IWorker } from '../worker.js'
+import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js'
 import type {
   IWorkerChoiceStrategy,
   WorkerChoiceStrategyOptions
-} from './selection-strategies-types'
+} from './selection-strategies-types.js'
 
 /**
  * Selects the least used worker.
@@ -24,10 +23,9 @@ export class LeastUsedWorkerChoiceStrategy<
   /** @inheritDoc */
   public constructor (
     pool: IPool<Worker, Data, Response>,
-    opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
+    opts?: WorkerChoiceStrategyOptions
   ) {
     super(pool, opts)
-    this.setTaskStatisticsRequirements(this.opts)
   }
 
   /** @inheritDoc */
@@ -41,27 +39,34 @@ export class LeastUsedWorkerChoiceStrategy<
   }
 
   /** @inheritDoc */
-  public choose (): number {
-    let minNumberOfTasks = Infinity
-    for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
-      const workerTaskStatistics = workerNode.workerUsage.tasks
-      const workerTasks =
-        workerTaskStatistics.executed +
-        workerTaskStatistics.executing +
-        workerTaskStatistics.queued
-      if (workerTasks === 0) {
-        this.nextWorkerNodeId = workerNodeKey
-        break
-      } else if (workerTasks < minNumberOfTasks) {
-        minNumberOfTasks = workerTasks
-        this.nextWorkerNodeId = workerNodeKey
-      }
-    }
-    return this.nextWorkerNodeId
+  public choose (): number | undefined {
+    this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey)
+    this.nextWorkerNodeKey = this.leastUsedNextWorkerNodeKey()
+    return this.nextWorkerNodeKey
   }
 
   /** @inheritDoc */
   public remove (): boolean {
     return true
   }
+
+  private leastUsedNextWorkerNodeKey (): number | undefined {
+    if (this.pool.workerNodes.length === 0) {
+      return undefined
+    }
+    return this.pool.workerNodes.reduce(
+      (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
+        return this.isWorkerNodeReady(workerNodeKey) &&
+          workerNode.usage.tasks.executed +
+            workerNode.usage.tasks.executing +
+            workerNode.usage.tasks.queued <
+            workerNodes[minWorkerNodeKey].usage.tasks.executed +
+              workerNodes[minWorkerNodeKey].usage.tasks.executing +
+              workerNodes[minWorkerNodeKey].usage.tasks.queued
+          ? workerNodeKey
+          : minWorkerNodeKey
+      },
+      0
+    )
+  }
 }