-
Notifications
You must be signed in to change notification settings - Fork 8
/
manual.go
439 lines (369 loc) · 10.6 KB
/
manual.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
package abtime
// In the docs, I say that "we can't distinguish between calls to After" or sleep.
// A clever programmer may decide that we could, if we require them all
// to use slightly different times; we could then key on times. However,
// that invites excessive binding of values between the concrete code and
// test suite. Plus that's just a weird binding that invites problems.
import (
"context"
"sync"
"time"
)
// The ManualTime object implements a time object you directly control.
//
// This allows you to manipulate "now", and control when events occur.
type ManualTime struct {
now time.Time
nows []time.Time
triggers map[int]*triggerInfo
sync.Mutex
}
type triggerInfo struct {
// the number of times this has been Triggered without anything in
// the triggers array. This accounts for when .Trigger is called
// before the thing has been registered.
count uint
triggers []trigger
}
type trigger interface {
// Note this is always called while the lock for *ManualTime is
// held.
trigger(mt *ManualTime) bool // if true, delete the token; if false, keep it.
}
func (mt *ManualTime) register(id int, trig trigger) {
mt.Lock()
defer mt.Unlock()
currentTriggerInfo, present := mt.triggers[id]
if !present {
mt.triggers[id] = &triggerInfo{0, []trigger{trig}}
return
}
currentTriggerInfo.triggers = append(currentTriggerInfo.triggers, trig)
triggerAll(mt, currentTriggerInfo)
}
// NewManual returns a new ManualTime object, with the Now populated
// from the time.Now().
func NewManual() *ManualTime {
return &ManualTime{now: time.Now(), nows: []time.Time{}, triggers: make(map[int]*triggerInfo)}
}
// NewManualAtTime returns a new ManualTime object, with the Now set to the
// time.Time you pass in.
func NewManualAtTime(now time.Time) *ManualTime {
return &ManualTime{now: now, nows: []time.Time{}, triggers: make(map[int]*triggerInfo)}
}
// triggerAll triggers all registered triggers count times, discarding triggers
// as requested.
func triggerAll(mt *ManualTime, ti *triggerInfo) {
for ti.count > 0 && len(ti.triggers) > 0 {
keep := []trigger{}
for _, toTrigger := range ti.triggers {
if !toTrigger.trigger(mt) {
keep = append(keep, toTrigger)
}
}
ti.triggers = keep
ti.count--
}
}
// Trigger takes the given ids for time events, and causes them to "occur":
// triggering messages on channels, ending sleeps, etc.
//
// Note this is the ONLY way to "trigger" such events. While this package
// allows you to manipulate "Now" in a couple of different ways, advancing
// "now" past a Trigger's set time will NOT trigger it. First, this keeps
// it simple to understand when things are triggered, and second, reality
// isn't so deterministic anyhow....
func (mt *ManualTime) Trigger(ids ...int) {
mt.Lock()
defer mt.Unlock()
for _, id := range ids {
triggers, hasTriggers := mt.triggers[id]
if !hasTriggers {
mt.triggers[id] = &triggerInfo{1, []trigger{}}
continue
}
triggers.count++
triggerAll(mt, triggers)
}
}
// Unregister will unregister a particular ID from the system. Normally the
// first one sticks, which means if you've got code that creates multiple
// timers in a loop or in multiple function calls, only the first one will
// work.
//
// NOTE: This method indicates a design flaw in abtime. It is not yet clear
// to me how to fix it in any reasonable way.
func (mt *ManualTime) Unregister(ids ...int) {
mt.Lock()
for _, id := range ids {
delete(mt.triggers, id)
}
mt.Unlock()
}
// UnregisterAll will unregister all current IDs from the manual time,
// returning you to a fresh view of the created channels and timers and
// such.
func (mt *ManualTime) UnregisterAll() {
mt.Lock()
mt.triggers = map[int]*triggerInfo{}
mt.Unlock()
}
// Now returns the ManualTime's current idea of "Now".
//
// If you have used QueueNow, this will advance to the next queued Now.
func (mt *ManualTime) Now() time.Time {
mt.Lock()
defer mt.Unlock()
if len(mt.nows) > 0 {
mt.now = mt.nows[0]
mt.nows = mt.nows[1:]
return mt.now
}
return mt.now
}
// Advance advances the manual time's idea of "now" by the given
// duration.
//
// If there is a queue of "Nows" from QueueNows, note this won't
// affect any of them.
func (mt *ManualTime) Advance(d time.Duration) {
mt.Lock()
defer mt.Unlock()
mt.now = mt.now.Add(d)
}
// QueueNows allows you to set a number of times to be retrieved by
// successive calls to "Now". Once the queue is consumed by calls to Now(),
// the last time in the queue "sticks" as the new Now.
//
// This is useful if you have code that is timing how long something took
// by successive calls to .Now, with no other place for the test code to
// intercede.
//
// If multiple threads are accessing the Manual, it is of course
// non-deterministic who gets what time. However this could still be
// useful.
func (mt *ManualTime) QueueNows(times ...time.Time) {
mt.Lock()
defer mt.Unlock()
mt.nows = append(mt.nows, times...)
}
type afterTrigger struct {
mt *ManualTime
d time.Duration
ch chan time.Time
}
func (afterT afterTrigger) trigger(mt *ManualTime) bool {
go func() { afterT.ch <- afterT.mt.now.Add(afterT.d) }()
return true
}
// After wraps time.After, and waits for the target id.
func (mt *ManualTime) After(d time.Duration, id int) <-chan time.Time {
timeChan := make(chan time.Time)
trigger := afterTrigger{mt, d, timeChan}
mt.register(id, trigger)
return timeChan
}
type sleepTrigger struct {
c chan struct{}
}
func (st sleepTrigger) trigger(mt *ManualTime) bool {
go func() { st.c <- struct{}{} }()
return true
}
// Sleep halts execution until you release it via Trigger.
func (mt *ManualTime) Sleep(d time.Duration, id int) {
ch := make(chan struct{})
mt.register(id, sleepTrigger{ch})
<-ch
}
type tickTrigger struct {
C chan time.Time
now time.Time
d time.Duration
stopped bool
sync.Mutex
}
func (tt *tickTrigger) trigger(mt *ManualTime) bool {
tt.Lock()
defer tt.Unlock()
if tt.stopped {
return true
}
tt.now = tt.now.Add(tt.d)
go func() { tt.C <- tt.now }()
return false
}
func (tt *tickTrigger) Stop() {
tt.Lock()
defer tt.Unlock()
tt.stopped = true
}
func (tt *tickTrigger) Channel() <-chan time.Time {
return tt.C
}
func (tt *tickTrigger) Reset(time.Duration) {}
// NewTicker wraps time.NewTicker. It takes a snapshot of "now" at the
// point of the TickToken call, and will increment the time it returns
// by the Duration of the tick.
//
// Note that this can cause times to arrive out of order relative to
// each other if you have many of these going at once, if you manually
// trigger the ticks in such a way that they will be out of order.
func (mt *ManualTime) NewTicker(d time.Duration, id int) Ticker {
ch := make(chan time.Time)
tt := &tickTrigger{C: ch, now: mt.now, d: d}
mt.register(id, tt)
return tt
}
// Tick allows you to create a ticker. See notes on NewTicker.
func (mt *ManualTime) Tick(d time.Duration, id int) <-chan time.Time {
return mt.NewTicker(d, id).(*tickTrigger).C
}
type afterFuncTrigger struct {
f func()
stopped bool
sync.Mutex
}
func (af *afterFuncTrigger) Reset(d time.Duration) bool {
af.Lock()
defer af.Unlock()
ret := af.stopped
af.stopped = false
return ret
}
func (af *afterFuncTrigger) Stop() bool {
af.Lock()
defer af.Unlock()
ret := !af.stopped
af.stopped = true
return ret
}
func (af *afterFuncTrigger) Channel() <-chan time.Time {
return nil
}
func (af *afterFuncTrigger) trigger(mt *ManualTime) bool {
af.Lock()
defer af.Unlock()
if !af.stopped {
go af.f()
}
af.stopped = true
return true
}
// AfterFunc fires the function in its own goroutine when the id is
// .Trigger()ed. The resulting Timer object will return nil for its Channel().
func (mt *ManualTime) AfterFunc(d time.Duration, f func(), id int) Timer {
af := &afterFuncTrigger{f: f, stopped: false}
mt.register(id, af)
return af
}
type timerTrigger struct {
c chan time.Time
initialNow time.Time
duration time.Duration
stopped bool
sync.Mutex
}
func (tt *timerTrigger) Reset(d time.Duration) bool {
tt.Lock()
defer tt.Unlock()
tt.duration = d
ret := !tt.stopped
tt.stopped = false
return ret
}
func (tt *timerTrigger) Stop() bool {
tt.Lock()
defer tt.Unlock()
ret := tt.stopped
tt.stopped = true
return !ret
}
func (tt *timerTrigger) Channel() <-chan time.Time {
return tt.c
}
func (tt *timerTrigger) trigger(mt *ManualTime) bool {
tt.Lock()
if tt.stopped {
tt.Unlock()
return true
}
tt.stopped = true
tt.Unlock()
go func() { tt.c <- tt.initialNow.Add(tt.duration) }()
return true
}
// NewTimer allows you to create a Ticker, which can be triggered
// via the given id, and also supports the Stop operation *time.Tickers have.
func (mt *ManualTime) NewTimer(d time.Duration, id int) Timer {
tt := &timerTrigger{c: make(chan time.Time), initialNow: mt.now, duration: d}
mt.register(id, tt)
return tt
}
type contextTrigger struct {
context.Context
deadline time.Time
closed bool
done chan struct{}
err error
mu sync.Mutex
}
func (ct *contextTrigger) Deadline() (time.Time, bool) {
return ct.deadline, true
}
func (ct *contextTrigger) Done() <-chan struct{} {
return ct.done
}
func (ct *contextTrigger) Err() error {
ct.mu.Lock()
defer ct.mu.Unlock()
return ct.err
}
func (ct *contextTrigger) Value(key interface{}) interface{} {
return ct.Context.Value(key)
}
func (ct *contextTrigger) cancel(err error) {
ct.mu.Lock()
defer ct.mu.Unlock()
if !ct.closed {
close(ct.done)
ct.closed = true
ct.err = err
}
}
func (ct *contextTrigger) trigger(_ *ManualTime) bool {
ct.cancel(context.DeadlineExceeded)
return true
}
// WithDeadline is a valid Context that is meant to drop in over a regular
// context.WithDeadline invocation. Instead of being canceled when reaching an
// actual deadline the context is canceled either by Trigger or by the returned
// CancelFunc.
func (mt *ManualTime) WithDeadline(parent context.Context, deadline time.Time, id int) (context.Context, context.CancelFunc) {
if parent == nil {
panic("cannot create context from nil parent")
}
ct := &contextTrigger{
Context: parent,
deadline: deadline,
done: make(chan struct{}),
}
cancelF := func() {
ct.cancel(context.Canceled)
}
mt.register(id, ct)
go func() {
select {
case <-parent.Done():
ct.cancel(parent.Err())
case <-ct.Done():
// do nothing
}
}()
return ct, context.CancelFunc(cancelF)
}
// WithTimeout is equivalent to WithDeadline invoked on a deadline equal to the
// current time plus the timeout.
func (mt *ManualTime) WithTimeout(parent context.Context, timeout time.Duration, id int) (context.Context, context.CancelFunc) {
return mt.WithDeadline(parent, mt.Now().Add(timeout), id)
}