Skip to content

Commit

Permalink
refactor: reuse timers instead of time.After in loops (#687)
Browse files Browse the repository at this point in the history
Closes #122

(cherry picked from commit 7bf89a7)
  • Loading branch information
gammazero committed Oct 22, 2024
1 parent 22371e8 commit 7780b0e
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 3 deletions.
5 changes: 4 additions & 1 deletion bitswap/network/ipfs_impl.go
Original file line number Diff line number Diff line change
Expand Up @@ -179,10 +179,13 @@ func (s *streamMessageSender) multiAttempt(ctx context.Context, fn func() error)
return err
}

timer := time.NewTimer(s.opts.SendErrorBackoff)
defer timer.Stop()

select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(s.opts.SendErrorBackoff):
case <-timer.C:
// wait a short time in case disconnect notifications are still propagating
log.Infof("send message to %s failed but context was not Done: %s", s.to, err)
}
Expand Down
6 changes: 5 additions & 1 deletion bootstrap/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -304,15 +304,19 @@ func peersConnect(ctx context.Context, ph host.Host, availablePeers []peer.AddrI
ctx, cancel := context.WithCancel(ctx)
defer cancel()
go func() {
timer := time.NewTimer(time.Second)
defer timer.Stop()

for {
select {
case <-ctx.Done():
return
case <-time.After(1 * time.Second):
case <-timer.C:
if int(atomic.LoadUint64(&connected)) >= needed {
cancel()
return
}
timer.Reset(time.Second)
}
}
}()
Expand Down
11 changes: 10 additions & 1 deletion mfs/repub.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,18 +169,27 @@ func (rp *Republisher) Run(lastPublished cid.Cid) {

// 2. If we have a value to publish, publish it now.
if toPublish.Defined() {
var timer *time.Timer
for {
err := rp.pubfunc(rp.ctx, toPublish)
if err == nil {
break
}

if timer == nil {
timer = time.NewTimer(rp.RetryTimeout)
defer timer.Stop()
} else {
timer.Reset(rp.RetryTimeout)
}

// Keep retrying until we succeed or we abort.
// TODO(steb): We could try pulling new values
// off `update` but that's not critical (and
// complicates this code a bit). We'll pull off
// a new value on the next loop through.
select {
case <-time.After(rp.RetryTimeout):
case <-timer.C:
case <-rp.ctx.Done():
return
}
Expand Down

0 comments on commit 7780b0e

Please sign in to comment.