acf1e5036aeed44a7ae8f6d11394160b95aec10a
[poolifier.git] / src / pools / selection-strategies / less-used-worker-choice-strategy.ts
1 import type { IWorker } from '../worker'
2 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
3 import type { IWorkerChoiceStrategy } from './selection-strategies-types'
4
5 /**
6 * Selects the less used worker.
7 *
8 * @typeParam Worker - Type of worker which manages the strategy.
9 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
10 * @typeParam Response - Type of response of execution. This can only be serializable data.
11 */
12 export class LessUsedWorkerChoiceStrategy<
13 Worker extends IWorker,
14 Data = unknown,
15 Response = unknown
16 >
17 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
18 implements IWorkerChoiceStrategy {
19 /** @inheritDoc */
20 public reset (): boolean {
21 return true
22 }
23
24 /** @inheritDoc */
25 public choose (): number {
26 const freeWorkerNodeKey = this.pool.findFreeWorkerNodeKey()
27 if (freeWorkerNodeKey !== -1) {
28 return freeWorkerNodeKey
29 }
30 let minNumberOfTasks = Infinity
31 let lessUsedWorkerNodeKey!: number
32 for (const [index, workerNode] of this.pool.workerNodes.entries()) {
33 const tasksUsage = workerNode.tasksUsage
34 const workerTasks = tasksUsage.run + tasksUsage.running
35 if (workerTasks === 0) {
36 return index
37 } else if (workerTasks < minNumberOfTasks) {
38 minNumberOfTasks = workerTasks
39 lessUsedWorkerNodeKey = index
40 }
41 }
42 return lessUsedWorkerNodeKey
43 }
44
45 /** @inheritDoc */
46 public remove (workerNodeKey: number): boolean {
47 return true
48 }
49 }