Commit | Line | Data |
---|---|---|
2fc5cae3 JB |
1 | import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils' |
2 | import type { IPool } from '../pool' | |
f06e48d8 | 3 | import type { IWorker } from '../worker' |
168c526f | 4 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' |
bf90656c JB |
5 | import 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 | */ |
18 | export 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 JB |
28 | avgRunTime: false, |
29 | medRunTime: false | |
168c526f JB |
30 | } |
31 | ||
2fc5cae3 JB |
32 | /** @inheritDoc */ |
33 | public constructor ( | |
34 | pool: IPool<Worker, Data, Response>, | |
35 | opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS | |
36 | ) { | |
37 | super(pool, opts) | |
a20f0ba5 | 38 | this.checkOptions(this.opts) |
2fc5cae3 JB |
39 | } |
40 | ||
afc003b2 | 41 | /** @inheritDoc */ |
168c526f JB |
42 | public reset (): boolean { |
43 | return true | |
44 | } | |
45 | ||
afc003b2 | 46 | /** @inheritDoc */ |
c923ce56 | 47 | public choose (): number { |
cb70b19d | 48 | const freeWorkerNodeKey = this.findFreeWorkerNodeKey() |
f06e48d8 JB |
49 | if (freeWorkerNodeKey !== -1) { |
50 | return freeWorkerNodeKey | |
c141008c | 51 | } |
168c526f | 52 | let minRunTime = Infinity |
f06e48d8 | 53 | let lessBusyWorkerNodeKey!: number |
08f3f44c | 54 | for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) { |
f06e48d8 | 55 | const workerRunTime = workerNode.tasksUsage.runTime |
cf9c7b65 | 56 | if (workerRunTime === 0) { |
08f3f44c | 57 | return workerNodeKey |
168c526f JB |
58 | } else if (workerRunTime < minRunTime) { |
59 | minRunTime = workerRunTime | |
08f3f44c | 60 | lessBusyWorkerNodeKey = workerNodeKey |
168c526f JB |
61 | } |
62 | } | |
f06e48d8 | 63 | return lessBusyWorkerNodeKey |
168c526f | 64 | } |
97a2abc3 | 65 | |
afc003b2 | 66 | /** @inheritDoc */ |
f06e48d8 | 67 | public remove (workerNodeKey: number): boolean { |
97a2abc3 JB |
68 | return true |
69 | } | |
168c526f | 70 | } |