-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathbatch_consumer.go
198 lines (156 loc) · 4.72 KB
/
batch_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
package kafka
import (
"time"
"github.com/segmentio/kafka-go"
kcronsumer "github.com/Trendyol/kafka-cronsumer/pkg/kafka"
)
type batchConsumer struct {
*base
consumeFn BatchConsumeFn
preBatchFn PreBatchFn
messageGroupLimit int
}
func (b *batchConsumer) Pause() {
b.base.Pause()
}
func (b *batchConsumer) Resume() {
b.base.Resume()
}
func newBatchConsumer(cfg *ConsumerConfig) (Consumer, error) {
consumerBase, err := newBase(cfg, cfg.BatchConfiguration.MessageGroupLimit*cfg.Concurrency)
if err != nil {
return nil, err
}
c := batchConsumer{
base: consumerBase,
consumeFn: cfg.BatchConfiguration.BatchConsumeFn,
preBatchFn: cfg.BatchConfiguration.PreBatchFn,
messageGroupLimit: cfg.BatchConfiguration.MessageGroupLimit,
}
if cfg.RetryEnabled {
c.base.setupCronsumer(cfg, func(message kcronsumer.Message) error {
return c.consumeFn([]*Message{toMessage(message)})
})
}
if cfg.APIEnabled {
c.base.setupAPI(cfg, c.metric)
}
return &c, nil
}
func (b *batchConsumer) GetMetric() *ConsumerMetric {
return b.metric
}
func (b *batchConsumer) Consume() {
go b.subprocesses.Start()
b.wg.Add(1)
go b.startConsume()
b.wg.Add(b.concurrency)
b.setupConcurrentWorkers()
b.wg.Add(1)
go b.startBatch()
}
func (b *batchConsumer) startBatch() {
defer b.wg.Done()
ticker := time.NewTicker(b.messageGroupDuration)
defer ticker.Stop()
maximumMessageLimit := b.messageGroupLimit * b.concurrency
messages := make([]*Message, 0, maximumMessageLimit)
commitMessages := make([]kafka.Message, 0, maximumMessageLimit)
for {
select {
case <-ticker.C:
if len(messages) == 0 {
continue
}
b.consume(&messages, &commitMessages)
case msg, ok := <-b.incomingMessageStream:
if !ok {
close(b.batchConsumingStream)
close(b.messageProcessedStream)
return
}
messages = append(messages, msg.message)
commitMessages = append(commitMessages, *msg.kafkaMessage)
if len(messages) == maximumMessageLimit {
b.consume(&messages, &commitMessages)
}
}
}
}
func (b *batchConsumer) setupConcurrentWorkers() {
for i := 0; i < b.concurrency; i++ {
go func() {
defer b.wg.Done()
for messages := range b.batchConsumingStream {
b.process(messages)
b.messageProcessedStream <- struct{}{}
}
}()
}
}
func chunkMessages(allMessages *[]*Message, chunkSize int) [][]*Message {
var chunks [][]*Message
allMessageList := *allMessages
for i := 0; i < len(allMessageList); i += chunkSize {
end := i + chunkSize
// necessary check to avoid slicing beyond
// slice capacity
if end > len(allMessageList) {
end = len(allMessageList)
}
chunks = append(chunks, allMessageList[i:end])
}
return chunks
}
func (b *batchConsumer) consume(allMessages *[]*Message, commitMessages *[]kafka.Message) {
chunks := chunkMessages(allMessages, b.messageGroupLimit)
if b.preBatchFn != nil {
preBatchResult := b.preBatchFn(*allMessages)
chunks = chunkMessages(&preBatchResult, b.messageGroupLimit)
}
// Send the messages to process
for _, chunk := range chunks {
b.batchConsumingStream <- chunk
}
// Wait the messages to be processed
for i := 0; i < len(chunks); i++ {
<-b.messageProcessedStream
}
if err := b.r.CommitMessages(*commitMessages); err != nil {
b.logger.Errorf("Commit Error %s,", err.Error())
}
// Clearing resources
*commitMessages = (*commitMessages)[:0]
*allMessages = (*allMessages)[:0]
}
func (b *batchConsumer) process(chunkMessages []*Message) {
consumeErr := b.consumeFn(chunkMessages)
if consumeErr != nil {
b.logger.Warnf("Consume Function Err %s, Messages will be retried", consumeErr.Error())
// Try to process same messages again for resolving transient network errors etc.
if consumeErr = b.consumeFn(chunkMessages); consumeErr != nil {
b.logger.Warnf("Consume Function Again Err %s, messages are sending to exception/retry topic %s", consumeErr.Error(), b.retryTopic)
b.metric.TotalUnprocessedMessagesCounter += int64(len(chunkMessages))
}
if consumeErr != nil && b.retryEnabled {
cronsumerMessages := make([]kcronsumer.Message, 0, len(chunkMessages))
if b.transactionalRetry {
for i := range chunkMessages {
cronsumerMessages = append(cronsumerMessages, chunkMessages[i].toRetryableMessage(b.retryTopic))
}
} else {
for i := range chunkMessages {
if chunkMessages[i].IsFailed {
cronsumerMessages = append(cronsumerMessages, chunkMessages[i].toRetryableMessage(b.retryTopic))
}
}
}
if produceErr := b.base.cronsumer.ProduceBatch(cronsumerMessages); produceErr != nil {
b.logger.Errorf("Error producing messages to exception/retry topic %s", produceErr.Error())
}
}
}
if consumeErr == nil {
b.metric.TotalProcessedMessagesCounter += int64(len(chunkMessages))
}
}