Debian Codegraph @

time.go

raw
1 package utils
2
3 import (
4 "sync"
5 "sync/atomic"
6 "time"
7 )
8
9 var (
10 timestamp atomic.Uint32
11 updaterMu sync.Mutex
12 stopUpdater chan struct{}
13 updaterDone chan struct{}
14 )
15
16 // now and newTicker are this package's clock: every production read of the wall
17 // clock goes through them, so replacing the pair is enough to drive the updater
18 // from a test without waiting on real time. Neither is reachable from outside
19 // the package, and Timestamp itself touches neither.
20 //
21 // newTicker hands back a channel and a stop function instead of a *time.Ticker
22 // because a Ticker the runtime did not build cannot stand in for one: its Stop
23 // panics.
24 var (
25 now = time.Now
26 newTicker = func(d time.Duration) (<-chan time.Time, func()) {
27 t := time.NewTicker(d)
28 return t.C, t.Stop
29 }
30 )
31
32 // Timestamp returns the current cached Unix timestamp (seconds).
33 // Call StartTimeStampUpdater() once at app startup for best performance.
34 func Timestamp() uint32 {
35 return timestamp.Load()
36 }
37
38 // StartTimeStampUpdater launches a background goroutine that updates the cached timestamp every second.
39 // It is safe to call multiple times and from multiple goroutines; only one updater runs at a time.
40 func StartTimeStampUpdater() {
41 updaterMu.Lock()
42 defer updaterMu.Unlock()
43 if stopUpdater != nil {
44 return
45 }
46
47 timestamp.Store(uint32(now().Unix()))
48 stopUpdater = make(chan struct{})
49 updaterDone = make(chan struct{})
50
51 // The tick source is created here, not in the goroutine, so it exists by
52 // the time this returns and a caller cannot race the goroutine's first
53 // statement.
54 tick, stopTick := newTicker(time.Second)
55
56 go func(stop, done chan struct{}) {
57 // stopTick before close(done), so that once StopTimeStampUpdater's
58 // wait returns the tick source is released rather than about to be.
59 defer close(done)
60 defer stopTick()
61
62 for {
63 select {
64 case <-tick:
65 timestamp.Store(uint32(now().Unix()))
66 case <-stop:
67 return
68 }
69 }
70 }(stopUpdater, updaterDone)
71 }
72
73 // StopTimeStampUpdater stops the background updater goroutine.
74 // Call this on app shutdown to avoid leaking goroutines.
75 // It is safe to call multiple times and from multiple goroutines.
76 func StopTimeStampUpdater() {
77 updaterMu.Lock()
78 defer updaterMu.Unlock()
79 if stopUpdater == nil {
80 return
81 }
82
83 close(stopUpdater)
84 <-updaterDone
85 stopUpdater = nil
86 updaterDone = nil
87 }