perf: allow finer grained control over tasks usage computation
[poolifier.git] / src / pools / selection-strategies / less-busy-worker-choice-strategy.ts
CommitLineData
168c526f
JB
1import type { IPoolWorker } from '../pool-worker'
2import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
bf90656c
JB
3import type {
4 IWorkerChoiceStrategy,
5 RequiredStatistics
6} from './selection-strategies-types'
168c526f
JB
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 */
15export class LessBusyWorkerChoiceStrategy<
bf90656c
JB
16 Worker extends IPoolWorker,
17 Data,
18 Response
19 >
20 extends AbstractWorkerChoiceStrategy<Worker, Data, Response>
21 implements IWorkerChoiceStrategy {
168c526f
JB
22 /** {@inheritDoc} */
23 public readonly requiredStatistics: RequiredStatistics = {
c6bd2650
JB
24 runTime: true,
25 avgRunTime: false
168c526f
JB
26 }
27
28 /** {@inheritDoc} */
29 public reset (): boolean {
30 return true
31 }
32
33 /** {@inheritDoc} */
c923ce56 34 public choose (): number {
c141008c 35 const freeWorkerKey = this.pool.findFreeWorkerKey()
bf90656c 36 if (!this.isDynamicPool && freeWorkerKey !== -1) {
c141008c
JB
37 return freeWorkerKey
38 }
168c526f 39 let minRunTime = Infinity
c923ce56
JB
40 let lessBusyWorkerKey!: number
41 for (const [index, workerItem] of this.pool.workers.entries()) {
42 const workerRunTime = workerItem.tasksUsage.runTime
cf9c7b65 43 if (workerRunTime === 0) {
c923ce56 44 return index
168c526f
JB
45 } else if (workerRunTime < minRunTime) {
46 minRunTime = workerRunTime
c923ce56 47 lessBusyWorkerKey = index
168c526f
JB
48 }
49 }
c923ce56 50 return lessBusyWorkerKey
168c526f 51 }
97a2abc3
JB
52
53 /** {@inheritDoc} */
54 public remove (workerKey: number): boolean {
55 return true
56 }
168c526f 57}