feat: emit updates from relay-worker

This commit is contained in:
2024-01-18 12:26:47 +00:00
parent 6d8c0325e4
commit 2d4c323cf7
7 changed files with 135 additions and 46 deletions

View File

@ -5,7 +5,7 @@ import { v4 as uuid } from "uuid";
export class WorkerRelayInterface {
#worker: Worker;
#log = (msg: any) => console.debug(msg);
#commandQueue: Map<string, (v: unknown) => void> = new Map();
#commandQueue: Map<string, (v: unknown, ports: ReadonlyArray<MessagePort>) => void> = new Map();
constructor(path: string) {
this.#log(`Module path: ${path}`);
@ -14,7 +14,7 @@ export class WorkerRelayInterface {
const cmd = e.data as WorkerMessage<any>;
if (cmd.cmd === "reply") {
const q = this.#commandQueue.get(cmd.id);
q?.(cmd);
q?.(cmd, e.ports);
this.#commandQueue.delete(cmd.id);
}
};
@ -37,7 +37,7 @@ export class WorkerRelayInterface {
}
async req(req: ReqCommand) {
return await this.#workerRpc<ReqCommand, Array<NostrEvent>>("req", req);
return await this.#workerRpc<ReqCommand, { results: Array<NostrEvent>; port?: Readonly<MessagePort> }>("req", req);
}
async count(req: ReqCommand) {
@ -48,6 +48,10 @@ export class WorkerRelayInterface {
return await this.#workerRpc<void, Record<string, number>>("summary");
}
async close(id: string) {
return await this.#workerRpc<string, boolean>("close", id);
}
#workerRpc<T, R>(cmd: string, args?: T, timeout = 30_000) {
const id = uuid();
const msg = {
@ -58,13 +62,14 @@ export class WorkerRelayInterface {
this.#worker.postMessage(msg);
return new Promise<R>((resolve, reject) => {
let t: ReturnType<typeof setTimeout>;
this.#commandQueue.set(id, v => {
this.#commandQueue.set(id, (v, ports) => {
clearTimeout(t);
const cmdReply = v as WorkerMessage<R>;
resolve(cmdReply.args);
resolve({ ...cmdReply.args, port: ports.length > 0 ? ports[0] : undefined });
});
t = setTimeout(() => {
reject("timeout");
this.#commandQueue.delete(id);
}, timeout);
});
}