feat: add less busy worker choice strategy
[poolifier.git] / src / pools / selection-strategies / less-used-worker-choice-strategy.ts
CommitLineData
ea7a90d3 1import type { IPoolWorker } from '../pool-worker'
bdaf31cd
JB
2import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
3
4/**
737c6d97 5 * Selects the less used worker.
bdaf31cd 6 *
38e795c1
JB
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.
bdaf31cd 10 */
737c6d97 11export class LessUsedWorkerChoiceStrategy<
ea7a90d3 12 Worker extends IPoolWorker,
bdaf31cd
JB
13 Data,
14 Response
15> extends AbstractWorkerChoiceStrategy<Worker, Data, Response> {
38e795c1 16 /** {@inheritDoc} */
a6f7f1b4 17 public reset (): boolean {
ea7a90d3
JB
18 return true
19 }
20
38e795c1 21 /** {@inheritDoc} */
bdaf31cd 22 public choose (): Worker {
f4ff1ce2 23 let minNumberOfTasks = Infinity
168c526f 24 let lessUsedWorker!: Worker
ffcbbad8
JB
25 for (const value of this.pool.workers.values()) {
26 const worker = value.worker
3032893a 27 const tasksUsage = this.pool.getWorkerTasksUsage(worker)
f4ff1ce2 28 const workerTasks =
3032893a 29 (tasksUsage?.run as number) + (tasksUsage?.running as number)
f4ff1ce2 30 if (!this.isDynamicPool && workerTasks === 0) {
bdaf31cd 31 return worker
f4ff1ce2
JB
32 } else if (workerTasks < minNumberOfTasks) {
33 minNumberOfTasks = workerTasks
168c526f 34 lessUsedWorker = worker
bdaf31cd
JB
35 }
36 }
168c526f 37 return lessUsedWorker
bdaf31cd
JB
38 }
39}