fd9cf1fb8b3f0499ed8c7615e805c1fc4ebffa31
[poolifier.git] / src / pools / selection-strategies / abstract-worker-choice-strategy.ts
1 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2 import { PoolType, type IPool } from '../pool'
3 import type { IWorker } from '../worker'
4 import type {
5 IWorkerChoiceStrategy,
6 RequiredStatistics,
7 WorkerChoiceStrategyOptions
8 } from './selection-strategies-types'
9
10 /**
11 * Worker choice strategy abstract base class.
12 *
13 * @typeParam Worker - Type of worker which manages the strategy.
14 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
15 * @typeParam Response - Type of response of execution. This can only be serializable data.
16 */
17 export abstract class AbstractWorkerChoiceStrategy<
18 Worker extends IWorker,
19 Data = unknown,
20 Response = unknown
21 > implements IWorkerChoiceStrategy {
22 /** @inheritDoc */
23 protected readonly isDynamicPool: boolean
24 /** @inheritDoc */
25 public readonly requiredStatistics: RequiredStatistics = {
26 runTime: false,
27 avgRunTime: false,
28 medRunTime: false
29 }
30
31 /**
32 * Constructs a worker choice strategy bound to the pool.
33 *
34 * @param pool - The pool instance.
35 * @param opts - The worker choice strategy options.
36 */
37 public constructor (
38 protected readonly pool: IPool<Worker, Data, Response>,
39 protected readonly opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
40 ) {
41 this.checkOptions(this.opts)
42 this.isDynamicPool = this.pool.type === PoolType.DYNAMIC
43 this.choose.bind(this)
44 }
45
46 private checkOptions (opts: WorkerChoiceStrategyOptions): void {
47 if (this.requiredStatistics.avgRunTime && opts.medRunTime === true) {
48 this.requiredStatistics.medRunTime = true
49 }
50 }
51
52 /** @inheritDoc */
53 public abstract reset (): boolean
54
55 /** @inheritDoc */
56 public abstract choose (): number
57
58 /** @inheritDoc */
59 public abstract remove (workerNodeKey: number): boolean
60 }