refactor: async routing (#489)

* feat: async routing

* chore: put dht extra api commands under content routing

* chore: add default option to createPeerInfo

Co-Authored-By: Jacob Heun <jacobheun@gmail.com>

* chore: address review

* chore: rm dlv
This commit is contained in:
Vasco Santos
2019-12-01 22:54:59 +01:00
committed by Jacob Heun
parent f77ce39484
commit a020db183a
24 changed files with 805 additions and 228 deletions

View File

@ -1,8 +1,7 @@
'use strict'
const tryEach = require('async/tryEach')
const errCode = require('err-code')
const promisify = require('promisify-es6')
const pAny = require('p-any')
module.exports = (node) => {
const routers = node._modules.peerRouting || []
@ -17,43 +16,25 @@ module.exports = (node) => {
* Iterates over all peer routers in series to find the given peer.
*
* @param {String} id The id of the peer to find
* @param {object} options
* @param {number} options.maxTimeout How long the query should run
* @param {function(Error, Result<Array>)} callback
* @returns {void}
* @param {object} [options]
* @param {number} [options.timeout] How long the query should run
* @returns {Promise<PeerInfo>}
*/
findPeer: promisify((id, options, callback) => {
if (typeof options === 'function') {
callback = options
options = {}
}
findPeer: async (id, options) => { // eslint-disable-line require-await
if (!routers.length) {
callback(errCode(new Error('No peer routers available'), 'NO_ROUTERS_AVAILABLE'))
throw errCode(new Error('No peer routers available'), 'NO_ROUTERS_AVAILABLE')
}
const tasks = routers.map((router) => {
return (cb) => router.findPeer(id, options, (err, result) => {
if (err) {
return cb(err)
}
return pAny(routers.map(async (router) => {
const result = await router.findPeer(id, options)
// If we don't have a result, we need to provide an error to keep trying
if (!result || Object.keys(result).length === 0) {
return cb(errCode(new Error('not found'), 'NOT_FOUND'), null)
}
cb(null, result)
})
})
tryEach(tasks, (err, results) => {
if (err) {
return callback(err)
// If we don't have a result, we need to provide an error to keep trying
if (!result || Object.keys(result).length === 0) {
throw errCode(new Error('not found'), 'NOT_FOUND')
}
results = results || []
callback(null, results)
})
})
return result
}))
}
}
}