Skip to content

Commit

Permalink
autorelay: remove ticker in favor of a dynamic timer
Browse files Browse the repository at this point in the history
  • Loading branch information
marten-seemann committed Jun 1, 2022
1 parent a0cf073 commit d5b6e06
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 10 deletions.
17 changes: 7 additions & 10 deletions p2p/host/autorelay/relay_finder.go
Original file line number Diff line number Diff line change
Expand Up @@ -191,20 +191,15 @@ func (rf *relayFinder) background(ctx context.Context) {
// This makes sure that as soon as we need to find relay candidates, we have them available.
func (rf *relayFinder) findNodes(ctx context.Context, relayDisconnected <-chan struct{}) {
peerChan := rf.peerSource(rf.conf.maxCandidates)
const tick = 5 * time.Minute
timer := rf.conf.clock.Timer(tick)
defer timer.Stop()

timer := newTimer(rf.conf.clock)
for {
select {
case <-relayDisconnected:
if !timer.Stop() {
<-timer.C
}
timer.Reset(0)
case now := <-timer.C:
case now := <-timer.Chan():
if peerChan != nil {
// We're still reading peers from the peerChan. No need to query for more peers now.
timer.Reset(tick)
continue
}
rf.relayMx.Lock()
Expand All @@ -216,15 +211,17 @@ func (rf *relayFinder) findNodes(ctx context.Context, relayDisconnected <-chan s

// Even if we are connected to the desired number of relays, or have enough candidates,
// we want to make sure that our candidate list doesn't become outdated.
newestCandidateAge := now.Sub(rf.lastCandidateAdded)
if (numRelays >= rf.conf.desiredRelays || numCandidates >= rf.conf.maxCandidates) &&
now.Sub(rf.lastCandidateAdded) < rf.conf.maxCandidateAge {
timer.Reset(tick)
newestCandidateAge < rf.conf.maxCandidateAge {
timer.Reset(rf.conf.maxCandidateAge - newestCandidateAge)
continue
}
peerChan = rf.peerSource(rf.conf.maxCandidates)
case pi, ok := <-peerChan:
if !ok {
peerChan = nil
timer.Reset(rf.conf.maxCandidateAge - rf.conf.clock.Now().Sub(rf.lastCandidateAdded))
continue
}
log.Debugw("found node", "id", pi.ID)
Expand Down
42 changes: 42 additions & 0 deletions p2p/host/autorelay/timer.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package autorelay

import (
"time"

"github.com/benbjohnson/clock"
)

type timer struct {
timer *clock.Timer
running bool
read bool
}

func newTimer(cl clock.Clock) *timer {
t := cl.Timer(100 * time.Hour) // There's no way to initialize a stopped timer
t.Stop()
return &timer{timer: t}
}

func (t *timer) Chan() <-chan time.Time {
return t.timer.C
}

func (t *timer) Stop() {
if !t.running {
return
}
if !t.timer.Stop() && !t.read {
<-t.timer.C
}
t.read = false
}

func (t *timer) SetRead() {
t.read = true
}

func (t *timer) Reset(d time.Duration) {
t.Stop()
t.timer.Reset(d)
}

0 comments on commit d5b6e06

Please sign in to comment.