fix: ensure worker removal impact is propated to worker choice strategy
[poolifier.git] / src / pools / selection-strategies / dynamic-pool-worker-choice-strategy.ts
CommitLineData
bdaf31cd 1import type { IPoolInternal } from '../pool-internal'
ea7a90d3 2import type { IPoolWorker } from '../pool-worker'
bdaf31cd
JB
3import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
4import type {
5 IWorkerChoiceStrategy,
6 WorkerChoiceStrategy
7} from './selection-strategies-types'
8import { WorkerChoiceStrategies } from './selection-strategies-types'
78cea37e 9import { getWorkerChoiceStrategy } from './selection-strategies-utils'
bdaf31cd
JB
10
11/**
bb3d5b74 12 * Selects the next worker for dynamic pool.
bdaf31cd 13 *
38e795c1
JB
14 * @typeParam Worker - Type of worker which manages the strategy.
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.
bdaf31cd
JB
17 */
18export class DynamicPoolWorkerChoiceStrategy<
ea7a90d3 19 Worker extends IPoolWorker,
bdaf31cd
JB
20 Data,
21 Response
22> extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
c923ce56 23 private readonly workerChoiceStrategy: IWorkerChoiceStrategy
bdaf31cd
JB
24
25 /**
bb3d5b74 26 * Constructs a worker choice strategy for dynamic pool.
bdaf31cd 27 *
38e795c1 28 * @param pool - The pool instance.
c923ce56
JB
29 * @param createWorkerCallback - The worker creation callback for dynamic pool.
30 * @param workerChoiceStrategy - The worker choice strategy when the pool is busy.
bdaf31cd
JB
31 */
32 public constructor (
33 pool: IPoolInternal<Worker, Data, Response>,
c923ce56 34 private readonly createWorkerCallback: () => number,
bdaf31cd
JB
35 workerChoiceStrategy: WorkerChoiceStrategy = WorkerChoiceStrategies.ROUND_ROBIN
36 ) {
37 super(pool)
78cea37e 38 this.workerChoiceStrategy = getWorkerChoiceStrategy(
bdaf31cd
JB
39 this.pool,
40 workerChoiceStrategy
41 )
10fcfaf4 42 this.requiredStatistics = this.workerChoiceStrategy.requiredStatistics
bdaf31cd
JB
43 }
44
38e795c1 45 /** {@inheritDoc} */
a6f7f1b4
JB
46 public reset (): boolean {
47 return this.workerChoiceStrategy.reset()
ea7a90d3
JB
48 }
49
38e795c1 50 /** {@inheritDoc} */
c923ce56
JB
51 public choose (): number {
52 const freeWorkerKey = this.pool.findFreeWorkerKey()
53 if (freeWorkerKey !== false) {
54 return freeWorkerKey
bdaf31cd
JB
55 }
56
78cea37e 57 if (this.pool.busy) {
bdaf31cd
JB
58 return this.workerChoiceStrategy.choose()
59 }
60
61 // All workers are busy, create a new worker
c923ce56 62 return this.createWorkerCallback()
bdaf31cd 63 }
97a2abc3
JB
64
65 /** {@inheritDoc} */
66 public remove (workerKey: number): boolean {
67 return this.workerChoiceStrategy.remove(workerKey)
68 }
bdaf31cd 69}