Merge branch 'master' of github.com:poolifier/poolifier
[poolifier.git] / src / pools / selection-strategies / abstract-worker-choice-strategy.ts
CommitLineData
bbeadd16 1import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
bdaf31cd
JB
2import type { IPoolInternal } from '../pool-internal'
3import { PoolType } from '../pool-internal'
f06e48d8 4import type { IWorker } from '../worker'
10fcfaf4
JB
5import type {
6 IWorkerChoiceStrategy,
da309861
JB
7 RequiredStatistics,
8 WorkerChoiceStrategyOptions
10fcfaf4 9} from './selection-strategies-types'
bdaf31cd
JB
10
11/**
9cd39dd4 12 * Worker choice strategy abstract base class.
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 abstract class AbstractWorkerChoiceStrategy<
f06e48d8 19 Worker extends IWorker,
b2b1d84e
JB
20 Data = unknown,
21 Response = unknown
17393ac8 22> implements IWorkerChoiceStrategy {
afc003b2 23 /** @inheritDoc */
8b4d4500 24 protected readonly isDynamicPool: boolean
afc003b2 25 /** @inheritDoc */
da309861 26 public readonly requiredStatistics: RequiredStatistics = {
c6bd2650 27 runTime: false,
78099a15
JB
28 avgRunTime: false,
29 medRunTime: false
10fcfaf4 30 }
bdaf31cd
JB
31
32 /**
6533c3e6 33 * Constructs a worker choice strategy bound to the pool.
bdaf31cd 34 *
38e795c1 35 * @param pool - The pool instance.
da309861 36 * @param opts - The worker choice strategy options.
bdaf31cd
JB
37 */
38 public constructor (
da309861 39 protected readonly pool: IPoolInternal<Worker, Data, Response>,
bbeadd16 40 protected readonly opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
b8f3418c 41 ) {
f9f00b5f 42 this.checkOptions(this.opts)
b8f3418c 43 this.isDynamicPool = this.pool.type === PoolType.DYNAMIC
1086026a 44 this.choose.bind(this)
b8f3418c 45 }
bdaf31cd 46
f9f00b5f
JB
47 private checkOptions (opts: WorkerChoiceStrategyOptions): void {
48 if (this.requiredStatistics.avgRunTime && opts.medRunTime === true) {
da309861
JB
49 this.requiredStatistics.medRunTime = true
50 }
51 }
52
afc003b2 53 /** @inheritDoc */
a6f7f1b4 54 public abstract reset (): boolean
ea7a90d3 55
afc003b2 56 /** @inheritDoc */
c923ce56 57 public abstract choose (): number
97a2abc3 58
afc003b2 59 /** @inheritDoc */
f06e48d8 60 public abstract remove (workerNodeKey: number): boolean
bdaf31cd 61}