fix: fix worker choice strategy options handling
[poolifier.git] / src / pools / selection-strategies / less-used-worker-choice-strategy.ts
CommitLineData
2fc5cae3
JB
1import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2import type { IPool } from '../pool'
f06e48d8 3import type { IWorker } from '../worker'
bdaf31cd 4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
2fc5cae3
JB
5import type {
6 IWorkerChoiceStrategy,
7 WorkerChoiceStrategyOptions
8} from './selection-strategies-types'
bdaf31cd
JB
9
10/**
737c6d97 11 * Selects the less used worker.
bdaf31cd 12 *
38e795c1
JB
13 * @typeParam Worker - Type of worker which manages the strategy.
14 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
02706357 15 * @typeParam Response - Type of execution response. This can only be serializable data.
bdaf31cd 16 */
737c6d97 17export class LessUsedWorkerChoiceStrategy<
f06e48d8 18 Worker extends IWorker,
b2b1d84e
JB
19 Data = unknown,
20 Response = unknown
bf90656c
JB
21 >
22 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 23 implements IWorkerChoiceStrategy {
2fc5cae3
JB
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.checkOptions(opts)
31 }
32
afc003b2 33 /** @inheritDoc */
a6f7f1b4 34 public reset (): boolean {
ea7a90d3
JB
35 return true
36 }
37
afc003b2 38 /** @inheritDoc */
c923ce56 39 public choose (): number {
f06e48d8
JB
40 const freeWorkerNodeKey = this.pool.findFreeWorkerNodeKey()
41 if (freeWorkerNodeKey !== -1) {
42 return freeWorkerNodeKey
c141008c 43 }
f4ff1ce2 44 let minNumberOfTasks = Infinity
f06e48d8
JB
45 let lessUsedWorkerNodeKey!: number
46 for (const [index, workerNode] of this.pool.workerNodes.entries()) {
47 const tasksUsage = workerNode.tasksUsage
53cf3405 48 const workerTasks = tasksUsage.run + tasksUsage.running
cf9c7b65 49 if (workerTasks === 0) {
c923ce56 50 return index
f4ff1ce2
JB
51 } else if (workerTasks < minNumberOfTasks) {
52 minNumberOfTasks = workerTasks
f06e48d8 53 lessUsedWorkerNodeKey = index
bdaf31cd
JB
54 }
55 }
f06e48d8 56 return lessUsedWorkerNodeKey
bdaf31cd 57 }
97a2abc3 58
afc003b2 59 /** @inheritDoc */
f06e48d8 60 public remove (workerNodeKey: number): boolean {
97a2abc3
JB
61 return true
62 }
bdaf31cd 63}