forked from uw-labs/substrate
/
consumer.go
205 lines (178 loc) · 4.62 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 (
"context"
"io"
"time"
"github.com/Shopify/sarama"
"github.com/hashicorp/go-multierror"
"github.com/charlie/substrate"
"github.com/charlie/substrate/internal/debug"
"github.com/uw-labs/sync/rungroup"
)
const (
// OffsetOldest indicates the oldest appropriate message available on the broker.
OffsetOldest int64 = sarama.OffsetOldest
// OffsetNewest indicates the next appropriate message available on the broker.
OffsetNewest int64 = sarama.OffsetNewest
defaultMetadataRefreshFrequency = 10 * time.Minute
defaultConsumerSessionTimeout = 10 * time.Second
)
// AsyncMessageSource represents a kafka message source and implements the
// substrate.AsyncMessageSource interface.
type AsyncMessageSourceConfig struct {
ConsumerGroup string
Topic string
Brokers []string
Offset int64
MetadataRefreshFrequency time.Duration
OffsetsRetention time.Duration
SessionTimeout time.Duration
Version string
Debug bool
}
func (ams *AsyncMessageSourceConfig) buildSaramaConsumerConfig() (*sarama.Config, error) {
offset := OffsetNewest
if ams.Offset != 0 {
offset = ams.Offset
}
mrf := defaultMetadataRefreshFrequency
if ams.MetadataRefreshFrequency > 0 {
mrf = ams.MetadataRefreshFrequency
}
st := defaultConsumerSessionTimeout
if ams.SessionTimeout != 0 {
st = ams.SessionTimeout
}
config := sarama.NewConfig()
config.Consumer.Return.Errors = true
config.Consumer.Offsets.Initial = offset
config.Metadata.RefreshFrequency = mrf
config.Consumer.Group.Session.Timeout = st
config.Consumer.Offsets.Retention = ams.OffsetsRetention
if ams.Version != "" {
version, err := sarama.ParseKafkaVersion(ams.Version)
if err != nil {
return nil, err
}
config.Version = version
}
return config, nil
}
func NewAsyncMessageSource(c AsyncMessageSourceConfig) (substrate.AsyncMessageSource, error) {
config, err := c.buildSaramaConsumerConfig()
if err != nil {
return nil, err
}
client, err := sarama.NewClient(c.Brokers, config)
if err != nil {
return nil, err
}
consumerGroup, err := sarama.NewConsumerGroupFromClient(c.ConsumerGroup, client)
if err != nil {
_ = client.Close()
return nil, err
}
return &asyncMessageSource{
client: client,
consumerGroup: consumerGroup,
topic: c.Topic,
debugger: debug.Debugger{
Enabled: c.Debug,
},
}, nil
}
type asyncMessageSource struct {
client sarama.Client
consumerGroup sarama.ConsumerGroup
topic string
debugger debug.Debugger
}
// MessageWithMetadata
type MessageWithMetadata interface {
GetMetadata() Metadata
}
type Metadata struct {
Topic string
Partition int32
Offset int64
}
type consumerMessage struct {
cm *sarama.ConsumerMessage
discard bool
offset *struct {
topic string
partition int32
offset int64
}
}
func (cm *consumerMessage) Data() []byte {
if cm.cm == nil {
panic("attempt to use payload after discarding.")
}
return cm.cm.Value
}
func (cm *consumerMessage) GetMetadata() Metadata {
return Metadata{
Topic: cm.offset.topic,
Partition: cm.offset.partition,
Offset: cm.offset.offset,
}
}
func (cm *consumerMessage) DiscardPayload() {
if cm.offset != nil {
// already discarded
return
}
cm.offset = &struct {
topic string
partition int32
offset int64
}{
cm.cm.Topic,
cm.cm.Partition,
cm.cm.Offset,
}
cm.cm = nil
}
func (ams *asyncMessageSource) ConsumeMessages(ctx context.Context, messages chan<- substrate.Message, acks <-chan substrate.Message) error {
rg, ctx := rungroup.New(ctx)
toAck := make(chan *consumerMessage)
sessCh := make(chan sarama.ConsumerGroupSession)
rebalanceCh := make(chan struct{})
rg.Go(func() error {
ap := &kafkaAcksProcessor{
toClient: messages,
fromKafka: toAck,
acks: acks,
sessCh: sessCh,
rebalanceCh: rebalanceCh,
debugger: ams.debugger,
}
return ap.run(ctx)
})
rg.Go(func() error {
// We need to run consume in infinite loop to handle rebalances.
for {
err := ams.consumerGroup.Consume(ctx, []string{ams.topic}, &consumerGroupHandler{
ctx: ctx,
toAck: toAck,
sessCh: sessCh,
rebalanceCh: rebalanceCh,
debugger: ams.debugger,
})
if err != nil || ctx.Err() != nil {
return err
}
}
})
return rg.Wait()
}
func (ams *asyncMessageSource) Status() (*substrate.Status, error) {
return status(ams.client, ams.topic)
}
func (ams *asyncMessageSource) Close() (err error) {
for _, closer := range []io.Closer{ams.consumerGroup, ams.client} {
err = multierror.Append(err, closer.Close()).ErrorOrNil()
}
return err
}