| 1 | import type { IPool } from '../pool.js' |
| 2 | import type { IWorker } from '../worker.js' |
| 3 | import type { |
| 4 | IWorkerChoiceStrategy, |
| 5 | TaskStatisticsRequirements, |
| 6 | WorkerChoiceStrategyOptions, |
| 7 | } from './selection-strategies-types.js' |
| 8 | |
| 9 | import { DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS } from '../utils.js' |
| 10 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js' |
| 11 | |
| 12 | /** |
| 13 | * Selects the least busy worker. |
| 14 | * @typeParam Worker - Type of worker which manages the strategy. |
| 15 | * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. |
| 16 | * @typeParam Response - Type of execution response. This can only be structured-cloneable 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 override readonly taskStatisticsRequirements: TaskStatisticsRequirements = |
| 27 | { |
| 28 | elu: DEFAULT_MEASUREMENT_STATISTICS_REQUIREMENTS, |
| 29 | runTime: { |
| 30 | aggregate: true, |
| 31 | average: false, |
| 32 | median: false, |
| 33 | }, |
| 34 | waitTime: { |
| 35 | aggregate: true, |
| 36 | average: false, |
| 37 | median: false, |
| 38 | }, |
| 39 | } |
| 40 | |
| 41 | /** @inheritDoc */ |
| 42 | public constructor ( |
| 43 | pool: IPool<Worker, Data, Response>, |
| 44 | opts?: WorkerChoiceStrategyOptions |
| 45 | ) { |
| 46 | super(pool, opts) |
| 47 | this.setTaskStatisticsRequirements(this.opts) |
| 48 | } |
| 49 | |
| 50 | private leastBusyNextWorkerNodeKey (): number | undefined { |
| 51 | return this.pool.workerNodes.reduce( |
| 52 | (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => { |
| 53 | return this.isWorkerNodeReady(workerNodeKey) && |
| 54 | (workerNode.usage.waitTime.aggregate ?? 0) + |
| 55 | (workerNode.usage.runTime.aggregate ?? 0) < |
| 56 | (workerNodes[minWorkerNodeKey].usage.waitTime.aggregate ?? 0) + |
| 57 | (workerNodes[minWorkerNodeKey].usage.runTime.aggregate ?? 0) |
| 58 | ? workerNodeKey |
| 59 | : minWorkerNodeKey |
| 60 | }, |
| 61 | 0 |
| 62 | ) |
| 63 | } |
| 64 | |
| 65 | /** @inheritDoc */ |
| 66 | public choose (): number | undefined { |
| 67 | this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey) |
| 68 | this.nextWorkerNodeKey = this.leastBusyNextWorkerNodeKey() |
| 69 | return this.nextWorkerNodeKey |
| 70 | } |
| 71 | |
| 72 | /** @inheritDoc */ |
| 73 | public remove (): boolean { |
| 74 | return true |
| 75 | } |
| 76 | |
| 77 | /** @inheritDoc */ |
| 78 | public reset (): boolean { |
| 79 | return true |
| 80 | } |
| 81 | |
| 82 | /** @inheritDoc */ |
| 83 | public update (): boolean { |
| 84 | return true |
| 85 | } |
| 86 | } |