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