build(deps-dev): apply updates
[poolifier.git] / src / pools / selection-strategies / least-used-worker-choice-strategy.ts
CommitLineData
d35e5717
JB
1import type { IPool } from '../pool.js'
2import type { IWorker } from '../worker.js'
3import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js'
2fc5cae3
JB
4import type {
5 IWorkerChoiceStrategy,
3a502712 6 WorkerChoiceStrategyOptions,
d35e5717 7} from './selection-strategies-types.js'
bdaf31cd
JB
8
9/**
e4543b14 10 * Selects the least used worker.
38e795c1 11 * @typeParam Worker - Type of worker which manages the strategy.
e102732c
JB
12 * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
13 * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
bdaf31cd 14 */
e4543b14 15export class LeastUsedWorkerChoiceStrategy<
f06e48d8 16 Worker extends IWorker,
b2b1d84e
JB
17 Data = unknown,
18 Response = unknown
bf90656c
JB
19 >
20 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 21 implements IWorkerChoiceStrategy {
2fc5cae3
JB
22 /** @inheritDoc */
23 public constructor (
24 pool: IPool<Worker, Data, Response>,
39618ede 25 opts?: WorkerChoiceStrategyOptions
2fc5cae3
JB
26 ) {
27 super(pool, opts)
2fc5cae3
JB
28 }
29
afc003b2 30 /** @inheritDoc */
a6f7f1b4 31 public reset (): boolean {
ea7a90d3
JB
32 return true
33 }
34
138d29a8
JB
35 /** @inheritDoc */
36 public update (): boolean {
db703c75
JB
37 return true
38 }
39
40 /** @inheritDoc */
b1aae695 41 public choose (): number | undefined {
baca80f7 42 this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey)
fce028d6 43 this.nextWorkerNodeKey = this.leastUsedNextWorkerNodeKey()
b1aae695 44 return this.nextWorkerNodeKey
9b106837
JB
45 }
46
47 /** @inheritDoc */
48 public remove (): boolean {
49 return true
50 }
51
b1aae695 52 private leastUsedNextWorkerNodeKey (): number | undefined {
f3a91bac
JB
53 return this.pool.workerNodes.reduce(
54 (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
ae3ab61d 55 return this.isWorkerNodeReady(workerNodeKey) &&
e0843544
JB
56 workerNode.usage.tasks.executing + workerNode.usage.tasks.queued <
57 workerNodes[minWorkerNodeKey].usage.tasks.executing +
ae3ab61d 58 workerNodes[minWorkerNodeKey].usage.tasks.queued
f3a91bac
JB
59 ? workerNodeKey
60 : minWorkerNodeKey
61 },
62 0
63 )
97a2abc3 64 }
bdaf31cd 65}