/
consumer.go
258 lines (216 loc) · 5.57 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
package consumer
import (
"context"
"fmt"
"sync"
"time"
"github.com/aws/aws-sdk-go/service/sqs"
)
type IConsumer interface {
Resume()
Pause()
Close()
Paused() bool
Closed() bool
Running() bool
Context() context.Context
WaitGroup() *sync.WaitGroup
Worker(h Handler)
WorkerPool(h Handler, poolSize int)
WithWaitGroup(wg *sync.WaitGroup) *Consumer
WithContext(ctx context.Context) *Consumer
WithInterval(interval int) *Consumer
WithEnableDebug(enabled bool) *Consumer
WithBatchSize(batchSize int64) *Consumer
WithReceiveWaitTimeSeconds(waitSeconds int64) *Consumer
WithReceiveVisibilityTimeout(visibilityTimeout int64) *Consumer
WithTerminateVisibilityTimeout(visibilityTimeout int64) *Consumer
}
type Consumer struct {
paused bool
closed bool
interval int
debug bool
wg *sync.WaitGroup
ctx context.Context
sqs ISqsClient
}
// Handler interface
type Handler interface {
HandleMessage(ctx context.Context, msg *sqs.Message) error
}
// BatchHandlerFunc batch handler function
type BatchHandlerFunc func(ctx context.Context, message []*sqs.Message) error
// HandlerFunc handler function
type HandlerFunc func(ctx context.Context, message *sqs.Message) error
// HandleMessage is used for the actual execution of each message
func (f HandlerFunc) HandleMessage(ctx context.Context, msg *sqs.Message) error {
return f(ctx, msg)
}
// New create a new consumer
func New(sqs *sqs.SQS, queueUrl string) IConsumer {
consumer := &Consumer{
closed: false,
paused: false,
debug: false,
interval: 100,
wg: &sync.WaitGroup{},
ctx: context.Background(),
sqs: NewSQSClient(sqs, queueUrl),
}
return consumer
}
func (con *Consumer) WithContext(ctx context.Context) *Consumer {
con.ctx = ctx
return con
}
func (con *Consumer) WithWaitGroup(wg *sync.WaitGroup) *Consumer {
con.wg = wg
return con
}
func (con *Consumer) WithInterval(ms int) *Consumer {
con.interval = ms
return con
}
func (con *Consumer) WithBatchSize(batchSize int64) *Consumer {
if con.sqs != nil {
con.sqs.WithBatchSize(batchSize)
}
return con
}
func (con *Consumer) WithEnableDebug(enabled bool) *Consumer {
con.debug = enabled
return con
}
func (con *Consumer) WithReceiveWaitTimeSeconds(waitSeconds int64) *Consumer {
if con.sqs != nil {
con.sqs.WithReceiveWaitTimeSeconds(waitSeconds)
}
return con
}
func (con *Consumer) WithReceiveVisibilityTimeout(visibilityTimeout int64) *Consumer {
if con.sqs != nil {
con.sqs.WithReceiveVisibilityTimeout(visibilityTimeout)
}
return con
}
func (con *Consumer) WithTerminateVisibilityTimeout(visibilityTimeout int64) *Consumer {
if con.sqs != nil {
con.sqs.WithTerminateVisibilityTimeout(visibilityTimeout)
}
return con
}
func (con *Consumer) Context() context.Context {
return con.ctx
}
func (con *Consumer) WaitGroup() *sync.WaitGroup {
return con.wg
}
func (con *Consumer) Resume() {
con.paused = false
}
// Stop processing
func (con *Consumer) Pause() {
con.paused = true
}
// Paused check worker is paused
func (con *Consumer) Paused() bool {
return con.paused
}
// Close allowing the process to exit gracefully
func (con *Consumer) Close() {
con.closed = true
}
// Closed check worker is closed
func (con *Consumer) Closed() bool {
return con.closed
}
// Running check if the mq client is running
func (con *Consumer) Running() bool {
return !con.Paused() && !con.Closed()
}
// WorkerPool worker pool
func (con *Consumer) WorkerPool(h Handler, poolSize int) {
if poolSize <= 0 {
poolSize = 1
}
for w := 1; w <= poolSize; w++ {
con.wg.Add(1)
go con.Worker(h)
}
}
// Worker Start polling and will continue polling till the application is forcibly stopped
func (con *Consumer) Worker(h Handler) {
defer con.wg.Done()
for {
select {
case <-con.ctx.Done():
return
default:
}
if con.Closed() {
return
}
if con.Paused() {
time.Sleep(time.Millisecond * time.Duration(con.interval))
continue
}
messages, err := con.sqs.ReceiveMessageWithContext(con.ctx)
if err != nil {
con.logError(ERROR, "Receive Message", err)
time.Sleep(time.Millisecond * time.Duration(con.interval))
continue
}
con.log(INFO, fmt.Sprintf("[ %-2v ] Message Received", len(messages)))
if len(messages) == 0 {
time.Sleep(time.Millisecond * time.Duration(con.interval))
continue
}
con.run(h, messages)
}
}
// run launches goroutine per received message and wait for all message to be processed
func (con *Consumer) run(h Handler, messages []*sqs.Message) {
wg := &sync.WaitGroup{}
for index, message := range messages {
select {
case <-con.ctx.Done():
con.terminate(messages[index:])
return
default:
}
if con.Closed() {
con.terminate(messages[index:])
return
}
wg.Add(1)
go func(m *sqs.Message) {
defer wg.Done()
if err := con.handleMessage(m, h); err != nil {
con.logError(ERROR, "Handle Message", err)
}
}(message)
}
wg.Wait()
}
func (con *Consumer) terminate(messages []*sqs.Message) {
if err := con.sqs.TerminateVisibilityTimeoutBatch(messages); err != nil {
con.logError(ERROR, "Terminate Message Visibility Timeout ", err)
}
}
func (con *Consumer) handleMessage(m *sqs.Message, h Handler) error {
if err := h.HandleMessage(con.ctx, m); err != nil {
return con.sqs.TerminateVisibilityTimeout(m)
}
return con.sqs.DeleteMessage(m)
}
func (con *Consumer) log(level string, message string) {
if con.debug {
fmt.Println(time.Now().Format(time.RFC3339), level, message)
}
}
func (con *Consumer) logError(level string, message string, err error) {
if con.debug {
fmt.Println(time.Now().Format(time.RFC3339), level, message, "-", err.Error())
}
}