]> Piment Noir Git Repositories - poolifier.git/commitdiff
refactor(pools): address Sonar maintainability findings (#3424)
authorJérôme Benoit <jerome.benoit@piment-noir.org>
Wed, 25 Nov 2026 23:48:46 +0000 (00:48 +0100)
committerGitHub <noreply@github.com>
Wed, 25 Nov 2026 23:48:46 +0000 (00:48 +0100)
* 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
src/pools/selection-strategies/abstract-worker-choice-strategy.ts
src/pools/selection-strategies/selection-strategies-utils.ts
src/pools/selection-strategies/worker-choice-strategies-context.ts
src/pools/utils.ts
tests/pools/selection-strategies/worker-choice-strategies-context.test.mjs

index 9a6c6638421f58b25f692e4df4f4c610b228a375..7776121bafd2befa84046544ae2d46a7c6e37dee 100644 (file)
@@ -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<Response>
       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 {
index 2abc13599f52ce29b294a099cca434894c56e996..c2ba42cc9b28d7a44d3325d16a0534eed9116952 100644 (file)
@@ -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<Worker, Data, Response>,
     protected opts?: WorkerChoiceStrategyOptions
   ) {
-    this.retriesCount = 0
-    this.nextWorkerNodeKey = 0
-    this.previousWorkerNodeKey = 0
     this.choose = this.choose.bind(this)
     this.setOptions(this.opts)
   }
index 4e496c797904b0f6e79dea16cfffba334f96f333..084842ae86f3d35a77d57da352ec7960de7e4cb6 100644 (file)
@@ -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,
   }
 }
index 0348b7106071184a6788de0ccaab09b82d8d31e5..2b85b02aa9ac0dd1f8122a2b826d10a20b092c8e 100644 (file)
@@ -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
   }
 
   /**
index f3b4ff1298d98f7afe38bc64657327f0bbae55bd..12c605476b078bb6a3a9a1e8364d712daa2f1c4b 100644 (file)
@@ -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) {
index d892d6fce90bbbb45caed9b22e96f133b2caebd9..8cf6ba7a89a0353f517db83c041cf95a295571c4 100644 (file)
@@ -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