-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathcounters.go
74 lines (60 loc) · 2.14 KB
/
counters.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package slogsampling
import (
"sync/atomic"
"time"
"github.com/samber/lo"
)
func newCounter() *counter {
return &counter{
resetAt: atomic.Int64{},
counter: atomic.Uint64{},
}
}
type counter struct {
resetAt atomic.Int64
counter atomic.Uint64
}
func (c *counter) Inc(tick time.Duration) uint64 {
// i prefer not using record.Time, because only the sampling middleware time is relevant
tn := time.Now().UnixNano()
resetAfter := c.resetAt.Load()
if resetAfter > tn {
return c.counter.Add(1)
}
c.counter.Store(1)
newResetAfter := tn + tick.Nanoseconds()
if !c.resetAt.CompareAndSwap(resetAfter, newResetAfter) {
// We raced with another goroutine trying to reset, and it also reset
// the counter to 1, so we need to reincrement the counter.
return c.counter.Add(1)
}
return 1
}
func newCounterWithMemory() *counterWithMemory {
c := &counterWithMemory{
resetAtAndPreviousCounter: atomic.Pointer[lo.Tuple2[int64, uint64]]{},
counter: atomic.Uint64{},
}
c.resetAtAndPreviousCounter.Store(lo.ToPtr(lo.T2(int64(0), uint64(0))))
return c
}
type counterWithMemory struct {
resetAtAndPreviousCounter atomic.Pointer[lo.Tuple2[int64, uint64]] // it would be more memory-efficient with a dedicated struct, but i'm lazy
counter atomic.Uint64
}
func (c *counterWithMemory) Inc(tick time.Duration) (n uint64, previousCycle uint64) {
// i prefer not using record.Time, because only the sampling middleware time is relevant
tn := time.Now().UnixNano()
resetAtAndPreviousCounter := c.resetAtAndPreviousCounter.Load()
if resetAtAndPreviousCounter.A > tn {
return c.counter.Add(1), resetAtAndPreviousCounter.B
}
old := c.counter.Swap(1)
newResetAfter := lo.T2(tn+tick.Nanoseconds(), old)
if !c.resetAtAndPreviousCounter.CompareAndSwap(resetAtAndPreviousCounter, lo.ToPtr(newResetAfter)) {
// We raced with another goroutine trying to reset, and it also reset
// the counter to 1, so we need to reincrement the counter.
return c.counter.Add(1), resetAtAndPreviousCounter.B // we should load again instead of returning this outdated value, but it's not a big deal
}
return 1, resetAtAndPreviousCounter.B
}