| 1 | import type { IPoolWorker } from '../pool-worker' |
| 2 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' |
| 3 | |
| 4 | /** |
| 5 | * Selects the less used worker. |
| 6 | * |
| 7 | * @typeParam Worker - Type of worker which manages the strategy. |
| 8 | * @typeParam Data - Type of data sent to the worker. This can only be serializable data. |
| 9 | * @typeParam Response - Type of response of execution. This can only be serializable data. |
| 10 | */ |
| 11 | export class LessUsedWorkerChoiceStrategy< |
| 12 | Worker extends IPoolWorker, |
| 13 | Data, |
| 14 | Response |
| 15 | > extends AbstractWorkerChoiceStrategy<Worker, Data, Response> { |
| 16 | /** {@inheritDoc} */ |
| 17 | public reset (): boolean { |
| 18 | return true |
| 19 | } |
| 20 | |
| 21 | /** {@inheritDoc} */ |
| 22 | public choose (): number { |
| 23 | let minNumberOfTasks = Infinity |
| 24 | let lessUsedWorkerKey!: number |
| 25 | for (const [index, workerItem] of this.pool.workers.entries()) { |
| 26 | const tasksUsage = workerItem.tasksUsage |
| 27 | const workerTasks = tasksUsage?.run + tasksUsage?.running |
| 28 | if (workerTasks === 0) { |
| 29 | return index |
| 30 | } else if (workerTasks < minNumberOfTasks) { |
| 31 | minNumberOfTasks = workerTasks |
| 32 | lessUsedWorkerKey = index |
| 33 | } |
| 34 | } |
| 35 | return lessUsedWorkerKey |
| 36 | } |
| 37 | |
| 38 | /** {@inheritDoc} */ |
| 39 | public remove (workerKey: number): boolean { |
| 40 | return true |
| 41 | } |
| 42 | } |