1 import type { AbstractPoolWorker
} from
'../abstract-pool-worker'
2 import type { IPoolInternal
} from
'../pool-internal'
3 import { PoolType
} from
'../pool-internal'
4 import { DynamicPoolWorkerChoiceStrategy
} from
'./dynamic-pool-worker-choice-strategy'
8 } from
'./selection-strategies-types'
9 import { WorkerChoiceStrategies
} from
'./selection-strategies-types'
10 import { SelectionStrategiesUtils
} from
'./selection-strategies-utils'
13 * The worker choice strategy context.
15 * @template Worker Type of worker.
16 * @template Data Type of data sent to the worker. This can only be serializable data.
17 * @template Response Type of response of execution. This can only be serializable data.
19 export class WorkerChoiceStrategyContext
<
20 Worker
extends AbstractPoolWorker
,
24 private workerChoiceStrategy
!: IWorkerChoiceStrategy
<Worker
>
27 * Worker choice strategy context constructor.
29 * @param pool The pool instance.
30 * @param createDynamicallyWorkerCallback The worker creation callback for dynamic pool.
31 * @param workerChoiceStrategy The worker choice strategy.
34 private readonly pool
: IPoolInternal
<Worker
, Data
, Response
>,
35 private createDynamicallyWorkerCallback
: () => Worker
,
36 workerChoiceStrategy
: WorkerChoiceStrategy
= WorkerChoiceStrategies
.ROUND_ROBIN
38 this.setWorkerChoiceStrategy(workerChoiceStrategy
)
42 * Get the worker choice strategy instance specific to the pool type.
44 * @param workerChoiceStrategy The worker choice strategy.
45 * @returns The worker choice strategy instance for the pool type.
47 private getPoolWorkerChoiceStrategy (
48 workerChoiceStrategy
: WorkerChoiceStrategy
= WorkerChoiceStrategies
.ROUND_ROBIN
49 ): IWorkerChoiceStrategy
<Worker
> {
50 if (this.pool
.type === PoolType
.DYNAMIC
) {
51 return new DynamicPoolWorkerChoiceStrategy(
53 this.createDynamicallyWorkerCallback
,
57 return SelectionStrategiesUtils
.getWorkerChoiceStrategy(
64 * Set the worker choice strategy to use in the context.
66 * @param workerChoiceStrategy The worker choice strategy to set.
68 public setWorkerChoiceStrategy (
69 workerChoiceStrategy
: WorkerChoiceStrategy
71 this.workerChoiceStrategy
= this.getPoolWorkerChoiceStrategy(
77 * Choose a worker with the underlying selection strategy.
79 * @returns The chosen one.
81 public execute (): Worker
{
82 return this.workerChoiceStrategy
.choose()