| 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 | WorkerChoiceStrategyOptions |
| 8 | } from './selection-strategies-types' |
| 9 | |
| 10 | /** |
| 11 | * Selects the least used worker. |
| 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 structured-cloneable data. |
| 15 | * @typeParam Response - Type of execution response. This can only be structured-cloneable data. |
| 16 | */ |
| 17 | export class LeastUsedWorkerChoiceStrategy< |
| 18 | Worker extends IWorker, |
| 19 | Data = unknown, |
| 20 | Response = unknown |
| 21 | > |
| 22 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> |
| 23 | implements IWorkerChoiceStrategy { |
| 24 | /** @inheritDoc */ |
| 25 | public constructor ( |
| 26 | pool: IPool<Worker, Data, Response>, |
| 27 | opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS |
| 28 | ) { |
| 29 | super(pool, opts) |
| 30 | this.setTaskStatisticsRequirements(this.opts) |
| 31 | } |
| 32 | |
| 33 | /** @inheritDoc */ |
| 34 | public reset (): boolean { |
| 35 | return true |
| 36 | } |
| 37 | |
| 38 | /** @inheritDoc */ |
| 39 | public update (): boolean { |
| 40 | return true |
| 41 | } |
| 42 | |
| 43 | /** @inheritDoc */ |
| 44 | public choose (): number { |
| 45 | return this.leastUsedNextWorkerNodeKey() |
| 46 | } |
| 47 | |
| 48 | /** @inheritDoc */ |
| 49 | public remove (): boolean { |
| 50 | return true |
| 51 | } |
| 52 | |
| 53 | private leastUsedNextWorkerNodeKey (): number { |
| 54 | let minNumberOfTasks = Infinity |
| 55 | for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) { |
| 56 | const workerTaskStatistics = workerNode.usage.tasks |
| 57 | const workerTasks = |
| 58 | workerTaskStatistics.executed + |
| 59 | workerTaskStatistics.executing + |
| 60 | workerTaskStatistics.queued |
| 61 | if (this.isWorkerNodeReady(workerNodeKey) && workerTasks === 0) { |
| 62 | this.nextWorkerNodeKey = workerNodeKey |
| 63 | break |
| 64 | } else if ( |
| 65 | this.isWorkerNodeReady(workerNodeKey) && |
| 66 | workerTasks < minNumberOfTasks |
| 67 | ) { |
| 68 | minNumberOfTasks = workerTasks |
| 69 | this.nextWorkerNodeKey = workerNodeKey |
| 70 | } |
| 71 | } |
| 72 | return this.nextWorkerNodeKey |
| 73 | } |
| 74 | } |