simclock.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. // Copyright 2018 The go-ethereum Authors
  2. // This file is part of the go-ethereum library.
  3. //
  4. // The go-ethereum library is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Lesser General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // The go-ethereum library is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Lesser General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Lesser General Public License
  15. // along with the go-ethereum library. If not, see <http://www.gnu.org/licenses/>.
  16. package mclock
  17. import (
  18. "container/heap"
  19. "sync"
  20. "time"
  21. )
  22. // Simulated implements a virtual Clock for reproducible time-sensitive tests. It
  23. // simulates a scheduler on a virtual timescale where actual processing takes zero time.
  24. //
  25. // The virtual clock doesn't advance on its own, call Run to advance it and execute timers.
  26. // Since there is no way to influence the Go scheduler, testing timeout behaviour involving
  27. // goroutines needs special care. A good way to test such timeouts is as follows: First
  28. // perform the action that is supposed to time out. Ensure that the timer you want to test
  29. // is created. Then run the clock until after the timeout. Finally observe the effect of
  30. // the timeout using a channel or semaphore.
  31. type Simulated struct {
  32. now AbsTime
  33. scheduled simTimerHeap
  34. mu sync.RWMutex
  35. cond *sync.Cond
  36. }
  37. // simTimer implements ChanTimer on the virtual clock.
  38. type simTimer struct {
  39. at AbsTime
  40. index int // position in s.scheduled
  41. s *Simulated
  42. do func()
  43. ch <-chan AbsTime
  44. }
  45. func (s *Simulated) init() {
  46. if s.cond == nil {
  47. s.cond = sync.NewCond(&s.mu)
  48. }
  49. }
  50. // Run moves the clock by the given duration, executing all timers before that duration.
  51. func (s *Simulated) Run(d time.Duration) {
  52. s.mu.Lock()
  53. s.init()
  54. end := s.now.Add(d)
  55. var do []func()
  56. for len(s.scheduled) > 0 && s.scheduled[0].at <= end {
  57. ev := heap.Pop(&s.scheduled).(*simTimer)
  58. do = append(do, ev.do)
  59. }
  60. s.now = end
  61. s.mu.Unlock()
  62. for _, fn := range do {
  63. fn()
  64. }
  65. }
  66. // ActiveTimers returns the number of timers that haven't fired.
  67. func (s *Simulated) ActiveTimers() int {
  68. s.mu.RLock()
  69. defer s.mu.RUnlock()
  70. return len(s.scheduled)
  71. }
  72. // WaitForTimers waits until the clock has at least n scheduled timers.
  73. func (s *Simulated) WaitForTimers(n int) {
  74. s.mu.Lock()
  75. defer s.mu.Unlock()
  76. s.init()
  77. for len(s.scheduled) < n {
  78. s.cond.Wait()
  79. }
  80. }
  81. // Now returns the current virtual time.
  82. func (s *Simulated) Now() AbsTime {
  83. s.mu.RLock()
  84. defer s.mu.RUnlock()
  85. return s.now
  86. }
  87. // Sleep blocks until the clock has advanced by d.
  88. func (s *Simulated) Sleep(d time.Duration) {
  89. <-s.After(d)
  90. }
  91. // NewTimer creates a timer which fires when the clock has advanced by d.
  92. func (s *Simulated) NewTimer(d time.Duration) ChanTimer {
  93. s.mu.Lock()
  94. defer s.mu.Unlock()
  95. ch := make(chan AbsTime, 1)
  96. var timer *simTimer
  97. timer = s.schedule(d, func() { ch <- timer.at })
  98. timer.ch = ch
  99. return timer
  100. }
  101. // After returns a channel which receives the current time after the clock
  102. // has advanced by d.
  103. func (s *Simulated) After(d time.Duration) <-chan AbsTime {
  104. return s.NewTimer(d).C()
  105. }
  106. // AfterFunc runs fn after the clock has advanced by d. Unlike with the system
  107. // clock, fn runs on the goroutine that calls Run.
  108. func (s *Simulated) AfterFunc(d time.Duration, fn func()) Timer {
  109. s.mu.Lock()
  110. defer s.mu.Unlock()
  111. return s.schedule(d, fn)
  112. }
  113. func (s *Simulated) schedule(d time.Duration, fn func()) *simTimer {
  114. s.init()
  115. at := s.now.Add(d)
  116. ev := &simTimer{do: fn, at: at, s: s}
  117. heap.Push(&s.scheduled, ev)
  118. s.cond.Broadcast()
  119. return ev
  120. }
  121. func (ev *simTimer) Stop() bool {
  122. ev.s.mu.Lock()
  123. defer ev.s.mu.Unlock()
  124. if ev.index < 0 {
  125. return false
  126. }
  127. heap.Remove(&ev.s.scheduled, ev.index)
  128. ev.s.cond.Broadcast()
  129. ev.index = -1
  130. return true
  131. }
  132. func (ev *simTimer) Reset(d time.Duration) {
  133. if ev.ch == nil {
  134. panic("mclock: Reset() on timer created by AfterFunc")
  135. }
  136. ev.s.mu.Lock()
  137. defer ev.s.mu.Unlock()
  138. ev.at = ev.s.now.Add(d)
  139. if ev.index < 0 {
  140. heap.Push(&ev.s.scheduled, ev) // already expired
  141. } else {
  142. heap.Fix(&ev.s.scheduled, ev.index) // hasn't fired yet, reschedule
  143. }
  144. ev.s.cond.Broadcast()
  145. }
  146. func (ev *simTimer) C() <-chan AbsTime {
  147. if ev.ch == nil {
  148. panic("mclock: C() on timer created by AfterFunc")
  149. }
  150. return ev.ch
  151. }
  152. type simTimerHeap []*simTimer
  153. func (h *simTimerHeap) Len() int {
  154. return len(*h)
  155. }
  156. func (h *simTimerHeap) Less(i, j int) bool {
  157. return (*h)[i].at < (*h)[j].at
  158. }
  159. func (h *simTimerHeap) Swap(i, j int) {
  160. (*h)[i], (*h)[j] = (*h)[j], (*h)[i]
  161. (*h)[i].index = i
  162. (*h)[j].index = j
  163. }
  164. func (h *simTimerHeap) Push(x interface{}) {
  165. t := x.(*simTimer)
  166. t.index = len(*h)
  167. *h = append(*h, t)
  168. }
  169. func (h *simTimerHeap) Pop() interface{} {
  170. end := len(*h) - 1
  171. t := (*h)[end]
  172. t.index = -1
  173. (*h)[end] = nil
  174. *h = (*h)[:end]
  175. return t
  176. }