| 1 | import { isMainThread } from 'node:worker_threads' |
| 2 | |
| 3 | import { mergeDeepRight } from 'rambda' |
| 4 | |
| 5 | import type { WorkerAbstract } from './WorkerAbstract.js' |
| 6 | import { DEFAULT_WORKER_OPTIONS } from './WorkerConstants.js' |
| 7 | import { WorkerDynamicPool } from './WorkerDynamicPool.js' |
| 8 | import { WorkerFixedPool } from './WorkerFixedPool.js' |
| 9 | import { WorkerSet } from './WorkerSet.js' |
| 10 | import { type WorkerData, type WorkerOptions, WorkerProcessType } from './WorkerTypes.js' |
| 11 | |
| 12 | // eslint-disable-next-line @typescript-eslint/no-extraneous-class |
| 13 | export class WorkerFactory { |
| 14 | private constructor () { |
| 15 | // This is intentional |
| 16 | } |
| 17 | |
| 18 | public static getWorkerImplementation<D extends WorkerData, R extends WorkerData>( |
| 19 | workerScript: string, |
| 20 | workerProcessType: WorkerProcessType, |
| 21 | workerOptions?: WorkerOptions |
| 22 | ): WorkerAbstract<D, R> { |
| 23 | if (!isMainThread) { |
| 24 | throw new Error('Cannot get a worker implementation outside the main thread') |
| 25 | } |
| 26 | workerOptions = mergeDeepRight<WorkerOptions>(DEFAULT_WORKER_OPTIONS, workerOptions ?? {}) |
| 27 | switch (workerProcessType) { |
| 28 | case WorkerProcessType.workerSet: |
| 29 | return new WorkerSet<D, R>(workerScript, workerOptions) |
| 30 | case WorkerProcessType.fixedPool: |
| 31 | return new WorkerFixedPool<D, R>(workerScript, workerOptions) |
| 32 | case WorkerProcessType.dynamicPool: |
| 33 | return new WorkerDynamicPool<D, R>(workerScript, workerOptions) |
| 34 | default: |
| 35 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
| 36 | throw new Error(`Worker implementation type '${workerProcessType}' not found`) |
| 37 | } |
| 38 | } |
| 39 | } |