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