comlink icon indicating copy to clipboard operation
comlink copied to clipboard

Making Comlink.proxy() work in node worker threads

Open guanzo opened this issue 6 years ago • 3 comments
trafficstars

Took me a while to figure out how to make Comlink.proxy() work in node worker threads. I'm not sure that Comlink itself needs to handle this, since the simple workaround is to override the default proxy transfer handler. Here's how I did it for anyone curious

// In worker-thread
const { parentPort } = require('worker_threads')
const { MessageChannel } = require('worker_threads')

const Comlink = require('comlink')
const nodeEndpoint = require('comlink/dist/umd/node-adapter.js')

// Override comlink's default proxy handler to use Node endpoints
Comlink.transferHandlers.set('proxy', {
	canHandle: obj => obj && obj[Comlink.proxyMarker],
	serialize: obj => {
		const { port1, port2 } = new MessageChannel()
		Comlink.expose(obj, nodeEndpoint(port1))
		return [port2, [port2]]
	},
	deserialize: port => {
		port = nodeEndpoint(port)
		port.start()
		return Comlink.wrap(port)
	}
})

const thingToProxy = '...'
const api = {
    thingToProxy: Comlink.proxy(thingToProxy)
    hello () {
        return 'HELLO12341567'
    },
}

Comlink.expose(api, nodeEndpoint(parentPort))

guanzo avatar Jun 21 '19 20:06 guanzo

(Sorry I never replied to this. This must have gotten lost in my email.)

Huh, the fact that the adapter doesn't work out of the box is not good. That's it entire purpose :D I'll see if I can fix this

surma avatar Oct 11 '19 08:10 surma

(Sorry I never replied to this. This must have gotten lost in my email.)

Huh, the fact that the adapter doesn't work out of the box is not good. That's it entire purpose :D I'll see if I can fix this

@surma did you manage to fix this within comlink or do consumers still need to override the default proxy transfer handler as per the above example? Thanks.

wigsaparelli avatar Aug 17 '21 11:08 wigsaparelli

Still doesn't work out of the box...

guytt avatar Feb 08 '22 13:02 guytt