Skip to content

Commit

Permalink
Merge pull request #96 from libp2p/fix/finish-dial-fast
Browse files Browse the repository at this point in the history
dialer: handle dial cancel and/or completion before trying new addresses
  • Loading branch information
Stebalien authored Jan 23, 2019
2 parents 10ab830 + 8d093f2 commit 7168ce8
Showing 1 changed file with 25 additions and 8 deletions.
33 changes: 25 additions & 8 deletions p2p/net/swarm/swarm_dial.go
Original file line number Diff line number Diff line change
Expand Up @@ -358,14 +358,34 @@ func (s *Swarm) dialAddrs(ctx context.Context, p peer.ID, remoteAddrs <-chan ma.
defer s.limiter.clearAllPeerDials(p)

var active int
for {
for remoteAddrs != nil || active > 0 {
// Check for context cancellations and/or responses first.
select {
case <-ctx.Done():
if exitErr == defaultDialFail {
exitErr = ctx.Err()
}
return nil, exitErr
case resp := <-respch:
active--
if resp.Err != nil {
log.Infof("got error on dial to %s: %s", resp.Addr, resp.Err)
// Errors are normal, lots of dials will fail
exitErr = resp.Err
} else if resp.Conn != nil {
return resp.Conn, nil
}

// We got a result, try again from the top.
continue
default:
}

// Now, attempt to dial.
select {
case addr, ok := <-remoteAddrs:
if !ok {
remoteAddrs = nil
if active == 0 {
return nil, exitErr
}
continue
}

Expand All @@ -382,15 +402,12 @@ func (s *Swarm) dialAddrs(ctx context.Context, p peer.ID, remoteAddrs <-chan ma.
log.Infof("got error on dial to %s: %s", resp.Addr, resp.Err)
// Errors are normal, lots of dials will fail
exitErr = resp.Err

if remoteAddrs == nil && active == 0 {
return nil, exitErr
}
} else if resp.Conn != nil {
return resp.Conn, nil
}
}
}
return nil, exitErr
}

// limitedDial will start a dial to the given peer when
Expand Down

0 comments on commit 7168ce8

Please sign in to comment.