X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Fpools%2Fselection-strategies%2Fleast-used-worker-choice-strategy.ts;h=d0adbcd7b77c4ef095f25fced318148498f42935;hb=9fe8fd698590c2494dc6793cfd8c08026fe88a31;hp=85e145a041b7868bc96565091a0beec16b7b6d89;hpb=5a5fc090d6f7eb9248df1ba5c0ff4d001461b6d4;p=poolifier.git diff --git a/src/pools/selection-strategies/least-used-worker-choice-strategy.ts b/src/pools/selection-strategies/least-used-worker-choice-strategy.ts index 85e145a0..d0adbcd7 100644 --- a/src/pools/selection-strategies/least-used-worker-choice-strategy.ts +++ b/src/pools/selection-strategies/least-used-worker-choice-strategy.ts @@ -11,8 +11,8 @@ import type { * 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, @@ -27,7 +27,7 @@ export class LeastUsedWorkerChoiceStrategy< opts: WorkerChoiceStrategyOptions = DEFAULT_WORKER_CHOICE_STRATEGY_OPTIONS ) { super(pool, opts) - this.setRequiredStatistics(this.opts) + this.setTaskStatisticsRequirements(this.opts) } /** @inheritDoc */ @@ -41,28 +41,36 @@ export class LeastUsedWorkerChoiceStrategy< } /** @inheritDoc */ - public choose (): number { - const freeWorkerNodeKey = this.findFreeWorkerNodeKey() - if (freeWorkerNodeKey !== -1) { - return freeWorkerNodeKey - } + public choose (): number | undefined { + this.nextWorkerNodeKey = this.leastUsedNextWorkerNodeKey() + return this.nextWorkerNodeKey + } + + /** @inheritDoc */ + public remove (): boolean { + return true + } + + private leastUsedNextWorkerNodeKey (): number | undefined { let minNumberOfTasks = Infinity - let leastUsedWorkerNodeKey!: number + let chosenWorkerNodeKey: number | undefined for (const [workerNodeKey, workerNode] of this.pool.workerNodes.entries()) { - const tasksUsage = workerNode.tasksUsage - const workerTasks = tasksUsage.run + tasksUsage.running + if (!this.isWorkerNodeEligible(workerNodeKey)) { + continue + } + const workerTaskStatistics = workerNode.usage.tasks + const workerTasks = + workerTaskStatistics.executed + + workerTaskStatistics.executing + + workerTaskStatistics.queued if (workerTasks === 0) { - return workerNodeKey + chosenWorkerNodeKey = workerNodeKey + break } else if (workerTasks < minNumberOfTasks) { minNumberOfTasks = workerTasks - leastUsedWorkerNodeKey = workerNodeKey + chosenWorkerNodeKey = workerNodeKey } } - return leastUsedWorkerNodeKey - } - - /** @inheritDoc */ - public remove (): boolean { - return true + return chosenWorkerNodeKey } }