-
-
Notifications
You must be signed in to change notification settings - Fork 156
/
consumer.go
1474 lines (1286 loc) · 43 KB
/
consumer.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
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package kgo
import (
"context"
"sync"
"sync/atomic"
"time"
"github.com/twmb/franz-go/pkg/kerr"
"github.com/twmb/franz-go/pkg/kmsg"
)
// Offset is a message offset in a partition.
type Offset struct {
at int64
relative int64
epoch int32
currentEpoch int32 // set by us when mapping offsets to brokers
}
// NewOffset creates and returns an offset to use in ConsumePartitions or
// ConsumeResetOffset.
//
// The default offset begins at the end.
func NewOffset() Offset {
return Offset{
at: -1,
epoch: -1,
}
}
// AtStart returns a copy of the calling offset, changing the returned offset
// to begin at the beginning of a partition.
func (o Offset) AtStart() Offset {
o.at = -2
return o
}
// AtEnd returns a copy of the calling offset, changing the returned offset to
// begin at the end of a partition.
func (o Offset) AtEnd() Offset {
o.at = -1
return o
}
// Relative returns a copy of the calling offset, changing the returned offset
// to be n relative to what it currently is. If the offset is beginning at the
// end, Relative(-100) will begin 100 before the end.
func (o Offset) Relative(n int64) Offset {
o.relative = n
return o
}
// WithEpoch returns a copy of the calling offset, changing the returned offset
// to use the given epoch. This epoch is used for truncation detection; the
// default of -1 implies no truncation detection.
func (o Offset) WithEpoch(e int32) Offset {
if e < 0 {
e = -1
}
o.epoch = e
return o
}
// At returns a copy of the calling offset, changing the returned offset to
// begin at exactly the requested offset.
//
// There are two potential special offsets to use: -2 allows for consuming at
// the start, and -1 allows for consuming at the end. These two offsets are
// equivalent to calling AtStart or AtEnd.
//
// If the offset is less than -2, the client bounds it to -2 to consume at the
// start.
func (o Offset) At(at int64) Offset {
if at < -2 {
at = -2
}
o.at = at
return o
}
type consumer struct {
cl *Client
bufferedRecords int64
// mu is grabbed when
// - polling fetches, for quickly draining sources / updating group uncommitted
// - calling assignPartitions (group / direct updates)
mu sync.Mutex
d *directConsumer // if non-nil, we are consuming partitions directly
g *groupConsumer // if non-nil, we are consuming as a group member
// On metadata update, if the consumer is set (direct or group), the
// client begins a goroutine that updates the consumer kind's
// assignments.
//
// This is done in a goroutine to not block the metadata loop, because
// the update **could** wait on a group consumer leaving if a
// concurrent LeaveGroup is called, or if restarting a session takes
// just a little bit of time.
//
// The update realistically should be instantaneous, but if it is slow,
// some metadata updates could pile up. We loop with our atomic work
// loop, which collapses repeated updates into one extra update, so we
// loop as little as necessary.
outstandingMetadataUpdates workLoop
// sessionChangeMu is grabbed when a session is stopped and held through
// when a session can be started again. The sole purpose is to block an
// assignment change running concurrently with a metadata update.
sessionChangeMu sync.Mutex
session atomic.Value // *consumerSession
usingCursors usedCursors
sourcesReadyMu sync.Mutex
sourcesReadyCond *sync.Cond
sourcesReadyForDraining []*source
fakeReadyForDraining []Fetch
}
// BufferedFetchRecords returns the number of records currently buffered from
// fetching within the client.
//
// This can be used as a gauge to determine how behind your application is for
// processing records the client has fetched. Note that it is perfectly normal
// to see a spike of buffered records, which would correspond to a fetch
// response being processed just before a call to this function. It is only
// problematic if for you if this function is consistently returning large
// values.
func (cl *Client) BufferedFetchRecords() int64 {
return atomic.LoadInt64(&cl.consumer.bufferedRecords)
}
type usedCursors map[*cursor]struct{}
func (u *usedCursors) use(c *cursor) {
if *u == nil {
*u = make(map[*cursor]struct{})
}
(*u)[c] = struct{}{}
}
func (c *consumer) init(cl *Client) {
c.cl = cl
c.sourcesReadyCond = sync.NewCond(&c.sourcesReadyMu)
if len(cl.cfg.topics) == 0 && len(cl.cfg.partitions) == 0 {
return // not consuming
}
defer cl.triggerUpdateMetadata(true) // we definitely want to trigger a metadata update
if len(cl.cfg.group) == 0 {
c.initDirect()
} else {
c.initGroup()
}
}
func (c *consumer) consuming() bool {
return c.g != nil || c.d != nil
}
// unset, called under the assign mu, transitions the consumer to the unset
// state, invalidating old assignments and leaving a group if it was in one.
//
// If in a group, this waits for the leave group to finish before returning.
func (c *consumer) unset() {
if !c.consuming() {
return
}
// Unsetting means all old cursors are useless. Before we return, we
// delete all old cursors. This is especially important in the context
// of a new assignment, which will create new cursors that may
// duplicate our old.
//
// Note that this is happening outside of the context of a valid
// consumer session, so we do not need to worry about much else.
//
// Since we are blocking metadata, sinksAndSources cannot be modified
// concurrently and we do not need a lock.
cl := c.cl
defer cl.blockingMetadataFn(func() {
for _, sns := range cl.sinksAndSources {
s := sns.source
s.cursorsMu.Lock()
s.cursors = nil
s.cursorsStart = 0
s.cursorsMu.Unlock()
}
})
wait := func() {} // wait AFTER we unlock
defer func() { wait() }()
c.mu.Lock() // lock for assign
defer c.mu.Unlock()
c.assignPartitions(nil, assignInvalidateAll, noTopicsPartitions)
if c.g != nil {
wait = c.g.leave()
}
}
// addSourceReadyForDraining tracks that a source needs its buffered fetch
// consumed.
func (c *consumer) addSourceReadyForDraining(source *source) {
c.sourcesReadyMu.Lock()
c.sourcesReadyForDraining = append(c.sourcesReadyForDraining, source)
c.sourcesReadyMu.Unlock()
c.sourcesReadyCond.Broadcast()
}
// addFakeReadyForDraining saves a fake fetch that has important partition
// errors--data loss or auth failures.
func (c *consumer) addFakeReadyForDraining(topic string, partition int32, err error) {
c.sourcesReadyMu.Lock()
c.fakeReadyForDraining = append(c.fakeReadyForDraining, Fetch{Topics: []FetchTopic{{
Topic: topic,
Partitions: []FetchPartition{{
Partition: partition,
Err: err,
}},
}}})
c.sourcesReadyMu.Unlock()
c.sourcesReadyCond.Broadcast()
}
// PollFetches waits for fetches to be available, returning as soon as any
// broker returns a fetch. If the context quits, this function quits. If the
// context is nil or is already canceled, this function will return immediately
// with any currently buffered records.
//
// It is important to check all partition errors in the returned fetches. If
// any partition has a fatal error and actually had no records, fake fetch will
// be injected with the error.
//
// If the client is closing or has closed, a fake fetch will be injected that
// has no topic, a partition of 0, and a partition error of ErrClientClosed.
// This can be used to detect if the client is closing and to break out of a
// poll loop.
func (cl *Client) PollFetches(ctx context.Context) Fetches {
return cl.PollRecords(ctx, 0)
}
// PollRecords waits for records to be available, returning as soon as any
// broker returns records in a fetch. If the context quits, this function
// quits. If the context is nil or is already canceled, this function will
// return immediately with any currently buffered records.
//
// This returns a maximum of maxPollRecords total across all fetches, or
// returns all buffered records if maxPollRecords is <= 0.
//
// It is important to check all partition errors in the returned fetches. If
// any partition has a fatal error and actually had no records, fake fetch will
// be injected with the error.
//
// If the client is closing or has closed, a fake fetch will be injected that
// has no topic, a partition of 0, and a partition error of ErrClientClosed.
// This can be used to detect if the client is closing and to break out of a
// poll loop.
func (cl *Client) PollRecords(ctx context.Context, maxPollRecords int) Fetches {
if maxPollRecords == 0 {
maxPollRecords = -1
}
c := &cl.consumer
var fetches Fetches
fill := func() {
// A group can grab the consumer lock then the group mu and
// assign partitions. The group mu is grabbed to update its
// uncommitted map. Assigning partitions clears sources ready
// for draining.
//
// We need to grab the consumer mu to ensure proper lock
// ordering and prevent lock inversion. Polling fetches also
// updates the group's uncommitted map; if we do not grab the
// consumer mu at the top, we have a problem: without the lock,
// we could have grabbed some sources, then a group assigned,
// and after the assign, we update uncommitted with fetches
// from the old assignment
c.mu.Lock()
defer c.mu.Unlock()
c.sourcesReadyMu.Lock()
if maxPollRecords < 0 {
for _, ready := range c.sourcesReadyForDraining {
fetches = append(fetches, ready.takeBuffered())
}
c.sourcesReadyForDraining = nil
} else {
for len(c.sourcesReadyForDraining) > 0 && maxPollRecords > 0 {
source := c.sourcesReadyForDraining[0]
fetch, taken, drained := source.takeNBuffered(maxPollRecords)
if drained {
c.sourcesReadyForDraining = c.sourcesReadyForDraining[1:]
}
maxPollRecords -= taken
fetches = append(fetches, fetch)
}
}
realFetches := fetches
fetches = append(fetches, c.fakeReadyForDraining...)
c.fakeReadyForDraining = nil
c.sourcesReadyMu.Unlock()
if len(realFetches) == 0 {
return
}
// Before returning, we want to update our uncommitted. If we
// updated after, then we could end up with weird interactions
// with group invalidations where we return a stale fetch after
// committing in onRevoke.
//
// A blocking onRevoke commit, on finish, allows a new group
// session to start. If we returned stale fetches that did not
// have their uncommitted offset tracked, then we would allow
// duplicates.
if c.g != nil {
c.g.updateUncommitted(realFetches)
}
}
fill()
if len(fetches) > 0 || ctx == nil {
return fetches
}
select {
case <-ctx.Done():
return fetches
default:
}
done := make(chan struct{})
quit := false
go func() {
c.sourcesReadyMu.Lock()
defer c.sourcesReadyMu.Unlock()
defer close(done)
for !quit && len(c.sourcesReadyForDraining) == 0 {
c.sourcesReadyCond.Wait()
}
}()
exit := func() {
c.sourcesReadyMu.Lock()
quit = true
c.sourcesReadyMu.Unlock()
c.sourcesReadyCond.Broadcast()
}
select {
case <-cl.ctx.Done():
// The client is closed: we inject an error right now, which
// will be drained immediately in the fill call just below, and
// then will be returned with our fetches.
c.addFakeReadyForDraining("", 0, ErrClientClosed)
exit()
case <-ctx.Done():
// The user canceled: no need to inject anything; just return.
exit()
case <-done:
}
fill()
return fetches
}
// assignHow controls how assignPartitions operates.
type assignHow int8
const (
// This option simply assigns new offsets, doing nothing with existing
// offsets / active fetches / buffered fetches.
assignWithoutInvalidating assignHow = iota
// This option invalidates active fetches so they will not buffer and
// drops all buffered fetches, and then continues to assign the new
// assignments.
assignInvalidateAll
// This option does not assign, but instead invalidates any active
// fetches for "assigned" (actually lost) partitions. This additionally
// drops all buffered fetches, because they could contain partitions we
// lost. Thus, with this option, the actual offset in the map is
// meaningless / a dummy offset.
assignInvalidateMatching
// The counterpart to assignInvalidateMatching, assignSetMatching
// resets all matching partitions to the specified offset / epoch.
assignSetMatching
)
func (h assignHow) String() string {
switch h {
case assignWithoutInvalidating:
return "assign without invalidating"
case assignInvalidateAll:
return "assign invalidate all"
case assignInvalidateMatching:
return "assign invalidate matching"
case assignSetMatching:
return "assign set matching"
}
return ""
}
// assignPartitions, called under the consumer's mu, is used to set new
// cursors or add to the existing cursors.
func (c *consumer) assignPartitions(assignments map[string]map[int32]Offset, how assignHow, tps *topicsPartitions) {
var session *consumerSession
var loadOffsets listOrEpochLoads
if how == assignInvalidateAll {
tps = nil
}
defer func() {
if session == nil { // if nil, we stopped the session
session = c.startNewSession(tps)
} else { // else we guarded it
c.unguardSessionChange(session)
}
loadOffsets.loadWithSession(session) // odds are this assign came from a metadata update, so no reason to force a refresh with loadWithSessionNow
// If we started a new session or if we unguarded, we have one
// worker. This one worker allowed us to safely add our load
// offsets before the session could be concurrently stopped
// again. Now that we have added the load offsets, we allow the
// session to be stopped.
session.decWorker()
}()
if how == assignWithoutInvalidating {
// Guarding a session change can actually create a new session
// if we had no session before, which is why we need to pass in
// our topicPartitions.
session = c.guardSessionChange(tps)
} else {
loadOffsets, _ = c.stopSession()
// First, over all cursors currently in use, we unset them or set them
// directly as appropriate. Anything we do not unset, we keep.
var keep usedCursors
for usedCursor := range c.usingCursors {
shouldKeep := true
if how == assignInvalidateAll {
usedCursor.unset()
shouldKeep = false
} else { // invalidateMatching or setMatching
if assignTopic, ok := assignments[usedCursor.topic]; ok {
if assignPart, ok := assignTopic[usedCursor.partition]; ok {
if how == assignInvalidateMatching {
usedCursor.unset()
shouldKeep = false
} else { // how == assignSetMatching
usedCursor.setOffset(cursorOffset{
offset: assignPart.at,
lastConsumedEpoch: assignPart.epoch,
})
}
}
}
}
if shouldKeep {
keep.use(usedCursor)
}
}
c.usingCursors = keep
// For any partition that was listing offsets or loading
// epochs, we want to ensure that if we are keeping those
// partitions, we re-start the list/load.
//
// Note that we do not need to unset cursors here; anything
// that actually resulted in a cursor is forever tracked in
// usedCursors. We only do not have used cursors if an
// assignment went straight to listing / epoch loading, and
// that list/epoch never finished.
switch how {
case assignInvalidateAll:
loadOffsets = listOrEpochLoads{}
case assignSetMatching:
// We had not yet loaded this partition, so there is
// nothing to set, and we keep everything.
case assignInvalidateMatching:
loadOffsets.keepFilter(func(t string, p int32) bool {
if assignTopic, ok := assignments[t]; ok {
if _, ok := assignTopic[p]; ok {
return false
}
}
return true
})
}
}
// This assignment could contain nothing (for the purposes of
// invalidating active fetches), so we only do this if needed.
if len(assignments) == 0 || how == assignInvalidateMatching || how == assignSetMatching {
return
}
c.cl.cfg.logger.Log(LogLevelDebug, "assign requires loading offsets")
topics := tps.load()
for topic, partitions := range assignments {
topicPartitions := topics.loadTopic(topic) // should be non-nil
if topicPartitions == nil {
c.cl.cfg.logger.Log(LogLevelError, "BUG! consumer was assigned topic that we did not ask for in ConsumeTopics nor ConsumePartitions, skipping!", "topic", topic)
continue
}
for partition, offset := range partitions {
// First, if the request is exact, get rid of the relative
// portion. We are modifying a copy of the offset, i.e. we
// are appropriately not modfying 'assignments' itself.
if offset.at >= 0 {
offset.at = offset.at + offset.relative
if offset.at < 0 {
offset.at = 0
}
offset.relative = 0
}
// If we are requesting an exact offset with an epoch,
// we do truncation detection and then use the offset.
//
// Otherwise, an epoch is specified without an exact
// request which is useless for us, or a request is
// specified without a known epoch.
//
// The client ensures the epoch is non-negative from
// fetch offsets only if the broker supports KIP-320,
// but we do not override the user manually specifying
// an epoch.
if offset.at >= 0 && offset.epoch >= 0 {
loadOffsets.addLoad(topic, partition, loadTypeEpoch, offsetLoad{
replica: -1,
Offset: offset,
})
continue
}
// If an exact offset is specified and we have loaded
// the partition, we use it. Without an epoch, if it is
// out of bounds, we just reset appropriately.
//
// If an offset is unspecified or we have not loaded
// the partition, we list offsets to find out what to
// use.
if offset.at >= 0 && partition >= 0 && partition < int32(len(topicPartitions.partitions)) {
part := topicPartitions.partitions[partition]
cursor := part.cursor
cursor.setOffset(cursorOffset{
offset: offset.at,
lastConsumedEpoch: part.leaderEpoch,
})
cursor.allowUsable()
c.usingCursors.use(cursor)
continue
}
loadOffsets.addLoad(topic, partition, loadTypeList, offsetLoad{
replica: -1,
Offset: offset,
})
}
}
}
func (c *consumer) doOnMetadataUpdate() {
if !c.consuming() {
return
}
// See the comment on the outstandingMetadataUpdates field for why this
// block below.
if c.outstandingMetadataUpdates.maybeBegin() {
doUpdate := func() {
// We forbid reassignments while we do a quick check for
// new assignments--for the direct consumer particularly,
// this prevents TOCTOU.
c.mu.Lock()
defer c.mu.Unlock()
switch {
case c.d != nil:
if new := c.d.findNewAssignments(); len(new) > 0 {
c.assignPartitions(new, assignWithoutInvalidating, c.d.tps)
}
case c.g != nil:
c.g.findNewAssignments()
}
go c.loadSession().doOnMetadataUpdate()
}
go func() {
again := true
for again {
doUpdate()
again = c.outstandingMetadataUpdates.maybeFinish(false)
}
}()
}
}
func (s *consumerSession) doOnMetadataUpdate() {
if s == nil || s == noConsumerSession { // no session started yet
return
}
s.listOrEpochMu.Lock()
defer s.listOrEpochMu.Unlock()
if s.listOrEpochMetaCh == nil {
return // nothing waiting to load epochs / offsets
}
select {
case s.listOrEpochMetaCh <- struct{}{}:
default:
}
}
// offsetLoad is effectively an Offset, but also includes a potential replica
// to directly use if a cursor had a preferred replica.
type offsetLoad struct {
replica int32 // -1 means leader
Offset
}
type offsetLoadMap map[string]map[int32]offsetLoad
func (o offsetLoadMap) errToLoaded(err error) []loadedOffset {
var loaded []loadedOffset
for t, ps := range o {
for p, o := range ps {
loaded = append(loaded, loadedOffset{
topic: t,
partition: p,
err: err,
request: o,
})
}
}
return loaded
}
// Combines list and epoch loads into one type for simplicity.
type listOrEpochLoads struct {
list offsetLoadMap
epoch offsetLoadMap
}
type listOrEpochLoadType uint8
const (
loadTypeList listOrEpochLoadType = iota
loadTypeEpoch
)
// adds an offset to be loaded, ensuring it exists only in the final loadType.
func (l *listOrEpochLoads) addLoad(t string, p int32, loadType listOrEpochLoadType, load offsetLoad) {
l.removeLoad(t, p)
dst := &l.list
if loadType == loadTypeEpoch {
dst = &l.epoch
}
if *dst == nil {
*dst = make(offsetLoadMap)
}
ps := (*dst)[t]
if ps == nil {
ps = make(map[int32]offsetLoad)
(*dst)[t] = ps
}
ps[p] = load
}
func (l *listOrEpochLoads) removeLoad(t string, p int32) {
for _, m := range []offsetLoadMap{
l.list,
l.epoch,
} {
if m == nil {
continue
}
ps := m[t]
if ps == nil {
continue
}
delete(ps, p)
if len(ps) == 0 {
delete(m, t)
}
}
}
func (l listOrEpochLoads) each(fn func(string, int32)) {
for _, m := range []offsetLoadMap{
l.list,
l.epoch,
} {
for topic, partitions := range m {
for partition := range partitions {
fn(topic, partition)
}
}
}
}
func (l *listOrEpochLoads) keepFilter(keep func(string, int32) bool) {
for _, m := range []offsetLoadMap{
l.list,
l.epoch,
} {
for t, ps := range m {
for p := range ps {
if !keep(t, p) {
delete(ps, p)
if len(ps) == 0 {
delete(m, t)
}
}
}
}
}
}
// Merges loads into the caller; used to coalesce loads while a metadata update
// is happening (see the only use below).
func (dst *listOrEpochLoads) mergeFrom(src listOrEpochLoads) {
for _, srcs := range []struct {
m offsetLoadMap
loadType listOrEpochLoadType
}{
{src.list, loadTypeList},
{src.epoch, loadTypeEpoch},
} {
for t, ps := range srcs.m {
for p, load := range ps {
dst.addLoad(t, p, srcs.loadType, load)
}
}
}
}
func (l listOrEpochLoads) isEmpty() bool { return len(l.list) == 0 && len(l.epoch) == 0 }
func (l listOrEpochLoads) loadWithSession(s *consumerSession) {
if !l.isEmpty() {
s.incWorker()
go s.listOrEpoch(l, false)
}
}
func (l listOrEpochLoads) loadWithSessionNow(s *consumerSession) bool {
if !l.isEmpty() {
s.incWorker()
go s.listOrEpoch(l, true)
return true
}
return false
}
// A consumer session is responsible for an era of fetching records for a set
// of cursors. The set can be added to without killing an active session, but
// it cannot be removed from. Removing any cursor from being consumed kills the
// current consumer session and begins a new one.
type consumerSession struct {
c *consumer
ctx context.Context
cancel func()
// tps tracks the topics that were assigned in this session. We use
// this field to build and handle list offset / load epoch requests.
tps *topicsPartitions
// desireFetchCh is sized to the number of concurrent fetches we are
// configured to be able to send.
//
// We receive desires from sources, we reply when they can fetch, and
// they send back when they are done. Thus, three level chan.
desireFetchCh chan chan chan struct{}
cancelFetchCh chan chan chan struct{}
allowedConcurrency int
fetchManagerStarted uint32 // atomic, once 1, we start the fetch manager
// Workers signify the number of fetch and list / epoch goroutines that
// are currently running within the context of this consumer session.
// Stopping a session only returns once workers hits zero.
workersMu sync.Mutex
workersCond *sync.Cond
workers int
listOrEpochMu sync.Mutex
listOrEpochLoadsWaiting listOrEpochLoads
listOrEpochMetaCh chan struct{} // non-nil if Loads is non-nil, signalled on meta update
listOrEpochLoadsLoading listOrEpochLoads
}
func (c *consumer) newConsumerSession(tps *topicsPartitions) *consumerSession {
if tps == nil || len(tps.load()) == 0 {
return noConsumerSession
}
ctx, cancel := context.WithCancel(c.cl.ctx)
session := &consumerSession{
c: c,
ctx: ctx,
cancel: cancel,
tps: tps,
desireFetchCh: make(chan chan chan struct{}, 8),
cancelFetchCh: make(chan chan chan struct{}, 4),
allowedConcurrency: c.cl.cfg.allowedConcurrentFetches,
}
session.workersCond = sync.NewCond(&session.workersMu)
return session
}
func (c *consumerSession) desireFetch() chan chan chan struct{} {
if atomic.SwapUint32(&c.fetchManagerStarted, 1) == 0 {
go c.manageFetchConcurrency()
}
return c.desireFetchCh
}
func (c *consumerSession) manageFetchConcurrency() {
var (
activeFetches int
doneFetch = make(chan struct{}, 20)
wantFetch []chan chan struct{}
ctxCh = c.ctx.Done()
wantQuit bool
)
for {
select {
case register := <-c.desireFetchCh:
wantFetch = append(wantFetch, register)
case cancel := <-c.cancelFetchCh:
var found bool
for i, want := range wantFetch {
if want == cancel {
_ = append(wantFetch[i:], wantFetch[i+1:]...)
wantFetch = wantFetch[:len(wantFetch)-1]
found = true
}
}
// If we did not find the channel, then we have already
// sent to it, removed it from our wantFetch list, and
// bumped activeFetches.
if !found {
activeFetches--
}
case <-doneFetch:
activeFetches--
case <-ctxCh:
wantQuit = true
ctxCh = nil
}
if len(wantFetch) > 0 && (activeFetches < c.allowedConcurrency || c.allowedConcurrency == 0) { // 0 means unbounded
wantFetch[0] <- doneFetch
wantFetch = wantFetch[1:]
activeFetches++
continue
}
if wantQuit && activeFetches == 0 {
return
}
}
}
func (c *consumerSession) incWorker() {
if c == noConsumerSession { // from startNewSession
return
}
c.workersMu.Lock()
defer c.workersMu.Unlock()
c.workers++
}
func (c *consumerSession) decWorker() {
if c == noConsumerSession { // from followup to startNewSession
return
}
c.workersMu.Lock()
defer c.workersMu.Unlock()
c.workers--
if c.workers == 0 {
c.workersCond.Broadcast()
}
}
// noConsumerSession exists because we cannot store nil into an atomic.Value.
var noConsumerSession = new(consumerSession)
func (c *consumer) loadSession() *consumerSession {
if session := c.session.Load(); session != nil {
return session.(*consumerSession)
}
return noConsumerSession
}
// Guards against a session being stopped, and must be paired with an unguard.
// This returns a new session if there was no session.
//
// The purpose of this function is when performing additive-only changes to an
// existing session, because additive-only changes can avoid killing a running
// session.
func (c *consumer) guardSessionChange(tps *topicsPartitions) *consumerSession {
c.sessionChangeMu.Lock()
session := c.loadSession()
if session == noConsumerSession {
// If there is no session, we simply store one. This is fine;
// sources will be able to begin a fetch loop, but they will
// have no cursors to consume yet.
session = c.newConsumerSession(tps)
c.session.Store(session)
}
return session
}
// For the same reason below as in startNewSession, we inc a worker before
// unguarding. This allows the unguarding to execute a bit of logic if
// necessary before the session can be stopped.
func (c *consumer) unguardSessionChange(session *consumerSession) {
session.incWorker()
c.sessionChangeMu.Unlock()
}
// Stops an active consumer session if there is one, and does not return until
// all fetching, listing, offset for leader epoching is complete. This
// invalidates any buffered fetches for the previous session and returns any
// partitions that were listing offsets or loading epochs.
func (c *consumer) stopSession() (listOrEpochLoads, *topicsPartitions) {
c.sessionChangeMu.Lock()
session := c.loadSession()
if session == noConsumerSession {
return listOrEpochLoads{}, noTopicsPartitions // we had no session
}
// Before storing noConsumerSession, cancel our old. This pairs
// with the reverse ordering in source, which checks noConsumerSession
// then checks the session context.
session.cancel()
// At this point, any in progress fetches, offset lists, or epoch loads
// will quickly die.
c.session.Store(noConsumerSession)
// At this point, no source can be started, because the session is
// noConsumerSession.
session.workersMu.Lock()
for session.workers > 0 {
session.workersCond.Wait()
}
session.workersMu.Unlock()
// At this point, all fetches, lists, and loads are dead. We can close
// our num-fetches manager without worrying about a source trying to
// register itself.
c.cl.sinksAndSourcesMu.Lock()
for _, sns := range c.cl.sinksAndSources {
sns.source.session.reset()
}
c.cl.sinksAndSourcesMu.Unlock()
// At this point, if we begin fetching anew, then the sources will not
// be using stale fetch sessions.
c.sourcesReadyMu.Lock()
defer c.sourcesReadyMu.Unlock()
for _, ready := range c.sourcesReadyForDraining {
ready.discardBuffered()
}