holepunchto / hypercore

Hypercore is a secure, distributed append-only log.
https://docs.holepunch.to
MIT License
2.53k stars 185 forks source link

registerExtension signature to send #236

Closed ghost closed 4 years ago

ghost commented 4 years ago

Right now if you call var ext = feed.registerExtension(name, handlers), in order to send messages inside your handlers, you need a reference to the ext object. This doesn't work very well for circumstances when you want to modularize your handlers:

feed.registerExtension(name, require('some-hypercore-extension-module'))

So I propose a new backwards-compatible api for extensions: if the handlers argument is a function, it will receive the extension object as its first argument. Then you can write fully self-contained extensions that can send as well as receive data:

feed.registerExtension(name, function (ext) {
  return {
    encoding: 'json',
    onmessage: function (msg, peer) {
      ext.send(msg.n+1)
    }
  }
})
telamon commented 4 years ago

I don't think there's many extensions out there yet so it dosen't have to be fully backwards compatible I suppose. For now I've been using the following pattern to make my extensions self-contained:

module.exports = function registrarAdapter(extensionHost, ...args) {
  const inst = new MyExt(...args)
  // Inject transmitter
  inst._ext = extensionHost.registerExtension('MyExtension', inst)
  return inst
}

class MyExt {
  constructor () { ... }

  get encoding { ... }

  onerror (e) { ... }

  onmessage (msg, peer) {
    this._ext.send(peer, "some response")
  }

  start () { this._ext.broadcast('...') }
}
module.exports.MyExt = MyExt

Also while we're on the self-contained extension subject. We might consider having an onconnected(peer) handler to signal the extension when the proposed send method is ready to be used - but I am unsure of how much work that would take to implement.

mafintosh commented 4 years ago

Should be fixed in the above dependency commit :) Reinstall.