From c2de5024932063f77b54225934bb01f6b8056b8c Mon Sep 17 00:00:00 2001 From: =?utf8?q?J=C3=A9r=C3=B4me=20Benoit?= Date: Thu, 26 Nov 2026 00:48:46 +0100 Subject: [PATCH] refactor(pools): address Sonar maintainability findings (#3424) * refactor(pools): address Sonar maintainability findings Separate rank-selection steps and simplify worker-state branches. Aggregate strategy results without allocating temporary arrays. * test(pools): cover strategy updates after failure * test(pools): cover successful strategy aggregation --- src/pools/abstract-pool.ts | 37 ++++--- .../abstract-worker-choice-strategy.ts | 9 +- .../selection-strategies-utils.ts | 8 +- .../worker-choice-strategies-context.ts | 22 +++-- src/pools/utils.ts | 97 ++++++++++++++----- .../worker-choice-strategies-context.test.mjs | 29 ++++++ 6 files changed, 142 insertions(+), 60 deletions(-) diff --git a/src/pools/abstract-pool.ts b/src/pools/abstract-pool.ts index 9a6c66384..7776121ba 100644 --- a/src/pools/abstract-pool.ts +++ b/src/pools/abstract-pool.ts @@ -1224,15 +1224,15 @@ export abstract class AbstractPool< workerNode.registerOnceWorkerEventHandler( 'error', (rawWorkerError: unknown) => { - workerError = - rawWorkerError instanceof Error - ? rawWorkerError - : new Error( - typeof rawWorkerError === 'string' - ? rawWorkerError - : 'Worker failed with a non-Error value', - { cause: rawWorkerError } - ) + if (rawWorkerError instanceof Error) { + workerError = rawWorkerError + } else { + const message = + typeof rawWorkerError === 'string' + ? rawWorkerError + : 'Worker failed with a non-Error value' + workerError = new Error(message, { cause: rawWorkerError }) + } taskResponses = this.captureTaskResponses(workerNode, taskResponses) workerNode.info.ready = false this.emitter?.emit(PoolEvents.error, rawWorkerError) @@ -1274,7 +1274,8 @@ export abstract class AbstractPool< const workerNodeKey = this.workerNodes.indexOf(workerNode) for (const [taskId, promiseResponse] of this.promiseResponseMap) { if (promiseResponse.workerNodeKey === workerNodeKey) { - ;(workerNodeTasks ??= new Map()).set(taskId, promiseResponse) + workerNodeTasks ??= new Map() + workerNodeTasks.set(taskId, promiseResponse) } } } @@ -1643,7 +1644,8 @@ export abstract class AbstractPool< const message = response.message as MessageValue if (message.taskId != null) { this.checkMessageWorkerId(message) - ;(taskResponses ??= []).push(message) + taskResponses ??= [] + taskResponses.push(message) } else if (message.taskFunctionOperationStatus != null) { workerNode.messageChannel.port1.emit('message', message) } @@ -2014,11 +2016,14 @@ export abstract class AbstractPool< abortSignal?: AbortSignal ): Error => { const abortError = abortSignal?.reason as Error | string - return abortError instanceof Error - ? abortError - : typeof abortError === 'string' - ? new Error(abortError) - : new Error(`Task '${taskName}' id '${taskId ?? randomUUID()}' aborted`) + if (abortError instanceof Error) { + return abortError + } + const message = + typeof abortError === 'string' + ? abortError + : `Task '${taskName}' id '${taskId ?? randomUUID()}' aborted` + return new Error(message) } private getQueuedTasks (): number { diff --git a/src/pools/selection-strategies/abstract-worker-choice-strategy.ts b/src/pools/selection-strategies/abstract-worker-choice-strategy.ts index 2abc13599..c2ba42cc9 100644 --- a/src/pools/selection-strategies/abstract-worker-choice-strategy.ts +++ b/src/pools/selection-strategies/abstract-worker-choice-strategy.ts @@ -29,7 +29,7 @@ export abstract class AbstractWorkerChoiceStrategy< public abstract readonly name: WorkerChoiceStrategy /** @inheritDoc */ - public retriesCount: number + public retriesCount = 0 /** @inheritDoc */ public readonly strategyPolicy: StrategyPolicy = Object.freeze({ @@ -48,12 +48,12 @@ export abstract class AbstractWorkerChoiceStrategy< /** * The next worker node key. */ - protected nextWorkerNodeKey: number | undefined + protected nextWorkerNodeKey: number | undefined = 0 /** * The previous worker node key. */ - protected previousWorkerNodeKey: number + protected previousWorkerNodeKey = 0 /** * Constructs a worker choice strategy bound to the pool. @@ -64,9 +64,6 @@ export abstract class AbstractWorkerChoiceStrategy< protected readonly pool: IPool, protected opts?: WorkerChoiceStrategyOptions ) { - this.retriesCount = 0 - this.nextWorkerNodeKey = 0 - this.previousWorkerNodeKey = 0 this.choose = this.choose.bind(this) this.setOptions(this.opts) } diff --git a/src/pools/selection-strategies/selection-strategies-utils.ts b/src/pools/selection-strategies/selection-strategies-utils.ts index 4e496c797..084842ae8 100644 --- a/src/pools/selection-strategies/selection-strategies-utils.ts +++ b/src/pools/selection-strategies/selection-strategies-utils.ts @@ -94,11 +94,9 @@ export const buildWorkerChoiceStrategyOptions = < opts = structuredClone(opts ?? {}) opts.weights = opts.weights ?? getDefaultWeights(pool.info.maxSize) return { - ...{ - elu: { median: false }, - runTime: { median: false }, - waitTime: { median: false }, - }, + elu: { median: false }, + runTime: { median: false }, + waitTime: { median: false }, ...opts, } } diff --git a/src/pools/selection-strategies/worker-choice-strategies-context.ts b/src/pools/selection-strategies/worker-choice-strategies-context.ts index 0348b7106..2b85b02aa 100644 --- a/src/pools/selection-strategies/worker-choice-strategies-context.ts +++ b/src/pools/selection-strategies/worker-choice-strategies-context.ts @@ -144,10 +144,13 @@ export class WorkerChoiceStrategiesContext< * @returns `true` if the removal is successful, `false` otherwise. */ public remove (workerNodeKey: number): boolean { - return Array.from( - this.workerChoiceStrategies, - ([_, workerChoiceStrategy]) => workerChoiceStrategy.remove(workerNodeKey) - ).every(r => r) + let removed = true + for (const workerChoiceStrategy of this.workerChoiceStrategies.values()) { + if (!workerChoiceStrategy.remove(workerNodeKey)) { + removed = false + } + } + return removed } /** @@ -209,10 +212,13 @@ export class WorkerChoiceStrategiesContext< * @returns `true` if the update is successful, `false` otherwise. */ public update (workerNodeKey: number): boolean { - return Array.from( - this.workerChoiceStrategies, - ([_, workerChoiceStrategy]) => workerChoiceStrategy.update(workerNodeKey) - ).every(r => r) + let updated = true + for (const workerChoiceStrategy of this.workerChoiceStrategies.values()) { + if (!workerChoiceStrategy.update(workerNodeKey)) { + updated = false + } + } + return updated } /** diff --git a/src/pools/utils.ts b/src/pools/utils.ts index f3b4ff129..12c605476 100644 --- a/src/pools/utils.ts +++ b/src/pools/utils.ts @@ -802,6 +802,75 @@ const SELECTION_INSERTION_CUTOFF = 12 */ const SELECTION_DEPTH_FACTOR = 2 +/** + * Sorts the inclusive range in place using insertion sort. + * @param data - Array to sort. + * @param left - First index in the range. + * @param right - Last index in the range. + */ +const sortSmallRange = ( + data: Float32Array, + left: number, + right: number +): void => { + for (let i = left + 1; i <= right; i++) { + const value = data[i] + let j = i - 1 + while (j >= left && data[j] > value) { + data[j + 1] = data[j] + --j + } + data[j + 1] = value + } +} + +/** + * Moves the median of the first, middle and last values to the right end. + * @param data - Array containing the pivot candidates. + * @param left - First index in the range. + * @param right - Last index in the range. + * @returns The pivot value. + */ +const movePivotToEnd = ( + data: Float32Array, + left: number, + right: number +): number => { + const middle = (left + right) >> 1 + if (data[middle] < data[left]) swap(data, middle, left) + if (data[right] < data[middle]) { + swap(data, middle, right) + if (data[middle] < data[left]) swap(data, middle, left) + } + const pivot = data[middle] + swap(data, middle, right) + return pivot +} + +/** + * Moves values below the pivot to the start, excluding the pivot slot. + * @param data - Array to partition. + * @param left - First index in the range. + * @param right - Index of the pivot, excluded from partitioning. + * @param pivot - Pivot value. + * @returns The first index after the values below the pivot. + */ +const partitionBelowPivot = ( + data: Float32Array, + left: number, + right: number, + pivot: number +): number => { + let lessEnd = left + for (let i = left; i < right; i++) { + if (data[i] < pivot) { + swap(data, i, lessEnd) + ++lessEnd + } + } + return lessEnd +} + /** * Selects the value at rank `k` of `data[0, size)` in place (partial sort). * Quickselect with median-of-three pivot, insertion cutoff and a depth limit @@ -818,37 +887,15 @@ const selectAtRank = (data: Float32Array, size: number, k: number): number => { for (;;) { const width = right - left + 1 if (width <= SELECTION_INSERTION_CUTOFF) { - for (let i = left + 1; i <= right; i++) { - const value = data[i] - let j = i - 1 - while (j >= left && data[j] > value) { - data[j + 1] = data[j] - --j - } - data[j + 1] = value - } + sortSmallRange(data, left, right) return data[k] } if (--depthLeft < 0) { data.subarray(left, right + 1).sort() return data[k] } - // Median-of-three pivot, stashed at the right end. - const middle = (left + right) >> 1 - if (data[middle] < data[left]) swap(data, middle, left) - if (data[right] < data[middle]) { - swap(data, middle, right) - if (data[middle] < data[left]) swap(data, middle, left) - } - const pivot = data[middle] - swap(data, middle, right) - let lessEnd = left - for (let i = left; i < right; i++) { - if (data[i] < pivot) { - swap(data, i, lessEnd) - ++lessEnd - } - } + const pivot = movePivotToEnd(data, left, right) + const lessEnd = partitionBelowPivot(data, left, right, pivot) let equalEnd = lessEnd for (let i = lessEnd; i < right; i++) { if (data[i] === pivot) { diff --git a/tests/pools/selection-strategies/worker-choice-strategies-context.test.mjs b/tests/pools/selection-strategies/worker-choice-strategies-context.test.mjs index d892d6fce..8cf6ba7a8 100644 --- a/tests/pools/selection-strategies/worker-choice-strategies-context.test.mjs +++ b/tests/pools/selection-strategies/worker-choice-strategies-context.test.mjs @@ -540,6 +540,35 @@ describe('Worker choice strategies context test suite', () => { expect(chosenWorkerKey).toBe(1) }) + it.each([ + ['remove', false], + ['remove', true], + ['update', false], + ['update', true], + ])( + 'Verify that %s() visits every strategy when the first returns %s', + (operation, firstResult) => { + const context = new WorkerChoiceStrategiesContext(fixedPool, [ + WorkerChoiceStrategies.LEAST_USED, + WorkerChoiceStrategies.ROUND_ROBIN, + ]) + const first = stub( + context.workerChoiceStrategies.get(WorkerChoiceStrategies.LEAST_USED), + operation + ).returns(firstResult) + const second = stub( + context.workerChoiceStrategies.get(WorkerChoiceStrategies.ROUND_ROBIN), + operation + ).returns(true) + const workerNodeKey = 1 + + expect(context[operation](workerNodeKey)).toBe(firstResult) + expect(first.calledOnceWithExactly(workerNodeKey)).toBe(true) + expect(second.calledOnceWithExactly(workerNodeKey)).toBe(true) + expect(first.calledBefore(second)).toBe(true) + } + ) + it('Verify that execute() with workerNodeKeys affinity filters worker selection', () => { const workerChoiceStrategiesContext = new WorkerChoiceStrategiesContext( fixedPool -- 2.53.0