]>
Commit | Line | Data |
---|---|---|
d35e5717 JB |
1 | import type { IPool } from '../pool.js' |
2 | import type { IWorker } from '../worker.js' | |
2fc5cae3 JB |
3 | import type { |
4 | IWorkerChoiceStrategy, | |
3a502712 | 5 | WorkerChoiceStrategyOptions, |
d35e5717 | 6 | } from './selection-strategies-types.js' |
bdaf31cd | 7 | |
97231086 JB |
8 | import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js' |
9 | ||
bdaf31cd | 10 | /** |
e4543b14 | 11 | * Selects the least used worker. |
38e795c1 | 12 | * @typeParam Worker - Type of worker which manages the strategy. |
e102732c JB |
13 | * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data. |
14 | * @typeParam Response - Type of execution response. This can only be structured-cloneable data. | |
bdaf31cd | 15 | */ |
e4543b14 | 16 | export class LeastUsedWorkerChoiceStrategy< |
f06e48d8 | 17 | Worker extends IWorker, |
b2b1d84e JB |
18 | Data = unknown, |
19 | Response = unknown | |
bf90656c JB |
20 | > |
21 | extends AbstractWorkerChoiceStrategy<Worker, Data, Response> | |
17393ac8 | 22 | implements IWorkerChoiceStrategy { |
2fc5cae3 JB |
23 | /** @inheritDoc */ |
24 | public constructor ( | |
25 | pool: IPool<Worker, Data, Response>, | |
39618ede | 26 | opts?: WorkerChoiceStrategyOptions |
2fc5cae3 JB |
27 | ) { |
28 | super(pool, opts) | |
2fc5cae3 JB |
29 | } |
30 | ||
db703c75 | 31 | /** @inheritDoc */ |
b1aae695 | 32 | public choose (): number | undefined { |
baca80f7 | 33 | this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey) |
fce028d6 | 34 | this.nextWorkerNodeKey = this.leastUsedNextWorkerNodeKey() |
b1aae695 | 35 | return this.nextWorkerNodeKey |
9b106837 JB |
36 | } |
37 | ||
38 | /** @inheritDoc */ | |
39 | public remove (): boolean { | |
40 | return true | |
41 | } | |
42 | ||
97231086 JB |
43 | /** @inheritDoc */ |
44 | public reset (): boolean { | |
45 | return true | |
46 | } | |
47 | ||
48 | /** @inheritDoc */ | |
49 | public update (): boolean { | |
50 | return true | |
97a2abc3 | 51 | } |
5de88a2a JB |
52 | |
53 | private leastUsedNextWorkerNodeKey (): number | undefined { | |
54 | return this.pool.workerNodes.reduce( | |
55 | (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => { | |
56 | return this.isWorkerNodeReady(workerNodeKey) && | |
57 | workerNode.usage.tasks.executing + workerNode.usage.tasks.queued < | |
58 | workerNodes[minWorkerNodeKey].usage.tasks.executing + | |
59 | workerNodes[minWorkerNodeKey].usage.tasks.queued | |
60 | ? workerNodeKey | |
61 | : minWorkerNodeKey | |
62 | }, | |
63 | 0 | |
64 | ) | |
65 | } | |
bdaf31cd | 66 | } |