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