-
Notifications
You must be signed in to change notification settings - Fork 4
/
timer.go
379 lines (299 loc) · 8.93 KB
/
timer.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
package boardgame
import (
"container/heap"
"time"
)
//ImmutableTimer is a Timer that does not have any mutator methods. See Timer
//for more.
type ImmutableTimer interface {
//Active returns true if the given timer has been Start()'d and has not
//yet fired or been canceled.
Active() bool
//TimerLeft reutrns the amount of time until the timer fires, if it is
//active.
TimeLeft() time.Duration
id() string
state() *state
setState(*state)
}
//Timer is a type of property that can be used in states that represents a
//countdown. Timers must exist in a given SubState in your state, and must
//always be non-nil, even if they aren't actively being used.
type Timer interface {
ImmutableTimer
//Start begins a timer that will automatically call game.ProposeMove(Move,
//AdminPlayerIndex) after the given duration has elapsed. Generally called
//from within a move.Apply() method.
Start(time.Duration, Move)
//Cancel cancels a previously Start()'d timer, so that it will no longer
//fire. If the timer was not active, it's a no-op. The return value is
//whether the timer was active before being canceled. Generally called
//during a move.Apply() method.
Cancel() bool
importFrom(other ImmutableTimer) error
}
type timer struct {
//Id will be an opaque identifier that is used to keep track of the
//corresponding underlying Timer object in the game engine. It is not
//meaningful to inspect yourself and should not be modified.
ID string
statePtr *state
}
//NewTimer returns a new blank timer, ready for use. Typically this would be
//used inside of GameDelegate.GameStateConstructor and friends. In practice
//however this is not necessary because the auto-crated StructInflaters for
//your structs will install a non-nil Timer even if not struct tags are
//provided, because no configuration is necessary. See StructInflater for
//more.
func NewTimer() Timer {
return &timer{}
}
func (t *timer) importFrom(other ImmutableTimer) error {
t.ID = other.id()
return nil
}
func (t *timer) id() string {
return t.ID
}
func (t *timer) state() *state {
return t.statePtr
}
func (t *timer) setState(state *state) {
t.statePtr = state
}
func (t *timer) MarshalJSON() ([]byte, error) {
obj := map[string]interface{}{
"ID": t.ID,
//TODO: this is a hack so client can find it easily
"IsTimer": true,
}
return DefaultMarshalJSON(obj)
}
//Active returns true if the timer is active and counting down.
func (t *timer) Active() bool {
return t.statePtr.game.manager.timers.TimerActive(t.ID)
}
//TimeLeft returns the number of nanoseconds left until this timer fires.
func (t *timer) TimeLeft() time.Duration {
return t.statePtr.game.manager.timers.GetTimerRemaining(t.ID)
}
//Start starts the timer. After duration has passed, the Move will be proposed
//via proposeMove. If the timer is already active, it will be canceled before
//the new timer is configured.
func (t *timer) Start(duration time.Duration, move Move) {
if t.Active() {
t.Cancel()
}
game := t.statePtr.game
manager := game.manager
t.ID = manager.timers.PrepareTimer(duration, t.statePtr, move)
t.statePtr.timersToStart = append(t.statePtr.timersToStart, t.ID)
}
//Cancel cancels an active timer. If the timer is not active, it has no
//effect. Returns true if the timer was active and canceled, false if the
//timer was not active.
func (t *timer) Cancel() bool {
wasActive := t.Active()
manager := t.statePtr.game.manager
manager.timers.CancelTimer(t.ID)
//Technically there's a case where Start() was called, but the state was
//never fully committed. However, StartTimer() on a canceled timer is a
//no-op so it's fine.
t.ID = ""
return wasActive
}
type timerRecord struct {
id string
gameID string
index int
//When the timer should fire. Set after the timer is fully Started().
//Before that it is impossibly far in the future.
fireTime time.Time
//The duration we were configured with. Only set when the timer is
//Prepared() but not yet Started().
duration time.Duration
game *Game
move Move
}
func (t *timerRecord) MarshalJSON() ([]byte, error) {
//TODO: return other information, evertyhing in TimerRecord struct in issue 698.
obj := map[string]interface{}{
//TimeLeft is only ever for the client (it's not read back in when
//deserialized), so put it in the more traditional milliseconds units,
//not nanoseconds.
"TimeLeft": t.TimeRemaining() / time.Millisecond,
}
return DefaultMarshalJSON(obj)
}
func (t *timerRecord) TimeRemaining() time.Duration {
//Before a timer is Started(), just say its duration as the time
//remaining.
if t.duration > 0 {
return t.duration
}
duration := t.fireTime.Sub(time.Now())
if duration < 0 {
duration = 0
}
return duration
}
type timerQueue []*timerRecord
type timerManager struct {
records timerQueue
recordsByID map[string]*timerRecord
//TODO: recordsByGameId for efficiency so we don't have to search
manager *GameManager
}
func newTimerManager(gameManager *GameManager) *timerManager {
return &timerManager{
//the default id in TimerProps is 0, so we should start beyond that.
records: make(timerQueue, 0),
recordsByID: make(map[string]*timerRecord),
manager: gameManager,
}
}
const timerIDLength = 16
func (t *timerManager) ActiveTimersForGame(gameID string) map[string]*timerRecord {
result := make(map[string]*timerRecord)
for _, rec := range t.recordsByID {
if rec.gameID == gameID {
result[rec.id] = rec
}
}
return result
}
//PrepareTimer creates a timer entry and gets it ready and an Id allocated.
//However, the timer doesn't actually start counting down until
//manager.StartTimer(id) is called.
func (t *timerManager) PrepareTimer(duration time.Duration, state *state, move Move) string {
record := &timerRecord{
id: randomString(timerIDLength, state.Rand()),
gameID: state.Game().ID(),
index: -1,
duration: duration,
//fireTime will be set when StartTimer is called. For now, set it to
//something impossibly far in the future.
fireTime: time.Now().Add(time.Hour * 100000),
game: state.Game(),
move: move,
}
t.recordsByID[record.id] = record
heap.Push(&t.records, record)
return record.id
}
//StartTimer actually triggers a timer that was previously PrepareTimer'd to
//start counting down.
func (t *timerManager) StartTimer(id string) {
if t.TimerActive(id) {
return
}
record := t.recordsByID[id]
if record == nil {
return
}
record.fireTime = time.Now().Add(record.duration)
record.duration = 0
heap.Fix(&t.records, record.index)
}
//TimerActive returns if the timer is active and counting down.
func (t *timerManager) TimerActive(id string) bool {
record := t.recordsByID[id]
if record == nil {
return false
}
if record.duration > 0 {
return false
}
return true
}
func (t *timerManager) GetTimerRemaining(id string) time.Duration {
record := t.recordsByID[id]
if record == nil {
return 0
}
return record.TimeRemaining()
}
func (t *timerManager) CancelTimer(id string) {
record := t.recordsByID[id]
if record == nil {
return
}
heap.Remove(&t.records, record.index)
record.index = -1
delete(t.recordsByID, record.id)
}
//ForceNextTimer is designed to force fire the next timer no matter when it's
//_supposed_ to fire. Will return true if a timer was fired. Primarily exists
//for debug purposes.
func (t *timerManager) ForceNextTimer() bool {
record := t.popNext(true)
if record == nil {
return false
}
<-record.game.ProposeMove(record.move, AdminPlayerIndex)
return true
}
//Should be called regularly by the manager to tell this to check and see if
//any timers have fired, and execute them if so.
func (t *timerManager) Tick() {
for t.nextTimerFired() {
record := t.popNext(false)
if record == nil {
continue
}
if err := <-record.game.ProposeMove(record.move, AdminPlayerIndex); err != nil {
//TODO: log the error or something
t.manager.Logger().Info("When timer failed the move could not be made: ", err, record.move)
}
}
}
//Whether the next timer in the queue is already fired
func (t *timerManager) nextTimerFired() bool {
if len(t.records) == 0 {
return false
}
record := t.records[0]
return record.TimeRemaining() <= 0
}
func (t *timerManager) popNext(force bool) *timerRecord {
if force {
if len(t.records) == 0 {
return nil
}
} else {
if !t.nextTimerFired() {
return nil
}
}
x := heap.Pop(&t.records)
record := x.(*timerRecord)
delete(t.recordsByID, record.id)
return record
}
func (t timerQueue) Len() int {
return len(t)
}
func (t timerQueue) Less(i, j int) bool {
return t[i].fireTime.Sub(t[j].fireTime) < 0
}
func (t timerQueue) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
t[i].index = i
t[j].index = j
}
//DO NOT USE THIS DIRECTLY. Use heap.Push(t)
func (t *timerQueue) Push(x interface{}) {
n := len(*t)
item := x.(*timerRecord)
item.index = n
*t = append(*t, item)
}
//DO NOT USE THIS DIRECTLY. Use heap.Pop()
func (t *timerQueue) Pop() interface{} {
old := *t
n := len(old)
item := old[n-1]
item.index = -1
*t = old[0 : n-1]
return item
}