Skip to content

Commit

Permalink
fix: revert to try each (libp2p#320)
Browse files Browse the repository at this point in the history
  • Loading branch information
Alan Shaw authored and jacobheun committed Apr 3, 2019
1 parent f31663f commit 805d1ad
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 22 deletions.
25 changes: 10 additions & 15 deletions src/limit-dialer/index.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,11 @@
'use strict'

const race = require('async/race')
const tryEach = require('async/tryEach')
const debug = require('debug')
const once = require('once')

const log = debug('libp2p:switch:dialer')

const DialQueue = require('./queue')
const { CONNECTION_FAILED } = require('../errors')

/**
* Track dials per peer and limited them.
Expand Down Expand Up @@ -39,29 +37,26 @@ class LimitDialer {
log('dialMany:start')
// we use a token to track if we want to cancel following dials
const token = { cancel: false }
callback = once(callback) // only call callback once

let errors = []
const tasks = addrs.map((m) => {
return (cb) => this.dialSingle(peer, transport, m, token, (err, res) => {
if (res) return cb(null, res)

errors.push(err || CONNECTION_FAILED())

if (errors.length === tasks.length) {
cb(errors)
return (cb) => this.dialSingle(peer, transport, m, token, (err, result) => {
if (err) {
errors.push(err)
return cb(err)
}
return cb(null, result)
})
})

race(tasks, (_, successfulDial) => {
if (successfulDial) {
tryEach(tasks, (_, result) => {
if (result && result.conn) {
log('dialMany:success')
return callback(null, successfulDial)
return callback(null, result)
}

log('dialMany:error')
return callback(errors)
callback(errors)
})
}

Expand Down
10 changes: 3 additions & 7 deletions test/limit-dialer.node.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,6 @@ describe('LimitDialer', () => {
it('two success', (done) => {
const dialer = new LimitDialer(2, 10)

expect(2).checks(done)

// mock transport
const t1 = {
dial (addr, cb) {
Expand All @@ -72,10 +70,7 @@ describe('LimitDialer', () => {
setTimeout(cb, 8)
return {
source: pull.values([2]),
sink: pull.onEnd((err) => {
// Verify the unused connection gets closed
expect(err).to.not.exist().mark()
})
sink: pull.drain()
}
}
}
Expand All @@ -89,7 +84,8 @@ describe('LimitDialer', () => {
conn,
pull.collect((err, res) => {
expect(err).to.not.exist()
expect(res).to.be.eql([1]).mark()
expect(res).to.be.eql([1])
done()
})
)
})
Expand Down

0 comments on commit 805d1ad

Please sign in to comment.