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