-
Notifications
You must be signed in to change notification settings - Fork 0
/
eventloop.go
574 lines (467 loc) · 11.6 KB
/
eventloop.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
package memqueue
import (
"fmt"
"math"
"time"
)
// directEventLoop implements the broker main event loop. It buffers events,
// but tries to forward events as early as possible.
type directEventLoop struct {
broker *Broker
buf ringBuffer
// active broker API channels
events chan pushRequest
get chan getRequest
pubCancel chan producerCancelRequest
// ack handling
acks chan int // ackloop -> eventloop : total number of events ACKed by outputs
schedACKS chan chanList // eventloop -> ackloop : active list of batches to be acked
pendingACKs chanList // ordered list of active batches to be send to the ackloop
ackSeq uint // ack batch sequence number to validate ordering
}
// bufferingEventLoop implements the broker main event loop.
// Events in the buffer are forwarded to consumers only if the buffer is full or on flush timeout.
type bufferingEventLoop struct {
broker *Broker
buf *batchBuffer
flushList flushList
eventCount int
minEvents int
maxEvents int
flushTimeout time.Duration
// active broker API channels
events chan pushRequest
get chan getRequest
pubCancel chan producerCancelRequest
// ack handling
acks chan int // ackloop -> eventloop : total number of events ACKed by outputs
schedACKS chan chanList // eventloop -> ackloop : active list of batches to be acked
pendingACKs chanList // ordered list of active batches to be send to the ackloop
ackSeq uint // ack batch sequence number to validate ordering
// buffer flush timer state
timer *time.Timer
idleC <-chan time.Time
}
type flushList struct {
head *batchBuffer
tail *batchBuffer
count int
}
func newDirectEventLoop(b *Broker, size int) *directEventLoop {
l := &directEventLoop{
broker: b,
events: b.events,
get: nil,
pubCancel: b.pubCancel,
acks: b.acks,
}
l.buf.init(b.logger, size)
return l
}
func (l *directEventLoop) run() {
var (
broker = l.broker
buf = &l.buf
)
for {
select {
case <-broker.done:
return
case req := <-l.events: // producer pushing new event
l.handleInsert(&req)
case req := <-l.pubCancel: // producer cancellig active events
l.handleCancel(&req)
case req := <-l.get: // consumer asking for next batch
l.handleConsumer(&req)
case l.schedACKS <- l.pendingACKs:
// on send complete list of pending batches has been forwarded -> clear list and queue
l.schedACKS = nil
l.pendingACKs = chanList{}
case count := <-l.acks:
l.handleACK(count)
}
// update get and idle timer after state machine
l.get = nil
if buf.Avail() > 0 {
l.get = broker.requests
}
}
}
func (l *directEventLoop) handleInsert(req *pushRequest) {
// log := l.broker.logger
// log.Debugf("push event: %v\t%v\t%p\n", req.event, req.seq, req.state)
if avail, ok := l.insert(req); ok && avail == 0 {
// log.Debugf("buffer: all regions full")
// no more space to accept new events -> unset events queue for time being
l.events = nil
}
}
func (l *directEventLoop) insert(req *pushRequest) (int, bool) {
var avail int
log := l.broker.logger
if req.state == nil {
_, avail = l.buf.insert(req.event, clientState{})
return avail, true
}
st := req.state
if st.cancelled {
reportCancelledState(log, req)
return -1, false
}
_, avail = l.buf.insert(req.event, clientState{
seq: req.seq,
state: st,
})
return avail, true
}
func (l *directEventLoop) handleCancel(req *producerCancelRequest) {
// log := l.broker.logger
// log.Debug("handle cancel request")
var (
removed int
broker = l.broker
)
if st := req.state; st != nil {
st.cancelled = true
removed = l.buf.cancel(st)
}
// signal cancel request being finished
if req.resp != nil {
req.resp <- producerCancelResponse{removed: removed}
}
// re-enable pushRequest if buffer can take new events
if !l.buf.Full() {
l.events = broker.events
}
}
func (l *directEventLoop) handleConsumer(req *getRequest) {
// log := l.broker.logger
// log.Debugf("try reserve %v events", req.sz)
start, buf := l.buf.reserve(req.sz)
count := len(buf)
if count == 0 {
panic("empty batch returned")
}
// log.Debug("newACKChan: ", b.ackSeq, count)
ackCH := newACKChan(l.ackSeq, start, count, l.buf.buf.clients)
l.ackSeq++
req.resp <- getResponse{ackCH, buf}
l.pendingACKs.append(ackCH)
l.schedACKS = l.broker.scheduledACKs
}
func (l *directEventLoop) handleACK(count int) {
// log := l.broker.logger
// log.Debug("receive buffer ack:", count)
// Give broker/buffer a chance to clean up most recent ACKs
// After handling ACKs some buffer has been freed up
// -> always reenable producers
l.buf.ack(count)
l.events = l.broker.events
}
// processACK is used by the ackLoop to process the list of acked batches
func (l *directEventLoop) processACK(lst chanList, N int) {
log := l.broker.logger
{
start := time.Now()
log.Debug("handle ACKs: ", N)
defer func() {
log.Debug("handle ACK took: ", time.Since(start))
}()
}
acks := lst.front()
start := acks.start
states := acks.states
// TODO: global boolean to check if clients will need an ACK
// no need to report ACKs if no client is interested in ACKs
idx := start + N - 1
if idx >= len(states) {
idx -= len(states)
}
total := 0
for i := N - 1; i >= 0; i-- {
if idx < 0 {
idx = len(states) - 1
}
st := &states[idx]
log.Debugf("try ack index: (idx=%v, i=%v, seq=%v)\n", idx, i, st.seq)
idx--
if st.state == nil {
log.Debug("no state set")
continue
}
count := (st.seq - st.state.lastACK)
if count == 0 || count > math.MaxUint32/2 {
// seq number comparison did underflow. This happens only if st.seq has
// already been acknowledged
// log.Debug("seq number already acked: ", st.seq)
st.state = nil
continue
}
log.Debugf("broker ACK events: count=%v, start-seq=%v, end-seq=%v\n",
count,
st.state.lastACK+1,
st.seq,
)
total += int(count)
if total > N {
panic(fmt.Sprintf("Too many events acked (expected=%v, total=%v)",
N, total,
))
}
st.state.cb(int(count))
st.state.lastACK = st.seq
st.state = nil
}
}
func newBufferingEventLoop(b *Broker, size int, minEvents int, flushTimeout time.Duration) *bufferingEventLoop {
l := &bufferingEventLoop{
broker: b,
maxEvents: size,
minEvents: minEvents,
flushTimeout: flushTimeout,
events: b.events,
get: nil,
pubCancel: b.pubCancel,
acks: b.acks,
}
l.buf = newBatchBuffer(l.minEvents)
l.timer = time.NewTimer(flushTimeout)
if !l.timer.Stop() {
<-l.timer.C
}
return l
}
func (l *bufferingEventLoop) run() {
var (
broker = l.broker
)
for {
select {
case <-broker.done:
return
case req := <-l.events: // producer pushing new event
l.handleInsert(&req)
case req := <-l.pubCancel: // producer cancelling active events
l.handleCancel(&req)
case req := <-l.get: // consumer asking for next batch
l.handleConsumer(&req)
case l.schedACKS <- l.pendingACKs:
l.schedACKS = nil
l.pendingACKs = chanList{}
case count := <-l.acks:
l.handleACK(count)
case <-l.idleC:
l.idleC = nil
l.timer.Stop()
if l.buf.length() > 0 {
l.flushBuffer()
}
}
}
}
func (l *bufferingEventLoop) handleInsert(req *pushRequest) {
if l.insert(req) {
l.eventCount++
if l.eventCount == l.maxEvents {
l.events = nil // stop inserting events if upper limit is reached
}
L := l.buf.length()
if !l.buf.flushed {
if L < l.minEvents {
l.startFlushTimer()
} else {
l.stopFlushTimer()
l.flushBuffer()
l.buf = newBatchBuffer(l.minEvents)
}
} else {
if L >= l.minEvents {
l.buf = newBatchBuffer(l.minEvents)
}
}
}
}
func (l *bufferingEventLoop) insert(req *pushRequest) bool {
if req.state == nil {
l.buf.add(req.event, clientState{})
return true
}
st := req.state
if st.cancelled {
reportCancelledState(l.broker.logger, req)
return false
}
l.buf.add(req.event, clientState{
seq: req.seq,
state: st,
})
return true
}
func (l *bufferingEventLoop) handleCancel(req *producerCancelRequest) {
removed := 0
if st := req.state; st != nil {
// remove from actively flushed buffers
for buf := l.flushList.head; buf != nil; buf = buf.next {
removed += buf.cancel(st)
}
if !l.buf.flushed {
removed += l.buf.cancel(st)
}
st.cancelled = true
}
if req.resp != nil {
req.resp <- producerCancelResponse{removed: removed}
}
// remove flushed but empty buffers:
tmpList := flushList{}
for l.flushList.head != nil {
b := l.flushList.head
l.flushList.head = b.next
if b.length() > 0 {
tmpList.add(b)
}
}
l.flushList = tmpList
if tmpList.empty() {
l.get = nil
}
l.eventCount -= removed
if l.eventCount < l.maxEvents {
l.events = l.broker.events
}
}
func (l *bufferingEventLoop) handleConsumer(req *getRequest) {
buf := l.flushList.head
if buf == nil {
panic("get from non-flushed buffers")
}
count := buf.length()
if count == 0 {
panic("empty buffer in flush list")
}
if sz := req.sz; sz > 0 {
if sz < count {
count = sz
}
}
if count == 0 {
panic("empty batch returned")
}
events := buf.events[:count]
clients := buf.clients[:count]
ackChan := newACKChan(l.ackSeq, 0, count, clients)
l.ackSeq++
req.resp <- getResponse{ackChan, events}
l.pendingACKs.append(ackChan)
l.schedACKS = l.broker.scheduledACKs
buf.events = buf.events[count:]
buf.clients = buf.clients[count:]
if buf.length() == 0 {
l.advanceFlushList()
}
}
func (l *bufferingEventLoop) handleACK(count int) {
l.eventCount -= count
if l.eventCount < l.maxEvents {
l.events = l.broker.events
}
}
func (l *bufferingEventLoop) startFlushTimer() {
if l.idleC == nil {
l.timer.Reset(l.flushTimeout)
l.idleC = l.timer.C
}
}
func (l *bufferingEventLoop) stopFlushTimer() {
if l.idleC != nil {
l.idleC = nil
if !l.timer.Stop() {
<-l.timer.C
}
}
}
func (l *bufferingEventLoop) advanceFlushList() {
l.flushList.pop()
if l.flushList.count == 0 {
l.get = nil
if l.buf.flushed {
l.buf = newBatchBuffer(l.minEvents)
}
}
}
func (l *bufferingEventLoop) flushBuffer() {
l.buf.flushed = true
if l.buf.length() == 0 {
panic("flushing empty buffer")
}
l.flushList.add(l.buf)
l.get = l.broker.requests
}
func (l *bufferingEventLoop) processACK(lst chanList, N int) {
log := l.broker.logger
total := 0
lst.reverse()
for !lst.empty() {
current := lst.pop()
states := current.states
for i := len(states) - 1; i >= 0; i-- {
st := &states[i]
if st.state == nil {
continue
}
count := st.seq - st.state.lastACK
if count == 0 || count > math.MaxUint32/2 {
// seq number comparison did underflow. This happens only if st.seq has
// already been acknowledged
// log.Debug("seq number already acked: ", st.seq)
st.state = nil
continue
}
log.Debugf("broker ACK events: count=%v, start-seq=%v, end-seq=%v\n",
count,
st.state.lastACK+1,
st.seq,
)
total += int(count)
if total > N {
panic(fmt.Sprintf("Too many events acked (expected=%v, total=%v)",
N, total,
))
}
st.state.cb(int(count))
st.state.lastACK = st.seq
st.state = nil
}
}
}
func (l *flushList) pop() {
l.count--
if l.count > 0 {
l.head = l.head.next
} else {
l.head = nil
l.tail = nil
}
}
func (l *flushList) empty() bool {
return l.head == nil
}
func (l *flushList) add(b *batchBuffer) {
l.count++
b.next = nil
if l.tail == nil {
l.head = b
l.tail = b
} else {
l.tail.next = b
l.tail = b
}
}
func reportCancelledState(log logger, req *pushRequest) {
log.Debugf("cancelled producer - ignore event: %v\t%v\t%p", req.event, req.seq, req.state)
// do not add waiting events if producer did send cancel signal
st := req.state
if cb := st.dropCB; cb != nil {
cb(req.event.Content)
}
}