refactor: apply stricter strategy design pattern requirements on worker
[poolifier.git] / src / pools / selection-strategies / worker-choice-strategy-context.ts
index 3d122f0292d77805a3e59fb56a386fbec1b54396..41b515b816d00dc991c27d8143efe80ec7c6116a 100644 (file)
@@ -1,5 +1,4 @@
 import type { IPoolInternal } from '../pool-internal'
-import { PoolType } from '../pool-internal'
 import type { IPoolWorker } from '../pool-worker'
 import type {
   IWorkerChoiceStrategy,
@@ -21,7 +20,7 @@ export class WorkerChoiceStrategyContext<
   Data,
   Response
 > {
-  private workerChoiceStrategy!: IWorkerChoiceStrategy
+  private workerChoiceStrategy: IWorkerChoiceStrategy<Worker, Data, Response>
 
   /**
    * Worker choice strategy context constructor.
@@ -31,12 +30,15 @@ export class WorkerChoiceStrategyContext<
    * @param workerChoiceStrategy - The worker choice strategy.
    */
   public constructor (
-    private readonly pool: IPoolInternal<Worker, Data, Response>,
+    pool: IPoolInternal<Worker, Data, Response>,
     private readonly createWorkerCallback: () => number,
     workerChoiceStrategy: WorkerChoiceStrategy = WorkerChoiceStrategies.ROUND_ROBIN
   ) {
     this.execute.bind(this)
-    this.setWorkerChoiceStrategy(workerChoiceStrategy)
+    this.workerChoiceStrategy = getWorkerChoiceStrategy<Worker, Data, Response>(
+      pool,
+      workerChoiceStrategy
+    )
   }
 
   /**
@@ -54,11 +56,12 @@ export class WorkerChoiceStrategyContext<
    * @param workerChoiceStrategy - The worker choice strategy to set.
    */
   public setWorkerChoiceStrategy (
+    pool: IPoolInternal<Worker, Data, Response>,
     workerChoiceStrategy: WorkerChoiceStrategy
   ): void {
     this.workerChoiceStrategy?.reset()
     this.workerChoiceStrategy = getWorkerChoiceStrategy<Worker, Data, Response>(
-      this.pool,
+      pool,
       workerChoiceStrategy
     )
   }
@@ -70,9 +73,9 @@ export class WorkerChoiceStrategyContext<
    */
   public execute (): number {
     if (
-      this.pool.type === PoolType.DYNAMIC &&
-      !this.pool.full &&
-      this.pool.findFreeWorkerKey() === -1
+      this.workerChoiceStrategy.isDynamicPool &&
+      !this.workerChoiceStrategy.pool.full &&
+      this.workerChoiceStrategy.pool.findFreeWorkerKey() === -1
     ) {
       return this.createWorkerCallback()
     }