X-Git-Url: https://git.piment-noir.org/?a=blobdiff_plain;f=src%2Futils.ts;h=8b88d2afc90424bdc23a4e2746f331295770b15c;hb=75de9f41ce00bec38febd6d82653d3d82f1bb884;hp=7a0ed2f6d0d877f25a57772540bd58083c51b726;hpb=fe8c464daf95d41241d675808d71b955025c1bd2;p=poolifier.git diff --git a/src/utils.ts b/src/utils.ts index 7a0ed2f6..8b88d2af 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -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: 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: 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 }