Skip to content

Commit

Permalink
fix(RollingCounter): prevent 'now' from accumulating during cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
mkaobao committed Nov 14, 2024
1 parent 083bfca commit 904997d
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
6 changes: 3 additions & 3 deletions memmetrics/counter.go
Original file line number Diff line number Diff line change
Expand Up @@ -131,9 +131,9 @@ func (c *RollingCounter) getBucket(t time.Time) int {
func (c *RollingCounter) cleanup() {
now := clock.Now().UTC()
for i := 0; i < len(c.values); i++ {
now = now.Add(time.Duration(-1*i) * c.resolution)
if now.Truncate(c.resolution).After(c.lastUpdated.Truncate(c.resolution)) {
c.values[c.getBucket(now)] = 0
checkPoint := now.Add(time.Duration(-1*i) * c.resolution)
if checkPoint.Truncate(c.resolution).After(c.lastUpdated.Truncate(c.resolution)) {
c.values[c.getBucket(checkPoint)] = 0
} else {
break
}
Expand Down
19 changes: 19 additions & 0 deletions memmetrics/counter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,22 @@ func TestCloneExpired(t *testing.T) {

assert.EqualValues(t, 2, out.Count())
}

func TestCleanup(t *testing.T) {
clock.Freeze(clock.Date(2012, 3, 4, 5, 6, 7, 0, clock.UTC))

cnt, err := NewCounter(10, clock.Second)
require.NoError(t, err)

cnt.Inc(1)
for i := 0; i < 9; i++ {
clock.Advance(clock.Second)
cnt.Inc(1)
}
// cnt will be [1 1 1 1 1 1 1 1 1 1]

clock.Advance(9 * clock.Second)
assert.EqualValues(t, 1, cnt.Count())
// cnt will be [0 0 0 0 0 0 1 0 0 0]
// old behavior [1 1 0 1 0 0 1 1 1 0]
}

0 comments on commit 904997d

Please sign in to comment.