GoogleChromeLabs / comlink

Comlink makes WebWorkers enjoyable.
Apache License 2.0
11.37k stars 390 forks source link

Making Comlink.proxy() work in node worker threads #313

Open guanzo opened 5 years ago

guanzo commented 5 years ago

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))
surma commented 5 years ago

(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

wigsaparelli commented 3 years ago

(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.

guytt commented 2 years ago

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