@hirosystems/api-toolkit
Version:
API development toolkit
67 lines • 2.86 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.filename = void 0;
const WorkerThreads = require("node:worker_threads");
const serialize_error_1 = require("./serialize-error");
// Minimal worker thread initialization code. This file is the entry point for worker threads
// and is responsible for setting up the worker environment and handling messages from the main thread.
// Imports should be kept to a minimum to avoid in worker thread init overhead and memory usage.
exports.filename = __filename;
/**
* Invokes a function that may return a value or a promise, and passes the result
* to a callback in a consistent format. Handles both synchronous and asynchronous cases,
* ensuring type safety and avoiding unnecessary async transitions for sync functions.
*/
function getMaybePromiseResult(fn, cb) {
try {
const maybePromise = fn();
if (maybePromise instanceof Promise) {
maybePromise.then(ok => cb({ ok }), (err) => cb({ err }));
}
else {
cb({ ok: maybePromise });
}
}
catch (err) {
cb({ err });
}
}
// Check if this file is being run in a worker thread. If so, it will set up the worker environment.
if (!WorkerThreads.isMainThread && WorkerThreads.workerData?.workerFile) {
const { workerFile } = WorkerThreads.workerData;
// eslint-disable-next-line @typescript-eslint/no-require-imports, @typescript-eslint/no-var-requires
const workerModule = require(workerFile);
const parentPort = WorkerThreads.parentPort;
// Determine if the worker module `processTask` function is a default export or a named export.
const processTask = 'default' in workerModule ? workerModule.default.processTask : workerModule.processTask;
parentPort.on('messageerror', err => {
console.error(`Worker thread message error`, err);
});
parentPort.on('message', (message) => {
const msg = message;
getMaybePromiseResult(() => processTask(...msg.req), result => {
try {
let reply;
if (result.ok) {
reply = {
msgId: msg.msgId,
resp: result.ok,
};
}
else {
const error = (0, serialize_error_1.isErrorLike)(result.err) ? (0, serialize_error_1.serializeError)(result.err) : result.err;
reply = {
msgId: msg.msgId,
error,
};
}
parentPort.postMessage(reply);
}
catch (err) {
console.error(`Critical bug in work task processing`, err);
}
});
});
parentPort.postMessage('ready');
}
//# sourceMappingURL=worker-thread-init.js.map