feat: add median task run time statistic
[poolifier.git] / src / pools / selection-strategies / weighted-round-robin-worker-choice-strategy.ts
index 24a25b4d30de7fa553f500615b5b5e8e06efd972..96b5867b5bfb1db98f8a8afd4505b5c24da75505 100644 (file)
@@ -2,7 +2,10 @@ import { cpus } from 'node:os'
 import type { IPoolInternal } from '../pool-internal'
 import type { IPoolWorker } from '../pool-worker'
 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
-import type { RequiredStatistics } from './selection-strategies-types'
+import type {
+  IWorkerChoiceStrategy,
+  RequiredStatistics
+} from './selection-strategies-types'
 
 /**
  * Virtual task runtime.
@@ -21,13 +24,17 @@ interface TaskRunTime {
  * @typeParam Response - Type of response of execution. This can only be serializable data.
  */
 export class WeightedRoundRobinWorkerChoiceStrategy<
-  Worker extends IPoolWorker,
-  Data,
-  Response
-> extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
-  /** {@inheritDoc} */
+    Worker extends IPoolWorker,
+    Data = unknown,
+    Response = unknown
+  >
+  extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
+  implements IWorkerChoiceStrategy {
+  /** @inheritDoc */
   public readonly requiredStatistics: RequiredStatistics = {
-    runTime: true
+    runTime: true,
+    avgRunTime: true,
+    medRunTime: false
   }
 
   /**
@@ -57,7 +64,7 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     this.initWorkersTaskRunTime()
   }
 
-  /** {@inheritDoc} */
+  /** @inheritDoc */
   public reset (): boolean {
     this.currentWorkerId = 0
     this.workersTaskRunTime.clear()
@@ -65,7 +72,7 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     return true
   }
 
-  /** {@inheritDoc} */
+  /** @inheritDoc */
   public choose (): number {
     const chosenWorkerKey = this.currentWorkerId
     if (this.isDynamicPool && !this.workersTaskRunTime.has(chosenWorkerKey)) {
@@ -93,13 +100,17 @@ export class WeightedRoundRobinWorkerChoiceStrategy<
     return chosenWorkerKey
   }
 
-  /** {@inheritDoc} */
+  /** @inheritDoc */
   public remove (workerKey: number): boolean {
     if (this.currentWorkerId === workerKey) {
-      this.currentWorkerId =
-        this.currentWorkerId > this.pool.workers.length - 1
-          ? this.pool.workers.length - 1
-          : this.currentWorkerId
+      if (this.pool.workers.length === 0) {
+        this.currentWorkerId = 0
+      } else {
+        this.currentWorkerId =
+          this.currentWorkerId > this.pool.workers.length - 1
+            ? this.pool.workers.length - 1
+            : this.currentWorkerId
+      }
     }
     const workerDeleted = this.workersTaskRunTime.delete(workerKey)
     for (const [key, value] of this.workersTaskRunTime) {