Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rewrite invoke without ports #1958

Closed
wants to merge 6 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 18 additions & 9 deletions impress.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,20 +100,29 @@ const startWorker = async (app, kind, port, id = ++impress.lastWorkerId) => {
},

invoke: async (msg) => {
const { status, port, exclusive } = msg;
if (status === 'done') return void app.pool.release(worker);
const promisedThread = exclusive ? app.pool.capture() : app.pool.next();
const next = await promisedThread.catch(() => {
const error = new Error('No thread available');
port.postMessage({ name: 'error', error });
const { from, to, exclusive } = msg;
if (to) {
const back = app.threads.get(to);
return void back.postMessage(msg);
}
const promised = exclusive ? app.pool.capture() : app.pool.next();
const next = await promised.catch(() => {
const error = { message: 'No thread available' };
const back = app.threads.get(from);
const data = { id, status: 'error', error };
back.postMessage({ name: 'invoke', to: from, data });
return null;
});
if (!next) return;
next.postMessage(msg, [port]);
next.postMessage(msg);
},

release: () => {
app.pool.release(worker);
},

terminate: (msg) => {
process.emit('TERMINATE', msg.code);
terminate: ({ code }) => {
process.emit('TERMINATE', code);
},
};

Expand Down
4 changes: 3 additions & 1 deletion lib/deps.js
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ node.StringDecoder = node['string_decoder'];
node.perfHooks = node['perf_hooks'];
node.asyncHooks = node['async_hooks'];
node.fsp = node.fs.promises;
node.timers.promises = require('node:timers/promises');
if (!node.timers.promises) {
node.timers.promises = require('node:timers/promises');
}

Object.freeze(node);
Object.freeze(npm);
Expand Down
68 changes: 37 additions & 31 deletions lib/worker.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
'use strict';

const { node, metarhia, notLoaded, wt } = require('./deps.js');
const { MessageChannel, parentPort, threadId, workerData } = wt;
const { parentPort, threadId, workerData } = wt;

const application = require('./application.js');

Expand All @@ -22,17 +22,21 @@ process.on('warning', logError('warning'));
process.on('uncaughtException', logError('uncaughtException'));
process.on('unhandledRejection', logError('unhandledRejection'));

let callId = 0;
const calls = new Map();

const invoke = async ({ method, args, exclusive = false }) => {
const { port1: port, port2 } = new MessageChannel();
const data = { method, args };
const msg = { name: 'invoke', exclusive, data, port };
const id = ++callId;
const data = { type: 'call', id, method, args };
const msg = { name: 'invoke', from: threadId, exclusive, data };
return new Promise((resolve, reject) => {
port2.on('message', ({ error, data }) => {
port2.close();
const handler = ({ error, result }) => {
calls.delete(id);
if (error) reject(error);
else resolve(data);
});
parentPort.postMessage(msg, [port]);
else resolve(result);
};
calls.set(id, handler);
parentPort.postMessage(msg);
});
};

Expand All @@ -48,34 +52,36 @@ const handlers = {
process.exit(0);
},

invoke: async ({ exclusive, data, port }) => {
const { method, args } = data;
invoke: async ({ from, to, exclusive, data }) => {
if (to) {
const { id, status, error, result } = data;
const handler = calls.get(id);
const err = status === 'error' ? new Error(error.message) : null;
return void handler({ error: err, result });
}
const { sandbox, config } = application;
const msg = { name: 'invoke', to: from };
const { timeout } = config.server.workers;
const { id, method, args } = data;
const handler = metarhia.metautil.namespaceByPath(sandbox, method);
if (!handler) {
const error = new Error('Handler not found');
return void port.postMessage({ name: 'error', error });
const error = { message: 'Handler not found' };
const data = { id, status: 'error', error };
return void parentPort.postMessage({ ...msg, data });
}
const msg = { name: 'invoke', status: 'done' };
const { timeout } = config.server.workers;
try {
let result;
if (timeout) {
const ac = new AbortController();
result = await Promise.race([
metarhia.metautil.timeout(timeout, ac.signal),
handler(args),
]);
ac.abort();
} else {
result = await handler(args);
}
port.postMessage({ ...msg, data: result });
} catch (error) {
port.postMessage({ name: 'error', error });
application.console.error(error.stack);
let promise = handler(args);
if (timeout) promise = metarhia.metautil.timeoutify(promise, timeout);
const result = await promise;
const data = { id, status: 'done', result };
parentPort.postMessage({ ...msg, data });
} catch (err) {
const error = { message: err.message };
const data = { id, status: 'error', error };
parentPort.postMessage({ ...msg, data });
application.console.error(err.stack);
} finally {
if (exclusive) parentPort.postMessage(msg);
if (exclusive) parentPort.postMessage({ name: 'release' });
}
},
};
Expand Down
Loading