-
Notifications
You must be signed in to change notification settings - Fork 694
/
queue.go
232 lines (201 loc) · 5.01 KB
/
queue.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
package queue
import (
"errors"
"expvar"
"sync"
"time"
)
// stats captures stats for the Queue.
var stats *expvar.Map
const (
numObjectsRx = "objects_rx"
numObjectsTx = "objects_tx"
numTimeout = "num_timeout"
numFlush = "num_flush"
)
func init() {
stats = expvar.NewMap("queue")
ResetStats()
}
// ResetStats resets the expvar stats for this module. Mostly for test purposes.
func ResetStats() {
stats.Init()
stats.Add(numObjectsRx, 0)
stats.Add(numObjectsTx, 0)
stats.Add(numTimeout, 0)
stats.Add(numFlush, 0)
}
// FlushChannel is the type passed to the Queue, if caller wants
// to know when a specific set of objects has been processed.
type FlushChannel chan bool
// Request represents a batch of objects to be processed.
type Request[T any] struct {
SequenceNumber int64
Objects []T
flushChans []FlushChannel
}
// Close closes a request, closing any associated flush channels.
func (r *Request[T]) Close() {
for _, c := range r.flushChans {
close(c)
}
}
type queuedObjects[T any] struct {
SequenceNumber int64
Objects []T
flushChan FlushChannel
}
func mergeQueued[T any](qs []*queuedObjects[T]) *Request[T] {
var o *Request[T]
if len(qs) > 0 {
o = &Request[T]{
SequenceNumber: qs[0].SequenceNumber,
flushChans: make([]FlushChannel, 0),
}
}
for i := range qs {
if o.SequenceNumber < qs[i].SequenceNumber {
o.SequenceNumber = qs[i].SequenceNumber
}
o.Objects = append(o.Objects, qs[i].Objects...)
if qs[i].flushChan != nil {
o.flushChans = append(o.flushChans, qs[i].flushChan)
}
}
return o
}
// Queue is a batching queue with a timeout.
type Queue[T any] struct {
maxSize int
batchSize int
timeout time.Duration
batchCh chan *queuedObjects[T]
sendCh chan *Request[T]
C <-chan *Request[T]
done chan struct{}
closed chan struct{}
flush chan struct{}
seqMu sync.Mutex
seqNum int64
// Whitebox unit-testing
numTimeouts int
}
// New returns a instance of a Queue
func New[T any](maxSize, batchSize int, t time.Duration) *Queue[T] {
q := &Queue[T]{
maxSize: maxSize,
batchSize: batchSize,
timeout: t,
batchCh: make(chan *queuedObjects[T], maxSize),
sendCh: make(chan *Request[T], 1),
done: make(chan struct{}),
closed: make(chan struct{}),
flush: make(chan struct{}),
seqNum: time.Now().UnixNano(),
}
q.C = q.sendCh
go q.run()
return q
}
// Write queues a request, and returns a monotonically incrementing
// sequence number associated with the slice of objects. A slice with
// a lower sequence number than second slice will always be transmitted
// on the Queue's C object before the second slice.
//
// c is an optional channel. If non-nil, it will be closed when the Request
// containing these statements is closed.
func (q *Queue[T]) Write(objects []T, c FlushChannel) (int64, error) {
select {
case <-q.done:
return 0, errors.New("queue is closed")
default:
}
// Take the lock and don't release it until the function returns.
// This ensures that the incremented sequence number and write to
// batch channel are synchronized.
q.seqMu.Lock()
defer q.seqMu.Unlock()
q.seqNum++
q.batchCh <- &queuedObjects[T]{
SequenceNumber: q.seqNum,
Objects: objects,
flushChan: c,
}
stats.Add(numObjectsRx, int64(len(objects)))
return q.seqNum, nil
}
// Flush flushes the queue
func (q *Queue[T]) Flush() error {
q.flush <- struct{}{}
return nil
}
// Close closes the queue. A closed queue should not be used.
func (q *Queue[T]) Close() error {
select {
case <-q.done:
default:
close(q.done)
<-q.closed
}
return nil
}
// Depth returns the number of queued requests
func (q *Queue[T]) Depth() int {
return len(q.batchCh)
}
// Stats returns stats on this queue.
func (q *Queue[T]) Stats() (map[string]interface{}, error) {
return map[string]interface{}{
"max_size": q.maxSize,
"batch_size": q.batchSize,
"timeout": q.timeout.String(),
}, nil
}
func (q *Queue[T]) run() {
defer close(q.closed)
queuedStmts := make([]*queuedObjects[T], 0)
// Create an initial timer, in the stopped state.
timer := time.NewTimer(0)
<-timer.C
writeFn := func() {
// mergeQueued returns a new object, ownership will pass
// implicitly to the other side of sendCh.
req := mergeQueued(queuedStmts)
if req != nil {
q.sendCh <- req
stats.Add(numObjectsTx, int64(len(req.Objects)))
queuedStmts = queuedStmts[:0] // Better on the GC than setting to nil.
}
}
for {
select {
case s := <-q.batchCh:
queuedStmts = append(queuedStmts, s)
if len(queuedStmts) == 1 {
// First item in queue, start the timer so that if
// we don't get in a batch, we'll still write.
timer.Reset(q.timeout)
}
if len(queuedStmts) == q.batchSize {
stopTimer(timer)
writeFn()
}
case <-timer.C:
stats.Add(numTimeout, 1)
q.numTimeouts++
writeFn()
case <-q.flush:
stats.Add(numFlush, 1)
stopTimer(timer)
writeFn()
case <-q.done:
stopTimer(timer)
return
}
}
}
func stopTimer(timer *time.Timer) {
if !timer.Stop() && len(timer.C) > 0 {
<-timer.C
}
}