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

requestResponseMessage handlers optimization #651

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
41 changes: 27 additions & 14 deletions src/comlink.ts
Original file line number Diff line number Diff line change
Expand Up @@ -388,10 +388,12 @@ function isMessagePort(endpoint: Endpoint): endpoint is MessagePort {
}

function closeEndPoint(endpoint: Endpoint) {
endpoint.removeEventListener("message", handleMessage);
if (isMessagePort(endpoint)) endpoint.close();
}

export function wrap<T>(ep: Endpoint, target?: any): Remote<T> {
ep.addEventListener("message", handleMessage);
return createProxy<T>(ep, [], target) as any;
}

Expand Down Expand Up @@ -593,25 +595,36 @@ function fromWireValue(value: WireValue): any {
}
}

const messageResolvers: Map<string, (value: WireValue | PromiseLike<WireValue>) => void> = new Map();

function handleMessage(ev: Event) {
const { data } = ev as MessageEvent;
if (!data || !data.id) {
return;
}
const resolver = messageResolvers.get(data.id);
if (resolver) {
try {
resolver(data);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this would benefit from a try/finally to ensure that you always delete the processed ID.

} finally {
messageResolvers.delete(data.id);
}
}
}

function requestResponseMessage(
ep: Endpoint,
msg: Message,
transfers?: Transferable[]
): Promise<WireValue> {
return new Promise((resolve) => {
const id = generateUUID();
ep.addEventListener("message", function l(ev: MessageEvent) {
if (!ev.data || !ev.data.id || ev.data.id !== id) {
return;
}
ep.removeEventListener("message", l as any);
resolve(ev.data);
} as any);
if (ep.start) {
ep.start();
}
ep.postMessage({ id, ...msg }, transfers);
});
return new Promise((resolve) => {
const id = generateUUID();
messageResolvers.set(id, resolve);
if (ep.start) {
ep.start();
}
ep.postMessage({ id, ...msg }, transfers);
});
}

function generateUUID(): string {
Expand Down