-import { DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS } from '../../utils'
-import type { IPool } from '../pool'
-import type { IWorker } from '../worker'
-import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy'
+import type { IPool } from '../pool.js'
+import type { IWorker } from '../worker.js'
+import { AbstractWorkerChoiceStrategy } from './abstract-worker-choice-strategy.js'
import type {
IWorkerChoiceStrategy,
- WorkerChoiceStrategyOptions
-} from './selection-strategies-types'
+ WorkerChoiceStrategyOptions,
+} from './selection-strategies-types.js'
/**
* 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 structured-cloneable data.
* @typeParam Response - Type of execution response. This can only be structured-cloneable data.
/** @inheritDoc */
public constructor (
pool: IPool<Worker, Data, Response>,
- opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS
+ opts?: WorkerChoiceStrategyOptions
) {
super(pool, opts)
- this.setTaskStatisticsRequirements(this.opts)
}
/** @inheritDoc */
/** @inheritDoc */
public choose (): number | undefined {
- const chosenWorkerNodeKey = this.leastUsedNextWorkerNodeKey()
- this.assignChosenWorkerNodeKey(chosenWorkerNodeKey)
+ this.setPreviousWorkerNodeKey(this.nextWorkerNodeKey)
+ this.nextWorkerNodeKey = this.leastUsedNextWorkerNodeKey()
return this.nextWorkerNodeKey
}
}
private leastUsedNextWorkerNodeKey (): number | undefined {
- let minNumberOfTasks = Infinity
- let chosenWorkerNodeKey: number | undefined
- for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) {
- const workerTaskStatistics = workerNode.usage.tasks
- const workerTasks =
- workerTaskStatistics.executed +
- workerTaskStatistics.executing +
- workerTaskStatistics.queued
- if (this.isWorkerNodeEligible(workerNodeKey) && workerTasks === 0) {
- chosenWorkerNodeKey = workerNodeKey
- break
- } else if (
- this.isWorkerNodeEligible(workerNodeKey) &&
- workerTasks < minNumberOfTasks
- ) {
- minNumberOfTasks = workerTasks
- chosenWorkerNodeKey = workerNodeKey
- }
- }
- return chosenWorkerNodeKey
+ return this.pool.workerNodes.reduce(
+ (minWorkerNodeKey, workerNode, workerNodeKey, workerNodes) => {
+ return this.isWorkerNodeReady(workerNodeKey) &&
+ workerNode.usage.tasks.executing + workerNode.usage.tasks.queued <
+ workerNodes[minWorkerNodeKey].usage.tasks.executing +
+ workerNodes[minWorkerNodeKey].usage.tasks.queued
+ ? workerNodeKey
+ : minWorkerNodeKey
+ },
+ 0
+ )
}
}