Commit | Line | Data |
---|---|---|
be245fda | 1 | import { isMainThread } from 'node:worker_threads'; |
b8da29bc | 2 | |
268a74bb | 3 | import type { WorkerAbstract } from './WorkerAbstract'; |
769d3b10 | 4 | import { DEFAULT_WORKER_OPTIONS } from './WorkerConstants'; |
268a74bb JB |
5 | import { WorkerDynamicPool } from './WorkerDynamicPool'; |
6 | import { WorkerSet } from './WorkerSet'; | |
7 | import { WorkerStaticPool } from './WorkerStaticPool'; | |
8 | import { type WorkerData, type WorkerOptions, WorkerProcessType } from './WorkerTypes'; | |
6013bc53 | 9 | |
268a74bb | 10 | export class WorkerFactory { |
6c3cfef8 JB |
11 | private constructor() { |
12 | // This is intentional | |
13 | } | |
8df3f0a9 | 14 | |
e7aeea18 JB |
15 | public static getWorkerImplementation<T extends WorkerData>( |
16 | workerScript: string, | |
17 | workerProcessType: WorkerProcessType, | |
5edd8ba0 | 18 | workerOptions?: WorkerOptions, |
e7aeea18 | 19 | ): WorkerAbstract<T> | null { |
ded13d97 | 20 | if (!isMainThread) { |
44a95b7f | 21 | throw new Error('Cannot get a worker implementation outside the main thread'); |
ded13d97 | 22 | } |
4a3807d1 | 23 | workerOptions = { ...DEFAULT_WORKER_OPTIONS, ...workerOptions }; |
1895299d | 24 | let workerImplementation: WorkerAbstract<T> | null = null; |
535aaa27 | 25 | switch (workerProcessType) { |
721646e9 | 26 | case WorkerProcessType.workerSet: |
d070d967 | 27 | workerImplementation = new WorkerSet(workerScript, workerOptions); |
535aaa27 | 28 | break; |
721646e9 | 29 | case WorkerProcessType.staticPool: |
d070d967 | 30 | workerImplementation = new WorkerStaticPool(workerScript, workerOptions); |
535aaa27 | 31 | break; |
721646e9 | 32 | case WorkerProcessType.dynamicPool: |
d070d967 | 33 | workerImplementation = new WorkerDynamicPool(workerScript, workerOptions); |
535aaa27 | 34 | break; |
fb226c9b | 35 | default: |
3fa0f0ed | 36 | // eslint-disable-next-line @typescript-eslint/restrict-template-expressions |
fb226c9b | 37 | throw new Error(`Worker implementation type '${workerProcessType}' not found`); |
6013bc53 | 38 | } |
535aaa27 | 39 | return workerImplementation; |
6013bc53 JB |
40 | } |
41 | } |