Skip to content

Commit

Permalink
fix(memmetrics): prevent 'now' from accumulating during cleanup (#245)
Browse files Browse the repository at this point in the history
Co-authored-by: Fernandez Ludovic <[email protected]>
  • Loading branch information
mkaobao and ldez authored Nov 14, 2024
1 parent 083bfca commit a0bcd32
Show file tree
Hide file tree
Showing 2 changed files with 26 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
23 changes: 23 additions & 0 deletions memmetrics/counter_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package memmetrics

import (
"math"
"testing"

"github.com/stretchr/testify/assert"
Expand All @@ -27,3 +28,25 @@ func TestCloneExpired(t *testing.T) {

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

func Test_cleanup(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(int(math.Pow10(i + 1)))
}

assert.EqualValues(t, 1111111111, cnt.Count())
assert.Equal(t, []int{1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000, 1, 10, 100}, cnt.values)

clock.Advance(9 * clock.Second)

assert.EqualValues(t, 1000000000, cnt.Count())
assert.Equal(t, []int{0, 0, 0, 0, 0, 0, 1000000000, 0, 0, 0}, cnt.values)
}

0 comments on commit a0bcd32

Please sign in to comment.