-import { WorkerOptions, WorkerProcessType } from '../types/Worker';
+import { isMainThread } from 'node:worker_threads';
-import Utils from '../utils/Utils';
-import WorkerAbstract from './WorkerAbstract';
-import WorkerDynamicPool from './WorkerDynamicPool';
-import WorkerSet from './WorkerSet';
-import WorkerStaticPool from './WorkerStaticPool';
-import { isMainThread } from 'worker_threads';
+import type { WorkerAbstract } from './WorkerAbstract';
+import { DEFAULT_WORKER_OPTIONS } from './WorkerConstants';
+import { WorkerDynamicPool } from './WorkerDynamicPool';
+import { WorkerFixedPool } from './WorkerFixedPool';
+import { WorkerSet } from './WorkerSet';
+import { type WorkerData, type WorkerOptions, WorkerProcessType } from './WorkerTypes';
-export default class WorkerFactory {
- public static getWorkerImplementation<T>(workerScript: string, workerProcessType: WorkerProcessType, options?: WorkerOptions): WorkerAbstract {
+export class WorkerFactory {
+ private constructor() {
+ // This is intentional
+ }
+
+ public static getWorkerImplementation<T extends WorkerData>(
+ workerScript: string,
+ workerProcessType: WorkerProcessType,
+ workerOptions?: WorkerOptions,
+ ): WorkerAbstract<T> | undefined {
if (!isMainThread) {
- throw new Error('Trying to get a worker implementation outside the main thread');
- }
- if (Utils.isUndefined(options)) {
- options = {} as WorkerOptions;
+ throw new Error('Cannot get a worker implementation outside the main thread');
}
+ workerOptions = { ...DEFAULT_WORKER_OPTIONS, ...workerOptions };
+ let workerImplementation: WorkerAbstract<T>;
switch (workerProcessType) {
- case WorkerProcessType.WORKER_SET:
- if (Utils.isUndefined(options.elementsPerWorker)) {
- options.elementsPerWorker = 1;
- }
- return new WorkerSet<T>(workerScript, options.elementsPerWorker);
- case WorkerProcessType.STATIC_POOL:
- if (Utils.isUndefined(options.poolMaxSize)) {
- options.poolMaxSize = 16;
- }
- return new WorkerStaticPool<T>(workerScript, options.poolMaxSize);
- case WorkerProcessType.DYNAMIC_POOL:
- if (Utils.isUndefined(options.poolMinSize)) {
- options.poolMinSize = 4;
- }
- if (Utils.isUndefined(options.poolMaxSize)) {
- options.poolMaxSize = 16;
- }
- return new WorkerDynamicPool<T>(workerScript, options.poolMinSize, options.poolMaxSize);
+ case WorkerProcessType.workerSet:
+ workerImplementation = new WorkerSet(workerScript, workerOptions);
+ break;
+ case WorkerProcessType.fixedPool:
+ workerImplementation = new WorkerFixedPool(workerScript, workerOptions);
+ break;
+ case WorkerProcessType.dynamicPool:
+ workerImplementation = new WorkerDynamicPool(workerScript, workerOptions);
+ break;
default:
- return null;
+ // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
+ throw new Error(`Worker implementation type '${workerProcessType}' not found`);
}
+ return workerImplementation;
}
}