-
Notifications
You must be signed in to change notification settings - Fork 1
/
consumer.go
177 lines (138 loc) · 3.72 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
package queue
import (
"context"
"fmt"
"runtime"
"sync"
"sync/atomic"
"github.com/ibllex/go-queue/internal"
"github.com/ibllex/go-queue/internal/logger"
)
//
// Consumer
//
type Handler interface {
Handle(Message)
}
type HandlerFunc func(Message)
func (fn HandlerFunc) Handle(message Message) {
fn(message)
}
func H(hanlder HandlerFunc) Handler {
return hanlder
}
// Consumer state
const (
StateStoped = iota
StateStarted
)
type ConsumerOption struct {
// For logging, if it is empty,
// a random string will be automatically generated
ID string
// Maximum number of goroutines processing messages.
// Default is the number of CPUs.
MaxNumWorker int32
// The number of messages prefetched in the queue in a poll.
// Default is 10.
PrefetchCount int
// Message handler
Handler Handler
}
// consumer reserves messages from the queue, processes them,
// and then either releases or deletes messages from the queue.
type Consumer struct {
opt *ConsumerOption
w Worker
state int32
// pending messages
pending chan struct{}
workersWG sync.WaitGroup
}
// Start consuming messages in the queue.
func (c *Consumer) Start(ctx context.Context) error {
if atomic.LoadInt32(&c.state) == StateStarted {
return fmt.Errorf("consumer[%s:%s] is already started", c.w.Name(), c.opt.ID)
}
go c.start(ctx)
atomic.StoreInt32(&c.state, StateStarted)
logger.Infof("consumer[%s:%s] started", c.w.Name(), c.opt.ID)
return nil
}
func (c *Consumer) start(ctx context.Context) {
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 64<<10)
buf = buf[:runtime.Stack(buf, false)]
logger.Errorf("errgroup: panic recovered: %s\n%s", r, buf)
}
}()
err := c.w.Daemon(ctx, func(m Message) {
c.workersWG.Add(1)
go func() {
defer func() {
if r := recover(); r != nil {
buf := make([]byte, 64<<10)
buf = buf[:runtime.Stack(buf, false)]
logger.Errorf("errgroup: panic recovered: %s\n%s", r, buf)
}
c.workersWG.Done()
<-c.pending
}()
c.Process(m)
}()
// Must be executed later than the worker,
// because it will block when all the workers are busy
c.pending <- struct{}{}
})
if err != nil {
logger.Errorf("consumer[%s:%s] exit with error %s", c.w.Name(), c.opt.ID, err)
return
}
atomic.StoreInt32(&c.state, StateStoped)
logger.Infof("consumer[%s:%s] waiting for all workers to exit", c.w.Name(), c.opt.ID)
c.workersWG.Wait()
logger.Infof("consumer[%s:%s] stopped", c.w.Name(), c.opt.ID)
}
// Process message bypassing the internal queue
func (c *Consumer) Process(msg Message) error {
logger.Infof("consumer[%s:%s] Processing %s", c.w.Name(), c.opt.ID, msg.Name())
if c.opt.Handler != nil {
c.opt.Handler.Handle(msg)
}
switch msg.Status() {
case Acked:
logger.Infof("consumer[%s:%s] Processed %s", c.w.Name(), c.opt.ID, msg.Name())
case Rejected:
logger.Error("consumer[%s:%s] Failed %s", c.w.Name(), c.opt.ID, msg.Name())
case Pending:
logger.Error("consumer[%s:%s] Still Pending %s", c.w.Name(), c.opt.ID, msg.Name())
}
return nil
}
func DefaultConsumerOption(opt *ConsumerOption) *ConsumerOption {
if opt == nil {
opt = &ConsumerOption{}
}
if opt.PrefetchCount <= 0 {
opt.PrefetchCount = 10
}
if opt.MaxNumWorker <= 0 {
opt.MaxNumWorker = int32(runtime.NumCPU())
}
if opt.ID == "" {
opt.ID = internal.RandomString(6)
}
return opt
}
func NewConsumer(w Worker, opt *ConsumerOption) (*Consumer, error) {
opt = DefaultConsumerOption(opt)
c := &Consumer{
w: w, opt: opt,
// The pending list must be one less than the maximum number of workers,
// otherwise when all workers are busy,
// there will always be a message that has been taken out and has not been processed
pending: make(chan struct{}, opt.MaxNumWorker-1),
}
return c, nil
}