From 78ab25556596c9ca877bb08407559b8156abc819 Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Thu, 6 Apr 2023 00:14:49 +0200 Subject: [PATCH] fix: ensure worker key can't be negative in worker choice strategies MIME-Version: 1.0 Content-Type: text/plain; charset=utf8 Content-Transfer-Encoding: 8bit Signed-off-by: Jérôme Benoit --- CHANGELOG.md | 4 ++++ .../round-robin-worker-choice-strategy.ts | 12 ++++++++---- .../weighted-round-robin-worker-choice-strategy.ts | 12 ++++++++---- 3 files changed, 20 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7db1df47..5a152e22 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 - Add `full` event to dynamic pool. - Keep worker choice strategy usage in memory for conditional reuse. +### Fixed + +- Fix possible negative worker key at worker removal in worker choice strategies. + ## [2.4.1] - 2023-04-05 ### Changed diff --git a/src/pools/selection-strategies/round-robin-worker-choice-strategy.ts b/src/pools/selection-strategies/round-robin-worker-choice-strategy.ts index 9b49d764..91ceb5bc 100644 --- a/src/pools/selection-strategies/round-robin-worker-choice-strategy.ts +++ b/src/pools/selection-strategies/round-robin-worker-choice-strategy.ts @@ -40,10 +40,14 @@ export class RoundRobinWorkerChoiceStrategy< /** {@inheritDoc} */ public remove (workerKey: number): boolean { if (this.nextWorkerId === workerKey) { - this.nextWorkerId = - this.nextWorkerId > this.pool.workers.length - 1 - ? this.pool.workers.length - 1 - : this.nextWorkerId + if (this.pool.workers.length === 0) { + this.nextWorkerId = 0 + } else { + this.nextWorkerId = + this.nextWorkerId > this.pool.workers.length - 1 + ? this.pool.workers.length - 1 + : this.nextWorkerId + } } return true } diff --git a/src/pools/selection-strategies/weighted-round-robin-worker-choice-strategy.ts b/src/pools/selection-strategies/weighted-round-robin-worker-choice-strategy.ts index c700c42a..e1325865 100644 --- a/src/pools/selection-strategies/weighted-round-robin-worker-choice-strategy.ts +++ b/src/pools/selection-strategies/weighted-round-robin-worker-choice-strategy.ts @@ -102,10 +102,14 @@ export class WeightedRoundRobinWorkerChoiceStrategy< /** {@inheritDoc} */ public remove (workerKey: number): boolean { if (this.currentWorkerId === workerKey) { - this.currentWorkerId = - this.currentWorkerId > this.pool.workers.length - 1 - ? this.pool.workers.length - 1 - : this.currentWorkerId + if (this.pool.workers.length === 0) { + this.currentWorkerId = 0 + } else { + this.currentWorkerId = + this.currentWorkerId > this.pool.workers.length - 1 + ? this.pool.workers.length - 1 + : this.currentWorkerId + } } const workerDeleted = this.workersTaskRunTime.delete(workerKey) for (const [key, value] of this.workersTaskRunTime) { -- 2.34.1