-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathconsumer.go
205 lines (163 loc) · 4.69 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
package kafka
import (
"fmt"
"time"
"github.com/prometheus/client_golang/prometheus"
"github.com/segmentio/kafka-go"
kcronsumer "github.com/Trendyol/kafka-cronsumer/pkg/kafka"
)
type consumer struct {
*base
consumeFn func(*Message) error
}
func (c *consumer) Pause() {
c.base.Pause()
}
func (c *consumer) Resume() {
c.base.Resume()
}
func newSingleConsumer(cfg *ConsumerConfig) (Consumer, error) {
consumerBase, err := newBase(cfg, cfg.Concurrency)
if err != nil {
return nil, err
}
c := consumer{
base: consumerBase,
consumeFn: cfg.ConsumeFn,
}
if cfg.RetryEnabled {
c.base.setupCronsumer(cfg, func(message kcronsumer.Message) error {
return c.consumeFn(toMessage(message))
})
}
if cfg.APIEnabled {
c.base.setupAPI(cfg, c.metric)
}
return &c, nil
}
func (c *consumer) GetMetricCollectors() []prometheus.Collector {
return c.base.GetMetricCollectors()
}
func (c *consumer) Consume() {
go c.subprocesses.Start()
c.wg.Add(1)
go c.startConsume()
c.setupConcurrentWorkers()
c.wg.Add(1)
go c.startBatch()
}
func (c *consumer) startBatch() {
defer c.wg.Done()
flushTimer := time.NewTimer(c.messageGroupDuration)
defer flushTimer.Stop()
messages := make([]*Message, 0, c.concurrency)
commitMessages := make([]kafka.Message, 0, c.concurrency)
flushBatch := func(reason string) {
if len(messages) == 0 {
return
}
c.consume(&messages, &commitMessages)
c.logger.Debugf("[singleConsumer] Flushed batch, reason=%s", reason)
// After flushing, we always reset the timer
// But first we need to stop it and drain any event that might be pending
if !flushTimer.Stop() {
drainTimer(flushTimer)
}
// Now reset to start a new "rolling" interval
flushTimer.Reset(c.messageGroupDuration)
}
for {
select {
case <-flushTimer.C:
flushBatch("time-based (rolling timer)")
case msg, ok := <-c.incomingMessageStream:
if !ok {
flushBatch("channel-closed (final flush)")
close(c.singleConsumingStream)
close(c.messageProcessedStream)
return
}
messages = append(messages, msg.message)
commitMessages = append(commitMessages, *msg.kafkaMessage)
if len(messages) == c.concurrency {
flushBatch("message-count-limit")
} else {
// Rolling timer logic: reset the timer each time we get a new message
// Because we "stop" it, we might need to drain the channel
if !flushTimer.Stop() {
drainTimer(flushTimer)
}
flushTimer.Reset(c.messageGroupDuration)
}
}
}
}
func (c *consumer) setupConcurrentWorkers() {
for i := 0; i < c.concurrency; i++ {
c.wg.Add(1)
go func() {
defer c.wg.Done()
for message := range c.singleConsumingStream {
c.process(message)
c.messageProcessedStream <- struct{}{}
}
}()
}
}
func (c *consumer) consume(messages *[]*Message, commitMessages *[]kafka.Message) {
messageList := *messages
// Send the messages to process
for _, message := range messageList {
c.singleConsumingStream <- message
}
// Wait the messages to be processed
for range messageList {
<-c.messageProcessedStream
}
if err := c.r.CommitMessages(*commitMessages); err != nil {
c.logger.Errorf("Commit Error %s,", err.Error())
}
// Clearing resources
*commitMessages = (*commitMessages)[:0]
*messages = (*messages)[:0]
}
func (c *consumer) process(message *Message) {
consumeErr := c.consumeFn(message)
if consumeErr != nil {
if c.transactionalRetry {
c.logger.Warnf("Consume Function Err %s, Message will be retried", consumeErr.Error())
// Try to process same message again
if consumeErr = c.consumeFn(message); consumeErr != nil {
c.logger.Warnf("Consume Function Again Err %s, message is sending to exception/retry topic %s", consumeErr.Error(), c.retryTopic)
c.metric.IncrementTotalUnprocessedMessagesCounter(1)
}
} else {
c.metric.IncrementTotalUnprocessedMessagesCounter(1)
}
}
if consumeErr != nil && c.retryEnabled {
retryableMsg := message.toRetryableMessage(c.retryTopic, consumeErr.Error())
if err := c.retryWithBackoff(retryableMsg); err != nil {
errorMessage := fmt.Sprintf(
"Error producing message %s to exception/retry topic %s. Error: %s",
string(message.Value), c.retryTopic, err.Error())
c.logger.Error(errorMessage)
panic(err.Error())
}
}
if consumeErr == nil {
c.metric.IncrementTotalProcessedMessagesCounter(1)
}
}
func (c *consumer) retryWithBackoff(retryableMsg kcronsumer.Message) error {
var produceErr error
for attempt := 1; attempt <= 5; attempt++ {
produceErr = c.cronsumer.Produce(retryableMsg)
if produceErr == nil {
return nil
}
c.logger.Warnf("Error producing message (attempt %d/%d): %v", attempt, 5, produceErr)
time.Sleep((50 * time.Millisecond) * time.Duration(1<<attempt))
}
return produceErr
}