/
consumer_batch.go
230 lines (176 loc) · 6.19 KB
/
consumer_batch.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
package stream
import (
"context"
"fmt"
"sync/atomic"
"time"
"github.com/justtrackio/gosoline/pkg/cfg"
"github.com/justtrackio/gosoline/pkg/kernel"
"github.com/justtrackio/gosoline/pkg/log"
"github.com/justtrackio/gosoline/pkg/tracing"
)
type BatchConsumerCallbackFactory func(ctx context.Context, config cfg.Config, logger log.Logger) (BatchConsumerCallback, error)
//go:generate mockery --name=BatchConsumerCallback
type BatchConsumerCallback interface {
BaseConsumerCallback
Consume(ctx context.Context, models []interface{}, attributes []map[string]string) ([]bool, error)
}
//go:generate mockery --name=RunnableBatchConsumerCallback
type RunnableBatchConsumerCallback interface {
BatchConsumerCallback
RunnableCallback
}
type BatchConsumerSettings struct {
IdleTimeout time.Duration `cfg:"idle_timeout" default:"10s"`
BatchSize int `cfg:"batch_size" default:"1"`
}
type BatchConsumer struct {
*baseConsumer
batch []*consumerData
callback BatchConsumerCallback
ticker *time.Ticker
settings *BatchConsumerSettings
}
func NewBatchConsumer(name string, callbackFactory BatchConsumerCallbackFactory) func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {
return func(ctx context.Context, config cfg.Config, logger log.Logger) (kernel.Module, error) {
loggerCallback := logger.WithChannel("consumerCallback")
contextEnforcingLogger := log.NewContextEnforcingLogger(loggerCallback)
callback, err := callbackFactory(ctx, config, contextEnforcingLogger)
if err != nil {
return nil, fmt.Errorf("can not initiate callback for consumer %s: %w", name, err)
}
contextEnforcingLogger.Enable()
settings := &BatchConsumerSettings{}
key := ConfigurableConsumerKey(name)
config.UnmarshalKey(key, settings)
ticker := time.NewTicker(settings.IdleTimeout)
baseConsumer, err := NewBaseConsumer(ctx, config, logger, name, callback)
if err != nil {
return nil, fmt.Errorf("can not initiate base consumer: %w", err)
}
batchConsumer := NewBatchConsumerWithInterfaces(baseConsumer, callback, ticker, settings)
return batchConsumer, nil
}
}
func NewBatchConsumerWithInterfaces(base *baseConsumer, callback BatchConsumerCallback, ticker *time.Ticker, settings *BatchConsumerSettings) *BatchConsumer {
consumer := &BatchConsumer{
baseConsumer: base,
callback: callback,
ticker: ticker,
settings: settings,
}
return consumer
}
func (c *BatchConsumer) Run(kernelCtx context.Context) error {
return c.baseConsumer.run(kernelCtx, c.readFromInput)
}
func (c *BatchConsumer) readFromInput(ctx context.Context) error {
logger := c.logger.WithContext(ctx)
defer logger.Debug("run is ending")
defer c.wg.Done()
defer c.processBatch(context.Background())
for {
force := false
select {
case <-ctx.Done():
return fmt.Errorf("return from consuming as the coffin is dying")
case cdata, ok := <-c.data:
if !ok {
return nil
}
if _, ok := cdata.msg.Attributes[AttributeAggregate]; ok {
c.processAggregateMessage(ctx, cdata)
} else {
c.processSingleMessage(ctx, cdata)
}
case <-c.ticker.C:
force = true
}
if len(c.batch) >= c.settings.BatchSize || force {
c.processBatch(ctx)
}
}
}
func (c *BatchConsumer) processAggregateMessage(ctx context.Context, cdata *consumerData) {
batch := make([]*Message, 0)
var err error
ctx, _, err = c.encoder.Decode(ctx, cdata.msg, &batch)
if err != nil {
c.logger.WithContext(ctx).Error("an error occurred during disaggregation of the message: %w", err)
return
}
for _, msg := range batch {
c.batch = append(c.batch, &consumerData{
msg: msg,
input: cdata.input,
})
}
}
func (c *BatchConsumer) processSingleMessage(_ context.Context, cdata *consumerData) {
c.batch = append(c.batch, cdata)
}
func (c *BatchConsumer) processBatch(ctx context.Context) {
batch := c.batch
c.batch = make([]*consumerData, 0, c.settings.BatchSize)
c.ticker.Stop()
c.ticker = time.NewTicker(c.settings.IdleTimeout)
c.consumeBatch(ctx, batch)
}
func (c *BatchConsumer) consumeBatch(ctx context.Context, batch []*consumerData) {
defer c.recover(ctx, nil)
start := c.clock.Now()
// make sure to create new context as we can't rely on the tracer to create a new one
batchCtx, cancel := context.WithCancel(ctx)
defer cancel()
var span tracing.Span
batchCtx, span = c.tracer.StartSpanFromContext(batchCtx, "stream.consumeBatch")
defer span.Finish()
if len(batch) == 0 {
return
}
batch, models, attributes, subSpans := c.decodeMessages(batchCtx, batch)
defer func() {
for i := range subSpans {
subSpans[i].Finish()
}
}()
logger := c.logger.WithContext(batchCtx)
acks, err := c.callback.Consume(batchCtx, models, attributes)
if err != nil {
logger.Error("an error occurred during the consume batch operation: %w", err)
}
if len(batch) != len(acks) {
logger.Error("number of acks does not match number of messages in batch: %d != %d", len(acks), len(batch))
}
ackMessages := make([]*consumerData, 0, len(batch))
for i, ack := range acks {
ackMessages = append(ackMessages, batch[i])
if !ack && !c.hasNativeRetry() {
c.retry(batchCtx, batch[i].msg)
}
}
c.AcknowledgeBatch(batchCtx, ackMessages, acks)
duration := c.clock.Now().Sub(start)
atomic.AddInt32(&c.processed, int32(len(ackMessages)))
c.writeMetricDurationAndProcessedCount(duration, len(batch))
}
func (c *BatchConsumer) decodeMessages(batchCtx context.Context, batch []*consumerData) ([]*consumerData, []interface{}, []map[string]string, []tracing.Span) {
models := make([]interface{}, 0, len(batch))
attributes := make([]map[string]string, 0, len(batch))
spans := make([]tracing.Span, 0, len(batch))
newBatch := make([]*consumerData, 0, len(batch))
for _, cdata := range batch {
model := c.callback.GetModel(cdata.msg.Attributes)
msgCtx, attribute, err := c.encoder.Decode(batchCtx, cdata.msg, model)
if err != nil {
c.logger.WithContext(msgCtx).Error("an error occurred during the batch decode message operation: %w", err)
continue
}
models = append(models, model)
attributes = append(attributes, attribute)
newBatch = append(newBatch, cdata)
_, span := c.tracer.StartSubSpan(msgCtx, c.id)
spans = append(spans, span)
}
return newBatch, models, attributes, spans
}