hyperdiscovery icon indicating copy to clipboard operation
hyperdiscovery copied to clipboard

opts.autoListen (?) - some way to make listen async

Open joehand opened this issue 7 years ago • 0 comments

I want to store the port option in a database for dat-node so we can reuse whatever port worked last. But I think we need some way to make listen & join async. Maybe opts.autoListen or something (default: true), would be a way to do this? Or any other more straightforward suggestions?

Sudo code implementation in dat-node:

// Check for existing port saved
// PROBLEM: Happens async
if (opts.port && db) {
    var subDb = sub(db, `${encoding.toStr(archive.discoveryKey)}-network`)
    subDb.get('port', function (err, val) {
      if (err && !err.notFound) throw new Error(err)
      if (val) opts.port = val
      doListen()
    })
}

// Happens sync
opts.autoListen = false
var swarm = hyperdiscovery(archive, opts)


// ... later with `autoListen = false`

function doListen () {
  swarm.once('error', function () {
    swarm.listen(0)
  })
  swarm.listen(opts.port)
  swarm.join(this.archive.discoveryKey)
  swarm.once('listening', function () {
    subDb.put('port', swarm.port) // save whatever port succeeded
  })
}

We could make the whole network function async in dat-node too. Maybe that is the easier solution but the rest of the networking APIs are sync.

joehand avatar Jan 20 '17 17:01 joehand