1 import type { IPoolInternal
} from
'../pool-internal'
2 import { PoolType
} from
'../pool-internal'
3 import type { IPoolWorker
} from
'../pool-worker'
8 } from
'./selection-strategies-types'
9 import { WorkerChoiceStrategies
} from
'./selection-strategies-types'
10 import { getWorkerChoiceStrategy
} from
'./selection-strategies-utils'
13 * The worker choice strategy context.
15 * @typeParam Worker - Type of worker.
16 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
17 * @typeParam Response - Type of response of execution. This can only be serializable data.
19 export class WorkerChoiceStrategyContext
<
20 Worker
extends IPoolWorker
,
24 private workerChoiceStrategy
!: IWorkerChoiceStrategy
27 * Worker choice strategy context constructor.
29 * @param pool - The pool instance.
30 * @param createWorkerCallback - The worker creation callback for dynamic pool.
31 * @param workerChoiceStrategy - The worker choice strategy.
34 private readonly pool
: IPoolInternal
<Worker
, Data
, Response
>,
35 private readonly createWorkerCallback
: () => number,
36 workerChoiceStrategy
: WorkerChoiceStrategy
= WorkerChoiceStrategies
.ROUND_ROBIN
38 this.execute
.bind(this)
39 this.setWorkerChoiceStrategy(workerChoiceStrategy
)
43 * Gets the worker choice strategy required statistics.
45 * @returns The required statistics.
47 public getRequiredStatistics (): RequiredStatistics
{
48 return this.workerChoiceStrategy
.requiredStatistics
52 * Sets the worker choice strategy to use in the context.
54 * @param workerChoiceStrategy - The worker choice strategy to set.
56 public setWorkerChoiceStrategy (
57 workerChoiceStrategy
: WorkerChoiceStrategy
59 this.workerChoiceStrategy
?.reset()
60 this.workerChoiceStrategy
= getWorkerChoiceStrategy
<Worker
, Data
, Response
>(
67 * Chooses a worker with the worker choice strategy.
69 * @returns The key of the chosen one.
71 public execute (): number {
73 this.pool
.type === PoolType
.DYNAMIC
&&
75 this.pool
.findFreeWorkerKey() === -1
77 return this.createWorkerCallback()
79 return this.workerChoiceStrategy
.choose()
83 * Removes a worker in the worker choice strategy internals.
85 * @param workerKey - The key of the worker to remove.
86 * @returns `true` if the removal is successful, `false` otherwise.
88 public remove (workerKey
: number): boolean {
89 return this.workerChoiceStrategy
.remove(workerKey
)