refactor: spell fixes
[poolifier.git] / src / pools / selection-strategies / least-busy-worker-choice-strategy.ts
1 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2 import type { IPool } from '../pool'
3 import type { IWorker } from '../worker'
4 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
5 import type {
6 IWorkerChoiceStrategy,
7 RequiredStatistics,
8 WorkerChoiceStrategyOptions
9 } from './selection-strategies-types'
10
11 /**
12 * Selects the least busy worker.
13 *
14 * @typeParam Worker - Type of worker which manages the strategy.
15 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
16 * @typeParam Response - Type of execution response. This can only be serializable data.
17 */
18 export class LeastBusyWorkerChoiceStrategy<
19 Worker extends IWorker,
20 Data = unknown,
21 Response = unknown
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
24 implements IWorkerChoiceStrategy {
25 /** @inheritDoc */
26 public readonly requiredStatistics: RequiredStatistics = {
27 runTime: true,
28 avgRunTime: false,
29 medRunTime: false
30 }
31
32 /** @inheritDoc */
33 public constructor (
34 pool: IPool<Worker, Data, Response>,
35 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
36 ) {
37 super(pool, opts)
38 this.setRequiredStatistics(this.opts)
39 }
40
41 /** @inheritDoc */
42 public reset (): boolean {
43 return true
44 }
45
46 /** @inheritDoc */
47 public update (): boolean {
48 return true
49 }
50
51 /** @inheritDoc */
52 public choose (): number {
53 const freeWorkerNodeKey = this.findFreeWorkerNodeKey()
54 if (freeWorkerNodeKey !== -1) {
55 return freeWorkerNodeKey
56 }
57 let minRunTime = Infinity
58 let leastBusyWorkerNodeKey!: number
59 for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
60 const workerRunTime = workerNode.tasksUsage.runTime
61 if (workerRunTime === 0) {
62 return workerNodeKey
63 } else if (workerRunTime < minRunTime) {
64 minRunTime = workerRunTime
65 leastBusyWorkerNodeKey = workerNodeKey
66 }
67 }
68 return leastBusyWorkerNodeKey
69 }
70
71 /** @inheritDoc */
72 public remove (): boolean {
73 return true
74 }
75 }