refactor: cleanup direct access to worker id
[poolifier.git] / src / utils.ts
index 7a0ed2f6d0d877f25a57772540bd58083c51b726..8b88d2afc90424bdc23a4e2746f331295770b15c 100644 (file)
@@ -1,10 +1,18 @@
 import * as os from 'node:os'
+import { webcrypto } from 'node:crypto'
+import { Worker as ClusterWorker } from 'node:cluster'
+import { Worker as ThreadWorker } from 'node:worker_threads'
 import type {
   MeasurementStatisticsRequirements,
   WorkerChoiceStrategyOptions
 } from './pools/selection-strategies/selection-strategies-types'
 import type { KillBehavior } from './worker/worker-options'
-import type { MeasurementStatistics } from './pools/worker'
+import {
+  type IWorker,
+  type MeasurementStatistics,
+  type WorkerType,
+  WorkerTypes
+} from './pools/worker'
 
 /**
  * Default task name.
@@ -108,6 +116,41 @@ export const average = (dataSet: number[]): number => {
   )
 }
 
+/**
+ * Returns the worker type of the given worker.
+ *
+ * @param worker - The worker to get the type of.
+ * @returns The worker type of the given worker.
+ * @internal
+ */
+export const getWorkerType = <Worker extends IWorker>(
+  worker: Worker
+): WorkerType | undefined => {
+  if (worker instanceof ThreadWorker) {
+    return WorkerTypes.thread
+  }
+  if (worker instanceof ClusterWorker) {
+    return WorkerTypes.cluster
+  }
+}
+
+/**
+ * Returns the worker id of the given worker.
+ *
+ * @param worker - The worker to get the id of.
+ * @returns The worker id of the given worker.
+ * @internal
+ */
+export const getWorkerId = <Worker extends IWorker>(
+  worker: Worker
+): number | undefined => {
+  if (worker instanceof ThreadWorker) {
+    return worker.threadId
+  } else if (worker instanceof ClusterWorker) {
+    return worker.id
+  }
+}
+
 /**
  * Computes the median of the given data set.
  *
@@ -253,5 +296,5 @@ export const once = (
  * @returns A number in the [0,1[ range
  */
 export const secureRandom = (): number => {
-  return crypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000
+  return webcrypto.getRandomValues(new Uint32Array(1))[0] / 0x100000000
 }