refactor: explicity extends Task for MessageValue type
[poolifier.git] / src / pools / selection-strategies / less-used-worker-choice-strategy.ts
CommitLineData
f06e48d8 1import type { IWorker } from '../worker'
bdaf31cd 2import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
bf90656c 3import type { IWorkerChoiceStrategy } from './selection-strategies-types'
bdaf31cd
JB
4
5/**
737c6d97 6 * Selects the less used worker.
bdaf31cd 7 *
38e795c1
JB
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.
02706357 10 * @typeParam Response - Type of execution response. This can only be serializable data.
bdaf31cd 11 */
737c6d97 12export class LessUsedWorkerChoiceStrategy<
f06e48d8 13 Worker extends IWorker,
b2b1d84e
JB
14 Data = unknown,
15 Response = unknown
bf90656c
JB
16 >
17 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 18 implements IWorkerChoiceStrategy {
afc003b2 19 /** @inheritDoc */
a6f7f1b4 20 public reset (): boolean {
ea7a90d3
JB
21 return true
22 }
23
afc003b2 24 /** @inheritDoc */
c923ce56 25 public choose (): number {
f06e48d8
JB
26 const freeWorkerNodeKey = this.pool.findFreeWorkerNodeKey()
27 if (freeWorkerNodeKey !== -1) {
28 return freeWorkerNodeKey
c141008c 29 }
f4ff1ce2 30 let minNumberOfTasks = Infinity
f06e48d8
JB
31 let lessUsedWorkerNodeKey!: number
32 for (const [index, workerNode] of this.pool.workerNodes.entries()) {
33 const tasksUsage = workerNode.tasksUsage
53cf3405 34 const workerTasks = tasksUsage.run + tasksUsage.running
cf9c7b65 35 if (workerTasks === 0) {
c923ce56 36 return index
f4ff1ce2
JB
37 } else if (workerTasks < minNumberOfTasks) {
38 minNumberOfTasks = workerTasks
f06e48d8 39 lessUsedWorkerNodeKey = index
bdaf31cd
JB
40 }
41 }
f06e48d8 42 return lessUsedWorkerNodeKey
bdaf31cd 43 }
97a2abc3 44
afc003b2 45 /** @inheritDoc */
f06e48d8 46 public remove (workerNodeKey: number): boolean {
97a2abc3
JB
47 return true
48 }
bdaf31cd 49}