Commit | Line | Data |
---|---|---|
168c526f JB |
1 | import type { IPoolWorker } from '../pool-worker' |
2 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' | |
bf90656c JB |
3 | import 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 | */ | |
15 | export 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 = { | |
24 | runTime: true | |
25 | } | |
26 | ||
27 | /** {@inheritDoc} */ | |
28 | public reset (): boolean { | |
29 | return true | |
30 | } | |
31 | ||
32 | /** {@inheritDoc} */ | |
c923ce56 | 33 | public choose (): number { |
c141008c | 34 | const freeWorkerKey = this.pool.findFreeWorkerKey() |
bf90656c | 35 | if (!this.isDynamicPool && freeWorkerKey !== -1) { |
c141008c JB |
36 | return freeWorkerKey |
37 | } | |
168c526f | 38 | let minRunTime = Infinity |
c923ce56 JB |
39 | let lessBusyWorkerKey!: number |
40 | for (const [index, workerItem] of this.pool.workers.entries()) { | |
41 | const workerRunTime = workerItem.tasksUsage.runTime | |
cf9c7b65 | 42 | if (workerRunTime === 0) { |
c923ce56 | 43 | return index |
168c526f JB |
44 | } else if (workerRunTime < minRunTime) { |
45 | minRunTime = workerRunTime | |
c923ce56 | 46 | lessBusyWorkerKey = index |
168c526f JB |
47 | } |
48 | } | |
c923ce56 | 49 | return lessBusyWorkerKey |
168c526f | 50 | } |
97a2abc3 JB |
51 | |
52 | /** {@inheritDoc} */ | |
53 | public remove (workerKey: number): boolean { | |
54 | return true | |
55 | } | |
168c526f | 56 | } |