refactor: align findFreeWorkerKey() return type with findIndex()
[poolifier.git] / src / pools / selection-strategies / less-busy-worker-choice-strategy.ts
1 import type { IPoolWorker } from '../pool-worker'
2 import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
3 import type {
4 IWorkerChoiceStrategy,
5 RequiredStatistics
6 } from './selection-strategies-types'
7
8 /**
9 * Selects the less busy worker.
10 *
11 * @typeParam Worker - Type of worker which manages the strategy.
12 * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
13 * @typeParam Response - Type of response of execution. This can only be serializable data.
14 */
15 export class LessBusyWorkerChoiceStrategy<
16 Worker extends IPoolWorker,
17 Data,
18 Response
19 >
20 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
21 implements IWorkerChoiceStrategy {
22 /** {@inheritDoc} */
23 public readonly requiredStatistics: RequiredStatistics = {
24 runTime: true
25 }
26
27 /** {@inheritDoc} */
28 public reset (): boolean {
29 return true
30 }
31
32 /** {@inheritDoc} */
33 public choose (): number {
34 const freeWorkerKey = this.pool.findFreeWorkerKey()
35 if (!this.isDynamicPool && freeWorkerKey !== -1) {
36 return freeWorkerKey
37 }
38 let minRunTime = Infinity
39 let lessBusyWorkerKey!: number
40 for (const [index, workerItem] of this.pool.workers.entries()) {
41 const workerRunTime = workerItem.tasksUsage.runTime
42 if (workerRunTime === 0) {
43 return index
44 } else if (workerRunTime < minRunTime) {
45 minRunTime = workerRunTime
46 lessBusyWorkerKey = index
47 }
48 }
49 return lessBusyWorkerKey
50 }
51
52 /** {@inheritDoc} */
53 public remove (workerKey: number): boolean {
54 return true
55 }
56 }