feat: add tasks wait time account per worker
[poolifier.git] / src / pools / selection-strategies / less-busy-worker-choice-strategy.ts
CommitLineData
2fc5cae3
JB
1import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2import type { IPool } from '../pool'
f06e48d8 3import type { IWorker } from '../worker'
168c526f 4import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
bf90656c
JB
5import type {
6 IWorkerChoiceStrategy,
2fc5cae3
JB
7 RequiredStatistics,
8 WorkerChoiceStrategyOptions
bf90656c 9} from './selection-strategies-types'
168c526f
JB
10
11/**
12 * Selects the less 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.
02706357 16 * @typeParam Response - Type of execution response. This can only be serializable data.
168c526f
JB
17 */
18export class LessBusyWorkerChoiceStrategy<
f06e48d8 19 Worker extends IWorker,
b2b1d84e
JB
20 Data = unknown,
21 Response = unknown
bf90656c
JB
22 >
23 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
17393ac8 24 implements IWorkerChoiceStrategy {
afc003b2 25 /** @inheritDoc */
168c526f 26 public readonly requiredStatistics: RequiredStatistics = {
c6bd2650 27 runTime: true,
78099a15 28 avgRunTime: false,
0567595a
JB
29 medRunTime: false,
30 waitTime: false,
31 avgWaitTime: false,
32 medWaitTime: false
168c526f
JB
33 }
34
2fc5cae3
JB
35 /** @inheritDoc */
36 public constructor (
37 pool: IPool<Worker, Data, Response>,
38 opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
39 ) {
40 super(pool, opts)
49be33fe 41 this.setRequiredStatistics(this.opts)
2fc5cae3
JB
42 }
43
afc003b2 44 /** @inheritDoc */
168c526f
JB
45 public reset (): boolean {
46 return true
47 }
48
138d29a8
JB
49 /** @inheritDoc */
50 public update (): boolean {
51 return true
52 }
53
afc003b2 54 /** @inheritDoc */
c923ce56 55 public choose (): number {
cb70b19d 56 const freeWorkerNodeKey = this.findFreeWorkerNodeKey()
f06e48d8
JB
57 if (freeWorkerNodeKey !== -1) {
58 return freeWorkerNodeKey
c141008c 59 }
168c526f 60 let minRunTime = Infinity
f06e48d8 61 let lessBusyWorkerNodeKey!: number
08f3f44c 62 for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
f06e48d8 63 const workerRunTime = workerNode.tasksUsage.runTime
cf9c7b65 64 if (workerRunTime === 0) {
08f3f44c 65 return workerNodeKey
168c526f
JB
66 } else if (workerRunTime < minRunTime) {
67 minRunTime = workerRunTime
08f3f44c 68 lessBusyWorkerNodeKey = workerNodeKey
168c526f
JB
69 }
70 }
f06e48d8 71 return lessBusyWorkerNodeKey
168c526f 72 }
97a2abc3 73
afc003b2 74 /** @inheritDoc */
a4958de2 75 public remove (): boolean {
97a2abc3
JB
76 return true
77 }
168c526f 78}