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
<Worker
, Data
, Response
>
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 pool
: IPoolInternal
<Worker
, Data
, Response
>,
34 private readonly createWorkerCallback
: () => number,
35 workerChoiceStrategy
: WorkerChoiceStrategy
= WorkerChoiceStrategies
.ROUND_ROBIN
37 this.execute
.bind(this)
38 this.workerChoiceStrategy
= getWorkerChoiceStrategy
<Worker
, Data
, Response
>(
45 * Gets the worker choice strategy required statistics.
47 * @returns The required statistics.
49 public getRequiredStatistics (): RequiredStatistics
{
50 return this.workerChoiceStrategy
.requiredStatistics
54 * Sets the worker choice strategy to use in the context.
56 * @param workerChoiceStrategy - The worker choice strategy to set.
58 public setWorkerChoiceStrategy (
59 pool
: IPoolInternal
<Worker
, Data
, Response
>,
60 workerChoiceStrategy
: WorkerChoiceStrategy
62 this.workerChoiceStrategy
?.reset()
63 this.workerChoiceStrategy
= getWorkerChoiceStrategy
<Worker
, Data
, Response
>(
70 * Chooses a worker with the worker choice strategy.
72 * @returns The key of the chosen one.
74 public execute (): number {
76 this.workerChoiceStrategy
.isDynamicPool
&&
77 !this.workerChoiceStrategy
.pool
.full
&&
78 this.workerChoiceStrategy
.pool
.findFreeWorkerKey() === -1
80 return this.createWorkerCallback()
82 return this.workerChoiceStrategy
.choose()
86 * Removes a worker in the worker choice strategy internals.
88 * @param workerKey - The key of the worker to remove.
89 * @returns `true` if the removal is successful, `false` otherwise.
91 public remove (workerKey
: number): boolean {
92 return this.workerChoiceStrategy
.remove(workerKey
)