UNPKG

redis-smq-common

Version:

RedisSMQ Common Library provides many components that are mainly used by RedisSMQ and RedisSMQ Monitor.

57 lines 2.09 kB
import { statSync } from 'fs'; import { extname } from 'path'; import { isMainThread, parentPort, workerData, } from 'worker_threads'; import { EWorkerThreadChildExitCode, EWorkerType, } from '../types/index.js'; import { handleWorkerCallable } from './worker-thread-callable.js'; import { exit } from './worker-thread-message.js'; import { handleWorkerRunnable } from './worker-thread-runnable.js'; function importWorkerInstance(filename, cb) { if (!['.js', '.cjs'].includes(extname(filename))) { exit(EWorkerThreadChildExitCode.FILE_EXTENSION_ERROR); } try { statSync(filename); } catch (e) { exit(EWorkerThreadChildExitCode.FILE_READ_ERROR, e); } import(filename) .then((importedModule) => { const fn = typeof importedModule !== 'function' && importedModule.default ? importedModule.default : importedModule; if (typeof fn !== 'function') { exit(EWorkerThreadChildExitCode.INVALID_WORKER_TYPE); } else cb(fn); }) .catch(() => { exit(EWorkerThreadChildExitCode.FILE_IMPORT_ERROR); }); } function isRunnableFunctionFactory(worker, type) { return type === EWorkerType.RUNNABLE; } if (!isMainThread && parentPort) { const { filename, type, initialPayload } = typeof workerData === 'object' ? workerData : {}; if (!filename || type === null || type === undefined || ![EWorkerType.CALLABLE, EWorkerType.RUNNABLE].includes(type)) { exit(EWorkerThreadChildExitCode.WORKER_DATA_REQUIRED); } else { const messagePort = parentPort; importWorkerInstance(filename, (worker) => { if (isRunnableFunctionFactory(worker, type)) handleWorkerRunnable(worker, messagePort, initialPayload); else handleWorkerCallable(worker, messagePort); }); } process.on('uncaughtException', (err) => { exit(EWorkerThreadChildExitCode.UNCAUGHT_EXCEPTION, err); }); } //# sourceMappingURL=worker-thread.js.map