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 | 16 | Worker extends IPoolWorker, |
b2b1d84e JB |
17 | Data = unknown, |
18 | Response = unknown | |
bf90656c JB |
19 | > |
20 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> | |
17393ac8 | 21 | implements IWorkerChoiceStrategy { |
afc003b2 | 22 | /** @inheritDoc */ |
168c526f | 23 | public readonly requiredStatistics: RequiredStatistics = { |
c6bd2650 | 24 | runTime: true, |
78099a15 JB |
25 | avgRunTime: false, |
26 | medRunTime: false | |
168c526f JB |
27 | } |
28 | ||
afc003b2 | 29 | /** @inheritDoc */ |
168c526f JB |
30 | public reset (): boolean { |
31 | return true | |
32 | } | |
33 | ||
afc003b2 | 34 | /** @inheritDoc */ |
c923ce56 | 35 | public choose (): number { |
c141008c | 36 | const freeWorkerKey = this.pool.findFreeWorkerKey() |
965415bb | 37 | if (freeWorkerKey !== -1) { |
c141008c JB |
38 | return freeWorkerKey |
39 | } | |
168c526f | 40 | let minRunTime = Infinity |
c923ce56 JB |
41 | let lessBusyWorkerKey!: number |
42 | for (const [index, workerItem] of this.pool.workers.entries()) { | |
43 | const workerRunTime = workerItem.tasksUsage.runTime | |
cf9c7b65 | 44 | if (workerRunTime === 0) { |
c923ce56 | 45 | return index |
168c526f JB |
46 | } else if (workerRunTime < minRunTime) { |
47 | minRunTime = workerRunTime | |
c923ce56 | 48 | lessBusyWorkerKey = index |
168c526f JB |
49 | } |
50 | } | |
c923ce56 | 51 | return lessBusyWorkerKey |
168c526f | 52 | } |
97a2abc3 | 53 | |
afc003b2 | 54 | /** @inheritDoc */ |
97a2abc3 JB |
55 | public remove (workerKey: number): boolean { |
56 | return true | |
57 | } | |
168c526f | 58 | } |