/
awssnssqs.go
1315 lines (1233 loc) · 42.5 KB
/
awssnssqs.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
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2018 The Go Cloud Development Kit Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package awssnssqs provides two implementations of pubsub.Topic, one that
// sends messages to AWS SNS (Simple Notification Service), and one that sends
// messages to SQS (Simple Queuing Service). It also provides an implementation
// of pubsub.Subscription that receives messages from SQS.
//
// # URLs
//
// For pubsub.OpenTopic, awssnssqs registers for the scheme "awssns" for
// an SNS topic, and "awssqs" for an SQS topic. For pubsub.OpenSubscription,
// it registers for the scheme "awssqs".
//
// The default URL opener will use an AWS session with the default credentials
// and configuration; see https://docs.aws.amazon.com/sdk-for-go/api/aws/session/
// for more details.
// To customize the URL opener, or for more details on the URL format,
// see URLOpener.
// See https://gocloud.dev/concepts/urls/ for background information.
//
// # Message Delivery Semantics
//
// AWS SQS supports at-least-once semantics; applications must call Message.Ack
// after processing a message, or it will be redelivered.
// See https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery
// for more background.
//
// # Escaping
//
// Go CDK supports all UTF-8 strings; to make this work with services lacking
// full UTF-8 support, strings must be escaped (during writes) and unescaped
// (during reads). The following escapes are required for awssnssqs:
// - Metadata keys: Characters other than "a-zA-z0-9_-.", and additionally "."
// when it's at the start of the key or the previous character was ".",
// are escaped using "__0x<hex>__". These characters were determined by
// experimentation.
// - Metadata values: Escaped using URL encoding.
// - Message body: AWS SNS/SQS only supports UTF-8 strings. See the
// BodyBase64Encoding enum in TopicOptions for strategies on how to send
// non-UTF-8 message bodies. By default, non-UTF-8 message bodies are base64
// encoded.
//
// # As
//
// awssnssqs exposes the following types for As:
// - Topic: (V1) *sns.SNS for OpenSNSTopic, *sqs.SQS for OpenSQSTopic; (V2) *snsv2.Client for OpenSNSTopicV2, *sqsv2.Client for OpenSQSTopicV2
// - Subscription: (V1) *sqs.SQS; (V2) *sqsv2.Client
// - Message: (V1) *sqs.Message; (V2) sqstypesv2.Message
// - Message.BeforeSend: (V1) *sns.PublishInput for OpenSNSTopic, *sqs.SendMessageBatchRequestEntry or *sqs.SendMessageInput(deprecated) for OpenSQSTopic; (V2) *snsv2.PublishInput for OpenSNSTopicV2, sqstypesv2.SendMessageBatchRequestEntry for OpenSQSTopicV2
// - Message.AfterSend: (V1) *sns.PublishOutput for OpenSNSTopic, *sqs.SendMessageBatchResultEntry for OpenSQSTopic; (V2) *snsv2.PublishOutput for OpenSNSTopicV2, sqstypesv2.SendMessageBatchResultEntry for OpenSQSTopicV2
// - Error: (V1) awserr.Error, (V2) any error type returned by the service, notably smithy.APIError
package awssnssqs // import "gocloud.dev/pubsub/awssnssqs"
import (
"context"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/url"
"path"
"strconv"
"strings"
"sync"
"time"
"unicode/utf8"
snsv2 "github.com/aws/aws-sdk-go-v2/service/sns"
snstypesv2 "github.com/aws/aws-sdk-go-v2/service/sns/types"
sqsv2 "github.com/aws/aws-sdk-go-v2/service/sqs"
sqstypesv2 "github.com/aws/aws-sdk-go-v2/service/sqs/types"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/smithy-go"
"github.com/google/wire"
gcaws "gocloud.dev/aws"
"gocloud.dev/gcerrors"
"gocloud.dev/internal/escape"
"gocloud.dev/pubsub"
"gocloud.dev/pubsub/batcher"
"gocloud.dev/pubsub/driver"
)
const (
// base64EncodedKey is the Message Attribute key used to flag that the
// message body is base64 encoded.
base64EncodedKey = "base64encoded"
// How long ReceiveBatch should wait if no messages are available; controls
// the poll interval of requests to SQS.
noMessagesPollDuration = 250 * time.Millisecond
)
var sendBatcherOptsSNS = &batcher.Options{
MaxBatchSize: 1, // SNS SendBatch only supports one message at a time
MaxHandlers: 100, // max concurrency for sends
}
var sendBatcherOptsSQS = &batcher.Options{
MaxBatchSize: 10, // SQS SendBatch supports 10 messages at a time
MaxHandlers: 100, // max concurrency for sends
}
var recvBatcherOpts = &batcher.Options{
// SQS supports receiving at most 10 messages at a time:
// https://godoc.org/github.com/aws/aws-sdk-go/service/sqs#SQS.ReceiveMessage
MaxBatchSize: 10,
MaxHandlers: 100, // max concurrency for receives
}
var ackBatcherOpts = &batcher.Options{
// SQS supports deleting/updating at most 10 messages at a time:
// https://godoc.org/github.com/aws/aws-sdk-go/service/sqs#SQS.DeleteMessageBatch
// https://godoc.org/github.com/aws/aws-sdk-go/service/sqs#SQS.ChangeMessageVisibilityBatch
MaxBatchSize: 10,
MaxHandlers: 100, // max concurrency for acks
}
func init() {
lazy := new(lazySessionOpener)
pubsub.DefaultURLMux().RegisterTopic(SNSScheme, lazy)
pubsub.DefaultURLMux().RegisterTopic(SQSScheme, lazy)
pubsub.DefaultURLMux().RegisterSubscription(SQSScheme, lazy)
}
// Set holds Wire providers for this package.
var Set = wire.NewSet(
wire.Struct(new(URLOpener), "ConfigProvider"),
)
// lazySessionOpener obtains the AWS session from the environment on the first
// call to OpenXXXURL.
type lazySessionOpener struct {
init sync.Once
opener *URLOpener
err error
}
func (o *lazySessionOpener) defaultOpener(u *url.URL) (*URLOpener, error) {
if gcaws.UseV2(u.Query()) {
return &URLOpener{UseV2: true}, nil
}
o.init.Do(func() {
sess, err := gcaws.NewDefaultSession()
if err != nil {
o.err = err
return
}
o.opener = &URLOpener{
ConfigProvider: sess,
}
})
return o.opener, o.err
}
func (o *lazySessionOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
opener, err := o.defaultOpener(u)
if err != nil {
return nil, fmt.Errorf("open topic %v: failed to open default session: %v", u, err)
}
return opener.OpenTopicURL(ctx, u)
}
func (o *lazySessionOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
opener, err := o.defaultOpener(u)
if err != nil {
return nil, fmt.Errorf("open subscription %v: failed to open default session: %v", u, err)
}
return opener.OpenSubscriptionURL(ctx, u)
}
// SNSScheme is the URL scheme for pubsub.OpenTopic (for an SNS topic) that
// awssnssqs registers its URLOpeners under on pubsub.DefaultMux.
const SNSScheme = "awssns"
// SQSScheme is the URL scheme for pubsub.OpenTopic (for an SQS topic) and for
// pubsub.OpenSubscription that awssnssqs registers its URLOpeners under on
// pubsub.DefaultMux.
const SQSScheme = "awssqs"
// URLOpener opens AWS SNS/SQS URLs like "awssns:///sns-topic-arn" for
// SNS topics or "awssqs://sqs-queue-url" for SQS topics and subscriptions.
//
// For SNS topics, the URL's host+path is used as the topic Amazon Resource Name
// (ARN). Since ARNs have ":" in them, and ":" precedes a port in URL
// hostnames, leave the host blank and put the ARN in the path
// (e.g., "awssns:///arn:aws:service:region:accountid:resourceType/resourcePath").
//
// For SQS topics and subscriptions, the URL's host+path is prefixed with
// "https://" to create the queue URL.
//
// Use "awssdk=v1" to force using AWS SDK v1, "awssdk=v2" to force using AWS SDK v2,
// or anything else to accept the default.
//
// For V1, see gocloud.dev/aws/ConfigFromURLParams for supported query parameters
// for overriding the aws.Session from the URL.
// For V2, see gocloud.dev/aws/V2ConfigFromURLParams.
//
// In addition, the following query parameters are supported:
//
// - raw (for "awssqs" Subscriptions only): sets SubscriberOptions.Raw. The
// value must be parseable by `strconv.ParseBool`.
// - waittime: sets SubscriberOptions.WaitTime, in time.ParseDuration formats.
//
// See gocloud.dev/aws/ConfigFromURLParams for other query parameters
// that affect the default AWS session.
type URLOpener struct {
// UseV2 indicates whether the AWS SDK V2 should be used.
UseV2 bool
// ConfigProvider configures the connection to AWS.
// It must be set to a non-nil value if UseV2 is false.
ConfigProvider client.ConfigProvider
// TopicOptions specifies the options to pass to OpenTopic.
TopicOptions TopicOptions
// SubscriptionOptions specifies the options to pass to OpenSubscription.
SubscriptionOptions SubscriptionOptions
}
// OpenTopicURL opens a pubsub.Topic based on u.
func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
// Trim leading "/" if host is empty, so that
// awssns:///arn:aws:service:region:accountid:resourceType/resourcePath
// gives "arn:..." instead of "/arn:...".
topicARN := strings.TrimPrefix(path.Join(u.Host, u.Path), "/")
qURL := "https://" + path.Join(u.Host, u.Path)
if o.UseV2 {
cfg, err := gcaws.V2ConfigFromURLParams(ctx, u.Query())
if err != nil {
return nil, fmt.Errorf("open topic %v: %v", u, err)
}
switch u.Scheme {
case SNSScheme:
return OpenSNSTopicV2(ctx, snsv2.NewFromConfig(cfg), topicARN, &o.TopicOptions), nil
case SQSScheme:
return OpenSQSTopicV2(ctx, sqsv2.NewFromConfig(cfg), qURL, &o.TopicOptions), nil
default:
return nil, fmt.Errorf("open topic %v: unsupported scheme", u)
}
}
configProvider := &gcaws.ConfigOverrider{
Base: o.ConfigProvider,
}
overrideCfg, err := gcaws.ConfigFromURLParams(u.Query())
if err != nil {
return nil, fmt.Errorf("open topic %v: %v", u, err)
}
configProvider.Configs = append(configProvider.Configs, overrideCfg)
switch u.Scheme {
case SNSScheme:
return OpenSNSTopic(ctx, configProvider, topicARN, &o.TopicOptions), nil
case SQSScheme:
return OpenSQSTopic(ctx, configProvider, qURL, &o.TopicOptions), nil
default:
return nil, fmt.Errorf("open topic %v: unsupported scheme", u)
}
}
// OpenSubscriptionURL opens a pubsub.Subscription based on u.
func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
// Clone the options since we might override Raw.
opts := o.SubscriptionOptions
q := u.Query()
if rawStr := q.Get("raw"); rawStr != "" {
var err error
opts.Raw, err = strconv.ParseBool(rawStr)
if err != nil {
return nil, fmt.Errorf("invalid value %q for raw: %v", rawStr, err)
}
q.Del("raw")
}
if waitTimeStr := q.Get("waittime"); waitTimeStr != "" {
var err error
opts.WaitTime, err = time.ParseDuration(waitTimeStr)
if err != nil {
return nil, fmt.Errorf("invalid value %q for waittime: %v", waitTimeStr, err)
}
q.Del("waittime")
}
qURL := "https://" + path.Join(u.Host, u.Path)
if o.UseV2 {
cfg, err := gcaws.V2ConfigFromURLParams(ctx, q)
if err != nil {
return nil, fmt.Errorf("open subscription %v: %v", u, err)
}
return OpenSubscriptionV2(ctx, sqsv2.NewFromConfig(cfg), qURL, &opts), nil
}
overrideCfg, err := gcaws.ConfigFromURLParams(q)
if err != nil {
return nil, fmt.Errorf("open subscription %v: %v", u, err)
}
configProvider := &gcaws.ConfigOverrider{
Base: o.ConfigProvider,
}
configProvider.Configs = append(configProvider.Configs, overrideCfg)
return OpenSubscription(ctx, configProvider, qURL, &opts), nil
}
type snsTopic struct {
useV2 bool
client *sns.SNS
clientV2 *snsv2.Client
arn string
opts *TopicOptions
}
// BodyBase64Encoding is an enum of strategies for when to base64 message
// bodies.
type BodyBase64Encoding int
const (
// NonUTF8Only means that message bodies that are valid UTF-8 encodings are
// sent as-is. Invalid UTF-8 message bodies are base64 encoded, and a
// MessageAttribute with key "base64encoded" is added to the message.
// When receiving messages, the "base64encoded" attribute is used to determine
// whether to base64 decode, and is then filtered out.
NonUTF8Only BodyBase64Encoding = 0
// Always means that all message bodies are base64 encoded.
// A MessageAttribute with key "base64encoded" is added to the message.
// When receiving messages, the "base64encoded" attribute is used to determine
// whether to base64 decode, and is then filtered out.
Always BodyBase64Encoding = 1
// Never means that message bodies are never base64 encoded. Non-UTF-8
// bytes in message bodies may be modified by SNS/SQS.
Never BodyBase64Encoding = 2
)
func (e BodyBase64Encoding) wantEncode(b []byte) bool {
switch e {
case Always:
return true
case Never:
return false
case NonUTF8Only:
return !utf8.Valid(b)
}
panic("unreachable")
}
// TopicOptions contains configuration options for topics.
type TopicOptions struct {
// BodyBase64Encoding determines when message bodies are base64 encoded.
// The default is NonUTF8Only.
BodyBase64Encoding BodyBase64Encoding
// BatcherOptions adds constraints to the default batching done for sends.
BatcherOptions batcher.Options
}
// OpenTopic is a shortcut for OpenSNSTopic, provided for backwards compatibility.
func OpenTopic(ctx context.Context, sess client.ConfigProvider, topicARN string, opts *TopicOptions) *pubsub.Topic {
return OpenSNSTopic(ctx, sess, topicARN, opts)
}
// OpenSNSTopic opens a topic that sends to the SNS topic with the given Amazon
// Resource Name (ARN).
func OpenSNSTopic(ctx context.Context, sess client.ConfigProvider, topicARN string, opts *TopicOptions) *pubsub.Topic {
bo := sendBatcherOptsSNS.NewMergedOptions(&opts.BatcherOptions)
return pubsub.NewTopic(openSNSTopic(ctx, sns.New(sess), topicARN, opts), bo)
}
// OpenSNSTopicV2 opens a topic that sends to the SNS topic with the given Amazon
// Resource Name (ARN), using AWS SDK V2.
func OpenSNSTopicV2(ctx context.Context, client *snsv2.Client, topicARN string, opts *TopicOptions) *pubsub.Topic {
bo := sendBatcherOptsSNS.NewMergedOptions(&opts.BatcherOptions)
return pubsub.NewTopic(openSNSTopicV2(ctx, client, topicARN, opts), bo)
}
// openSNSTopic returns the driver for OpenSNSTopic. This function exists so the test
// harness can get the driver interface implementation if it needs to.
func openSNSTopic(ctx context.Context, client *sns.SNS, topicARN string, opts *TopicOptions) driver.Topic {
if opts == nil {
opts = &TopicOptions{}
}
return &snsTopic{
useV2: false,
client: client,
arn: topicARN,
opts: opts,
}
}
// openSNSTopicV2 returns the driver for OpenSNSTopic. This function exists so the test
// harness can get the driver interface implementation if it needs to.
func openSNSTopicV2(ctx context.Context, client *snsv2.Client, topicARN string, opts *TopicOptions) driver.Topic {
if opts == nil {
opts = &TopicOptions{}
}
return &snsTopic{
useV2: true,
clientV2: client,
arn: topicARN,
opts: opts,
}
}
var stringDataType = aws.String("String")
// encodeMetadata encodes the keys and values of md as needed.
func encodeMetadata(md map[string]string) map[string]string {
retval := map[string]string{}
for k, v := range md {
// See the package comments for more details on escaping of metadata
// keys & values.
k = escape.HexEscape(k, func(runes []rune, i int) bool {
c := runes[i]
switch {
case escape.IsASCIIAlphanumeric(c):
return false
case c == '_' || c == '-':
return false
case c == '.' && i != 0 && runes[i-1] != '.':
return false
}
return true
})
retval[k] = escape.URLEscape(v)
}
return retval
}
// maybeEncodeBody decides whether body should base64-encoded based on opt, and
// returns the (possibly encoded) body as a string, along with a boolean
// indicating whether encoding occurred.
func maybeEncodeBody(body []byte, opt BodyBase64Encoding) (string, bool) {
if opt.wantEncode(body) {
return base64.StdEncoding.EncodeToString(body), true
}
return string(body), false
}
// SendBatch implements driver.Topic.SendBatch.
func (t *snsTopic) SendBatch(ctx context.Context, dms []*driver.Message) error {
if len(dms) != 1 {
panic("snsTopic.SendBatch should only get one message at a time")
}
dm := dms[0]
if t.useV2 {
attrs := map[string]snstypesv2.MessageAttributeValue{}
for k, v := range encodeMetadata(dm.Metadata) {
attrs[k] = snstypesv2.MessageAttributeValue{
DataType: stringDataType,
StringValue: aws.String(v),
}
}
body, didEncode := maybeEncodeBody(dm.Body, t.opts.BodyBase64Encoding)
if didEncode {
attrs[base64EncodedKey] = snstypesv2.MessageAttributeValue{
DataType: stringDataType,
StringValue: aws.String("true"),
}
}
if len(attrs) == 0 {
attrs = nil
}
input := &snsv2.PublishInput{
Message: aws.String(body),
MessageAttributes: attrs,
TopicArn: &t.arn,
}
if dm.BeforeSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(**snsv2.PublishInput); ok {
*p = input
return true
}
return false
}
if err := dm.BeforeSend(asFunc); err != nil {
return err
}
}
po, err := t.clientV2.Publish(ctx, input)
if err != nil {
return err
}
if dm.AfterSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(**snsv2.PublishOutput); ok {
*p = po
return true
}
return false
}
if err := dm.AfterSend(asFunc); err != nil {
return err
}
}
return nil
}
attrs := map[string]*sns.MessageAttributeValue{}
for k, v := range encodeMetadata(dm.Metadata) {
attrs[k] = &sns.MessageAttributeValue{
DataType: stringDataType,
StringValue: aws.String(v),
}
}
body, didEncode := maybeEncodeBody(dm.Body, t.opts.BodyBase64Encoding)
if didEncode {
attrs[base64EncodedKey] = &sns.MessageAttributeValue{
DataType: stringDataType,
StringValue: aws.String("true"),
}
}
if len(attrs) == 0 {
attrs = nil
}
input := &sns.PublishInput{
Message: aws.String(body),
MessageAttributes: attrs,
TopicArn: &t.arn,
}
if dm.BeforeSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(**sns.PublishInput); ok {
*p = input
return true
}
return false
}
if err := dm.BeforeSend(asFunc); err != nil {
return err
}
}
po, err := t.client.PublishWithContext(ctx, input)
if err != nil {
return err
}
if dm.AfterSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(**sns.PublishOutput); ok {
*p = po
return true
}
return false
}
if err := dm.AfterSend(asFunc); err != nil {
return err
}
}
return nil
}
// IsRetryable implements driver.Topic.IsRetryable.
func (t *snsTopic) IsRetryable(error) bool {
// The client handles retries.
return false
}
// As implements driver.Topic.As.
func (t *snsTopic) As(i interface{}) bool {
if t.useV2 {
c, ok := i.(**snsv2.Client)
if !ok {
return false
}
*c = t.clientV2
return true
}
c, ok := i.(**sns.SNS)
if !ok {
return false
}
*c = t.client
return true
}
// ErrorAs implements driver.Topic.ErrorAs.
func (t *snsTopic) ErrorAs(err error, i interface{}) bool {
return errorAs(err, t.useV2, i)
}
// ErrorCode implements driver.Topic.ErrorCode.
func (t *snsTopic) ErrorCode(err error) gcerrors.ErrorCode {
return errorCode(err)
}
// Close implements driver.Topic.Close.
func (*snsTopic) Close() error { return nil }
type sqsTopic struct {
useV2 bool
client *sqs.SQS
clientV2 *sqsv2.Client
qURL string
opts *TopicOptions
}
// OpenSQSTopic opens a topic that sends to the SQS topic with the given SQS
// queue URL.
func OpenSQSTopic(ctx context.Context, sess client.ConfigProvider, qURL string, opts *TopicOptions) *pubsub.Topic {
bo := sendBatcherOptsSQS.NewMergedOptions(&opts.BatcherOptions)
return pubsub.NewTopic(openSQSTopic(ctx, sqs.New(sess), qURL, opts), bo)
}
// OpenSQSTopicV2 opens a topic that sends to the SQS topic with the given SQS
// queue URL, using AWS SDK V2.
func OpenSQSTopicV2(ctx context.Context, client *sqsv2.Client, qURL string, opts *TopicOptions) *pubsub.Topic {
bo := sendBatcherOptsSQS.NewMergedOptions(&opts.BatcherOptions)
return pubsub.NewTopic(openSQSTopicV2(ctx, client, qURL, opts), bo)
}
// openSQSTopic returns the driver for OpenSQSTopic. This function exists so the test
// harness can get the driver interface implementation if it needs to.
func openSQSTopic(ctx context.Context, client *sqs.SQS, qURL string, opts *TopicOptions) driver.Topic {
if opts == nil {
opts = &TopicOptions{}
}
return &sqsTopic{
useV2: false,
client: client,
qURL: qURL,
opts: opts,
}
}
// openSQSTopicV2 returns the driver for OpenSQSTopic. This function exists so the test
// harness can get the driver interface implementation if it needs to.
func openSQSTopicV2(ctx context.Context, client *sqsv2.Client, qURL string, opts *TopicOptions) driver.Topic {
if opts == nil {
opts = &TopicOptions{}
}
return &sqsTopic{
useV2: true,
clientV2: client,
qURL: qURL,
opts: opts,
}
}
// SendBatch implements driver.Topic.SendBatch.
func (t *sqsTopic) SendBatch(ctx context.Context, dms []*driver.Message) error {
if t.useV2 {
req := &sqsv2.SendMessageBatchInput{
QueueUrl: aws.String(t.qURL),
}
for _, dm := range dms {
attrs := map[string]sqstypesv2.MessageAttributeValue{}
for k, v := range encodeMetadata(dm.Metadata) {
attrs[k] = sqstypesv2.MessageAttributeValue{
DataType: stringDataType,
StringValue: aws.String(v),
}
}
body, didEncode := maybeEncodeBody(dm.Body, t.opts.BodyBase64Encoding)
if didEncode {
attrs[base64EncodedKey] = sqstypesv2.MessageAttributeValue{
DataType: stringDataType,
StringValue: aws.String("true"),
}
}
if len(attrs) == 0 {
attrs = nil
}
entry := sqstypesv2.SendMessageBatchRequestEntry{
Id: aws.String(strconv.Itoa(len(req.Entries))),
MessageAttributes: attrs,
MessageBody: aws.String(body),
}
req.Entries = append(req.Entries, entry)
if dm.BeforeSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(*sqstypesv2.SendMessageBatchRequestEntry); ok {
*p = entry
return true
}
return false
}
if err := dm.BeforeSend(asFunc); err != nil {
return err
}
}
}
resp, err := t.clientV2.SendMessageBatch(ctx, req)
if err != nil {
return err
}
if numFailed := len(resp.Failed); numFailed > 0 {
first := resp.Failed[0]
return awserr.New(aws.StringValue(first.Code), fmt.Sprintf("sqs.SendMessageBatch failed for %d message(s): %s", numFailed, aws.StringValue(first.Message)), nil)
}
if len(resp.Successful) == len(dms) {
for n, dm := range dms {
if dm.AfterSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(*sqstypesv2.SendMessageBatchResultEntry); ok {
*p = resp.Successful[n]
return true
}
return false
}
if err := dm.AfterSend(asFunc); err != nil {
return err
}
}
}
}
return nil
}
req := &sqs.SendMessageBatchInput{
QueueUrl: aws.String(t.qURL),
}
for _, dm := range dms {
attrs := map[string]*sqs.MessageAttributeValue{}
for k, v := range encodeMetadata(dm.Metadata) {
attrs[k] = &sqs.MessageAttributeValue{
DataType: stringDataType,
StringValue: aws.String(v),
}
}
body, didEncode := maybeEncodeBody(dm.Body, t.opts.BodyBase64Encoding)
if didEncode {
attrs[base64EncodedKey] = &sqs.MessageAttributeValue{
DataType: stringDataType,
StringValue: aws.String("true"),
}
}
if len(attrs) == 0 {
attrs = nil
}
entry := &sqs.SendMessageBatchRequestEntry{
Id: aws.String(strconv.Itoa(len(req.Entries))),
MessageAttributes: attrs,
MessageBody: aws.String(body),
}
req.Entries = append(req.Entries, entry)
if dm.BeforeSend != nil {
// A previous revision used the non-batch API SendMessage, which takes
// a *sqs.SendMessageInput. For backwards compatibility for As, continue
// to support that type. If it is requested, create a SendMessageInput
// with the fields from SendMessageBatchRequestEntry that were set, and
// then copy all of the matching fields back after calling dm.BeforeSend.
var smi *sqs.SendMessageInput
asFunc := func(i interface{}) bool {
if p, ok := i.(**sqs.SendMessageInput); ok {
smi = &sqs.SendMessageInput{
// Id does not exist on SendMessageInput.
MessageAttributes: entry.MessageAttributes,
MessageBody: entry.MessageBody,
}
*p = smi
return true
}
if p, ok := i.(**sqs.SendMessageBatchRequestEntry); ok {
*p = entry
return true
}
return false
}
if err := dm.BeforeSend(asFunc); err != nil {
return err
}
if smi != nil {
// Copy all of the fields that may have been modified back to the entry.
entry.DelaySeconds = smi.DelaySeconds
entry.MessageAttributes = smi.MessageAttributes
entry.MessageBody = smi.MessageBody
entry.MessageDeduplicationId = smi.MessageDeduplicationId
entry.MessageGroupId = smi.MessageGroupId
}
}
}
resp, err := t.client.SendMessageBatchWithContext(ctx, req)
if err != nil {
return err
}
if numFailed := len(resp.Failed); numFailed > 0 {
first := resp.Failed[0]
return awserr.New(aws.StringValue(first.Code), fmt.Sprintf("sqs.SendMessageBatch failed for %d message(s): %s", numFailed, aws.StringValue(first.Message)), nil)
}
if len(resp.Successful) == len(dms) {
for n, dm := range dms {
if dm.AfterSend != nil {
asFunc := func(i interface{}) bool {
if p, ok := i.(**sqs.SendMessageBatchResultEntry); ok {
*p = resp.Successful[n]
return true
}
return false
}
if err := dm.AfterSend(asFunc); err != nil {
return err
}
}
}
}
return nil
}
// IsRetryable implements driver.Topic.IsRetryable.
func (t *sqsTopic) IsRetryable(error) bool {
// The client handles retries.
return false
}
// As implements driver.Topic.As.
func (t *sqsTopic) As(i interface{}) bool {
if t.useV2 {
c, ok := i.(**sqsv2.Client)
if !ok {
return false
}
*c = t.clientV2
return true
}
c, ok := i.(**sqs.SQS)
if !ok {
return false
}
*c = t.client
return true
}
// ErrorAs implements driver.Topic.ErrorAs.
func (t *sqsTopic) ErrorAs(err error, i interface{}) bool {
return errorAs(err, t.useV2, i)
}
// ErrorCode implements driver.Topic.ErrorCode.
func (t *sqsTopic) ErrorCode(err error) gcerrors.ErrorCode {
return errorCode(err)
}
// Close implements driver.Topic.Close.
func (*sqsTopic) Close() error { return nil }
func errorCode(err error) gcerrors.ErrorCode {
var code string
var ae smithy.APIError
if errors.As(err, &ae) {
code = ae.ErrorCode()
} else if ae, ok := err.(awserr.Error); ok {
code = ae.Code()
} else {
return gcerrors.Unknown
}
ec, ok := errorCodeMap[code]
if !ok {
return gcerrors.Unknown
}
return ec
}
var errorCodeMap = map[string]gcerrors.ErrorCode{
sns.ErrCodeAuthorizationErrorException: gcerrors.PermissionDenied,
sns.ErrCodeKMSAccessDeniedException: gcerrors.PermissionDenied,
sns.ErrCodeKMSDisabledException: gcerrors.FailedPrecondition,
sns.ErrCodeKMSInvalidStateException: gcerrors.FailedPrecondition,
sns.ErrCodeKMSOptInRequired: gcerrors.FailedPrecondition,
sqs.ErrCodeMessageNotInflight: gcerrors.FailedPrecondition,
sqs.ErrCodePurgeQueueInProgress: gcerrors.FailedPrecondition,
sqs.ErrCodeQueueDeletedRecently: gcerrors.FailedPrecondition,
sqs.ErrCodeQueueNameExists: gcerrors.FailedPrecondition,
sns.ErrCodeInternalErrorException: gcerrors.Internal,
sns.ErrCodeInvalidParameterException: gcerrors.InvalidArgument,
sns.ErrCodeInvalidParameterValueException: gcerrors.InvalidArgument,
sqs.ErrCodeBatchEntryIdsNotDistinct: gcerrors.InvalidArgument,
sqs.ErrCodeBatchRequestTooLong: gcerrors.InvalidArgument,
sqs.ErrCodeEmptyBatchRequest: gcerrors.InvalidArgument,
sqs.ErrCodeInvalidAttributeName: gcerrors.InvalidArgument,
sqs.ErrCodeInvalidBatchEntryId: gcerrors.InvalidArgument,
sqs.ErrCodeInvalidIdFormat: gcerrors.InvalidArgument,
sqs.ErrCodeInvalidMessageContents: gcerrors.InvalidArgument,
sqs.ErrCodeReceiptHandleIsInvalid: gcerrors.InvalidArgument,
sqs.ErrCodeTooManyEntriesInBatchRequest: gcerrors.InvalidArgument,
sqs.ErrCodeUnsupportedOperation: gcerrors.InvalidArgument,
sns.ErrCodeInvalidSecurityException: gcerrors.PermissionDenied,
sns.ErrCodeKMSNotFoundException: gcerrors.NotFound,
sns.ErrCodeNotFoundException: gcerrors.NotFound,
sqs.ErrCodeQueueDoesNotExist: gcerrors.NotFound,
sns.ErrCodeFilterPolicyLimitExceededException: gcerrors.ResourceExhausted,
sns.ErrCodeSubscriptionLimitExceededException: gcerrors.ResourceExhausted,
sns.ErrCodeTopicLimitExceededException: gcerrors.ResourceExhausted,
sqs.ErrCodeOverLimit: gcerrors.ResourceExhausted,
sns.ErrCodeKMSThrottlingException: gcerrors.ResourceExhausted,
sns.ErrCodeThrottledException: gcerrors.ResourceExhausted,
"RequestCanceled": gcerrors.Canceled,
sns.ErrCodeEndpointDisabledException: gcerrors.Unknown,
sns.ErrCodePlatformApplicationDisabledException: gcerrors.Unknown,
}
type subscription struct {
useV2 bool
client *sqs.SQS
clientV2 *sqsv2.Client
qURL string
opts *SubscriptionOptions
}
// SubscriptionOptions will contain configuration for subscriptions.
type SubscriptionOptions struct {
// Raw determines how the Subscription will process message bodies.
//
// If the subscription is expected to process messages sent directly to
// SQS, or messages from SNS topics configured to use "raw" delivery,
// set this to true. Message bodies will be passed through untouched.
//
// If false, the Subscription will use best-effort heuristics to
// identify whether message bodies are raw or SNS JSON; this may be
// inefficient for raw messages.
//
// See https://aws.amazon.com/sns/faqs/#Raw_message_delivery.
Raw bool
// WaitTime passed to ReceiveMessage to enable long polling.
// https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html#sqs-long-polling.
// Note that a non-zero WaitTime can delay delivery of messages
// by up to that duration.
WaitTime time.Duration
// ReceiveBatcherOptions adds constraints to the default batching done for receives.
ReceiveBatcherOptions batcher.Options
// AckBatcherOptions adds constraints to the default batching done for acks.
AckBatcherOptions batcher.Options
}
// OpenSubscription opens a subscription based on AWS SQS for the given SQS
// queue URL. The queue is assumed to be subscribed to some SNS topic, though
// there is no check for this.
func OpenSubscription(ctx context.Context, sess client.ConfigProvider, qURL string, opts *SubscriptionOptions) *pubsub.Subscription {
rbo := recvBatcherOpts.NewMergedOptions(&opts.ReceiveBatcherOptions)
abo := ackBatcherOpts.NewMergedOptions(&opts.AckBatcherOptions)
return pubsub.NewSubscription(openSubscription(ctx, sqs.New(sess), qURL, opts), rbo, abo)
}
// OpenSubscriptionV2 opens a subscription based on AWS SQS for the given SQS
// queue URL, using AWS SDK V2. The queue is assumed to be subscribed to some SNS topic, though
// there is no check for this.
func OpenSubscriptionV2(ctx context.Context, client *sqsv2.Client, qURL string, opts *SubscriptionOptions) *pubsub.Subscription {
rbo := recvBatcherOpts.NewMergedOptions(&opts.ReceiveBatcherOptions)
abo := ackBatcherOpts.NewMergedOptions(&opts.AckBatcherOptions)
return pubsub.NewSubscription(openSubscriptionV2(ctx, client, qURL, opts), rbo, abo)
}
// openSubscription returns a driver.Subscription.
func openSubscription(ctx context.Context, client *sqs.SQS, qURL string, opts *SubscriptionOptions) driver.Subscription {
if opts == nil {
opts = &SubscriptionOptions{}
}
return &subscription{
useV2: false,
client: client,
qURL: qURL, opts: opts,
}
}
// openSubscriptionV2 returns a driver.Subscription.
func openSubscriptionV2(ctx context.Context, client *sqsv2.Client, qURL string, opts *SubscriptionOptions) driver.Subscription {
if opts == nil {
opts = &SubscriptionOptions{}
}
return &subscription{
useV2: true,
clientV2: client,
qURL: qURL, opts: opts,
}
}
// ReceiveBatch implements driver.Subscription.ReceiveBatch.
func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
var ms []*driver.Message
if s.useV2 {
req := &sqsv2.ReceiveMessageInput{
QueueUrl: aws.String(s.qURL),
MaxNumberOfMessages: int32(maxMessages),
MessageAttributeNames: []string{"All"},
AttributeNames: []sqstypesv2.QueueAttributeName{"All"},
}
if s.opts.WaitTime != 0 {
req.WaitTimeSeconds = int32(s.opts.WaitTime.Seconds())
}
output, err := s.clientV2.ReceiveMessage(ctx, req)
if err != nil {
return nil, err
}
for _, m := range output.Messages {
m := m
bodyStr := aws.StringValue(m.Body)
rawAttrs := map[string]string{}
for k, v := range m.MessageAttributes {
rawAttrs[k] = aws.StringValue(v.StringValue)
}
bodyStr, rawAttrs = extractBody(bodyStr, rawAttrs, s.opts.Raw)