This commit is contained in:
Manav Rathi
2024-07-30 19:53:39 +05:30
parent 18cb596d57
commit 3f3d10f57b
3 changed files with 12 additions and 11 deletions

View File

@@ -33,7 +33,7 @@ const log = {
};
/**
* Send a message to the main process using a barebones protocol.
* Send a message to the main process using a barebones RPC protocol.
*/
const mainProcess = (method: string, param: unknown) =>
process.parentPort.postMessage({ method, p: param });

View File

@@ -128,6 +128,6 @@ const handleMessagesFromUtilityProcess = (child: UtilityProcess) => {
break;
}
}
log.info("Ignoring unexpected message from ML worker", m);
log.info("Ignoring unknown message from ML worker", m);
});
};

View File

@@ -63,16 +63,15 @@ globalThis.onmessage = (event: MessageEvent) => {
const IPCResponse = z.object({
id: z.number(),
data: z.any(),
result: z.any().optional(),
error: z.string().optional(),
});
/**
* Our hand-rolled IPC handler and router - the web worker end.
*
* Sibling of the handleMessageFromRenderer function (in `ml-worker.ts`) in the
* desktop code.
* Make a call to the ML worker running in the Node.js layer using our
* hand-rolled RPC protocol. See: [Note: Node.js ML worker RPC protocol].
*/
const electronMLWorker = async (type: string, data: string) => {
const electronMLWorker = async (method: string, p: string) => {
const port = _port;
if (!port) {
throw new Error(
@@ -82,15 +81,17 @@ const electronMLWorker = async (type: string, data: string) => {
// Generate a unique nonce to identify this RPC interaction.
const id = Math.random();
return new Promise((resolve) => {
return new Promise((resolve, reject) => {
const handleMessage = (event: MessageEvent) => {
const response = IPCResponse.parse(event.data);
if (response.id != id) return;
port.removeEventListener("message", handleMessage);
resolve(response.data);
const error = response.error;
if (error) reject(new Error(error));
else resolve(response.result);
};
port.addEventListener("message", handleMessage);
port.postMessage({ type, id, data });
port.postMessage({ id, method, p });
});
};