Debian Codegraph @

time_test.go

raw
1 package utils
2
3 import (
4 "sync"
5 "sync/atomic"
6 "testing"
7 "time"
8
9 "github.com/stretchr/testify/require"
10 )
11
12 var timerTestMu sync.Mutex
13
14 // testEpoch is an arbitrary fixed instant. Nothing depends on its value, only
15 // on the differences between it and the times derived from it.
16 var testEpoch = time.Unix(1_700_000_000, 0)
17
18 // fakeClock stands in for the package clock so the updater can be stepped
19 // instead of waited on.
20 type fakeClock struct {
21 mu sync.Mutex
22 t time.Time
23 tick chan time.Time
24
25 creates atomic.Int32
26 stops atomic.Int32
27 }
28
29 // withFakeClock locks out the other timestamp tests, installs a fake clock
30 // reading start, and returns it with the teardown the caller must defer.
31 // Teardown order matters: the updater has to be stopped and the real clock put
32 // back before the next test takes the lock.
33 func withFakeClock(tb testing.TB, start time.Time) (*fakeClock, func()) {
34 tb.Helper()
35 timerTestMu.Lock()
36
37 fc := &fakeClock{t: start, tick: make(chan time.Time)}
38 realNow, realNewTicker := now, newTicker
39 now, newTicker = fc.now, fc.newTicker
40
41 return fc, func() {
42 StopTimeStampUpdater()
43 now, newTicker = realNow, realNewTicker
44 timerTestMu.Unlock()
45 }
46 }
47
48 func (fc *fakeClock) now() time.Time {
49 fc.mu.Lock()
50 defer fc.mu.Unlock()
51 return fc.t
52 }
53
54 func (fc *fakeClock) set(t time.Time) {
55 fc.mu.Lock()
56 defer fc.mu.Unlock()
57 fc.t = t
58 }
59
60 func (fc *fakeClock) newTicker(time.Duration) (<-chan time.Time, func()) {
61 fc.creates.Add(1)
62 return fc.tick, func() { fc.stops.Add(1) }
63 }
64
65 // advance moves the clock to t and ticks the updater, returning once the new
66 // value is published. The second send is the synchronization: the updater
67 // handles ticks one at a time, so it can only take that one after the store
68 // that followed the first. It stores the same value again, so it changes
69 // nothing.
70 func (fc *fakeClock) advance(t time.Time) {
71 fc.set(t)
72 fc.tick <- t
73 fc.tick <- t
74 }
75
76 func checkTimeStamp(tb testing.TB, expectedCurrent, actualCurrent uint32) {
77 tb.Helper()
78 // Test with buffer of ±2 seconds for CI environment tolerance. The
79 // failure message is built only on failure: boxing require.True's
80 // variadic args allocated on every call, which made the fiber_asserted
81 // benchmark's B/op metric nondeterministic.
82 if actualCurrent < expectedCurrent-2 || actualCurrent > expectedCurrent+2 {
83 tb.Fatalf("Expected timestamp %d (±2s), got %d (diff: %d)",
84 expectedCurrent, actualCurrent, int64(actualCurrent)-int64(expectedCurrent))
85 }
86 }
87
88 // Test_NewTicker exercises the production tick source. Every other test here
89 // replaces it, so without this one nothing proves that the real one delivers a
90 // live channel or that the stop it hands back works. A millisecond period keeps
91 // the only real-time wait in this file down to the cost of one tick; the
92 // generous timeout is there to fail loudly rather than hang a loaded CI box.
93 func Test_NewTicker(t *testing.T) {
94 timerTestMu.Lock()
95 defer timerTestMu.Unlock()
96
97 tick, stop := newTicker(time.Millisecond)
98 defer stop()
99
100 select {
101 case <-tick:
102 case <-time.After(5 * time.Second):
103 t.Fatal("the real tick source never fired")
104 }
105 }
106
107 func Test_TimeStampUpdater(t *testing.T) {
108 fc, done := withFakeClock(t, testEpoch)
109 defer done()
110
111 StartTimeStampUpdater()
112
113 base := uint32(testEpoch.Unix())
114 require.Equal(t, base, Timestamp(), "Start should publish the current time before returning")
115
116 fc.advance(testEpoch.Add(time.Second))
117 require.Equal(t, base+1, Timestamp(), "a tick should publish the current time")
118
119 fc.advance(testEpoch.Add(90 * time.Second))
120 require.Equal(t, base+90, Timestamp(), "each tick republishes, it does not increment")
121 }
122
123 func Test_StartTimeStampUpdater_Idempotent(t *testing.T) {
124 fc, done := withFakeClock(t, testEpoch)
125 defer done()
126
127 StartTimeStampUpdater()
128 StartTimeStampUpdater()
129 require.Equal(t, int32(1), fc.creates.Load(), "a second Start must not launch a second updater")
130
131 fc.advance(testEpoch.Add(time.Second))
132 require.Equal(t, uint32(testEpoch.Unix())+1, Timestamp())
133 }
134
135 func Test_StopTimeStampUpdater(t *testing.T) {
136 fc, done := withFakeClock(t, testEpoch)
137 defer done()
138
139 StartTimeStampUpdater()
140 StopTimeStampUpdater()
141 require.Equal(t, int32(1), fc.stops.Load(), "Stop should release the tick source before returning")
142
143 StopTimeStampUpdater()
144 require.Equal(t, int32(1), fc.stops.Load(), "a second Stop must be a no-op")
145
146 // The updater is gone, so the clock can move without the cache following.
147 // No tick is sent because there is nothing left to receive one.
148 fc.set(testEpoch.Add(time.Hour))
149 require.Equal(t, uint32(testEpoch.Unix()), Timestamp(), "the timestamp must not move after Stop")
150 }
151
152 func Test_StartStopRepeat(t *testing.T) {
153 fc, done := withFakeClock(t, testEpoch)
154 defer done()
155
156 StartTimeStampUpdater()
157 StopTimeStampUpdater()
158
159 fc.set(testEpoch.Add(5 * time.Second))
160 StartTimeStampUpdater()
161
162 require.Equal(t, uint32(testEpoch.Unix())+5, Timestamp(), "a restart republishes the current time")
163 require.Equal(t, int32(2), fc.creates.Load(), "the restart needs its own tick source")
164 require.Equal(t, int32(1), fc.stops.Load(), "only the first run's tick source is released so far")
165
166 fc.advance(testEpoch.Add(6 * time.Second))
167 require.Equal(t, uint32(testEpoch.Unix())+6, Timestamp(), "the restarted updater still ticks")
168 }
169
170 // Benchmark_CalculateTimestamp runs on the real clock: it measures Timestamp
171 // against time.Now, and the ±2s tolerance below is the cache's own lag.
172 func Benchmark_CalculateTimestamp(b *testing.B) {
173 timerTestMu.Lock()
174 defer timerTestMu.Unlock()
175 StartTimeStampUpdater()
176 defer StopTimeStampUpdater()
177
178 b.Run("fiber", func(bb *testing.B) {
179 bb.ReportAllocs()
180 bb.ResetTimer()
181 for n := 0; n < bb.N; n++ {
182 _ = Timestamp()
183 }
184 })
185
186 b.Run("default", func(bb *testing.B) {
187 bb.ReportAllocs()
188 bb.ResetTimer()
189 for n := 0; n < bb.N; n++ {
190 _ = uint32(time.Now().Unix())
191 }
192 })
193
194 // Simplified asserted benchmarks - measure the realistic cost including validation
195 b.Run("fiber_asserted", func(bb *testing.B) {
196 bb.ReportAllocs()
197 bb.ResetTimer()
198 for n := 0; n < bb.N; n++ {
199 res := Timestamp()
200 expected := uint32(time.Now().Unix())
201 checkTimeStamp(bb, expected, res)
202 }
203 })
204
205 b.Run("default_asserted", func(bb *testing.B) {
206 bb.ReportAllocs()
207 bb.ResetTimer()
208 for n := 0; n < bb.N; n++ {
209 expected := uint32(time.Now().Unix())
210 res := uint32(time.Now().Unix())
211 checkTimeStamp(bb, expected, res)
212 }
213 })
214 }