forked from st3v/go-plugins
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sqs.go
347 lines (294 loc) · 7.75 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
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
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
package sqs
import (
"context"
"errors"
"fmt"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/micro/go-log"
"github.com/micro/go-micro/broker"
"github.com/micro/go-micro/cmd"
)
const (
defaultMaxMessages = 1
defaultVisibilityTimeout = 3
defaultWaitSeconds = 10
)
// Amazon SQS Broker
type sqsBroker struct {
svc *sqs.SQS
options broker.Options
}
// A subscriber (poller) to an SQS queue
type subscriber struct {
options broker.SubscribeOptions
queueName string
svc *sqs.SQS
URL string
exit chan bool
}
// A wrapper around a message published on an SQS queue and delivered via subscriber
type publication struct {
sMessage *sqs.Message
svc *sqs.SQS
m *broker.Message
URL string
queueName string
}
func init() {
cmd.DefaultBrokers["sqs"] = NewBroker
}
// run is designed to run as a goroutine and poll SQS for new messages. Note that it's possible to receive
// more than one message from a single poll depending on the options configured for the plugin
func (s *subscriber) run(hdlr broker.Handler) {
log.Log(fmt.Sprintf("SQS subscription started. Queue:%s, URL: %s", s.queueName, s.URL))
for {
select {
case <-s.exit:
return
default:
result, err := s.svc.ReceiveMessage(&sqs.ReceiveMessageInput{
QueueUrl: &s.URL,
MaxNumberOfMessages: s.getMaxMessages(),
VisibilityTimeout: s.getVisibilityTimeout(),
WaitTimeSeconds: s.getWaitSeconds(),
AttributeNames: aws.StringSlice([]string{
"SentTimestamp", // TODO: not currently exposing this to plugin users
}),
MessageAttributeNames: aws.StringSlice([]string{
"All",
}),
})
if err != nil {
time.Sleep(time.Second)
log.Log(fmt.Sprintf("Error receiving SQS message: %s", err.Error()))
continue
}
if len(result.Messages) == 0 {
time.Sleep(time.Second)
continue
}
for _, sm := range result.Messages {
s.handleMessage(sm, hdlr)
}
}
}
}
func (s *subscriber) getMaxMessages() *int64 {
if v := s.options.Context.Value(maxMessagesKey{}); v != nil {
v2 := v.(int64)
return aws.Int64(v2)
}
return aws.Int64(defaultMaxMessages)
}
func (s *subscriber) getVisibilityTimeout() *int64 {
if v := s.options.Context.Value(visiblityTimeoutKey{}); v != nil {
v2 := v.(int64)
return aws.Int64(v2)
}
return aws.Int64(defaultVisibilityTimeout)
}
func (s *subscriber) getWaitSeconds() *int64 {
if v := s.options.Context.Value(waitTimeSecondsKey{}); v != nil {
v2 := v.(int64)
return aws.Int64(v2)
}
return aws.Int64(defaultWaitSeconds)
}
func (s *subscriber) handleMessage(msg *sqs.Message, hdlr broker.Handler) {
log.Log(fmt.Sprintf("Received SQS message: %d bytes", len(*msg.Body)))
m := &broker.Message{
Header: buildMessageHeader(msg.MessageAttributes),
Body: []byte(*msg.Body),
}
p := &publication{
sMessage: msg,
m: m,
URL: s.URL,
queueName: s.queueName,
svc: s.svc,
}
if err := hdlr(p); err != nil {
fmt.Println(err)
}
if s.options.AutoAck {
err := p.Ack()
if err != nil {
log.Log(fmt.Sprintf("Failed auto-acknowledge of message: %s", err.Error()))
}
}
}
func (s *subscriber) Options() broker.SubscribeOptions {
return s.options
}
func (s *subscriber) Topic() string {
return s.queueName
}
func (s *subscriber) Unsubscribe() error {
select {
case <-s.exit:
return nil
default:
close(s.exit)
return nil
}
}
func (p *publication) Ack() error {
_, err := p.svc.DeleteMessage(&sqs.DeleteMessageInput{
QueueUrl: &p.URL,
ReceiptHandle: p.sMessage.ReceiptHandle,
})
return err
}
func (p *publication) Topic() string {
return p.queueName
}
func (p *publication) Message() *broker.Message {
return p.m
}
func (b *sqsBroker) Options() broker.Options {
return b.options
}
func (b *sqsBroker) Address() string {
return ""
}
func (b *sqsBroker) Connect() error {
if svc := b.getSQSClient(); svc != nil {
b.svc = svc
return nil
}
sess := session.Must(session.NewSessionWithOptions(session.Options{
SharedConfigState: session.SharedConfigEnable,
}))
svc := sqs.New(sess)
b.svc = svc
return nil
}
// Disconnect does nothing as there's no live connection to terminate
func (b *sqsBroker) Disconnect() error {
return nil
}
// Init initializes a broker and configures an AWS session and SQS struct
func (b *sqsBroker) Init(opts ...broker.Option) error {
for _, o := range opts {
o(&b.options)
}
return nil
}
// Publish publishes a message via SQS
func (b *sqsBroker) Publish(queueName string, msg *broker.Message, opts ...broker.PublishOption) error {
queueURL, err := b.urlFromQueueName(queueName)
if err != nil {
return err
}
input := &sqs.SendMessageInput{
MessageBody: aws.String(string(msg.Body[:])),
QueueUrl: &queueURL,
}
input.MessageAttributes = copyMessageHeader(msg)
input.MessageDeduplicationId = b.generateDedupID(msg)
input.MessageGroupId = b.generateGroupID(msg)
log.Log(fmt.Sprintf("Publishing SQS message, %d bytes", len(msg.Body)))
_, err = b.svc.SendMessage(input)
if err != nil {
return err
}
// Broker interfaces don't let us do anything with message ID or sequence number
return nil
}
// Subscribe subscribes to an SQS queue, starting a goroutine to poll for messages
func (b *sqsBroker) Subscribe(queueName string, h broker.Handler, opts ...broker.SubscribeOption) (broker.Subscriber, error) {
queueURL, err := b.urlFromQueueName(queueName)
if err != nil {
return nil, err
}
options := broker.SubscribeOptions{
AutoAck: true,
Queue: queueName,
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
subscriber := &subscriber{
options: options,
URL: queueURL,
queueName: queueName,
svc: b.svc,
exit: make(chan bool),
}
go subscriber.run(h)
return subscriber, nil
}
func (b *sqsBroker) urlFromQueueName(queueName string) (string, error) {
resultURL, err := b.svc.GetQueueUrl(&sqs.GetQueueUrlInput{
QueueName: aws.String(queueName),
})
if err != nil {
if aerr, ok := err.(awserr.Error); ok && aerr.Code() == sqs.ErrCodeQueueDoesNotExist {
return "", errors.New(fmt.Sprintf("Unable to find queue %s: %s", queueName, err.Error()))
}
return "", errors.New(fmt.Sprintf("Unable to determine URL for queue %s: %s", queueName, err.Error()))
}
return *resultURL.QueueUrl, nil
}
// String returns the name of the broker plugin
func (b *sqsBroker) String() string {
return "sqs"
}
func copyMessageHeader(m *broker.Message) (attribs map[string]*sqs.MessageAttributeValue) {
attribs = make(map[string]*sqs.MessageAttributeValue)
for k, v := range m.Header {
attribs[k] = &sqs.MessageAttributeValue{
DataType: aws.String("String"),
StringValue: aws.String(v),
}
}
return attribs
}
func buildMessageHeader(attribs map[string]*sqs.MessageAttributeValue) map[string]string {
res := make(map[string]string)
for k, v := range attribs {
res[k] = *v.StringValue
}
return res
}
func (b *sqsBroker) getSQSClient() *sqs.SQS {
raw := b.options.Context.Value(sqsClientKey{})
if raw != nil {
s := raw.(*sqs.SQS)
return s
}
return nil
}
func (b *sqsBroker) generateGroupID(m *broker.Message) *string {
raw := b.options.Context.Value(groupIdFunctionKey{})
if raw != nil {
s := raw.(StringFromMessageFunc)(m)
return &s
}
return nil
}
func (b *sqsBroker) generateDedupID(m *broker.Message) *string {
raw := b.options.Context.Value(dedupFunctionKey{})
if raw != nil {
s := raw.(StringFromMessageFunc)(m)
return &s
}
return nil
}
// NewBroker creates a new broker with options
func NewBroker(opts ...broker.Option) broker.Broker {
options := broker.Options{
Context: context.Background(),
}
for _, o := range opts {
o(&options)
}
return &sqsBroker{
options: options,
}
}