Commit | Line | Data |
---|---|---|
168c526f JB |
1 | import type { IPoolWorker } from '../pool-worker' |
2 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' | |
3 | import type { RequiredStatistics } from './selection-strategies-types' | |
4 | ||
5 | /** | |
6 | * Selects the less busy worker. | |
7 | * | |
8 | * @typeParam Worker - Type of worker which manages the strategy. | |
9 | * @typeParam Data - Type of data sent to the worker. This can only be serializable data. | |
10 | * @typeParam Response - Type of response of execution. This can only be serializable data. | |
11 | */ | |
12 | export class LessBusyWorkerChoiceStrategy< | |
13 | Worker extends IPoolWorker, | |
14 | Data, | |
15 | Response | |
16 | > extends AbstractWorkerChoiceStrategy<Worker, Data, Response> { | |
17 | /** {@inheritDoc} */ | |
18 | public readonly requiredStatistics: RequiredStatistics = { | |
19 | runTime: true | |
20 | } | |
21 | ||
22 | /** {@inheritDoc} */ | |
23 | public reset (): boolean { | |
24 | return true | |
25 | } | |
26 | ||
27 | /** {@inheritDoc} */ | |
28 | public choose (): Worker { | |
29 | let minRunTime = Infinity | |
30 | let lessBusyWorker!: Worker | |
31 | for (const value of this.pool.workers.values()) { | |
32 | const worker = value.worker | |
33 | const workerRunTime = this.pool.getWorkerTasksUsage(worker) | |
34 | ?.runTime as number | |
35 | if (!this.isDynamicPool && workerRunTime === 0) { | |
36 | return worker | |
37 | } else if (workerRunTime < minRunTime) { | |
38 | minRunTime = workerRunTime | |
39 | lessBusyWorker = worker | |
40 | } | |
41 | } | |
42 | return lessBusyWorker | |
43 | } | |
44 | } |