-
Notifications
You must be signed in to change notification settings - Fork 0
/
consumer.go
222 lines (192 loc) · 5.61 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
package easykafka
import (
"encoding/json"
"github.com/panjf2000/ants/v2"
"github.com/segmentio/kafka-go"
"golang.org/x/net/context"
"io"
"regexp"
"sync"
"time"
)
type ConsumerErrorHandler[T any] func(k *Consumer[T], err error)
type ConsumerTopicsListUpdatedHandler[T any] func(k *Consumer[T], topics []string)
// Consumer is a wrapper around kafka.Reader
type Consumer[T any] struct {
LoggerContainer
brokers []string
topics []string
concurrency uint
maxBlockingTasks uint
groupId string
partitions uint
topicNamesRegexMatch bool
readerConfig kafka.ReaderConfig
onWrongMessage *ConsumerErrorHandler[T]
onReadError *ConsumerErrorHandler[T]
onFailCommit *ConsumerErrorHandler[T]
onTopicsListUpdated *ConsumerTopicsListUpdatedHandler[T]
threads []*Consumer[T]
oldReader *kafka.Reader
reader *kafka.Reader
conn *kafka.Conn
leaderConn *kafka.Conn
readerLock sync.Mutex
dynamicTopicsDiscovery bool
dynamicTopicsDiscoveryInterval time.Duration
discoveredTopics []string
}
// ErrorHandler is a function that handles errors
type ErrorHandler[T any] func(k *Consumer[T], err error)
// ConsumerOption is a function that sets some option
type ConsumerOption[T any] func(kafka *Consumer[T]) error
// ConsumerHandler is a function that handles messages
type ConsumerHandler[T any] func(message *T, kafkaMessage *kafka.Message) error
// InitConsumer creates a new consumer instance
func InitConsumer[T any](
brokers []string,
topicsList []string,
groupId string,
opts ...ConsumerOption[T],
) (consumer *Consumer[T], close func() error) {
var err error
consumer = &Consumer[T]{
brokers: brokers,
topics: topicsList,
groupId: groupId,
partitions: 3,
concurrency: 3,
maxBlockingTasks: 0,
readerConfig: kafka.ReaderConfig{},
dynamicTopicsDiscoveryInterval: 1000 * time.Millisecond,
}
for _, opt := range opts {
if err := opt(consumer); err != nil {
panic(err)
}
}
// Init conn
consumer.conn = mustConnect(brokers)
consumer.leaderConn = getLeaderConn(consumer.conn)
// Reader configuration
consumer.readerConfig.Brokers = consumer.brokers
consumer.readerConfig.GroupID = consumer.groupId
// Can't reuse connection :(
//consumer.readerConfig.Dialer = &kafka.Dialer{
// DialFunc: func(ctx context.Context, network string, addr string) (net.Conn, error) {
// return consumer.conn, nil
// },
//}
if consumer.dynamicTopicsDiscovery {
go consumer.dynamicDiscoveryTopics(topicsList)
} else {
consumer.discoveryTopicsAndUpdateReader(topicsList)
if consumer.reader == nil {
panic("Error: maybe you have wrong topic name or topic not exists")
}
}
return consumer, func() error {
err = consumer.reader.Close()
if err != nil {
return err
}
err = consumer.conn.Close()
if err != nil {
return err
}
return nil
}
}
// updateReader updates reader with new topics list
func (k *Consumer[T]) updateReader(topics []string) {
conf := k.readerConfig
conf.GroupTopics = topics
k.readerLock.Lock()
if k.reader != nil {
err := k.reader.Close()
if err != nil {
panic(err)
}
}
k.reader = kafka.NewReader(conf)
k.readerLock.Unlock()
}
// discoveryTopicsAndUpdateReader updates topics list and reader
func (k *Consumer[T]) discoveryTopicsAndUpdateReader(topics []string) {
var matchingTopics []string
if k.topicNamesRegexMatch {
var patterns []*regexp.Regexp
for _, t := range topics {
patterns = append(patterns, regexp.MustCompile(t))
}
matchingTopics = matchTopicsFromConnectionByRegex(k.leaderConn, patterns...)
} else {
matchingTopics = matchTopicsFromConnection(k.leaderConn, topics...)
}
if !unorderedStringsEqual(k.discoveredTopics, matchingTopics) {
k.discoveredTopics = matchingTopics
if k.onTopicsListUpdated != nil {
(*k.onTopicsListUpdated)(k, matchingTopics)
}
k.updateReader(matchingTopics)
}
}
// dynamicDiscoveryTopics updates topics list every 3 seconds
func (k *Consumer[T]) dynamicDiscoveryTopics(topics []string) {
ticker := time.NewTicker(k.dynamicTopicsDiscoveryInterval)
for range ticker.C {
k.discoveryTopicsAndUpdateReader(topics)
}
}
// Consume starts consuming messages from kafka
func (k *Consumer[T]) Consume(ctx context.Context, handler ConsumerHandler[T]) {
k.log("start consuming messages")
pool, _ := ants.NewPool(int(k.concurrency),
ants.WithMaxBlockingTasks(int(k.maxBlockingTasks)),
)
defer pool.Release()
for {
k.readerLock.Lock()
r := k.reader
k.readerLock.Unlock()
if r == nil {
time.Sleep(100 * time.Millisecond)
continue
}
m, err := r.FetchMessage(ctx)
if err != nil {
if k.onReadError != nil {
(*k.onReadError)(k, err)
continue
}
if err == io.EOF {
continue
}
panic(err)
}
var message T
err = json.Unmarshal(m.Value, &message)
if err != nil {
if k.onWrongMessage != nil {
(*k.onWrongMessage)(k, err)
}
continue
}
err = pool.Submit(func() {
err = handler(&message, &m)
if err == nil {
k.log("commit message")
err = k.reader.CommitMessages(ctx, m)
if err != nil {
k.error("error commit message: %s", err.Error())
if k.onFailCommit != nil {
(*k.onFailCommit)(k, err)
}
}
}
})
if err != nil {
panic(err)
}
}
}