| 1 | import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils' |
| 2 | import type { IPool } from '../pool' |
| 3 | import type { IWorker } from '../worker' |
| 4 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' |
| 5 | import type { |
| 6 | IWorkerChoiceStrategy, |
| 7 | RequiredStatistics, |
| 8 | WorkerChoiceStrategyOptions |
| 9 | } from './selection-strategies-types' |
| 10 | |
| 11 | /** |
| 12 | * Selects the least busy worker. |
| 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 execution response. This can only be serializable data. |
| 17 | */ |
| 18 | export class LeastBusyWorkerChoiceStrategy< |
| 19 | Worker extends IWorker, |
| 20 | Data = unknown, |
| 21 | Response = unknown |
| 22 | > |
| 23 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> |
| 24 | implements IWorkerChoiceStrategy { |
| 25 | /** @inheritDoc */ |
| 26 | public readonly requiredStatistics: RequiredStatistics = { |
| 27 | runTime: true, |
| 28 | avgRunTime: false, |
| 29 | medRunTime: false, |
| 30 | waitTime: false, |
| 31 | avgWaitTime: false, |
| 32 | medWaitTime: false |
| 33 | } |
| 34 | |
| 35 | /** @inheritDoc */ |
| 36 | public constructor ( |
| 37 | pool: IPool<Worker, Data, Response>, |
| 38 | opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS |
| 39 | ) { |
| 40 | super(pool, opts) |
| 41 | this.setRequiredStatistics(this.opts) |
| 42 | } |
| 43 | |
| 44 | /** @inheritDoc */ |
| 45 | public reset (): boolean { |
| 46 | return true |
| 47 | } |
| 48 | |
| 49 | /** @inheritDoc */ |
| 50 | public update (): boolean { |
| 51 | return true |
| 52 | } |
| 53 | |
| 54 | /** @inheritDoc */ |
| 55 | public choose (): number { |
| 56 | const freeWorkerNodeKey = this.findFreeWorkerNodeKey() |
| 57 | if (freeWorkerNodeKey !== -1) { |
| 58 | return freeWorkerNodeKey |
| 59 | } |
| 60 | let minRunTime = Infinity |
| 61 | let leastBusyWorkerNodeKey!: number |
| 62 | for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) { |
| 63 | const workerRunTime = workerNode.tasksUsage.runTime |
| 64 | if (workerRunTime === 0) { |
| 65 | return workerNodeKey |
| 66 | } else if (workerRunTime < minRunTime) { |
| 67 | minRunTime = workerRunTime |
| 68 | leastBusyWorkerNodeKey = workerNodeKey |
| 69 | } |
| 70 | } |
| 71 | return leastBusyWorkerNodeKey |
| 72 | } |
| 73 | |
| 74 | /** @inheritDoc */ |
| 75 | public remove (): boolean { |
| 76 | return true |
| 77 | } |
| 78 | } |