-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprocessor_test.go
More file actions
292 lines (261 loc) · 6.92 KB
/
processor_test.go
File metadata and controls
292 lines (261 loc) · 6.92 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
package sqsprocessor_test
import (
"context"
"encoding/json"
"errors"
"fmt"
"math/rand"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/sqs"
"github.com/aws/aws-sdk-go-v2/service/sqs/types"
sqsprocessor "github.com/barrett370/sqs-processor"
"github.com/stretchr/testify/mock"
"github.com/stretchr/testify/require"
)
const (
methodReceive = "receive"
methodDelete = "delete"
methodChangeVisibility = "change_visibility"
)
type mockMessage struct {
ID string
}
type mockSQSClient struct {
sync.Mutex
called map[string]int
incoming chan types.Message
inflight []types.Message
cfg sqs.ReceiveMessageInput
}
func (m *mockSQSClient) incr(method string) {
m.Lock()
m.called[method]++
m.Unlock()
}
func (m *mockSQSClient) deleteInflight(handle string) (found bool) {
m.Lock()
defer m.Unlock()
var n int
for _, msg := range m.inflight {
if handle != *msg.ReceiptHandle {
m.inflight[n] = msg
n++
} else {
found = true
}
}
m.inflight = m.inflight[:n]
return
}
func (m *mockSQSClient) ReceiveMessage(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) {
m.incr(methodReceive)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
var messages []types.Message
out:
for {
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(time.Duration(params.WaitTimeSeconds) * time.Second):
break out
case msg := <-m.incoming:
println("got message")
messages = append(messages, msg)
m.Lock()
m.inflight = append(m.inflight, msg)
go func() {
<-time.After(time.Duration(m.cfg.VisibilityTimeout) * time.Second)
found := m.deleteInflight(*msg.ReceiptHandle)
if found {
println("republishing message")
m.incoming <- msg
}
}()
m.Unlock()
}
}
ret := &sqs.ReceiveMessageOutput{
Messages: messages,
}
return ret, nil
}
func (m *mockSQSClient) DeleteMessage(ctx context.Context, params *sqs.DeleteMessageInput, optFns ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) {
m.incr(methodDelete)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
fmt.Printf("got message to delete %v, %v\n", params, m.inflight)
found := m.deleteInflight(*params.ReceiptHandle)
fmt.Printf("deleted message %v\n", m.inflight)
var err error
if !found {
err = errors.New("message not found")
}
return nil, err
}
func (m *mockSQSClient) ChangeMessageVisibility(ctx context.Context, params *sqs.ChangeMessageVisibilityInput, optFns ...func(*sqs.Options)) (*sqs.ChangeMessageVisibilityOutput, error) {
fmt.Printf("changing visibility of %s to %d", *params.ReceiptHandle, params.VisibilityTimeout)
m.incr(methodChangeVisibility)
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, nil
}
type results struct {
sync.Mutex
messages []mockMessage
}
var res *results
type mockService struct {
mock.Mock
}
func (m *mockService) mockWorkFunc(ctx context.Context, msg types.Message) sqsprocessor.ProcessResult {
var wi mockMessage
err := json.Unmarshal([]byte(*msg.Body), &wi)
if err != nil {
return sqsprocessor.ProcessResultNack
}
args := m.Called(wi)
fmt.Printf("got work to process %+v\n", wi)
res.Lock()
defer res.Unlock()
res.messages = append(res.messages, wi)
return args.Get(0).(sqsprocessor.ProcessResult)
}
func TestProcessor(t *testing.T) {
msvc := &mockService{}
res = &results{}
messages := make(chan types.Message, 100)
c := &mockSQSClient{
called: map[string]int{},
incoming: messages,
cfg: sqs.ReceiveMessageInput{VisibilityTimeout: 2},
}
config := sqsprocessor.ProcessorConfig{
Receive: sqs.ReceiveMessageInput{
WaitTimeSeconds: 1,
MaxNumberOfMessages: 1,
VisibilityTimeout: 2,
},
NumWorkers: 2,
Backoff: time.Millisecond * 100,
}
p := sqsprocessor.New(c, config)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
cleanup := func() {
cancel()
<-done
}
go func() {
p.Process(ctx, msvc.mockWorkFunc)
close(done)
}()
msg1 := mockMessage{ID: "333"}
msgBodyBytes, err := json.Marshal(msg1)
require.NoError(t, err)
msgBody := string(msgBodyBytes)
msvc.On("mockWorkFunc", msg1).Return(sqsprocessor.ProcessResultAck)
messages <- types.Message{
ReceiptHandle: aws.String("1234"),
Body: &msgBody,
}
msg2 := mockMessage{ID: "444"}
msg2BodyBytes, err := json.Marshal(msg2)
require.NoError(t, err)
msg2Body := string(msg2BodyBytes)
msvc.On("mockWorkFunc", msg2).Return(sqsprocessor.ProcessResultNack)
messages <- types.Message{
ReceiptHandle: aws.String("1235"),
Body: &msg2Body,
}
time.Sleep(time.Millisecond * 1500)
cleanup()
// res.Lock()
// require.Len(t, res.messages, 2)
// res.Unlock()
require.Equal(t, 2, c.called[methodReceive])
require.Equal(t, 1, c.called[methodDelete])
require.Equal(t, 1, c.called[methodChangeVisibility])
}
type benchSQSClient struct {
consumed *atomic.Int64
}
var (
benchBody = "bench"
benchHandle = "123"
)
func (m *benchSQSClient) ReceiveMessage(ctx context.Context, params *sqs.ReceiveMessageInput, optFns ...func(*sqs.Options)) (*sqs.ReceiveMessageOutput, error) {
var messages []types.Message
for i := 0; i < int(params.MaxNumberOfMessages); i++ {
messages = append(messages, types.Message{Body: &benchBody, ReceiptHandle: &benchHandle})
}
ret := &sqs.ReceiveMessageOutput{
Messages: messages[:params.MaxNumberOfMessages],
}
return ret, nil
}
func (m *benchSQSClient) DeleteMessage(ctx context.Context, params *sqs.DeleteMessageInput, optFns ...func(*sqs.Options)) (*sqs.DeleteMessageOutput, error) {
_ = m.consumed.Add(1)
return nil, nil
}
func (m *benchSQSClient) ChangeMessageVisibility(ctx context.Context, params *sqs.ChangeMessageVisibilityInput, optFns ...func(*sqs.Options)) (*sqs.ChangeMessageVisibilityOutput, error) {
return nil, nil
}
func benchWorkFunc(ctx context.Context, msg types.Message) sqsprocessor.ProcessResult {
select {
case <-ctx.Done():
return sqsprocessor.ProcessResultNack
case <-time.After(time.Duration(rand.Intn(100)) * time.Millisecond):
}
return sqsprocessor.ProcessResultAck
}
func TestProcessorThroughput(t *testing.T) {
c := &benchSQSClient{
consumed: &atomic.Int64{},
}
testcases := []struct {
name string
config sqsprocessor.ProcessorConfig
}{
{
name: "foo",
config: sqsprocessor.ProcessorConfig{
Receive: sqs.ReceiveMessageInput{
MaxNumberOfMessages: 10,
WaitTimeSeconds: 1,
VisibilityTimeout: 2,
},
NumWorkers: 100,
},
},
}
for _, tt := range testcases {
t.Run(tt.name, func(t *testing.T) {
p := sqsprocessor.New(c, tt.config)
ctx, cancel := context.WithCancel(context.Background())
done := make(chan struct{})
go func() {
p.Process(ctx, benchWorkFunc)
close(done)
}()
time.Sleep(time.Second * 1)
cancel()
<-done
fmt.Printf("processed %d messages\n", c.consumed.Load())
c.consumed.Store(0)
})
}
}