-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmonitor.go
126 lines (103 loc) · 2.36 KB
/
monitor.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
// Copyright (C) 2019-2025, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package simplex
import (
"context"
"go.uber.org/zap"
"sync/atomic"
"time"
)
type Monitor struct {
logger Logger
close chan struct{}
time atomic.Value
ticks chan time.Time
tasks chan func()
futureTask atomic.Value
}
type futureTask struct {
deadline time.Time
f func()
}
func NewMonitor(startTime time.Time, logger Logger) *Monitor {
m := &Monitor{
logger: logger,
close: make(chan struct{}),
tasks: make(chan func(), 1),
ticks: make(chan time.Time, 1),
}
m.time.Store(startTime)
go m.run()
return m
}
func (m *Monitor) AdvanceTime(t time.Time) {
m.time.Store(t)
select {
case m.ticks <- t:
default:
}
}
func (m *Monitor) tick(now time.Time, taskID uint64) {
defer m.logger.Trace("Ticked", zap.Uint64("taskID", taskID), zap.Time("time", now))
ft := m.futureTask.Load()
if ft == nil {
return
}
task := ft.(*futureTask)
if task.f == nil || task.deadline.IsZero() || now.Before(task.deadline) {
return
}
m.logger.Debug("Executing f", zap.Uint64("taskID", taskID), zap.Time("deadline", task.deadline))
task.f()
m.logger.Debug("Executed f", zap.Uint64("taskID", taskID), zap.Time("time", now), zap.Time("deadline", task.deadline))
// clean up future task to mark we have already executed it and to release memory
m.futureTask.Store(&futureTask{})
}
func (m *Monitor) run() {
var taskID uint64
for m.shouldRun() {
select {
case tick := <-m.ticks:
m.tick(tick, taskID)
taskID++
case f := <-m.tasks:
m.logger.Debug("Executing f", zap.Uint64("taskID", taskID))
f()
m.logger.Debug("Task executed", zap.Uint64("taskID", taskID))
}
}
}
func (m *Monitor) shouldRun() bool {
select {
case <-m.close:
return false
default:
return true
}
}
func (m *Monitor) Close() {
select {
case <-m.close:
return
default:
close(m.close)
}
}
func (m *Monitor) WaitFor(f func()) {
select {
case m.tasks <- f:
default:
}
}
func (m *Monitor) WaitUntil(timeout time.Duration, f func()) context.CancelFunc {
t := m.time.Load()
time := t.(time.Time)
m.futureTask.Store(&futureTask{
f: f,
deadline: time.Add(timeout),
})
m.logger.Debug("Scheduling task", zap.Duration("timeout", timeout), zap.Time("deadline", time))
return func() {
m.futureTask.Store(&futureTask{})
}
}