-
Notifications
You must be signed in to change notification settings - Fork 0
/
timeout_chan.go
273 lines (250 loc) · 5.94 KB
/
timeout_chan.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
package goproc
import (
"container/heap"
"context"
"fmt"
"sync"
"time"
)
// Deadliner is the interface implemented by an object that can return a deadline time.
type Deadliner interface {
Deadline() time.Time
}
// TimeoutChanStats contains timeout chan statistics returned from TimeoutChan.Stats().
type TimeoutChanStats struct {
Pushed int
Popped int
Cleared int
}
// String implements fmt.Stringer.
func (s TimeoutChanStats) String() string {
return fmt.Sprintf("TimeoutChanStats: Pushed=%d Popped=%d Cleared=%d", s.Pushed, s.Popped, s.Cleared)
}
// TimeoutChan is a type representing a channel for Deadliner objects.
// TimeoutChan accepts Deadliner from TimeoutChan.In and sends Deadliner to Timeout.Out when its
// deadline is reached.
type TimeoutChan struct {
In chan<- Deadliner
Out <-chan Deadliner
ctx context.Context
pushCtrl *Controller
popCtrl *Controller
resolution time.Duration
limit int
in chan Deadliner
out chan Deadliner
resumePush chan interface{}
resumePop chan interface{}
reschedule chan interface{}
closePush chan interface{}
mu *sync.RWMutex
pq *PriorityQueue
pushed int
popped int
cleared int
}
// NewTimeoutChan creates a new TimeoutChan. With 0 limit an unlimited timeout chan will be
// returned.
func NewTimeoutChan(ctx context.Context, resolution time.Duration, limit int) *TimeoutChan {
size := limit
if limit == 0 {
size = 1024
}
in := make(chan Deadliner)
out := make(chan Deadliner)
tc := &TimeoutChan{
In: in,
Out: out,
ctx: ctx,
pushCtrl: NewController(ctx, "TimeoutChan Push"),
popCtrl: NewController(ctx, "TimeoutChan Pop"),
resolution: resolution,
limit: limit,
in: in,
out: out,
resumePush: make(chan interface{}),
resumePop: make(chan interface{}),
reschedule: make(chan interface{}),
closePush: make(chan interface{}),
mu: &sync.RWMutex{},
pq: NewPriorityQueue(false, size),
pushed: 0,
popped: 0,
cleared: 0,
}
tc.popCtrl.Go(tc.popProcess)
tc.pushCtrl.Go(tc.pushProcess)
return tc
}
// Push is an alias of TimeoutChan.In <- (in Deadliner), but bypasses background push process for
// unlimited TimeoutChan.
func (c *TimeoutChan) Push(in Deadliner) {
if c.limit == 0 {
c.push(in)
} else {
c.In <- in
}
}
// Clear clears buffered Deadliners in TimeoutChan.
func (c *TimeoutChan) Clear() int {
c.mu.Lock()
defer c.mu.Unlock()
c.pushCtrl.Shutdown()
c.popCtrl.Shutdown()
l := c.pq.Clear()
if c.limit > 0 && l == c.limit {
defer func() { c.resumePush <- nil }() // queue is not full, resume
}
c.cleared += l
c.pushCtrl = NewController(c.ctx, "TimeoutChan Push")
c.popCtrl = NewController(c.ctx, "TimeoutChan Pop")
c.popCtrl.Go(c.popProcess)
c.pushCtrl.Go(c.pushProcess)
return l
}
// Close closes TimeoutChan and waits until all buffered Deadliners in TimeoutChan to be sent and
// read in TimeoutChan.Out before it returns.
func (c *TimeoutChan) Close() {
close(c.in)
c.pushCtrl.Wait()
close(c.closePush)
c.popCtrl.Wait()
close(c.out)
close(c.resumePush)
close(c.resumePop)
close(c.reschedule)
}
// Shutdown closes TimeoutChan and returns immediately, any buffered Deadliners in TimeoutChan will
// be ignored.
func (c *TimeoutChan) Shutdown() {
close(c.in)
c.pushCtrl.Shutdown()
close(c.closePush)
c.popCtrl.Shutdown()
close(c.out)
close(c.resumePush)
close(c.resumePop)
close(c.reschedule)
}
// Stats returns TimeoutChan statistics.
func (c *TimeoutChan) Stats() TimeoutChanStats {
c.mu.RLock()
defer c.mu.RUnlock()
return TimeoutChanStats{
Pushed: c.pushed,
Popped: c.popped,
Cleared: c.cleared,
}
}
func (c *TimeoutChan) len() int {
c.mu.RLock()
defer c.mu.RUnlock()
return c.pq.Len()
}
func (c *TimeoutChan) peek() (<-chan interface{}, time.Duration) {
c.mu.RLock()
defer c.mu.RUnlock()
return c.reschedule, c.pq.Peek().(Deadliner).Deadline().Sub(time.Now())
}
type prioritierWrapper struct {
Deadliner
}
func (w prioritierWrapper) Priority() int64 {
return w.Deadline().UnixNano()
}
func (c *TimeoutChan) push(in Deadliner) {
c.mu.Lock()
defer c.mu.Unlock()
if c.pq.Len() == 0 {
defer func() { c.resumePop <- nil }()
} else {
if in.Deadline().Before(c.pq.Peek().(Deadliner).Deadline()) {
// Most recent deadline changed, send reschedule notice
defer func() {
close(c.reschedule)
c.reschedule = make(chan interface{})
}()
}
}
heap.Push(c.pq, prioritierWrapper{in})
c.pushed++
}
func (c *TimeoutChan) pop() Deadliner {
c.mu.Lock()
defer c.mu.Unlock()
if c.limit > 0 && c.pq.Len() == c.limit {
defer func() { c.resumePush <- nil }() // queue is not full, resume
}
c.popped++
return heap.Pop(c.pq).(prioritierWrapper).Deadliner // unwrap
}
func (c *TimeoutChan) pushProcess(ctx context.Context) {
for {
// Working phase
select {
case in, ok := <-c.in:
if !ok {
// End push process because `in` channel is closed and drained
return
}
c.push(in)
if c.limit == 0 || c.len() < c.limit {
continue
} // else queue is full, suspense
case <-ctx.Done():
return
}
// Suspending phase
select {
case <-c.resumePush:
case <-ctx.Done():
return
}
}
}
func (c *TimeoutChan) popProcess(ctx context.Context) {
for {
// Suspending phase
select {
case <-c.resumePop:
case <-c.closePush:
if c.len() == 0 {
return
}
case <-ctx.Done():
return
}
// Working phase
outerLoop:
for {
// Peeking sub-phase
reschedule, delta := c.peek()
if delta <= 0 {
select {
case c.out <- c.pop():
if c.len() == 0 {
break outerLoop // queue is empty, suspend
}
case <-ctx.Done():
return
}
}
// Spinning sub-phase
if d := delta / 2; d > c.resolution {
delta = d
} else if delta > c.resolution {
delta = c.resolution
}
timer := time.NewTimer(delta)
select {
case <-reschedule: // should receive any reschedule after last peek
if !timer.Stop() {
<-timer.C
}
case <-timer.C:
case <-ctx.Done():
return
}
}
}
}