Download this file
| 1 | package team |
| 2 | |
| 3 | import ( |
| 4 | "sync" |
| 5 | "time" |
| 6 | ) |
| 7 | |
| 8 | // Clock is the store's only source of time. Production passes RealClock; |
| 9 | // tests pass a FakeClock and move it by hand, so lease expiry and admission |
| 10 | // expiry are deterministic. |
| 11 | type Clock interface { |
| 12 | Now() time.Time |
| 13 | } |
| 14 | |
| 15 | // RealClock reads the wall clock in UTC. |
| 16 | type RealClock struct{} |
| 17 | |
| 18 | func (RealClock) Now() time.Time { return time.Now().UTC() } |
| 19 | |
| 20 | // FakeClock is a settable clock. It never advances on its own. |
| 21 | type FakeClock struct { |
| 22 | mu sync.Mutex |
| 23 | now time.Time |
| 24 | } |
| 25 | |
| 26 | // NewFakeClock starts at t. |
| 27 | func NewFakeClock(t time.Time) *FakeClock { return &FakeClock{now: t.UTC()} } |
| 28 | |
| 29 | func (c *FakeClock) Now() time.Time { |
| 30 | c.mu.Lock() |
| 31 | defer c.mu.Unlock() |
| 32 | return c.now |
| 33 | } |
| 34 | |
| 35 | // Advance moves the clock forward by d. |
| 36 | func (c *FakeClock) Advance(d time.Duration) { |
| 37 | c.mu.Lock() |
| 38 | defer c.mu.Unlock() |
| 39 | c.now = c.now.Add(d) |
| 40 | } |
| 41 | |
| 42 | // Corrections up to two seconds use the high-water time. This gives NTP room |
| 43 | // without extending leases or reducing elapsed charges. Larger rollbacks remain |
| 44 | // visible to observeClock and require containment and recovery. |
| 45 | type storeClock struct { |
| 46 | source Clock |
| 47 | mu sync.Mutex |
| 48 | high time.Time |
| 49 | } |
| 50 | |
| 51 | func (c *storeClock) remember(high time.Time) { |
| 52 | c.mu.Lock() |
| 53 | defer c.mu.Unlock() |
| 54 | if high.After(c.high) { |
| 55 | c.high = high |
| 56 | } |
| 57 | } |
| 58 | func (c *storeClock) Now() time.Time { |
| 59 | c.mu.Lock() |
| 60 | defer c.mu.Unlock() |
| 61 | now := c.source.Now() |
| 62 | if now.Before(c.high) && c.high.Sub(now) <= 2*time.Second { |
| 63 | return c.high |
| 64 | } |
| 65 | if now.After(c.high) { |
| 66 | c.high = now |
| 67 | } |
| 68 | return now |
| 69 | } |
| 70 | |