perf: optimize a pool type test
[poolifier.git] / src / pools / selection-strategies / worker-choice-strategy-context.ts
1 import type { IPoolInternal } from '../pool-internal'
2 import type { IPoolWorker } from '../pool-worker'
3 import type {
4 IWorkerChoiceStrategy,
5 RequiredStatistics,
6 WorkerChoiceStrategy
7 } from './selection-strategies-types'
8 import { WorkerChoiceStrategies } from './selection-strategies-types'
9 import { getWorkerChoiceStrategy } from './selection-strategies-utils'
10
11 /**
12 * The worker choice strategy context.
13 *
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.
17 */
18 export class WorkerChoiceStrategyContext<
19 Worker extends IPoolWorker,
20 Data,
21 Response
22 > {
23 private workerChoiceStrategy!: IWorkerChoiceStrategy
24
25 /**
26 * Worker choice strategy context constructor.
27 *
28 * @param pool - The pool instance.
29 * @param createWorkerCallback - The worker creation callback for dynamic pool.
30 * @param workerChoiceStrategy - The worker choice strategy.
31 */
32 public constructor (
33 private readonly pool: IPoolInternal<Worker, Data, Response>,
34 private readonly createWorkerCallback: () => number,
35 workerChoiceStrategy: WorkerChoiceStrategy = WorkerChoiceStrategies.ROUND_ROBIN
36 ) {
37 this.execute.bind(this)
38 this.setWorkerChoiceStrategy(workerChoiceStrategy)
39 }
40
41 /**
42 * Gets the worker choice strategy required statistics.
43 *
44 * @returns The required statistics.
45 */
46 public getRequiredStatistics (): RequiredStatistics {
47 return this.workerChoiceStrategy.requiredStatistics
48 }
49
50 /**
51 * Sets the worker choice strategy to use in the context.
52 *
53 * @param workerChoiceStrategy - The worker choice strategy to set.
54 */
55 public setWorkerChoiceStrategy (
56 workerChoiceStrategy: WorkerChoiceStrategy
57 ): void {
58 this.workerChoiceStrategy?.reset()
59 this.workerChoiceStrategy = getWorkerChoiceStrategy<Worker, Data, Response>(
60 this.pool,
61 workerChoiceStrategy
62 )
63 }
64
65 /**
66 * Chooses a worker with the worker choice strategy.
67 *
68 * @returns The key of the chosen one.
69 */
70 public execute (): number {
71 if (
72 this.workerChoiceStrategy.isDynamicPool &&
73 !this.pool.full &&
74 this.pool.findFreeWorkerKey() === -1
75 ) {
76 return this.createWorkerCallback()
77 }
78 return this.workerChoiceStrategy.choose()
79 }
80
81 /**
82 * Removes a worker in the worker choice strategy internals.
83 *
84 * @param workerKey - The key of the worker to remove.
85 * @returns `true` if the removal is successful, `false` otherwise.
86 */
87 public remove (workerKey: number): boolean {
88 return this.workerChoiceStrategy.remove(workerKey)
89 }
90 }