1 import type { IPoolInternal
} from
'../pool-internal'
2 import type { IPoolWorker
} from
'../pool-worker'
7 } from
'./selection-strategies-types'
8 import { WorkerChoiceStrategies
} from
'./selection-strategies-types'
9 import { getWorkerChoiceStrategy
} from
'./selection-strategies-utils'
12 * The worker choice strategy context.
14 * @typeParam Worker - Type of worker.
15 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
16 * @typeParam Response - Type of response of execution. This can only be serializable data.
18 export class WorkerChoiceStrategyContext
<
19 Worker
extends IPoolWorker
,
23 private workerChoiceStrategy
!: IWorkerChoiceStrategy
26 * Worker choice strategy context constructor.
28 * @param pool - The pool instance.
29 * @param createWorkerCallback - The worker creation callback for dynamic pool.
30 * @param workerChoiceStrategy - The worker choice strategy.
33 private readonly pool
: IPoolInternal
<Worker
, Data
, Response
>,
34 private readonly createWorkerCallback
: () => number,
35 workerChoiceStrategy
: WorkerChoiceStrategy
= WorkerChoiceStrategies
.ROUND_ROBIN
37 this.execute
.bind(this)
38 this.setWorkerChoiceStrategy(workerChoiceStrategy
)
42 * Gets the worker choice strategy required statistics.
44 * @returns The required statistics.
46 public getRequiredStatistics (): RequiredStatistics
{
47 return this.workerChoiceStrategy
.requiredStatistics
51 * Sets the worker choice strategy to use in the context.
53 * @param workerChoiceStrategy - The worker choice strategy to set.
55 public setWorkerChoiceStrategy (
56 workerChoiceStrategy
: WorkerChoiceStrategy
58 this.workerChoiceStrategy
?.reset()
59 this.workerChoiceStrategy
= getWorkerChoiceStrategy
<Worker
, Data
, Response
>(
66 * Chooses a worker with the worker choice strategy.
68 * @returns The key of the chosen one.
70 public execute (): number {
72 this.workerChoiceStrategy
.isDynamicPool
&&
74 this.pool
.findFreeWorkerKey() === -1
76 return this.createWorkerCallback()
78 return this.workerChoiceStrategy
.choose()
82 * Removes a worker in the worker choice strategy internals.
84 * @param workerKey - The key of the worker to remove.
85 * @returns `true` if the removal is successful, `false` otherwise.
87 public remove (workerKey
: number): boolean {
88 return this.workerChoiceStrategy
.remove(workerKey
)