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' |
bdaf31cd | 4 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy' |
2fc5cae3 JB |
5 | import type { |
6 | IWorkerChoiceStrategy, | |
7 | WorkerChoiceStrategyOptions | |
8 | } from './selection-strategies-types' | |
bdaf31cd JB |
9 | |
10 | /** | |
e4543b14 | 11 | * Selects the least used worker. |
bdaf31cd | 12 | * |
38e795c1 JB |
13 | * @typeParam Worker - Type of worker which manages the strategy. |
14 | * @typeParam Data - Type of data sent to the worker. This can only be serializable data. | |
02706357 | 15 | * @typeParam Response - Type of execution response. This can only be serializable data. |
bdaf31cd | 16 | */ |
e4543b14 | 17 | export class LeastUsedWorkerChoiceStrategy< |
f06e48d8 | 18 | Worker extends IWorker, |
b2b1d84e JB |
19 | Data = unknown, |
20 | Response = unknown | |
bf90656c JB |
21 | > |
22 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> | |
17393ac8 | 23 | implements IWorkerChoiceStrategy { |
2fc5cae3 JB |
24 | /** @inheritDoc */ |
25 | public constructor ( | |
26 | pool: IPool<Worker, Data, Response>, | |
27 | opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS | |
28 | ) { | |
29 | super(pool, opts) | |
49be33fe | 30 | this.setRequiredStatistics(this.opts) |
2fc5cae3 JB |
31 | } |
32 | ||
afc003b2 | 33 | /** @inheritDoc */ |
a6f7f1b4 | 34 | public reset (): boolean { |
ea7a90d3 JB |
35 | return true |
36 | } | |
37 | ||
138d29a8 JB |
38 | /** @inheritDoc */ |
39 | public update (): boolean { | |
40 | return true | |
41 | } | |
42 | ||
afc003b2 | 43 | /** @inheritDoc */ |
c923ce56 | 44 | public choose (): number { |
cb70b19d | 45 | const freeWorkerNodeKey = this.findFreeWorkerNodeKey() |
f06e48d8 JB |
46 | if (freeWorkerNodeKey !== -1) { |
47 | return freeWorkerNodeKey | |
c141008c | 48 | } |
f4ff1ce2 | 49 | let minNumberOfTasks = Infinity |
e4543b14 | 50 | let leastUsedWorkerNodeKey!: number |
08f3f44c | 51 | for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) { |
f06e48d8 | 52 | const tasksUsage = workerNode.tasksUsage |
1ab50fe5 | 53 | const workerTasks = tasksUsage.ran + tasksUsage.running |
cf9c7b65 | 54 | if (workerTasks === 0) { |
08f3f44c | 55 | return workerNodeKey |
f4ff1ce2 JB |
56 | } else if (workerTasks < minNumberOfTasks) { |
57 | minNumberOfTasks = workerTasks | |
e4543b14 | 58 | leastUsedWorkerNodeKey = workerNodeKey |
bdaf31cd JB |
59 | } |
60 | } | |
e4543b14 | 61 | return leastUsedWorkerNodeKey |
bdaf31cd | 62 | } |
97a2abc3 | 63 | |
afc003b2 | 64 | /** @inheritDoc */ |
a4958de2 | 65 | public remove (): boolean { |
97a2abc3 JB |
66 | return true |
67 | } | |
bdaf31cd | 68 | } |