-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathprocessor.go
More file actions
306 lines (260 loc) · 7.38 KB
/
Copy pathprocessor.go
File metadata and controls
306 lines (260 loc) · 7.38 KB
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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package sequin
import (
"context"
"errors"
"fmt"
"log"
"golang.org/x/sync/errgroup"
"golang.org/x/sync/semaphore"
)
// ProcessorFunc processes a batch of messages.
// It should return an error if processing fails.
//
// If an error is returned, none of the messages in the batch will be acknowledged
// and they will be redelivered after the visibility timeout.
type ProcessorFunc func(context.Context, []Message) error
// PrefetchingOptions configures message prefetching behavior.
type PrefetchingOptions struct {
// BufferSize determines how many messages to prefetch.
// Must be > 0.
BufferSize int
}
func (o *PrefetchingOptions) validate() error {
if o.BufferSize <= 0 {
return fmt.Errorf("BufferSize must be > 0, got %d", o.BufferSize)
}
return nil
}
// ProcessorOptions configures the behavior of a Processor.
type ProcessorOptions struct {
// MaxBatchSize is the maximum number of messages to process in a single batch.
// The processor will call ProcessorFunc with up to this many messages.
// If zero, defaults to 1.
MaxBatchSize int
// FetchBatchSize is the number of messages to request from the server in a single call.
// This can be larger than MaxBatchSize to improve throughput.
// If zero, defaults to MaxBatchSize.
FetchBatchSize int
// MaxConcurrent is the maximum number of concurrent batch processors.
// If zero, defaults to 1.
MaxConcurrent int
// Prefetching configures message prefetching behavior.
// If nil, messages are processed immediately as they arrive.
Prefetching *PrefetchingOptions
// ErrorHandler is called when message processing fails.
// If nil, errors are logged to stderr.
ErrorHandler func(context.Context, []Message, error)
}
// validate checks ProcessorOptions and applies defaults.
func (o *ProcessorOptions) validate() error {
if o.MaxBatchSize < 0 {
return fmt.Errorf("MaxBatchSize must be >= 0, got %d", o.MaxBatchSize)
}
if o.MaxBatchSize == 0 {
o.MaxBatchSize = 1
}
if o.FetchBatchSize < 0 {
return fmt.Errorf("FetchBatchSize must be >= 0, got %d", o.FetchBatchSize)
}
if o.FetchBatchSize == 0 {
o.FetchBatchSize = o.MaxBatchSize
}
if o.MaxConcurrent < 0 {
return fmt.Errorf("MaxConcurrent must be >= 0, got %d", o.MaxConcurrent)
}
if o.MaxConcurrent == 0 {
o.MaxConcurrent = 1
}
if o.Prefetching != nil {
if err := o.Prefetching.validate(); err != nil {
return fmt.Errorf("invalid prefetching options: %w", err)
}
}
if o.ErrorHandler == nil {
o.ErrorHandler = func(_ context.Context, msgs []Message, err error) {
log.Printf("Error processing batch of %d messages: %v", len(msgs), err)
}
}
return nil
}
type Processor struct {
client SequinClient
consumerGroup string
handler ProcessorFunc
opts ProcessorOptions
msgBuffer chan Message
}
func NewProcessor(client SequinClient, consumerGroup string, handler ProcessorFunc, opts ProcessorOptions) (*Processor, error) {
if client == nil {
return nil, errors.New("client cannot be nil")
}
if consumerGroup == "" {
return nil, errors.New("consumer group cannot be empty")
}
if handler == nil {
return nil, errors.New("handler cannot be nil")
}
if err := opts.validate(); err != nil {
return nil, fmt.Errorf("invalid options: %w", err)
}
p := &Processor{
client: client,
consumerGroup: consumerGroup,
handler: handler,
opts: opts,
}
// Initialize message buffer if prefetching is enabled
if opts.Prefetching != nil {
p.msgBuffer = make(chan Message, opts.Prefetching.BufferSize)
}
return p, nil
}
func (p *Processor) Run(ctx context.Context) error {
g, ctx := errgroup.WithContext(ctx)
if p.opts.Prefetching != nil {
// With prefetching: separate fetcher and processor goroutines
g.Go(func() error {
return p.fetch(ctx)
})
g.Go(func() error {
return p.processFromBuffer(ctx)
})
} else {
// Without prefetching: direct processing
g.Go(func() error {
return p.processDirectly(ctx)
})
}
return g.Wait()
}
func (p *Processor) fetch(ctx context.Context) error {
for {
select {
case <-ctx.Done():
return ctx.Err()
default:
messages, err := p.client.Receive(ctx, p.consumerGroup, &ReceiveParams{
MaxBatchSize: p.opts.FetchBatchSize,
WaitFor: 120000, // 2 minute long polling
})
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
p.opts.ErrorHandler(ctx, nil, fmt.Errorf("receiving messages: %w", err))
continue
}
for _, msg := range messages {
select {
case <-ctx.Done():
return ctx.Err()
case p.msgBuffer <- msg:
}
}
}
}
}
// processDirectly processes messages as they arrive without buffering
func (p *Processor) processDirectly(ctx context.Context) error {
sem := semaphore.NewWeighted(int64(p.opts.MaxConcurrent))
for {
// Check context before receiving
select {
case <-ctx.Done():
// Wait for any in-flight processing to complete
if err := sem.Acquire(ctx, int64(p.opts.MaxConcurrent)); err != nil {
return fmt.Errorf("waiting for in-flight processing: %w", err)
}
return ctx.Err()
default:
}
messages, err := p.client.Receive(ctx, p.consumerGroup, &ReceiveParams{
MaxBatchSize: p.opts.MaxBatchSize,
WaitFor: 120000, // 2 minute long polling
})
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
p.opts.ErrorHandler(ctx, nil, fmt.Errorf("receiving messages: %w", err))
continue
}
if len(messages) == 0 {
continue
}
// Process the batch
if err := sem.Acquire(ctx, 1); err != nil {
return fmt.Errorf("acquiring semaphore: %w", err)
}
messagesCopy := make([]Message, len(messages))
copy(messagesCopy, messages)
// Process synchronously since we're already in a goroutine
err = p.processBatch(ctx, messagesCopy)
sem.Release(1)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
p.opts.ErrorHandler(ctx, messagesCopy, err)
continue
}
}
}
// processFromBuffer processes messages from the prefetch buffer
func (p *Processor) processFromBuffer(ctx context.Context) error {
sem := semaphore.NewWeighted(int64(p.opts.MaxConcurrent))
g, ctx := errgroup.WithContext(ctx)
for {
batch := make([]Message, 0, p.opts.MaxBatchSize)
// Try to fill a batch
for len(batch) < p.opts.MaxBatchSize {
select {
case <-ctx.Done():
return ctx.Err()
case msg := <-p.msgBuffer:
batch = append(batch, msg)
default:
// No more messages immediately available
goto ProcessBatch
}
}
ProcessBatch:
if len(batch) == 0 {
// Wait for at least one message
select {
case <-ctx.Done():
return ctx.Err()
case msg := <-p.msgBuffer:
batch = append(batch, msg)
}
}
if err := sem.Acquire(ctx, 1); err != nil {
return fmt.Errorf("acquiring semaphore: %w", err)
}
batchCopy := make([]Message, len(batch))
copy(batchCopy, batch)
g.Go(func() error {
defer sem.Release(1)
if err := p.processBatch(ctx, batchCopy); err != nil {
p.opts.ErrorHandler(ctx, batchCopy, err)
}
return nil
})
}
}
func (p *Processor) processBatch(ctx context.Context, msgs []Message) error {
// Process the batch
if err := p.handler(ctx, msgs); err != nil {
return fmt.Errorf("handler failed: %w", err)
}
// Collect ack IDs
ackIDs := make([]string, len(msgs))
for i, msg := range msgs {
ackIDs[i] = msg.AckID
}
// Acknowledge the batch
if err := p.client.Ack(ctx, p.consumerGroup, ackIDs); err != nil {
return fmt.Errorf("acknowledging messages: %w", err)
}
return nil
}