| 1 | package clock |
| 2 | |
| 3 | import ( |
| 4 | "sort" |
| 5 | "sync" |
| 6 | "time" |
| 7 | ) |
| 8 | |
| 9 | // Clock represents an interface to the functions in the standard library time |
| 10 | // package. Two implementations are available in the clock package. The first |
| 11 | // is a real-time clock which simply wraps the time package's functions. The |
| 12 | // second is a mock clock which will only make forward progress when |
| 13 | // programmatically adjusted. |
| 14 | type Clock interface { |
| 15 | After(d time.Duration) <-chan time.Time |
| 16 | AfterFunc(d time.Duration, f func()) *Timer |
| 17 | Now() time.Time |
| 18 | Since(t time.Time) time.Duration |
| 19 | Sleep(d time.Duration) |
| 20 | Tick(d time.Duration) <-chan time.Time |
| 21 | Ticker(d time.Duration) *Ticker |
| 22 | Timer(d time.Duration) *Timer |
| 23 | } |
| 24 | |
| 25 | // New returns an instance of a real-time clock. |
| 26 | func New() Clock { |
| 27 | return &clock{} |
| 28 | } |
| 29 | |
| 30 | // clock implements a real-time clock by simply wrapping the time package functions. |
| 31 | type clock struct{} |
| 32 | |
| 33 | func (c *clock) After(d time.Duration) <-chan time.Time { return time.After(d) } |
| 34 | |
| 35 | func (c *clock) AfterFunc(d time.Duration, f func()) *Timer { |
| 36 | return &Timer{timer: time.AfterFunc(d, f)} |
| 37 | } |
| 38 | |
| 39 | func (c *clock) Now() time.Time { return time.Now() } |
| 40 | |
| 41 | func (c *clock) Since(t time.Time) time.Duration { return time.Since(t) } |
| 42 | |
| 43 | func (c *clock) Sleep(d time.Duration) { time.Sleep(d) } |
| 44 | |
| 45 | func (c *clock) Tick(d time.Duration) <-chan time.Time { return time.Tick(d) } |
| 46 | |
| 47 | func (c *clock) Ticker(d time.Duration) *Ticker { |
| 48 | t := time.NewTicker(d) |
| 49 | return &Ticker{C: t.C, ticker: t} |
| 50 | } |
| 51 | |
| 52 | func (c *clock) Timer(d time.Duration) *Timer { |
| 53 | t := time.NewTimer(d) |
| 54 | return &Timer{C: t.C, timer: t} |
| 55 | } |
| 56 | |
| 57 | // Mock represents a mock clock that only moves forward programmically. |
| 58 | // It can be preferable to a real-time clock when testing time-based functionality. |
| 59 | type Mock struct { |
| 60 | mu sync.Mutex |
| 61 | now time.Time // current time |
| 62 | timers clockTimers // tickers & timers |
| 63 | gosched func() |
| 64 | } |
| 65 | |
| 66 | type MockOpt struct { |
| 67 | // Gosched is a function which is called to schedule other (app-specific) |
| 68 | // goroutines. Default implementation just sleeps for 1 millisecond. It is |
| 69 | // often not acceptable because it slows down tests significantly and is also |
| 70 | // potentialy fragile. |
| 71 | Gosched func() |
| 72 | } |
| 73 | |
| 74 | // NewMock returns an instance of a mock clock with the default options. |
| 75 | // See also NewMockOpt |
| 76 | func NewMock() *Mock { |
| 77 | return NewMockOpt(MockOpt{}) |
| 78 | } |
| 79 | |
| 80 | // NewMockOpt returns an instance of a mock clock. |
| 81 | // The current time of the mock clock on initialization is the Unix epoch. |
| 82 | // See MockOpt for description of available options. |
| 83 | func NewMockOpt(opt MockOpt) *Mock { |
| 84 | mock := &Mock{ |
| 85 | now: time.Unix(0, 0), |
| 86 | gosched: opt.Gosched, |
| 87 | } |
| 88 | if mock.gosched == nil { |
| 89 | mock.gosched = func() { |
| 90 | time.Sleep(1 * time.Millisecond) |
| 91 | } |
| 92 | } |
| 93 | |
| 94 | return mock |
| 95 | } |
| 96 | |
| 97 | // Add moves the current time of the mock clock forward by the duration. |
| 98 | // This should only be called from a single goroutine at a time. |
| 99 | func (m *Mock) Add(d time.Duration) { |
| 100 | // Calculate the final current time. |
| 101 | t := m.now.Add(d) |
| 102 | |
| 103 | // Continue to execute timers until there are no more before the new time. |
| 104 | for { |
| 105 | if !m.runNextTimer(t) { |
| 106 | break |
| 107 | } |
| 108 | } |
| 109 | |
| 110 | // Ensure that we end with the new time. |
| 111 | m.mu.Lock() |
| 112 | m.now = t |
| 113 | m.mu.Unlock() |
| 114 | |
| 115 | // Give a small buffer to make sure the other goroutines get handled. |
| 116 | m.gosched() |
| 117 | } |
| 118 | |
| 119 | // Set sets the current time of the mock clock to a specific one. |
| 120 | // This should only be called from a single goroutine at a time. |
| 121 | func (m *Mock) Set(t time.Time) { |
| 122 | // Continue to execute timers until there are no more before the new time. |
| 123 | for { |
| 124 | if !m.runNextTimer(t) { |
| 125 | break |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | // Ensure that we end with the new time. |
| 130 | m.mu.Lock() |
| 131 | m.now = t |
| 132 | m.mu.Unlock() |
| 133 | |
| 134 | // Give a small buffer to make sure the other goroutines get handled. |
| 135 | m.gosched() |
| 136 | } |
| 137 | |
| 138 | // runNextTimer executes the next timer in chronological order and moves the |
| 139 | // current time to the timer's next tick time. The next time is not executed if |
| 140 | // it's next time if after the max time. Returns true if a timer is executed. |
| 141 | func (m *Mock) runNextTimer(max time.Time) bool { |
| 142 | m.mu.Lock() |
| 143 | |
| 144 | // Sort timers by time. |
| 145 | sort.Sort(m.timers) |
| 146 | |
| 147 | // If we have no more timers then exit. |
| 148 | if len(m.timers) == 0 { |
| 149 | m.mu.Unlock() |
| 150 | return false |
| 151 | } |
| 152 | |
| 153 | // Retrieve next timer. Exit if next tick is after new time. |
| 154 | t := m.timers[0] |
| 155 | if t.Next().After(max) { |
| 156 | m.mu.Unlock() |
| 157 | return false |
| 158 | } |
| 159 | |
| 160 | // Move "now" forward and unlock clock. |
| 161 | m.now = t.Next() |
| 162 | m.mu.Unlock() |
| 163 | |
| 164 | // Execute timer. |
| 165 | t.Tick(m.now) |
| 166 | return true |
| 167 | } |
| 168 | |
| 169 | // After waits for the duration to elapse and then sends the current time on the returned channel. |
| 170 | func (m *Mock) After(d time.Duration) <-chan time.Time { |
| 171 | return m.Timer(d).C |
| 172 | } |
| 173 | |
| 174 | // AfterFunc waits for the duration to elapse and then executes a function. |
| 175 | // A Timer is returned that can be stopped. |
| 176 | func (m *Mock) AfterFunc(d time.Duration, f func()) *Timer { |
| 177 | t := m.Timer(d) |
| 178 | t.C = nil |
| 179 | t.fn = f |
| 180 | return t |
| 181 | } |
| 182 | |
| 183 | // Now returns the current wall time on the mock clock. |
| 184 | func (m *Mock) Now() time.Time { |
| 185 | m.mu.Lock() |
| 186 | defer m.mu.Unlock() |
| 187 | return m.now |
| 188 | } |
| 189 | |
| 190 | // Since returns time since the mock clocks wall time. |
| 191 | func (m *Mock) Since(t time.Time) time.Duration { |
| 192 | return m.Now().Sub(t) |
| 193 | } |
| 194 | |
| 195 | // Sleep pauses the goroutine for the given duration on the mock clock. |
| 196 | // The clock must be moved forward in a separate goroutine. |
| 197 | func (m *Mock) Sleep(d time.Duration) { |
| 198 | <-m.After(d) |
| 199 | } |
| 200 | |
| 201 | // Tick is a convenience function for Ticker(). |
| 202 | // It will return a ticker channel that cannot be stopped. |
| 203 | func (m *Mock) Tick(d time.Duration) <-chan time.Time { |
| 204 | return m.Ticker(d).C |
| 205 | } |
| 206 | |
| 207 | // Ticker creates a new instance of Ticker. |
| 208 | func (m *Mock) Ticker(d time.Duration) *Ticker { |
| 209 | m.mu.Lock() |
| 210 | defer m.mu.Unlock() |
| 211 | ch := make(chan time.Time, 1) |
| 212 | t := &Ticker{ |
| 213 | C: ch, |
| 214 | c: ch, |
| 215 | mock: m, |
| 216 | d: d, |
| 217 | next: m.now.Add(d), |
| 218 | } |
| 219 | m.timers = append(m.timers, (*internalTicker)(t)) |
| 220 | return t |
| 221 | } |
| 222 | |
| 223 | // Timer creates a new instance of Timer. |
| 224 | func (m *Mock) Timer(d time.Duration) *Timer { |
| 225 | m.mu.Lock() |
| 226 | defer m.mu.Unlock() |
| 227 | ch := make(chan time.Time, 1) |
| 228 | t := &Timer{ |
| 229 | C: ch, |
| 230 | c: ch, |
| 231 | mock: m, |
| 232 | next: m.now.Add(d), |
| 233 | stopped: false, |
| 234 | } |
| 235 | m.timers = append(m.timers, (*internalTimer)(t)) |
| 236 | return t |
| 237 | } |
| 238 | |
| 239 | func (m *Mock) removeClockTimer(t clockTimer) { |
| 240 | m.mu.Lock() |
| 241 | defer m.mu.Unlock() |
| 242 | for i, timer := range m.timers { |
| 243 | if timer == t { |
| 244 | copy(m.timers[i:], m.timers[i+1:]) |
| 245 | m.timers[len(m.timers)-1] = nil |
| 246 | m.timers = m.timers[:len(m.timers)-1] |
| 247 | break |
| 248 | } |
| 249 | } |
| 250 | sort.Sort(m.timers) |
| 251 | } |
| 252 | |
| 253 | // clockTimer represents an object with an associated start time. |
| 254 | type clockTimer interface { |
| 255 | Next() time.Time |
| 256 | Tick(time.Time) |
| 257 | } |
| 258 | |
| 259 | // clockTimers represents a list of sortable timers. |
| 260 | type clockTimers []clockTimer |
| 261 | |
| 262 | func (a clockTimers) Len() int { return len(a) } |
| 263 | func (a clockTimers) Swap(i, j int) { a[i], a[j] = a[j], a[i] } |
| 264 | func (a clockTimers) Less(i, j int) bool { return a[i].Next().Before(a[j].Next()) } |
| 265 | |
| 266 | // Timer represents a single event. |
| 267 | // The current time will be sent on C, unless the timer was created by AfterFunc. |
| 268 | type Timer struct { |
| 269 | C <-chan time.Time |
| 270 | c chan time.Time |
| 271 | timer *time.Timer // realtime impl, if set |
| 272 | next time.Time // next tick time |
| 273 | mock *Mock // mock clock, if set |
| 274 | fn func() // AfterFunc function, if set |
| 275 | stopped bool // True if stopped, false if running |
| 276 | } |
| 277 | |
| 278 | // Stop turns off the ticker. |
| 279 | func (t *Timer) Stop() bool { |
| 280 | if t.timer != nil { |
| 281 | return t.timer.Stop() |
| 282 | } |
| 283 | |
| 284 | t.mock.mu.Lock() |
| 285 | registered := !t.stopped |
| 286 | t.mock.mu.Unlock() |
| 287 | |
| 288 | t.mock.removeClockTimer((*internalTimer)(t)) |
| 289 | t.mock.mu.Lock() |
| 290 | defer t.mock.mu.Unlock() |
| 291 | t.stopped = true |
| 292 | return registered |
| 293 | } |
| 294 | |
| 295 | // Reset changes the expiry time of the timer |
| 296 | func (t *Timer) Reset(d time.Duration) bool { |
| 297 | if t.timer != nil { |
| 298 | return t.timer.Reset(d) |
| 299 | } |
| 300 | |
| 301 | t.next = t.mock.now.Add(d) |
| 302 | t.mock.mu.Lock() |
| 303 | defer t.mock.mu.Unlock() |
| 304 | |
| 305 | registered := !t.stopped |
| 306 | if t.stopped { |
| 307 | t.mock.timers = append(t.mock.timers, (*internalTimer)(t)) |
| 308 | } |
| 309 | |
| 310 | t.stopped = false |
| 311 | return registered |
| 312 | } |
| 313 | |
| 314 | type internalTimer Timer |
| 315 | |
| 316 | func (t *internalTimer) Next() time.Time { return t.next } |
| 317 | func (t *internalTimer) Tick(now time.Time) { |
| 318 | if t.fn != nil { |
| 319 | t.fn() |
| 320 | } else { |
| 321 | t.c <- now |
| 322 | } |
| 323 | t.mock.removeClockTimer((*internalTimer)(t)) |
| 324 | t.mock.mu.Lock() |
| 325 | defer t.mock.mu.Unlock() |
| 326 | |
| 327 | t.stopped = true |
| 328 | t.mock.gosched() |
| 329 | } |
| 330 | |
| 331 | // Ticker holds a channel that receives "ticks" at regular intervals. |
| 332 | type Ticker struct { |
| 333 | C <-chan time.Time |
| 334 | c chan time.Time |
| 335 | ticker *time.Ticker // realtime impl, if set |
| 336 | next time.Time // next tick time |
| 337 | mock *Mock // mock clock, if set |
| 338 | d time.Duration // time between ticks |
| 339 | } |
| 340 | |
| 341 | // Stop turns off the ticker. |
| 342 | func (t *Ticker) Stop() { |
| 343 | if t.ticker != nil { |
| 344 | t.ticker.Stop() |
| 345 | } else { |
| 346 | t.mock.removeClockTimer((*internalTicker)(t)) |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | type internalTicker Ticker |
| 351 | |
| 352 | func (t *internalTicker) Next() time.Time { return t.next } |
| 353 | func (t *internalTicker) Tick(now time.Time) { |
| 354 | select { |
| 355 | case t.c <- now: |
| 356 | default: |
| 357 | } |
| 358 | t.next = now.Add(t.d) |
| 359 | t.mock.gosched() |
| 360 | } |