]> Piment Noir Git Repositories - poolifier.git/commitdiff
refactor(pools): simplify cluster option handling (#3426)
authorJérôme Benoit <jerome.benoit@piment-noir.org>
Thu, 26 Nov 2026 18:38:21 +0000 (19:38 +0100)
committerGitHub <noreply@github.com>
Thu, 26 Nov 2026 18:38:21 +0000 (19:38 +0100)
* refactor(pools): simplify cluster option handling

Separate stdio entry validation from slot materialization and share
case-insensitive key selection across environment sources.

* test(cluster): cover option precedence edge cases

* test(cluster): verify Windows key order independence

src/pools/utils.ts
tests/pools/utils.test.mjs

index ce26b75e4d45697e643db840933068b0b4371c60..08beb6d8f3dc2307d6d5a9c04c98919ebe2390a9 100644 (file)
@@ -223,6 +223,35 @@ const getStdioControlValue = (
   return descriptor.value
 }
 
+const validateClusterStdioEntry = (entry: unknown): void => {
+  if (typeof entry !== 'object' || entry === null) {
+    return
+  }
+  const fdOwner = getPropertyOwner(entry, 'fd')
+  const fdValue = getStdioControlValue(entry, 'fd', fdOwner)
+  if (typeof fdValue === 'number') {
+    if (fdOwner === Object.prototype) {
+      throw new TypeError(
+        "Invalid cluster.settings.stdio entry: inherited 'fd' from Object.prototype is not allowed"
+      )
+    }
+    return
+  }
+  for (const key of ['handle', '_handle']) {
+    const owner = getPropertyOwner(entry, key)
+    const value = getStdioControlValue(entry, key, owner)
+    if (
+      owner === Object.prototype &&
+      ((typeof value === 'object' && value !== null) ||
+        typeof value === 'function')
+    ) {
+      throw new TypeError(
+        `Invalid cluster.settings.stdio entry: inherited '${key}' from Object.prototype is not allowed`
+      )
+    }
+  }
+}
+
 /**
  * Materializes missing cluster stdio slots and validates object-valued entries
  * before Node reads them.
@@ -239,32 +268,7 @@ export const validateAndMaterializeClusterStdio = (stdio: unknown): void => {
     }
   }
   for (const entry of stdio as unknown[]) {
-    if (typeof entry !== 'object' || entry === null) {
-      continue
-    }
-    const fdOwner = getPropertyOwner(entry, 'fd')
-    const fdValue = getStdioControlValue(entry, 'fd', fdOwner)
-    if (typeof fdValue === 'number') {
-      if (fdOwner === Object.prototype) {
-        throw new TypeError(
-          "Invalid cluster.settings.stdio entry: inherited 'fd' from Object.prototype is not allowed"
-        )
-      }
-      continue
-    }
-    for (const key of ['handle', '_handle']) {
-      const owner = getPropertyOwner(entry, key)
-      const value = getStdioControlValue(entry, key, owner)
-      if (
-        owner === Object.prototype &&
-        ((typeof value === 'object' && value !== null) ||
-          typeof value === 'function')
-      ) {
-        throw new TypeError(
-          `Invalid cluster.settings.stdio entry: inherited '${key}' from Object.prototype is not allowed`
-        )
-      }
-    }
+    validateClusterStdioEntry(entry)
   }
 }
 
@@ -290,6 +294,43 @@ const normalizeResourceLimits = (resourceLimits: object): object => {
   return normalizedResourceLimits
 }
 
+const getCaseInsensitiveEnvironmentKeys = (
+  source: object
+): Map<string, string> => {
+  const entries = new Map<string, string>()
+  for (const key of Object.keys(source)) {
+    const logicalKey = key.toUpperCase()
+    const previousKey = entries.get(logicalKey)
+    if (previousKey == null || key < previousKey) {
+      entries.set(logicalKey, key)
+    }
+  }
+  return entries
+}
+
+const mergeCaseInsensitiveEnvironmentEntries = (
+  processEnv: NodeJS.ProcessEnv,
+  workerEnv: Record<string, unknown> | undefined
+): Map<string, { key: string; value: unknown }> => {
+  const effectiveEntries = new Map<string, { key: string; value: unknown }>()
+  for (const source of [processEnv, workerEnv]) {
+    if (source == null) {
+      continue
+    }
+    for (const [logicalKey, sourceKey] of getCaseInsensitiveEnvironmentKeys(
+      source
+    )) {
+      const previousEntry = effectiveEntries.get(logicalKey)
+      const key =
+        previousEntry != null && previousEntry.key < sourceKey
+          ? previousEntry.key
+          : sourceKey
+      effectiveEntries.set(logicalKey, { key, value: source[sourceKey] })
+    }
+  }
+  return effectiveEntries
+}
+
 /**
  * Builds the environment passed through Node's cluster boundary.
  * @param processEnv - The process environment.
@@ -316,37 +357,11 @@ export const buildClusterWorkerEnvironment = (
     return environment
   }
 
-  const effectiveEntries = new Map<string, { key: string; value: unknown }>()
-  for (const source of [processEnv, workerEnv]) {
-    if (source == null) {
-      continue
-    }
-    const sourceEntries = new Map<string, string>()
-    for (const key of Object.keys(source)) {
-      const logicalKey = key.toUpperCase()
-      const previousKey = sourceEntries.get(logicalKey)
-      if (previousKey == null || key < previousKey) {
-        sourceEntries.set(logicalKey, key)
-      }
-    }
-    for (const [logicalKey, sourceKey] of sourceEntries) {
-      const previousEntry = effectiveEntries.get(logicalKey)
-      const key =
-        previousEntry != null && previousEntry.key < sourceKey
-          ? previousEntry.key
-          : sourceKey
-      effectiveEntries.set(logicalKey, { key, value: source[sourceKey] })
-    }
-  }
-
-  const prototypeEntries = new Map<string, string>()
-  for (const key of Object.keys(Object.prototype)) {
-    const logicalKey = key.toUpperCase()
-    const previousKey = prototypeEntries.get(logicalKey)
-    if (previousKey == null || key < previousKey) {
-      prototypeEntries.set(logicalKey, key)
-    }
-  }
+  const effectiveEntries = mergeCaseInsensitiveEnvironmentEntries(
+    processEnv,
+    workerEnv
+  )
+  const prototypeEntries = getCaseInsensitiveEnvironmentKeys(Object.prototype)
 
   const environment = Object.create(null) as Record<string, unknown>
   for (const [logicalKey, effectiveEntry] of effectiveEntries) {
index 7bf5ae3f7b591b091461f32dd31f2f4afa0e09b6..894de1d72bf3e0ce8ec661ba98c5a6fb24cdd9c9 100644 (file)
@@ -2,7 +2,7 @@ import { Worker as ClusterWorker } from 'node:cluster'
 import { once } from 'node:events'
 import { PassThrough } from 'node:stream'
 import { SHARE_ENV, Worker as ThreadWorker } from 'node:worker_threads'
-import { describe, expect, it } from 'vitest'
+import { describe, expect, it, vi } from 'vitest'
 
 import { CircularBuffer } from '../../lib/circular-buffer.mjs'
 import { WorkerTypes } from '../../lib/index.mjs'
@@ -127,6 +127,27 @@ describe('Pool utils test suite', () => {
     )
   })
 
+  it.each([
+    ['path', 'PATH'],
+    ['PATH', 'path'],
+  ])(
+    'selects the smallest Windows key within one source ordered %s, %s',
+    (firstKey, secondKey) => {
+      const processEnvironment = {
+        [firstKey]: `${firstKey}-value`,
+        [secondKey]: `${secondKey}-value`,
+      }
+      const environment = buildClusterWorkerEnvironment(
+        processEnvironment,
+        undefined,
+        true
+      )
+
+      expect(Object.keys(environment)).toStrictEqual(['PATH'])
+      expect(environment.PATH).toBe('PATH-value')
+    }
+  )
+
   it('uses Object.prototype keys to mask Windows environment variants', () => {
     // eslint-disable-next-line no-extend-native
     Object.defineProperty(Object.prototype, 'NODE_OPTIONS', {
@@ -419,23 +440,22 @@ parentPort.postMessage({
     }
   })
 
-  it('accepts numeric stdio fd before irrelevant inherited controls', () => {
-    const opaqueStdioEntry = Object.create({})
+  it('skips stdio handle controls when fd is numeric', () => {
+    const readHandle = vi.fn()
+    const opaqueStdioEntry = Object.create(
+      Object.defineProperties(
+        {},
+        {
+          _handle: { get: readHandle },
+          handle: { get: readHandle },
+        }
+      )
+    )
     Object.defineProperty(opaqueStdioEntry, 'fd', { value: 0 })
-    // eslint-disable-next-line no-extend-native
-    Object.defineProperty(Object.prototype, 'handle', {
-      configurable: true,
-      enumerable: true,
-      value: -1,
-      writable: true,
-    })
-    try {
-      expect(() =>
-        validateAndMaterializeClusterStdio([opaqueStdioEntry])
-      ).not.toThrow()
-    } finally {
-      Reflect.deleteProperty(Object.prototype, 'handle')
-    }
+
+    validateAndMaterializeClusterStdio([opaqueStdioEntry])
+
+    expect(readHandle).not.toHaveBeenCalled()
   })
 
   it('ignores nonnumeric inherited fd before a legitimate handle', () => {