comlink icon indicating copy to clipboard operation
comlink copied to clipboard

Re-proxying across threads

Open eyyyyyyy3 opened this issue 1 year ago • 2 comments

Let's say we have the main thread A and the web worker B which is spawned by A and the web worker C which is spawned by B. Now we create a callback function within C that we want to attach to some event in A. In C we proxy the callback function as follows: const proxyListener = Comlink.proxy(listener); and then pass the proxy to B. Is it necessary to re-proxy the proxy from C in B to A? I tested it and it works without re-proxying but I don't know if this is the right way of doing it.

eyyyyyyy3 avatar Nov 04 '24 12:11 eyyyyyyy3

Yeah, Comlink does not (cannot?) handle this directly. For this purpose, each proxy has a createEndpoint method that creates a new MessagePort endpoint for the same object. You can transfer that endpoint via postMessage can call Comlink.wrap() on it to create a new proxy for the same exposed object. That way you avoid the re-proxy.

surma avatar Nov 05 '24 11:11 surma

So instead of re-proxying I expose the function from C, then wrap it in B which will give me a Remote object on which I then call the createEndpoint function which will give me a MessagePort. This port will then be forwarded to A, am I right? Seems kinda like a lot. Also do I have to postMessage if I want to pass it through multiple workers and only call wrap on the worker which should have the proxy? Currently I am creating the proxy with the proxy function in C and the function in B which passes the proxy to A expects something that is & ProxyMarked. It does not create another proxy. The function in A which is called by B also expects the listener to be & ProxyMarked. If you want some deeper insight into the code, you can find it here. The relevant parts are the extension-service(in this case A), the extension-host(in this case B) and the extension-worker(in this case C). The weird thing is that it works without re-proxying.

eyyyyyyy3 avatar Nov 11 '24 15:11 eyyyyyyy3