Skip to content

Commit

Permalink
spv: delay reconnect attempts
Browse files Browse the repository at this point in the history
  • Loading branch information
norwnd committed Oct 15, 2024
1 parent 4ec0b8b commit 4e54ee9
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions spv/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -480,7 +480,7 @@ var errBreaksMinVersionTarget = errors.New("peer uses too low version to satisif

// connectAndRunPeer connects to and runs the syncing process with the specified
// peer. It blocks until the peer disconnects and logs any errors.
func (s *Syncer) connectAndRunPeer(ctx context.Context, raddr string, persistent bool) {
func (s *Syncer) connectAndRunPeer(ctx context.Context, raddr string, persistent bool) error {
// Attempt connection to peer.
rp, err := s.lp.ConnectOutbound(ctx, raddr, reqSvcs)
if err != nil {
Expand All @@ -492,7 +492,7 @@ func (s *Syncer) connectAndRunPeer(ctx context.Context, raddr string, persistent
if !errors.Is(err, context.Canceled) {
log.Warnf("Peering attempt failed: %v", err)
}
return
return err
}

// Track peer as running as opposed to attempting connection.
Expand All @@ -502,7 +502,7 @@ func (s *Syncer) connectAndRunPeer(ctx context.Context, raddr string, persistent
s.remotesMu.Unlock()
log.Debugf("Disconnecting %v: %v", raddr, errBreaksMinVersionTarget)
rp.Disconnect(errBreaksMinVersionTarget)
return
return errBreaksMinVersionTarget
}
s.remotes[raddr] = rp
n := len(s.remotes)
Expand Down Expand Up @@ -535,16 +535,17 @@ func (s *Syncer) connectAndRunPeer(ctx context.Context, raddr string, persistent
log.Infof("Lost peer %v", raddr)
}
rp.Disconnect(err)
return
return err
}

// Finally, block until the peer disconnects.
err = rp.Err()
if !errors.Is(err, context.Canceled) {
log.Warnf("Lost peer %v: %v", raddr, err)
} else {
log.Infof("Lost peer %v", raddr)
return err
}
log.Infof("Lost peer %v", raddr)
return nil
}

func (s *Syncer) breaksMinVersionTarget(rp *p2p.RemotePeer) bool {
Expand All @@ -569,7 +570,7 @@ func (s *Syncer) breaksMinVersionTarget(rp *p2p.RemotePeer) bool {

func (s *Syncer) connectToPersistent(ctx context.Context, raddr string) error {
for {
s.connectAndRunPeer(ctx, raddr, true)
_ = s.connectAndRunPeer(ctx, raddr, true)

// Retry persistent peer after 5 seconds.
select {
Expand Down Expand Up @@ -607,9 +608,14 @@ func (s *Syncer) connectToCandidates(ctx context.Context) error {

wg.Add(1)
go func() {
defer wg.Done()
raddr := na.String()
s.connectAndRunPeer(ctx, raddr, false)
wg.Done()
err := s.connectAndRunPeer(ctx, raddr, false)
if err != nil {
// Delay next connect attempt to save resources and not overwhelm peers,
// it's unlikely to succeed anyway if we do retry immediately.
time.Sleep(5 * time.Second)
}
<-sem
}()
}
Expand Down

0 comments on commit 4e54ee9

Please sign in to comment.