-
Notifications
You must be signed in to change notification settings - Fork 13
/
consumer.go
448 lines (334 loc) · 14 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
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
package queue
import (
"context"
"encoding/json"
"log"
"strings"
"time"
"github.com/latolukasz/beeorm"
"github.com/coretrix/hitrix"
"github.com/coretrix/hitrix/service"
)
const (
obtainLockRetryDuration = time.Second
)
type ConsumerOneByModulo interface {
GetMaxModulo() int
Consume(ormService *beeorm.Engine, event beeorm.Event) error
GetQueueName(moduloID int) string
GetGroupName(moduloID int, suffix *string) string
}
type ConsumerManyByModulo interface {
GetMaxModulo() int
Consume(ormService *beeorm.Engine, events []beeorm.Event) error
GetQueueName(moduloID int) string
GetGroupName(moduloID int, suffix *string) string
}
type ConsumerOne interface {
Consume(ormService *beeorm.Engine, event beeorm.Event) error
GetQueueName() string
GetGroupName(suffix *string) string
}
type ConsumerMany interface {
Consume(ormService *beeorm.Engine, events []beeorm.Event) error
GetQueueName() string
GetGroupName(suffix *string) string
}
type ConsumerRunner struct {
ctx context.Context
}
func NewConsumerRunner(ctx context.Context) *ConsumerRunner {
return &ConsumerRunner{ctx: ctx}
}
func (r *ConsumerRunner) RunConsumerMany(consumer ConsumerMany, groupNameSuffix *string, prefetchCount int) {
queueName := consumer.GetQueueName()
log.Printf("RunConsumerMany initialized (%s)", queueName)
ormService := service.DI().OrmEngine().Clone()
eventsConsumer := ormService.GetEventBroker().Consumer(consumer.GetGroupName(groupNameSuffix))
service.DI().App().Add(1)
defer service.DI().App().Done()
for {
// eventsConsumer.Consume should block and not return anything
// if it returns true => this consumer is exited with no errors, but still not consuming
// if it returns false => this consumer is exited with error "could not obtain lock", so we should retry
if exitedWithNoErrors := eventsConsumer.Consume(r.ctx, prefetchCount, func(events []beeorm.Event) {
log.Printf("We have %d new dirty events in %s", len(events), queueName)
if err := consumer.Consume(ormService, events); err != nil {
panic(err)
}
log.Printf("We consumed %d dirty events in %s", len(events), queueName)
}); !exitedWithNoErrors {
log.Printf("RunConsumerMany failed to start (%s) - retrying in %.1f seconds", queueName, obtainLockRetryDuration.Seconds())
time.Sleep(obtainLockRetryDuration)
continue
}
log.Println("eventsConsumer.Consume returned true")
log.Printf("RunConsumerMany exited (%s)", queueName)
break
}
}
func (r *ConsumerRunner) RunConsumerOne(consumer ConsumerOne, groupNameSuffix *string, prefetchCount int) {
queueName := consumer.GetQueueName()
log.Printf("RunConsumerOne initialized (%s)", queueName)
ormService := service.DI().OrmEngine().Clone()
eventsConsumer := ormService.GetEventBroker().Consumer(consumer.GetGroupName(groupNameSuffix))
service.DI().App().Add(1)
defer service.DI().App().Done()
for {
// eventsConsumer.Consume should block and not return anything
// if it returns true => this consumer is exited with no errors, but still not consuming
// if it returns false => this consumer is exited with error "could not obtain lock", so we should retry
if exitedWithNoErrors := eventsConsumer.Consume(r.ctx, prefetchCount, func(events []beeorm.Event) {
log.Printf("We have %d new dirty events in %s", len(events), queueName)
for _, event := range events {
if err := consumer.Consume(ormService, event); err != nil {
panic(err)
}
event.Ack()
}
log.Printf("We consumed %d dirty events in %s", len(events), queueName)
}); !exitedWithNoErrors {
log.Printf("RunConsumerOne failed to start (%s) - retrying in %.1f seconds", queueName, obtainLockRetryDuration.Seconds())
time.Sleep(obtainLockRetryDuration)
continue
}
log.Println("eventsConsumer.Consume returned true")
break
}
log.Printf("RunConsumerOne exited (%s)", queueName)
}
func (r *ConsumerRunner) RunConsumerOneByModulo(consumer ConsumerOneByModulo, groupNameSuffix *string, prefetchCount int) {
maxModulo := consumer.GetMaxModulo()
baseQueueName := ""
queueNameParts := strings.Split(consumer.GetQueueName(maxModulo), "_")
if len(queueNameParts) > 0 {
baseQueueName = queueNameParts[0]
}
log.Printf("RunConsumerOneByModulo initialized (%s)", baseQueueName)
for moduloID := 1; moduloID <= maxModulo; moduloID++ {
currentModulo := moduloID
hitrix.GoroutineWithRestart(func() {
queueName := consumer.GetQueueName(currentModulo)
consumerGroupName := consumer.GetGroupName(currentModulo, groupNameSuffix)
log.Printf("RunConsumerOneByModulo started goroutine %d (%s)", currentModulo, queueName)
ormService := service.DI().OrmEngine().Clone()
eventsConsumer := ormService.GetEventBroker().Consumer(consumerGroupName)
service.DI().App().Add(1)
defer service.DI().App().Done()
for {
// eventsConsumer.Consume should block and not return anything
// if it returns true => this consumer is exited with no errors, but still not consuming
// if it returns false => this consumer is exited with error "could not obtain lock", so we should retry
if exitedWithNoErrors := eventsConsumer.Consume(r.ctx, prefetchCount, func(events []beeorm.Event) {
log.Printf("We have %d new dirty events in %s", len(events), consumerGroupName)
for _, event := range events {
if err := consumer.Consume(ormService, event); err != nil {
panic(err)
}
event.Ack()
}
log.Printf("We consumed %d dirty events in %s", len(events), consumerGroupName)
}); !exitedWithNoErrors {
log.Printf(
"RunConsumerOneByModulo failed to start for goroutine %d (%s) - retrying in %.1f seconds",
currentModulo,
queueName,
obtainLockRetryDuration.Seconds())
time.Sleep(obtainLockRetryDuration)
continue
}
log.Printf("eventsConsumer.Consume returned true for goroutine %d (%s)", currentModulo, queueName)
log.Printf("RunConsumerOneByModulo exited (%s)", baseQueueName)
break
}
log.Printf("RunConsumerOneByModulo goroutine %d (%s) exited", currentModulo, queueName)
})
time.Sleep(time.Second)
}
}
func (r *ConsumerRunner) RunConsumerManyByModulo(consumer ConsumerManyByModulo, groupNameSuffix *string, prefetchCount int) {
maxModulo := consumer.GetMaxModulo()
baseQueueName := ""
queueNameParts := strings.Split(consumer.GetQueueName(maxModulo), "_")
if len(queueNameParts) > 0 {
baseQueueName = queueNameParts[0]
}
log.Printf("RunConsumerManyByModulo initialized (%s)", baseQueueName)
for moduloID := 1; moduloID <= maxModulo; moduloID++ {
currentModulo := moduloID
hitrix.GoroutineWithRestart(func() {
queueName := consumer.GetQueueName(currentModulo)
consumerGroupName := consumer.GetGroupName(currentModulo, groupNameSuffix)
log.Printf("RunConsumerManyByModulo started goroutine %d (%s)", currentModulo, queueName)
ormService := service.DI().OrmEngine().Clone()
eventsConsumer := ormService.GetEventBroker().Consumer(consumerGroupName)
service.DI().App().Add(1)
defer service.DI().App().Done()
for {
// eventsConsumer.Consume should block and not return anything
// if it returns true => this consumer is exited with no errors, but still not consuming
// if it returns false => this consumer is exited with error "could not obtain lock", so we should retry
if exitedWithNoErrors := eventsConsumer.Consume(r.ctx, prefetchCount, func(events []beeorm.Event) {
log.Printf("We have %d new dirty events in %s", len(events), consumerGroupName)
if err := consumer.Consume(ormService, events); err != nil {
panic(err)
}
log.Printf("We consumed %d dirty events in %s", len(events), consumerGroupName)
}); !exitedWithNoErrors {
log.Printf(
"RunConsumerManyByModulo failed to start for goroutine %d (%s) - retrying in %.1f seconds",
currentModulo,
queueName,
obtainLockRetryDuration.Seconds())
time.Sleep(obtainLockRetryDuration)
continue
}
log.Printf("eventsConsumer.Consume returned true for goroutine %d (%s)", currentModulo, queueName)
log.Printf("RunConsumerManyByModulo exited (%s)", baseQueueName)
break
}
log.Printf("RunConsumerManyByModulo goroutine %d (%s) exited", currentModulo, queueName)
})
time.Sleep(time.Second)
}
}
type ScalableConsumerRunner struct {
ctx context.Context
redisPool string
}
func NewScalableConsumerRunner(ctx context.Context, redisPool string) *ScalableConsumerRunner {
return &ScalableConsumerRunner{ctx: ctx, redisPool: redisPool}
}
func (r *ScalableConsumerRunner) RunScalableConsumerMany(consumer ConsumerMany, groupNameSuffix *string, prefetchCount int) {
ormService := service.DI().OrmEngine().Clone()
redis := ormService.GetRedis(r.redisPool)
queueName := consumer.GetQueueName()
consumerGroupName := consumer.GetGroupName(groupNameSuffix)
currentIndex := addConsumerGroup(redis, consumerGroupName)
log.Printf("RunScalableConsumerMany index (%d) initialized (%s)", currentIndex, queueName)
eventsConsumer := ormService.GetEventBroker().Consumer(consumerGroupName)
service.DI().App().Add(1)
defer service.DI().App().Done()
for {
// eventsConsumer.ConsumeMany should block and not return anything
// if it returns true => this consumer is exited with no errors, but still not consuming
// if it returns false => this consumer is exited with error "could not obtain lock", so we should retry
if exitedWithNoErrors := eventsConsumer.ConsumeMany(r.ctx, currentIndex, prefetchCount, func(events []beeorm.Event) {
log.Printf("We have %d new dirty events in %s", len(events), queueName)
if err := consumer.Consume(ormService, events); err != nil {
removeConsumerGroup(eventsConsumer, redis, consumerGroupName, currentIndex)
panic(err)
}
log.Printf("We consumed %d dirty events in %s", len(events), queueName)
}); !exitedWithNoErrors {
log.Printf("RunScalableConsumerMany failed to start (%s) - retrying in %.1f seconds", queueName, obtainLockRetryDuration.Seconds())
time.Sleep(obtainLockRetryDuration)
continue
}
log.Println("eventsConsumer.ConsumeMany returned true")
break
}
removeConsumerGroup(eventsConsumer, redis, consumerGroupName, currentIndex)
}
func (r *ScalableConsumerRunner) RunScalableConsumerOne(consumer ConsumerOne, groupNameSuffix *string, prefetchCount int) {
ormService := service.DI().OrmEngine().Clone()
redis := ormService.GetRedis(r.redisPool)
queueName := consumer.GetQueueName()
consumerGroupName := consumer.GetGroupName(groupNameSuffix)
currentIndex := addConsumerGroup(redis, consumerGroupName)
log.Printf("RunScalableConsumerOne index (%d) initialized (%s)", currentIndex, queueName)
eventsConsumer := ormService.GetEventBroker().Consumer(consumerGroupName)
service.DI().App().Add(1)
defer service.DI().App().Done()
for {
// eventsConsumer.ConsumeMany should block and not return anything
// if it returns true => this consumer is exited with no errors, but still not consuming
// if it returns false => this consumer is exited with error "could not obtain lock", so we should retry
if exitedWithNoErrors := eventsConsumer.ConsumeMany(r.ctx, currentIndex, prefetchCount, func(events []beeorm.Event) {
log.Printf("We have %d new dirty events in %s", len(events), queueName)
for _, event := range events {
if err := consumer.Consume(ormService, event); err != nil {
removeConsumerGroup(eventsConsumer, redis, consumerGroupName, currentIndex)
panic(err)
}
event.Ack()
}
log.Printf("We consumed %d dirty events in %s", len(events), queueName)
}); !exitedWithNoErrors {
log.Printf("RunScalableConsumerOne failed to start (%s) - retrying in %.1f seconds", queueName, obtainLockRetryDuration.Seconds())
time.Sleep(obtainLockRetryDuration)
continue
}
log.Println("eventsConsumer.ConsumeMany returned true")
break
}
removeConsumerGroup(eventsConsumer, redis, consumerGroupName, currentIndex)
log.Printf("RunScalableConsumerOne exited (%s)", queueName)
}
const consumerGroupsKey = "consumer_groups"
type indexer struct {
LatestIndex int
ActiveConsumerIndexes map[int]*struct{}
}
func addConsumerGroup(redis *beeorm.RedisCache, consumerGroupName string) int {
indexerValue, err := getConsumerGroupIndexer(redis, consumerGroupName)
if err != nil {
panic(err)
}
if indexerValue == nil {
indexerValue = &indexer{}
}
if indexerValue.ActiveConsumerIndexes == nil {
indexerValue.ActiveConsumerIndexes = map[int]*struct{}{}
}
indexerValue.LatestIndex++
indexerValue.ActiveConsumerIndexes[indexerValue.LatestIndex] = &struct{}{}
err = setConsumerGroupIndexer(redis, consumerGroupName, indexerValue)
if err != nil {
panic(err)
}
return indexerValue.LatestIndex
}
func removeConsumerGroup(consumer beeorm.EventsConsumer, redis *beeorm.RedisCache, consumerGroupName string, indexToRemove int) {
indexerValue, err := getConsumerGroupIndexer(redis, consumerGroupName)
if err != nil {
panic(err)
}
delete(indexerValue.ActiveConsumerIndexes, indexToRemove)
err = setConsumerGroupIndexer(redis, consumerGroupName, indexerValue)
if err != nil {
panic(err)
}
// transfer pending items from stopped consumer to another if available as per:
// https://beeorm.io/guide/event_broker.html#consumers-scaling
if len(indexerValue.ActiveConsumerIndexes) != 0 {
indexToTransferClaimedItems := 0
for index := range indexerValue.ActiveConsumerIndexes {
indexToTransferClaimedItems = index
break
}
if indexToTransferClaimedItems != 0 {
log.Printf("claiming from %d to %d", indexToRemove, indexToTransferClaimedItems)
consumer.Claim(indexToRemove, indexToTransferClaimedItems)
}
}
}
func setConsumerGroupIndexer(redis *beeorm.RedisCache, consumerGroupName string, indexer *indexer) error {
marshaled, err := json.Marshal(indexer)
if err != nil {
return err
}
redis.HSet(consumerGroupsKey, consumerGroupName, marshaled)
return err
}
func getConsumerGroupIndexer(redis *beeorm.RedisCache, consumerGroupName string) (*indexer, error) {
marshaled, has := redis.HGet(consumerGroupsKey, consumerGroupName)
if !has {
return nil, nil
}
indexer := &indexer{}
if err := json.Unmarshal([]byte(marshaled), indexer); err != nil {
return nil, err
}
return indexer, nil
}