-
Notifications
You must be signed in to change notification settings - Fork 0
/
queue_consumer_test.go
332 lines (265 loc) · 10.3 KB
/
queue_consumer_test.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
package sqsconsumer
import (
"sort"
"sync"
"testing"
"time"
"runtime"
"sync/atomic"
"io/ioutil"
"log"
"os"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/assert"
"github.com/tprovoost/sqsconsumer/mock"
"golang.org/x/net/context"
)
func TestQueueConsumerRunProcessesMessages(t *testing.T) {
// log to /dev/null because the deleter is chatty
log.SetOutput(ioutil.Discard)
defer func() {
log.SetOutput(os.Stderr)
}()
ctl := gomock.NewController(t)
defer ctl.Finish()
// delay so that the cancel occurs during 2nd receive
delay := func(x interface{}) {
time.Sleep(10 * time.Millisecond)
}
m := mock.NewMockSQSAPI(ctl)
received := &sqs.ReceiveMessageOutput{
Messages: []*sqs.Message{
&sqs.Message{MessageId: aws.String("i1"), ReceiptHandle: aws.String("r1")},
&sqs.Message{MessageId: aws.String("i2"), ReceiptHandle: aws.String("r2")},
},
}
// return 2 messages the first time, and an error the second time
first := m.EXPECT().ReceiveMessage(gomock.Any()).Do(delay).Return(received, nil)
m.EXPECT().ReceiveMessage(gomock.Any()).Do(delay).Return(nil, assert.AnError).After(first).AnyTimes()
m.EXPECT().DeleteMessageBatch(gomock.Any()).AnyTimes().Return(&sqs.DeleteMessageBatchOutput{}, nil)
// count messages processed
var callCount int64
fn := func(ctx context.Context, msg *sqs.Message) error {
atomic.AddInt64(&callCount, 1)
return nil
}
s := &SQSService{Svc: m, Logger: NoopLogger}
q := NewConsumer(s, fn)
q.delayAfterReceiveError = time.Millisecond
q.DeleteMessageDrainTimeout = 25 * time.Millisecond
// wait long enough to ensure ReceiveMessage is running
ctx, _ := context.WithTimeout(context.Background(), 15*time.Millisecond)
// record number of goroutines before run to ensure no leaks
ngo := runtime.NumGoroutine()
// run the fetcher
q.Run(ctx)
// ensure no routines were leaked other than the receive messages goroutine (leaks on purpose)
time.Sleep(time.Millisecond)
assert.InDelta(t, ngo, runtime.NumGoroutine(), 2, "Should not leak goroutines")
// ensure all messages were processed
assert.Equal(t, int64(2), callCount)
}
func TestQueueConsumerRunDoesNotFetchMoreMessagesThanItCanProcess(t *testing.T) {
// log to /dev/null because the deleter is chatty
log.SetOutput(ioutil.Discard)
defer func() {
log.SetOutput(os.Stderr)
}()
ctl := gomock.NewController(t)
defer ctl.Finish()
m := mock.NewMockSQSAPI(ctl)
received := &sqs.ReceiveMessageOutput{
Messages: []*sqs.Message{
&sqs.Message{MessageId: aws.String("i1"), ReceiptHandle: aws.String("r1")},
&sqs.Message{MessageId: aws.String("i2"), ReceiptHandle: aws.String("r2")},
&sqs.Message{MessageId: aws.String("i3"), ReceiptHandle: aws.String("r3")},
&sqs.Message{MessageId: aws.String("i4"), ReceiptHandle: aws.String("r4")},
&sqs.Message{MessageId: aws.String("i5"), ReceiptHandle: aws.String("r5")},
&sqs.Message{MessageId: aws.String("i6"), ReceiptHandle: aws.String("r6")},
&sqs.Message{MessageId: aws.String("i7"), ReceiptHandle: aws.String("r7")},
&sqs.Message{MessageId: aws.String("i8"), ReceiptHandle: aws.String("r8")},
&sqs.Message{MessageId: aws.String("i9"), ReceiptHandle: aws.String("r9")},
&sqs.Message{MessageId: aws.String("i10"), ReceiptHandle: aws.String("r10")},
},
}
// return 10 messages - the first 10 will never finish so the second batch will block and there will be no third request
m.EXPECT().ReceiveMessage(gomock.Any()).Return(received, nil).Times(2)
m.EXPECT().DeleteMessageBatch(gomock.Any()).AnyTimes().Return(&sqs.DeleteMessageBatchOutput{}, nil)
m.EXPECT().ChangeMessageVisibilityBatch(gomock.Any()).AnyTimes()
// hang until cancelled
fn := func(ctx context.Context, msg *sqs.Message) error {
<-ctx.Done()
return nil
}
s := &SQSService{Svc: m, Logger: NoopLogger}
q := NewConsumer(s, fn)
q.delayAfterReceiveError = time.Millisecond
q.DeleteMessageDrainTimeout = 25 * time.Millisecond
// wait long enough to ensure ReceiveMessage would have been invoked multiple times if it was too greedy
ctx, _ := context.WithTimeout(context.Background(), 500*time.Millisecond)
// record number of goroutines before run to ensure no leaks
ngo := runtime.NumGoroutine()
// run the fetcher
q.Run(ctx)
// ensure no routines were leaked
time.Sleep(time.Millisecond)
assert.InDelta(t, ngo, runtime.NumGoroutine(), 2, "Should not leak goroutines")
}
func TestQueueConsumerRunStopsGracefullyWhenCancelled(t *testing.T) {
// log to /dev/null because the deleter is chatty
log.SetOutput(ioutil.Discard)
defer func() {
log.SetOutput(os.Stderr)
}()
ctl := gomock.NewController(t)
defer ctl.Finish()
// delay so that the cancel occurs mid-receive
delay := func(x interface{}) {
time.Sleep(10 * time.Millisecond)
}
m := mock.NewMockSQSAPI(ctl)
m.EXPECT().ReceiveMessage(gomock.Any()).Do(delay).Return(&sqs.ReceiveMessageOutput{}, nil).AnyTimes()
m.EXPECT().DeleteMessageBatch(gomock.Any()).AnyTimes().Return(&sqs.DeleteMessageBatchOutput{}, nil)
m.EXPECT().ChangeMessageVisibilityBatch(gomock.Any()).AnyTimes()
s := &SQSService{Svc: m, Logger: NoopLogger}
q := NewConsumer(s, noop)
q.delayAfterReceiveError = time.Millisecond
ngo := runtime.NumGoroutine()
// wait long enough to ensure ReceiveMessage is running
ctx, _ := context.WithTimeout(context.Background(), 5*time.Millisecond)
err := q.Run(ctx)
assert.Error(t, err)
time.Sleep(time.Millisecond) // time for goroutines to end
assert.InDelta(t, ngo, runtime.NumGoroutine(), 2, "Should not leak goroutines")
}
func TestQueueConsumerRunRetriesOnErrors(t *testing.T) {
// log to /dev/null because the deleter is chatty
log.SetOutput(ioutil.Discard)
defer func() {
log.SetOutput(os.Stderr)
}()
ctl := gomock.NewController(t)
defer ctl.Finish()
// delay so that the cancel occurs after 2 receives
var receiveCount int64
delay := func(x interface{}) {
atomic.AddInt64(&receiveCount, 1)
time.Sleep(2 * time.Millisecond)
}
m := mock.NewMockSQSAPI(ctl)
m.EXPECT().ReceiveMessage(gomock.Any()).Do(delay).Return(nil, assert.AnError).AnyTimes()
m.EXPECT().DeleteMessageBatch(gomock.Any()).AnyTimes().Return(&sqs.DeleteMessageBatchOutput{}, nil)
m.EXPECT().ChangeMessageVisibilityBatch(gomock.Any()).AnyTimes()
s := &SQSService{Svc: m, Logger: NoopLogger}
q := NewConsumer(s, noop)
q.delayAfterReceiveError = time.Millisecond
q.DeleteMessageDrainTimeout = 25 * time.Millisecond
ngo := runtime.NumGoroutine()
// wait long enough to ensure ReceiveMessage ran at least twice
ctx, _ := context.WithTimeout(context.Background(), 5*time.Millisecond)
q.Run(ctx)
assert.InDelta(t, 2, atomic.LoadInt64(&receiveCount), 1, "ReceiveMessage should have been retried 1-3 times")
time.Sleep(time.Millisecond) // time for goroutines to end
assert.InDelta(t, ngo, runtime.NumGoroutine(), 2, "Should not leak goroutines")
}
func TestQueueConsumerRunDrainsOnShutdown(t *testing.T) {
ctl := gomock.NewController(t)
defer ctl.Finish()
received := &sqs.ReceiveMessageOutput{
Messages: []*sqs.Message{
&sqs.Message{MessageId: aws.String("i1"), ReceiptHandle: aws.String("r1"), Body: aws.String("b01")},
&sqs.Message{MessageId: aws.String("i2"), ReceiptHandle: aws.String("r2"), Body: aws.String("b02")},
&sqs.Message{MessageId: aws.String("i3"), ReceiptHandle: aws.String("r3"), Body: aws.String("b03")},
&sqs.Message{MessageId: aws.String("i4"), ReceiptHandle: aws.String("r4"), Body: aws.String("b04")},
&sqs.Message{MessageId: aws.String("i5"), ReceiptHandle: aws.String("r5"), Body: aws.String("b05")},
},
}
m := mock.NewMockSQSAPI(ctl)
h := &handler{}
q := NewConsumer(&SQSService{Svc: m, Logger: NoopLogger}, h.HandleMessage)
shutDown := make(chan struct{})
m.EXPECT().
ReceiveMessage(gomock.Any()).
Do(func(*sqs.ReceiveMessageInput) {
if shutDown != nil {
close(shutDown)
shutDown = nil
}
}).
Return(received, nil).
AnyTimes()
m.EXPECT().DeleteMessageBatch(gomock.Any()).AnyTimes().Return(&sqs.DeleteMessageBatchOutput{}, nil)
m.EXPECT().ChangeMessageVisibilityBatch(gomock.Any()).AnyTimes()
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
err := q.Run(ctx, WithShutdownChan(shutDown))
assert.NoError(t, err)
expected := []string{"b01", "b02", "b03", "b04", "b05"}
sort.Strings(h.messages)
assert.Equal(t, expected, h.messages)
}
func TestQueueConsumerRunHonorsContextOnShutdown(t *testing.T) {
ctl := gomock.NewController(t)
defer ctl.Finish()
handler := func(ctx context.Context, _ *sqs.Message) error {
assert.Error(t, ctx.Err())
return nil
}
m := mock.NewMockSQSAPI(ctl)
q := NewConsumer(&SQSService{Svc: m, Logger: NoopLogger}, handler)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
shutDown := make(chan struct{})
m.EXPECT().
ReceiveMessage(gomock.Any()).
Do(func(*sqs.ReceiveMessageInput) {
if shutDown != nil {
close(shutDown)
shutDown = nil
}
cancel()
}).
Return(
&sqs.ReceiveMessageOutput{
Messages: []*sqs.Message{
&sqs.Message{MessageId: aws.String("i1"), ReceiptHandle: aws.String("r1"), Body: aws.String("b01")},
&sqs.Message{MessageId: aws.String("i2"), ReceiptHandle: aws.String("r2"), Body: aws.String("b02")},
&sqs.Message{MessageId: aws.String("i3"), ReceiptHandle: aws.String("r3"), Body: aws.String("b03")},
},
},
nil).
AnyTimes()
m.EXPECT().DeleteMessageBatch(gomock.Any()).Return(&sqs.DeleteMessageBatchOutput{}, nil).AnyTimes()
m.EXPECT().ChangeMessageVisibilityBatch(gomock.Any()).AnyTimes()
err := q.Run(ctx, WithShutdownChan(shutDown))
assert.Equal(t, context.Canceled, err)
}
func TestQueueConsumerRunReturnsErrorAfterShutdown(t *testing.T) {
ctl := gomock.NewController(t)
defer ctl.Finish()
handler := func(context.Context, *sqs.Message) error { return nil }
m := mock.NewMockSQSAPI(ctl)
q := NewConsumer(&SQSService{Svc: m, Logger: NoopLogger}, handler)
shutDown := make(chan struct{})
close(shutDown)
err := q.Run(context.Background(), WithShutdownChan(shutDown))
assert.Equal(t, ErrShutdownChannelClosed, err)
}
func noop(ctx context.Context, msg *sqs.Message) error {
return nil
}
type handler struct {
lock sync.Mutex
messages []string
}
func (h *handler) HandleMessage(ctx context.Context, msg *sqs.Message) error {
if ctx.Err() != nil {
return ctx.Err()
}
h.lock.Lock()
defer h.lock.Unlock()
h.messages = append(h.messages, *msg.Body)
return nil
}