Skip to content

Commit

Permalink
Fix race on test
Browse files Browse the repository at this point in the history
  • Loading branch information
alanprot committed May 6, 2024
1 parent 8071742 commit c85eead
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 6 deletions.
12 changes: 6 additions & 6 deletions pkg/util/time.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,15 +207,15 @@ func (t *SlottedTicker) Stop() {
t.done()
}

func (s *SlottedTicker) nextInterval() time.Duration {
func (t *SlottedTicker) nextInterval() time.Duration {
now := time.Now()
slot := time.UnixMilli((now.UnixMilli() / s.d.Milliseconds()) * s.d.Milliseconds())
slitIndex, totalSlots := s.sf()
slotSize := time.Duration(s.d.Milliseconds()/int64(totalSlots)) * time.Millisecond
offset := time.Millisecond * time.Duration(int64(float64(slitIndex)/float64(totalSlots)*float64(s.d.Milliseconds())))
slot := time.UnixMilli((now.UnixMilli() / t.d.Milliseconds()) * t.d.Milliseconds())
slitIndex, totalSlots := t.sf()
slotSize := time.Duration(t.d.Milliseconds()/int64(totalSlots)) * time.Millisecond
offset := time.Millisecond * time.Duration(int64(float64(slitIndex)/float64(totalSlots)*float64(t.d.Milliseconds())))
slot = slot.Add(offset)
for slot.Before(now) {
slot = slot.Add(s.d)
slot = slot.Add(t.d)
}
i := slot.Sub(now)
return i + PositiveJitter(slotSize, 1)
Expand Down
6 changes: 6 additions & 0 deletions pkg/util/time_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"net/http"
"strconv"
"sync"
"testing"
"time"

Expand Down Expand Up @@ -215,7 +216,10 @@ func TestSlottedTicker(t *testing.T) {
for name, tc := range testCases {
t.Run(name, func(t *testing.T) {
d := time.Millisecond * 100
m := sync.RWMutex{}
infoFunc := func() (int, int) {
m.RLock()
defer m.RUnlock()
return tc.indexSlotSlice[0], tc.totalSlotsSlice[0]
}
ticker := NewSlottedTicker(infoFunc, d)
Expand All @@ -227,6 +231,7 @@ func TestSlottedTicker(t *testing.T) {
_, totalSlots := infoFunc()
slotSize := time.Duration(d.Milliseconds()/int64(totalSlots)) * time.Millisecond
require.LessOrEqual(t, slotDiff, (slotSize + time.Millisecond*10).Milliseconds())
m.Lock()
if len(tc.indexSlotSlice) > 1 {
tc.indexSlotSlice = tc.indexSlotSlice[1:]
}
Expand All @@ -236,6 +241,7 @@ func TestSlottedTicker(t *testing.T) {
if len(tc.expectedShifts) > 1 {
tc.expectedShifts = tc.expectedShifts[1:]
}
m.Unlock()
}
ticker.Stop()
})
Expand Down

0 comments on commit c85eead

Please sign in to comment.