| 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 execution response. 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 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS |
| 40 | ) { |
| 41 | this.isDynamicPool = this.pool.type === PoolType.DYNAMIC |
| 42 | this.choose.bind(this) |
| 43 | } |
| 44 | |
| 45 | protected checkOptions (opts: WorkerChoiceStrategyOptions): void { |
| 46 | if (this.requiredStatistics.avgRunTime && opts.medRunTime === true) { |
| 47 | this.requiredStatistics.avgRunTime = false |
| 48 | this.requiredStatistics.medRunTime = opts.medRunTime as boolean |
| 49 | } |
| 50 | if (this.requiredStatistics.medRunTime && opts.medRunTime === false) { |
| 51 | this.requiredStatistics.avgRunTime = true |
| 52 | this.requiredStatistics.medRunTime = opts.medRunTime as boolean |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | /** @inheritDoc */ |
| 57 | public abstract reset (): boolean |
| 58 | |
| 59 | /** @inheritDoc */ |
| 60 | public abstract choose (): number |
| 61 | |
| 62 | /** @inheritDoc */ |
| 63 | public abstract remove (workerNodeKey: number): boolean |
| 64 | |
| 65 | /** @inheritDoc */ |
| 66 | public setOptions (opts: WorkerChoiceStrategyOptions): void { |
| 67 | this.checkOptions(opts) |
| 68 | this.opts = opts |
| 69 | } |
| 70 | } |