forked from matryer/vice
/
sqs.go
280 lines (238 loc) · 6.21 KB
/
sqs.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
// Package sqs provides a Vice implementation for Amazon Simple Queue Service.
package sqs
import (
"fmt"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
"github.com/matryer/vice"
)
// Transport is a vice.Transport for Amazon's SQS
type Transport struct {
batchSize int
batchInterval time.Duration
wg *sync.WaitGroup
sm sync.Mutex
sendChans map[string]chan []byte
rm sync.Mutex
receiveChans map[string]chan []byte
errChan chan error
stopchan chan struct{}
stopPubChan chan struct{}
stopSubChan chan struct{}
NewService func(region string) (sqsiface.SQSAPI, error)
}
// New returns a new transport
// Credentials are automatically sourced using the AWS SDK credential chain,
// for more info see the AWS SDK docs:
// https://godoc.org/github.com/aws/aws-sdk-go#hdr-Configuring_Credentials
func New(batchSize int, batchInterval time.Duration) *Transport {
if batchSize > 10 {
batchSize = 10
}
if batchInterval == 0 {
batchInterval = 200 * time.Millisecond
}
return &Transport{
wg: &sync.WaitGroup{},
batchSize: batchSize,
batchInterval: batchInterval,
sendChans: make(map[string]chan []byte),
receiveChans: make(map[string]chan []byte),
errChan: make(chan error, 10),
stopchan: make(chan struct{}),
stopPubChan: make(chan struct{}),
stopSubChan: make(chan struct{}),
NewService: func(region string) (sqsiface.SQSAPI, error) {
awsConfig := aws.NewConfig().WithRegion(region)
s, err := session.NewSession(awsConfig)
if err != nil {
return nil, err
}
return sqs.New(s), nil
},
}
}
// Receive gets a channel on which to receive messages
// with the specified name. The name is the queue's url
func (t *Transport) Receive(name string) <-chan []byte {
t.rm.Lock()
defer t.rm.Unlock()
ch, ok := t.receiveChans[name]
if ok {
return ch
}
ch, err := t.makeSubscriber(name)
if err != nil {
t.errChan <- vice.Err{Name: name, Err: err}
return make(chan []byte)
}
t.receiveChans[name] = ch
return ch
}
// RegionFromURL parses an sqs url and returns the aws region
func RegionFromURL(url string) string {
pieces := strings.Split(url, ".")
if len(pieces) > 2 {
return pieces[1]
}
return ""
}
func (t *Transport) makeSubscriber(name string) (chan []byte, error) {
region := RegionFromURL(name)
svc, err := t.NewService(region)
if err != nil {
return nil, err
}
ch := make(chan []byte, 1024)
params := &sqs.ReceiveMessageInput{
QueueUrl: aws.String(name),
MaxNumberOfMessages: aws.Int64(1),
VisibilityTimeout: aws.Int64(1),
WaitTimeSeconds: aws.Int64(1),
}
go func() {
for {
select {
case <-t.stopSubChan:
return
default:
resp, err := svc.ReceiveMessage(params)
if err != nil {
t.errChan <- vice.Err{Name: name, Err: err}
continue
}
if len(resp.Messages) > 0 {
for _, m := range resp.Messages {
if m.ReceiptHandle != nil {
delParams := &sqs.DeleteMessageInput{
QueueUrl: aws.String(name),
ReceiptHandle: aws.String(*m.ReceiptHandle),
}
_, err := svc.DeleteMessage(delParams)
if err != nil {
t.errChan <- vice.Err{Name: name, Err: err}
continue
}
}
ch <- []byte(*m.Body)
}
}
}
}
}()
return ch, nil
}
// Send gets a channel on which messages with the
// specified name may be sent. The name is the queue's
// URL
func (t *Transport) Send(name string) chan<- []byte {
t.sm.Lock()
defer t.sm.Unlock()
ch, ok := t.sendChans[name]
if ok {
return ch
}
ch, err := t.makePublisher(name)
if err != nil {
t.errChan <- vice.Err{Name: name, Err: err}
return make(chan []byte)
}
t.sendChans[name] = ch
return ch
}
func (t *Transport) makePublisher(name string) (chan []byte, error) {
region := RegionFromURL(name)
svc, err := t.NewService(region)
if err != nil {
return nil, err
}
ch := make(chan []byte, 1024)
t.wg.Add(1)
go func() {
defer t.wg.Done()
var accum []*sqs.SendMessageBatchRequestEntry
defer func() {
if t.batchSize == 0 && len(accum) == 0 {
return
}
t.sendBatch(svc, name, accum)
accum = make([]*sqs.SendMessageBatchRequestEntry, 0, t.batchSize)
}()
for {
select {
case <-t.stopPubChan:
if len(ch) != 0 {
continue
}
return
case msg := <-ch:
if t.batchSize == 0 {
params := &sqs.SendMessageInput{
MessageBody: aws.String(string(msg)),
QueueUrl: aws.String(name),
}
_, err := svc.SendMessage(params)
if err != nil {
t.errChan <- vice.Err{Message: msg, Name: name, Err: err}
}
continue
}
id := fmt.Sprintf("%d", time.Now().UnixNano())
accum = append(accum, &sqs.SendMessageBatchRequestEntry{
MessageBody: aws.String(string(msg)),
Id: aws.String(id),
})
if len(accum) < t.batchSize {
continue
}
t.sendBatch(svc, name, accum)
accum = make([]*sqs.SendMessageBatchRequestEntry, 0, t.batchSize)
case <-time.After(t.batchInterval):
if len(accum) == 0 {
continue
}
t.sendBatch(svc, name, accum)
accum = make([]*sqs.SendMessageBatchRequestEntry, 0, t.batchSize)
}
}
}()
return ch, nil
}
func (t *Transport) sendBatch(svc sqsiface.SQSAPI, name string, entries []*sqs.SendMessageBatchRequestEntry) {
batchParams := &sqs.SendMessageBatchInput{
Entries: entries,
QueueUrl: aws.String(name),
}
resp, err := svc.SendMessageBatch(batchParams)
if err != nil {
t.errChan <- vice.Err{Name: name, Err: err}
return
}
for _, v := range resp.Failed {
err := fmt.Errorf("%s", *v.Message)
t.errChan <- vice.Err{Name: name, Err: err}
}
}
// ErrChan gets the channel on which errors are sent.
func (t *Transport) ErrChan() <-chan error {
return t.errChan
}
// Stop stops the transport.
// The channel returned from Done() will be closed
// when the transport has stopped.
func (t *Transport) Stop() {
close(t.stopSubChan)
close(t.stopPubChan)
t.wg.Wait()
close(t.stopchan)
}
// Done gets a channel which is closed when the
// transport has successfully stopped.
func (t *Transport) Done() chan struct{} {
return t.stopchan
}