bf67b80e84ef257bd8d10ffe86946a53b2433b8a
[poolifier.git] / src / pools / selection-strategies / abstract-worker-choice-strategy.ts
1 import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
2 import type { IPool } from '../pool'
3 import type { IWorker } from '../worker'
4 import type {
5 IWorkerChoiceStrategy,
6 RequiredStatistics,
7 WorkerChoiceStrategyOptions
8 } from './selection-strategies-types'
9
10 /**
11 * Worker choice strategy abstract base class.
12 *
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.
15 * @typeParam Response - Type of execution response. This can only be serializable data.
16 */
17 export abstract class AbstractWorkerChoiceStrategy<
18 Worker extends IWorker,
19 Data = unknown,
20 Response = unknown
21 > implements IWorkerChoiceStrategy {
22 /**
23 * Toggles finding the last free worker node key.
24 */
25 private toggleFindLastFreeWorkerNodeKey: boolean = false
26 /** @inheritDoc */
27 public readonly requiredStatistics: RequiredStatistics = {
28 runTime: false,
29 avgRunTime: false,
30 medRunTime: false
31 }
32
33 /**
34 * Constructs a worker choice strategy bound to the pool.
35 *
36 * @param pool - The pool instance.
37 * @param opts - The worker choice strategy options.
38 */
39 public constructor (
40 protected readonly pool: IPool<Worker, Data, Response>,
41 protected opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
42 ) {
43 this.choose = this.choose.bind(this)
44 }
45
46 protected checkOptions (opts: WorkerChoiceStrategyOptions): void {
47 if (this.requiredStatistics.avgRunTime && opts.medRunTime === true) {
48 this.requiredStatistics.avgRunTime = false
49 this.requiredStatistics.medRunTime = opts.medRunTime as boolean
50 }
51 if (this.requiredStatistics.medRunTime && opts.medRunTime === false) {
52 this.requiredStatistics.avgRunTime = true
53 this.requiredStatistics.medRunTime = opts.medRunTime as boolean
54 }
55 if (
56 opts.weights != null &&
57 Object.keys(opts.weights).length < this.pool.size
58 ) {
59 throw new Error(
60 'Worker choice strategy options must have a weight for each worker node.'
61 )
62 }
63 }
64
65 /** @inheritDoc */
66 public abstract reset (): boolean
67
68 /** @inheritDoc */
69 public abstract update (workerNodeKey: number): boolean
70
71 /** @inheritDoc */
72 public abstract choose (): number
73
74 /** @inheritDoc */
75 public abstract remove (workerNodeKey: number): boolean
76
77 /** @inheritDoc */
78 public setOptions (opts: WorkerChoiceStrategyOptions): void {
79 opts = opts ?? DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
80 this.checkOptions(opts)
81 this.opts = opts
82 }
83
84 /**
85 * Finds a free worker node key.
86 *
87 * @returns The free worker node key or `-1` if there is no free worker node.
88 */
89 protected findFreeWorkerNodeKey (): number {
90 if (this.toggleFindLastFreeWorkerNodeKey) {
91 this.toggleFindLastFreeWorkerNodeKey = false
92 return this.findLastFreeWorkerNodeKey()
93 }
94 this.toggleFindLastFreeWorkerNodeKey = true
95 return this.findFirstFreeWorkerNodeKey()
96 }
97
98 /**
99 * Finds the first free worker node key based on the number of tasks the worker has applied.
100 *
101 * If a worker is found with `0` running tasks, it is detected as free and its worker node key is returned.
102 *
103 * If no free worker is found, `-1` is returned.
104 *
105 * @returns A worker node key if there is one, `-1` otherwise.
106 */
107 private findFirstFreeWorkerNodeKey (): number {
108 return this.pool.workerNodes.findIndex(workerNode => {
109 return workerNode.tasksUsage.running === 0
110 })
111 }
112
113 /**
114 * Finds the last free worker node key based on the number of tasks the worker has applied.
115 *
116 * If a worker is found with `0` running tasks, it is detected as free and its worker node key is returned.
117 *
118 * If no free worker is found, `-1` is returned.
119 *
120 * @returns A worker node key if there is one, `-1` otherwise.
121 */
122 private findLastFreeWorkerNodeKey (): number {
123 // It requires node >= 18.0.0:
124 // return this.workerNodes.findLastIndex(workerNode => {
125 // return workerNode.tasksUsage.running === 0
126 // })
127 for (
128 let workerNodeKey = this.pool.workerNodes.length - 1;
129 workerNodeKey >= 0;
130 workerNodeKey--
131 ) {
132 if (this.pool.workerNodes[workerNodeKey].tasksUsage.running === 0) {
133 return workerNodeKey
134 }
135 }
136 return -1
137 }
138 }