* Selects the least used worker.
*
* @typeParam Worker - Type of worker which manages the strategy.
- * @typeParam Data - Type of data sent to the worker. This can only be serializable data.
- * @typeParam Response - Type of execution response. This can only be serializable data.
+ * @typeParam Data - Type of data sent to the worker. This can only be structured-cloneable data.
+ * @typeParam Response - Type of execution response. This can only be structured-cloneable data.
*/
export class LeastUsedWorkerChoiceStrategy<
Worker extends IWorker,
opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
) {
super(pool, opts)
- this.setRequiredStatistics(this.opts)
+ this.setTaskStatisticsRequirements(this.opts)
}
/** @inheritDoc */
/** @inheritDoc */
public choose (): number {
- const freeWorkerNodeKey = this.findFreeWorkerNodeKey()
- if (freeWorkerNodeKey !== -1) {
- return freeWorkerNodeKey
- }
- let minNumberOfTasks = Infinity
- let leastUsedWorkerNodeKey!: number
- for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
- const tasksUsage = workerNode.tasksUsage
- const workerTasks = tasksUsage.ran + tasksUsage.running
- if (workerTasks === 0) {
- return workerNodeKey
- } else if (workerTasks < minNumberOfTasks) {
- minNumberOfTasks = workerTasks
- leastUsedWorkerNodeKey = workerNodeKey
- }
- }
- return leastUsedWorkerNodeKey
+ return this.leastUsedNextWorkerNodeKey()
}
/** @inheritDoc */
public remove (): boolean {
return true
}
+
+ private leastUsedNextWorkerNodeKey (): number {
+ let minNumberOfTasks = Infinity
+ for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
+ const workerTaskStatistics = workerNode.usage.tasks
+ const workerTasks =
+ workerTaskStatistics.executed +
+ workerTaskStatistics.executing +
+ workerTaskStatistics.queued
+ if (this.isWorkerNodeReady(workerNodeKey) && workerTasks === 0) {
+ this.nextWorkerNodeKey = workerNodeKey
+ break
+ } else if (
+ this.isWorkerNodeReady(workerNodeKey) &&
+ workerTasks < minNumberOfTasks
+ ) {
+ minNumberOfTasks = workerTasks
+ this.nextWorkerNodeKey = workerNodeKey
+ }
+ }
+ return this.nextWorkerNodeKey
+ }
}