Debian Codegraph @

pubsub/awssnssqs/awssnssqs.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // Package awssnssqs provides two implementations of pubsub.Topic, one that
16 // sends messages to AWS SNS (Simple Notification Service), and one that sends
17 // messages to SQS (Simple Queuing Service). It also provides an implementation
18 // of pubsub.Subscription that receives messages from SQS.
19 //
20 // # URLs
21 //
22 // For pubsub.OpenTopic, awssnssqs registers for the scheme "awssns" for
23 // an SNS topic, and "awssqs" for an SQS topic. For pubsub.OpenSubscription,
24 // it registers for the scheme "awssqs".
25 //
26 // The default URL opener will use an AWS session with the default credentials
27 // and configuration.
28 //
29 // To customize the URL opener, or for more details on the URL format,
30 // see URLOpener.
31 // See https://gocloud.dev/concepts/urls/ for background information.
32 //
33 // # Message Delivery Semantics
34 //
35 // AWS SQS supports at-least-once semantics; applications must call Message.Ack
36 // after processing a message, or it will be redelivered.
37 // See https://godoc.org/gocloud.dev/pubsub#hdr-At_most_once_and_At_least_once_Delivery
38 // for more background.
39 //
40 // # Escaping
41 //
42 // Go CDK supports all UTF-8 strings; to make this work with services lacking
43 // full UTF-8 support, strings must be escaped (during writes) and unescaped
44 // (during reads). The following escapes are required for awssnssqs:
45 // - Metadata keys: Characters other than "a-zA-z0-9_-.", and additionally "."
46 // when it's at the start of the key or the previous character was ".",
47 // are escaped using "__0x<hex>__". These characters were determined by
48 // experimentation.
49 // - Metadata values: Escaped using URL encoding.
50 // - Message body: AWS SNS/SQS only supports UTF-8 strings. See the
51 // BodyBase64Encoding enum in TopicOptions for strategies on how to send
52 // non-UTF-8 message bodies. By default, non-UTF-8 message bodies are base64
53 // encoded.
54 //
55 // # As
56 //
57 // awssnssqs exposes the following types for As:
58 // - Topic: *sns.Client for OpenSNSTopic, *sqs.Client for OpenSQSTopic
59 // - Subscription: *sqs.Client
60 // - Message: sqstypes.Message
61 // - Message.BeforeSend: *sns.PublishBatchRequestEntry or *sns.PublishInput (deprecated) for OpenSNSTopic, *sqstypes.SendMessageBatchRequestEntry for OpenSQSTopic
62 // - Message.AfterSend: snstypes.PublishBatchResultEntry or *sns.PublishOutput (deprecated) for OpenSNSTopic, sqstypes.SendMessageBatchResultEntry for OpenSQSTopic
63 // - Error: any error type returned by the service, notably smithy.APIError
64 package awssnssqs // import "gocloud.dev/pubsub/awssnssqs"
65
66 import (
67 "context"
68 "encoding/base64"
69 "encoding/json"
70 "errors"
71 "fmt"
72 "net/url"
73 "path"
74 "strconv"
75 "strings"
76 "sync"
77 "time"
78 "unicode/utf8"
79
80 "github.com/aws/aws-sdk-go-v2/aws"
81 "github.com/aws/aws-sdk-go-v2/service/sns"
82 snstypes "github.com/aws/aws-sdk-go-v2/service/sns/types"
83 "github.com/aws/aws-sdk-go-v2/service/sqs"
84 sqstypes "github.com/aws/aws-sdk-go-v2/service/sqs/types"
85 "github.com/aws/smithy-go"
86 "github.com/google/wire"
87 gcaws "gocloud.dev/aws"
88 "gocloud.dev/gcerrors"
89 "gocloud.dev/internal/escape"
90 "gocloud.dev/pubsub"
91 "gocloud.dev/pubsub/batcher"
92 "gocloud.dev/pubsub/driver"
93 )
94
95 const (
96 // base64EncodedKey is the Message Attribute key used to flag that the
97 // message body is base64 encoded.
98 base64EncodedKey = "base64encoded"
99 // How long ReceiveBatch should wait if no messages are available; controls
100 // the poll interval of requests to SQS.
101 noMessagesPollDuration = 250 * time.Millisecond
102 )
103
104 var sendBatcherOptsSNS = &batcher.Options{
105 MaxBatchSize: 10, // SNS SendBatch supports 10 message at a time
106 MaxHandlers: 100, // max concurrency for sends
107 }
108
109 var sendBatcherOptsSQS = &batcher.Options{
110 MaxBatchSize: 10, // SQS SendBatch supports 10 messages at a time
111 MaxHandlers: 100, // max concurrency for sends
112 }
113
114 var recvBatcherOpts = &batcher.Options{
115 // SQS supports receiving at most 10 messages at a time:
116 // https://godoc.org/github.com/aws/aws-sdk-go/service/sqs#SQS.ReceiveMessage
117 MaxBatchSize: 10,
118 MaxHandlers: 100, // max concurrency for receives
119 }
120
121 var ackBatcherOpts = &batcher.Options{
122 // SQS supports deleting/updating at most 10 messages at a time:
123 // https://godoc.org/github.com/aws/aws-sdk-go/service/sqs#SQS.DeleteMessageBatch
124 // https://godoc.org/github.com/aws/aws-sdk-go/service/sqs#SQS.ChangeMessageVisibilityBatch
125 MaxBatchSize: 10,
126 MaxHandlers: 100, // max concurrency for acks
127 }
128
129 func init() {
130 lazy := new(lazySessionOpener)
131 pubsub.DefaultURLMux().RegisterTopic(SNSScheme, lazy)
132 pubsub.DefaultURLMux().RegisterTopic(SQSScheme, lazy)
133 pubsub.DefaultURLMux().RegisterSubscription(SQSScheme, lazy)
134 }
135
136 // Set holds Wire providers for this package.
137 var Set = wire.NewSet(
138 DialSNS,
139 DialSQS,
140 )
141
142 // DialSNS gets an AWS SNS service client using the AWS SDK V2.
143 func DialSNS(cfg aws.Config) *sns.Client {
144 return sns.NewFromConfig(cfg)
145 }
146
147 // DialSQS gets an AWS SQS service client using the AWS SDK V2.
148 func DialSQS(cfg aws.Config) *sqs.Client {
149 return sqs.NewFromConfig(cfg)
150 }
151
152 // lazySessionOpener obtains the AWS session from the environment on the first
153 // call to OpenXXXURL.
154 type lazySessionOpener struct {
155 init sync.Once
156 opener *URLOpener
157 err error
158 }
159
160 func (o *lazySessionOpener) defaultOpener(u *url.URL) (*URLOpener, error) {
161 return &URLOpener{}, nil
162 }
163
164 func (o *lazySessionOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
165 opener, err := o.defaultOpener(u)
166 if err != nil {
167 return nil, fmt.Errorf("open topic %v: failed to open default session: %v", u, err)
168 }
169 return opener.OpenTopicURL(ctx, u)
170 }
171
172 func (o *lazySessionOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
173 opener, err := o.defaultOpener(u)
174 if err != nil {
175 return nil, fmt.Errorf("open subscription %v: failed to open default session: %v", u, err)
176 }
177 return opener.OpenSubscriptionURL(ctx, u)
178 }
179
180 // SNSScheme is the URL scheme for pubsub.OpenTopic (for an SNS topic) that
181 // awssnssqs registers its URLOpeners under on pubsub.DefaultMux.
182 const SNSScheme = "awssns"
183
184 // SQSScheme is the URL scheme for pubsub.OpenTopic (for an SQS topic) and for
185 // pubsub.OpenSubscription that awssnssqs registers its URLOpeners under on
186 // pubsub.DefaultMux.
187 const SQSScheme = "awssqs"
188
189 // URLOpener opens AWS SNS/SQS URLs like "awssns:///sns-topic-arn" for
190 // SNS topics or "awssqs://sqs-queue-url" for SQS topics and subscriptions.
191 //
192 // For SNS topics, the URL's host+path is used as the topic Amazon Resource Name
193 // (ARN). Since ARNs have ":" in them, and ":" precedes a port in URL
194 // hostnames, leave the host blank and put the ARN in the path
195 // (e.g., "awssns:///arn:aws:service:region:accountid:resourceType/resourcePath").
196 //
197 // For SQS topics and subscriptions, the URL's host+path is prefixed with
198 // "https://" to create the queue URL.
199 //
200 // See https://pkg.go.dev/gocloud.dev/aws#V2ConfigFromURLParams.
201 //
202 // In addition, the following query parameters are supported:
203 //
204 // - raw (for "awssqs" Subscriptions only): sets SubscriberOptions.Raw. The
205 // value must be parseable by `strconv.ParseBool`.
206 // - nacklazy (for "awssqs" Subscriptions only): sets SubscriberOptions.NackLazy. The
207 // value must be parseable by `strconv.ParseBool`.
208 // - waittime: sets SubscriberOptions.WaitTime, in time.ParseDuration formats.
209 type URLOpener struct {
210 // TopicOptions specifies the options to pass to OpenTopic.
211 TopicOptions TopicOptions
212 // SubscriptionOptions specifies the options to pass to OpenSubscription.
213 SubscriptionOptions SubscriptionOptions
214 }
215
216 // OpenTopicURL opens a pubsub.Topic based on u.
217 func (o *URLOpener) OpenTopicURL(ctx context.Context, u *url.URL) (*pubsub.Topic, error) {
218 // Trim leading "/" if host is empty, so that
219 // awssns:///arn:aws:service:region:accountid:resourceType/resourcePath
220 // gives "arn:..." instead of "/arn:...".
221 topicARN := strings.TrimPrefix(path.Join(u.Host, u.Path), "/")
222 qURL := "https://" + path.Join(u.Host, u.Path)
223 cfg, err := gcaws.V2ConfigFromURLParams(ctx, u.Query())
224 if err != nil {
225 return nil, fmt.Errorf("open topic %v: %v", u, err)
226 }
227 switch u.Scheme {
228 case SNSScheme:
229 return OpenSNSTopic(ctx, sns.NewFromConfig(cfg), topicARN, &o.TopicOptions), nil
230 case SQSScheme:
231 return OpenSQSTopic(ctx, sqs.NewFromConfig(cfg), qURL, &o.TopicOptions), nil
232 default:
233 return nil, fmt.Errorf("open topic %v: unsupported scheme", u)
234 }
235 }
236
237 // OpenSubscriptionURL opens a pubsub.Subscription based on u.
238 func (o *URLOpener) OpenSubscriptionURL(ctx context.Context, u *url.URL) (*pubsub.Subscription, error) {
239 // Clone the options since we might override Raw.
240 opts := o.SubscriptionOptions
241 q := u.Query()
242 if rawStr := q.Get("raw"); rawStr != "" {
243 var err error
244 opts.Raw, err = strconv.ParseBool(rawStr)
245 if err != nil {
246 return nil, fmt.Errorf("invalid value %q for raw: %v", rawStr, err)
247 }
248 q.Del("raw")
249 }
250 if nackLazyStr := q.Get("nacklazy"); nackLazyStr != "" {
251 var err error
252 opts.NackLazy, err = strconv.ParseBool(nackLazyStr)
253 if err != nil {
254 return nil, fmt.Errorf("invalid value %q for nacklazy: %v", nackLazyStr, err)
255 }
256 q.Del("nacklazy")
257 }
258 if waitTimeStr := q.Get("waittime"); waitTimeStr != "" {
259 var err error
260 opts.WaitTime, err = time.ParseDuration(waitTimeStr)
261 if err != nil {
262 return nil, fmt.Errorf("invalid value %q for waittime: %v", waitTimeStr, err)
263 }
264 q.Del("waittime")
265 }
266 qURL := "https://" + path.Join(u.Host, u.Path)
267 cfg, err := gcaws.V2ConfigFromURLParams(ctx, q)
268 if err != nil {
269 return nil, fmt.Errorf("open subscription %v: %v", u, err)
270 }
271 return OpenSubscription(ctx, sqs.NewFromConfig(cfg), qURL, &opts), nil
272 }
273
274 type snsTopic struct {
275 client *sns.Client
276 arn string
277 opts *TopicOptions
278 }
279
280 // BodyBase64Encoding is an enum of strategies for when to base64 message
281 // bodies.
282 type BodyBase64Encoding int
283
284 const (
285 // NonUTF8Only means that message bodies that are valid UTF-8 encodings are
286 // sent as-is. Invalid UTF-8 message bodies are base64 encoded, and a
287 // MessageAttribute with key "base64encoded" is added to the message.
288 // When receiving messages, the "base64encoded" attribute is used to determine
289 // whether to base64 decode, and is then filtered out.
290 NonUTF8Only BodyBase64Encoding = 0
291 // Always means that all message bodies are base64 encoded.
292 // A MessageAttribute with key "base64encoded" is added to the message.
293 // When receiving messages, the "base64encoded" attribute is used to determine
294 // whether to base64 decode, and is then filtered out.
295 Always BodyBase64Encoding = 1
296 // Never means that message bodies are never base64 encoded. Non-UTF-8
297 // bytes in message bodies may be modified by SNS/SQS.
298 Never BodyBase64Encoding = 2
299 )
300
301 func (e BodyBase64Encoding) wantEncode(b []byte) bool {
302 switch e {
303 case Always:
304 return true
305 case Never:
306 return false
307 case NonUTF8Only:
308 return !utf8.Valid(b)
309 }
310 panic("unreachable")
311 }
312
313 // TopicOptions contains configuration options for topics.
314 type TopicOptions struct {
315 // BodyBase64Encoding determines when message bodies are base64 encoded.
316 // The default is NonUTF8Only.
317 BodyBase64Encoding BodyBase64Encoding
318
319 // BatcherOptions adds constraints to the default batching done for sends.
320 BatcherOptions batcher.Options
321 }
322
323 // OpenSNSTopic opens a topic that sends to the SNS topic with the given Amazon
324 // Resource Name (ARN), using AWS SDK V2.
325 func OpenSNSTopic(ctx context.Context, client *sns.Client, topicARN string, opts *TopicOptions) *pubsub.Topic {
326 if opts == nil {
327 opts = &TopicOptions{}
328 }
329 bo := sendBatcherOptsSNS.NewMergedOptions(&opts.BatcherOptions)
330 return pubsub.NewTopic(openSNSTopic(ctx, client, topicARN, opts), bo)
331 }
332
333 var OpenSNSTopicV2 = OpenSNSTopic
334
335 // openSNSTopic returns the driver for OpenSNSTopic. This function exists so the test
336 // harness can get the driver interface implementation if it needs to.
337 func openSNSTopic(ctx context.Context, client *sns.Client, topicARN string, opts *TopicOptions) driver.Topic {
338 return &snsTopic{
339 client: client,
340 arn: topicARN,
341 opts: opts,
342 }
343 }
344
345 var stringDataType = aws.String("String")
346
347 // encodeMetadata encodes the keys and values of md as needed.
348 func encodeMetadata(md map[string]string) map[string]string {
349 retval := map[string]string{}
350 for k, v := range md {
351 // See the package comments for more details on escaping of metadata
352 // keys & values.
353 k = escape.HexEscape(k, func(runes []rune, i int) bool {
354 c := runes[i]
355 switch {
356 case escape.IsASCIIAlphanumeric(c):
357 return false
358 case c == '_' || c == '-':
359 return false
360 case c == '.' && i != 0 && runes[i-1] != '.':
361 return false
362 }
363 return true
364 })
365 retval[k] = escape.URLEscape(v)
366 }
367 return retval
368 }
369
370 // maybeEncodeBody decides whether body should base64-encoded based on opt, and
371 // returns the (possibly encoded) body as a string, along with a boolean
372 // indicating whether encoding occurred.
373 func maybeEncodeBody(body []byte, opt BodyBase64Encoding) (string, bool) {
374 if opt.wantEncode(body) {
375 return base64.StdEncoding.EncodeToString(body), true
376 }
377 return string(body), false
378 }
379
380 // Defines values for Metadata keys used by the driver for setting message
381 // attributes on SNS ([sns.PublishBatchRequestEntry]/[snstypes.PublishBatchRequestEntry])
382 // and SQS ([sqs.SendMessageBatchRequestEntry]/[sqstypes.SendMessageBatchRequestEntry])
383 // messages.
384 //
385 // For example, to set a deduplication ID and message group ID on a message:
386 //
387 // import (
388 // "gocloud.dev/pubsub"
389 // "gocloud.dev/pubsub/awssnssqs"
390 // )
391 //
392 // message := pubsub.Message{
393 // Body: []byte("Hello, World!"),
394 // Metadata: map[string]string{
395 // awssnssqs.MetadataKeyDeduplicationID: "my-dedup-id",
396 // awssnssqs.MetadataKeyMessageGroupID: "my-group-id",
397 // },
398 // }
399 const (
400 MetadataKeyDeduplicationID = "DeduplicationId"
401 MetadataKeyMessageGroupID = "MessageGroupId"
402 )
403
404 // reviseSnsEntryAttributes sets attributes on a [snstypes.PublishBatchRequestEntry] based on [driver.Message.Metadata].
405 func reviseSnsEntryAttributes(dm *driver.Message, entry *snstypes.PublishBatchRequestEntry) {
406 if dedupID, ok := dm.Metadata[MetadataKeyDeduplicationID]; ok {
407 entry.MessageDeduplicationId = aws.String(dedupID)
408 }
409 if groupID, ok := dm.Metadata[MetadataKeyMessageGroupID]; ok {
410 entry.MessageGroupId = aws.String(groupID)
411 }
412 }
413
414 // SendBatch implements driver.Topic.SendBatch.
415 func (t *snsTopic) SendBatch(ctx context.Context, dms []*driver.Message) error {
416 req := &sns.PublishBatchInput{
417 TopicArn: &t.arn,
418 }
419 for _, dm := range dms {
420 attrs := map[string]snstypes.MessageAttributeValue{}
421 for k, v := range encodeMetadata(dm.Metadata) {
422 attrs[k] = snstypes.MessageAttributeValue{
423 DataType: stringDataType,
424 StringValue: aws.String(v),
425 }
426 }
427 body, didEncode := maybeEncodeBody(dm.Body, t.opts.BodyBase64Encoding)
428 if didEncode {
429 attrs[base64EncodedKey] = snstypes.MessageAttributeValue{
430 DataType: stringDataType,
431 StringValue: aws.String("true"),
432 }
433 }
434 if len(attrs) == 0 {
435 attrs = nil
436 }
437 entry := &snstypes.PublishBatchRequestEntry{
438 Id: aws.String(strconv.Itoa(len(req.PublishBatchRequestEntries))),
439 MessageAttributes: attrs,
440 Message: aws.String(body),
441 }
442 reviseSnsEntryAttributes(dm, entry)
443 if dm.BeforeSend != nil {
444 // A previous revision used the non-batch API PublishInput, which takes
445 // a *sns.PublishInput. For backwards compatibility for As, continue
446 // to support that type. If it is requested, create a PublishInput
447 // with the fields from PublishBatchRequestEntry that were set, and
448 // then copy all of the matching fields back after calling dm.BeforeSend.
449 var pi *sns.PublishInput
450 asFunc := func(i any) bool {
451 if p, ok := i.(**sns.PublishInput); ok {
452 pi = &sns.PublishInput{
453 // Id does not exist on PublishInput.
454 MessageAttributes: entry.MessageAttributes,
455 Message: entry.Message,
456 }
457 *p = pi
458 return true
459 }
460 if p, ok := i.(**snstypes.PublishBatchRequestEntry); ok {
461 *p = entry
462 return true
463 }
464 return false
465 }
466 if err := dm.BeforeSend(asFunc); err != nil {
467 return err
468 }
469 if pi != nil {
470 // Copy all of the fields that may have been modified back to the entry.
471 entry.MessageAttributes = pi.MessageAttributes
472 entry.Message = pi.Message
473 entry.MessageDeduplicationId = pi.MessageDeduplicationId
474 entry.MessageGroupId = pi.MessageGroupId
475 entry.MessageStructure = pi.MessageStructure
476 entry.Subject = pi.Subject
477 }
478 }
479 req.PublishBatchRequestEntries = append(req.PublishBatchRequestEntries, *entry)
480 }
481 resp, err := t.client.PublishBatch(ctx, req)
482 if err != nil {
483 return err
484 }
485 if numFailed := len(resp.Failed); numFailed > 0 {
486 first := resp.Failed[0]
487 return fmt.Errorf("sns.PublishBatch failed for %d message(s): %s, %s", numFailed, aws.ToString(first.Code), aws.ToString(first.Message))
488 }
489 if len(resp.Successful) == len(dms) {
490 for n, dm := range dms {
491 if dm.AfterSend != nil {
492 asFunc := func(i any) bool {
493 if p, ok := i.(*snstypes.PublishBatchResultEntry); ok {
494 *p = resp.Successful[n]
495 return true
496 }
497 if p, ok := i.(**sns.PublishOutput); ok {
498 // For backwards compability.
499 *p = &sns.PublishOutput{
500 MessageId: resp.Successful[n].MessageId,
501 SequenceNumber: resp.Successful[n].SequenceNumber,
502 }
503 return true
504 }
505 return false
506 }
507 if err := dm.AfterSend(asFunc); err != nil {
508 return err
509 }
510 }
511 }
512 }
513 return nil
514 }
515
516 // IsRetryable implements driver.Topic.IsRetryable.
517 func (t *snsTopic) IsRetryable(error) bool {
518 // The client handles retries.
519 return false
520 }
521
522 // As implements driver.Topic.As.
523 func (t *snsTopic) As(i any) bool {
524 c, ok := i.(**sns.Client)
525 if !ok {
526 return false
527 }
528 *c = t.client
529 return true
530 }
531
532 // ErrorAs implements driver.Topic.ErrorAs.
533 func (t *snsTopic) ErrorAs(err error, i any) bool {
534 return errorAs(err, i)
535 }
536
537 // ErrorCode implements driver.Topic.ErrorCode.
538 func (t *snsTopic) ErrorCode(err error) gcerrors.ErrorCode {
539 return errorCode(err)
540 }
541
542 // Close implements driver.Topic.Close.
543 func (*snsTopic) Close() error { return nil }
544
545 type sqsTopic struct {
546 client *sqs.Client
547 qURL string
548 opts *TopicOptions
549 }
550
551 // OpenSQSTopic opens a topic that sends to the SQS topic with the given SQS
552 // queue URL, using AWS SDK V2.
553 func OpenSQSTopic(ctx context.Context, client *sqs.Client, qURL string, opts *TopicOptions) *pubsub.Topic {
554 if opts == nil {
555 opts = &TopicOptions{}
556 }
557 bo := sendBatcherOptsSQS.NewMergedOptions(&opts.BatcherOptions)
558 return pubsub.NewTopic(openSQSTopic(ctx, client, qURL, opts), bo)
559 }
560
561 var OpenSQSTopicV2 = OpenSQSTopic
562
563 // openSQSTopic returns the driver for OpenSQSTopic. This function exists so the test
564 // harness can get the driver interface implementation if it needs to.
565 func openSQSTopic(ctx context.Context, client *sqs.Client, qURL string, opts *TopicOptions) driver.Topic {
566 return &sqsTopic{
567 client: client,
568 qURL: qURL,
569 opts: opts,
570 }
571 }
572
573 // reviseSqsEntryAttributes sets attributes on a [sqstypes.SendMessageBatchRequestEntry] based on [driver.Message.Metadata].
574 func reviseSqsEntryAttributes(dm *driver.Message, entry *sqstypes.SendMessageBatchRequestEntry) {
575 if dedupID, ok := dm.Metadata[MetadataKeyDeduplicationID]; ok {
576 entry.MessageDeduplicationId = aws.String(dedupID)
577 }
578 if groupID, ok := dm.Metadata[MetadataKeyMessageGroupID]; ok {
579 entry.MessageGroupId = aws.String(groupID)
580 }
581 }
582
583 // SendBatch implements driver.Topic.SendBatch.
584 func (t *sqsTopic) SendBatch(ctx context.Context, dms []*driver.Message) error {
585 req := &sqs.SendMessageBatchInput{
586 QueueUrl: aws.String(t.qURL),
587 }
588 for _, dm := range dms {
589 attrs := map[string]sqstypes.MessageAttributeValue{}
590 for k, v := range encodeMetadata(dm.Metadata) {
591 attrs[k] = sqstypes.MessageAttributeValue{
592 DataType: stringDataType,
593 StringValue: aws.String(v),
594 }
595 }
596 body, didEncode := maybeEncodeBody(dm.Body, t.opts.BodyBase64Encoding)
597 if didEncode {
598 attrs[base64EncodedKey] = sqstypes.MessageAttributeValue{
599 DataType: stringDataType,
600 StringValue: aws.String("true"),
601 }
602 }
603 if len(attrs) == 0 {
604 attrs = nil
605 }
606 entry := &sqstypes.SendMessageBatchRequestEntry{
607 Id: aws.String(strconv.Itoa(len(req.Entries))),
608 MessageAttributes: attrs,
609 MessageBody: aws.String(body),
610 }
611 reviseSqsEntryAttributes(dm, entry)
612 if dm.BeforeSend != nil {
613 asFunc := func(i any) bool {
614 if p, ok := i.(**sqstypes.SendMessageBatchRequestEntry); ok {
615 *p = entry
616 return true
617 }
618 return false
619 }
620 if err := dm.BeforeSend(asFunc); err != nil {
621 return err
622 }
623 }
624 req.Entries = append(req.Entries, *entry)
625 }
626 resp, err := t.client.SendMessageBatch(ctx, req)
627 if err != nil {
628 return err
629 }
630 if numFailed := len(resp.Failed); numFailed > 0 {
631 first := resp.Failed[0]
632 return fmt.Errorf("sqs.SendMessageBatch failed for %d message(s): %s, %s", numFailed, aws.ToString(first.Code), aws.ToString(first.Message))
633 }
634 if len(resp.Successful) == len(dms) {
635 for n, dm := range dms {
636 if dm.AfterSend != nil {
637 asFunc := func(i any) bool {
638 if p, ok := i.(*sqstypes.SendMessageBatchResultEntry); ok {
639 *p = resp.Successful[n]
640 return true
641 }
642 return false
643 }
644 if err := dm.AfterSend(asFunc); err != nil {
645 return err
646 }
647 }
648 }
649 }
650 return nil
651 }
652
653 // IsRetryable implements driver.Topic.IsRetryable.
654 func (t *sqsTopic) IsRetryable(error) bool {
655 // The client handles retries.
656 return false
657 }
658
659 // As implements driver.Topic.As.
660 func (t *sqsTopic) As(i any) bool {
661 c, ok := i.(**sqs.Client)
662 if !ok {
663 return false
664 }
665 *c = t.client
666 return true
667 }
668
669 // ErrorAs implements driver.Topic.ErrorAs.
670 func (t *sqsTopic) ErrorAs(err error, i any) bool {
671 return errorAs(err, i)
672 }
673
674 // ErrorCode implements driver.Topic.ErrorCode.
675 func (t *sqsTopic) ErrorCode(err error) gcerrors.ErrorCode {
676 return errorCode(err)
677 }
678
679 // Close implements driver.Topic.Close.
680 func (*sqsTopic) Close() error { return nil }
681
682 func errorCode(err error) gcerrors.ErrorCode {
683 var code string
684 var ae smithy.APIError
685 if errors.As(err, &ae) {
686 code = ae.ErrorCode()
687 } else {
688 return gcerrors.Unknown
689 }
690 ec, ok := errorCodeMap[code]
691 if !ok {
692 return gcerrors.Unknown
693 }
694 return ec
695 }
696
697 var errorCodeMap = map[string]gcerrors.ErrorCode{
698 (&snstypes.AuthorizationErrorException{}).ErrorCode(): gcerrors.PermissionDenied,
699 (&snstypes.KMSAccessDeniedException{}).ErrorCode(): gcerrors.PermissionDenied,
700 (&snstypes.KMSDisabledException{}).ErrorCode(): gcerrors.FailedPrecondition,
701 (&snstypes.KMSInvalidStateException{}).ErrorCode(): gcerrors.FailedPrecondition,
702 (&snstypes.KMSOptInRequired{}).ErrorCode(): gcerrors.FailedPrecondition,
703 (&sqstypes.MessageNotInflight{}).ErrorCode(): gcerrors.FailedPrecondition,
704 (&sqstypes.PurgeQueueInProgress{}).ErrorCode(): gcerrors.FailedPrecondition,
705 (&sqstypes.QueueDeletedRecently{}).ErrorCode(): gcerrors.FailedPrecondition,
706 (&sqstypes.QueueNameExists{}).ErrorCode(): gcerrors.FailedPrecondition,
707 (&snstypes.InternalErrorException{}).ErrorCode(): gcerrors.Internal,
708 (&snstypes.InvalidParameterException{}).ErrorCode(): gcerrors.InvalidArgument,
709 (&snstypes.InvalidParameterValueException{}).ErrorCode(): gcerrors.InvalidArgument,
710 (&sqstypes.BatchEntryIdsNotDistinct{}).ErrorCode(): gcerrors.InvalidArgument,
711 (&sqstypes.BatchRequestTooLong{}).ErrorCode(): gcerrors.InvalidArgument,
712 (&sqstypes.EmptyBatchRequest{}).ErrorCode(): gcerrors.InvalidArgument,
713 (&sqstypes.InvalidAttributeName{}).ErrorCode(): gcerrors.InvalidArgument,
714 (&sqstypes.InvalidBatchEntryId{}).ErrorCode(): gcerrors.InvalidArgument,
715 (&sqstypes.InvalidIdFormat{}).ErrorCode(): gcerrors.InvalidArgument,
716 (&sqstypes.InvalidMessageContents{}).ErrorCode(): gcerrors.InvalidArgument,
717 (&sqstypes.ReceiptHandleIsInvalid{}).ErrorCode(): gcerrors.InvalidArgument,
718 (&sqstypes.TooManyEntriesInBatchRequest{}).ErrorCode(): gcerrors.InvalidArgument,
719 (&sqstypes.UnsupportedOperation{}).ErrorCode(): gcerrors.InvalidArgument,
720 (&snstypes.InvalidSecurityException{}).ErrorCode(): gcerrors.PermissionDenied,
721 (&snstypes.KMSNotFoundException{}).ErrorCode(): gcerrors.NotFound,
722 (&snstypes.NotFoundException{}).ErrorCode(): gcerrors.NotFound,
723 (&sqstypes.QueueDoesNotExist{}).ErrorCode(): gcerrors.NotFound,
724 "AWS.SimpleQueueService.NonExistentQueue": gcerrors.NotFound,
725 (&snstypes.FilterPolicyLimitExceededException{}).ErrorCode(): gcerrors.ResourceExhausted,
726 (&snstypes.SubscriptionLimitExceededException{}).ErrorCode(): gcerrors.ResourceExhausted,
727 (&snstypes.TopicLimitExceededException{}).ErrorCode(): gcerrors.ResourceExhausted,
728 (&sqstypes.OverLimit{}).ErrorCode(): gcerrors.ResourceExhausted,
729 (&snstypes.KMSThrottlingException{}).ErrorCode(): gcerrors.ResourceExhausted,
730 (&snstypes.ThrottledException{}).ErrorCode(): gcerrors.ResourceExhausted,
731 "RequestCanceled": gcerrors.Canceled,
732 (&snstypes.EndpointDisabledException{}).ErrorCode(): gcerrors.Unknown,
733 (&snstypes.PlatformApplicationDisabledException{}).ErrorCode(): gcerrors.Unknown,
734 }
735
736 type subscription struct {
737 client *sqs.Client
738 qURL string
739 opts *SubscriptionOptions
740 }
741
742 // SubscriptionOptions will contain configuration for subscriptions.
743 type SubscriptionOptions struct {
744 // Raw determines how the Subscription will process message bodies.
745 //
746 // If the subscription is expected to process messages sent directly to
747 // SQS, or messages from SNS topics configured to use "raw" delivery,
748 // set this to true. Message bodies will be passed through untouched.
749 //
750 // If false, the Subscription will use best-effort heuristics to
751 // identify whether message bodies are raw or SNS JSON; this may be
752 // inefficient for raw messages.
753 //
754 // See https://aws.amazon.com/sns/faqs/#Raw_message_delivery.
755 Raw bool
756
757 // NackLazy determines what Nack does.
758 //
759 // By default, Nack uses ChangeMessageVisibility to set the VisibilityTimeout
760 // for the nacked message to 0, so that it will be redelivered immediately.
761 // Set NackLazy to true to bypass this behavior; Nack will do nothing,
762 // and the message will be redelivered after the existing VisibilityTimeout
763 // expires (defaults to 30s, but can be configured per queue).
764 //
765 // See https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-visibility-timeout.html.
766 NackLazy bool
767
768 // WaitTime passed to ReceiveMessage to enable long polling.
769 // https://docs.aws.amazon.com/AWSSimpleQueueService/latest/SQSDeveloperGuide/sqs-short-and-long-polling.html#sqs-long-polling.
770 // Note that a non-zero WaitTime can delay delivery of messages
771 // by up to that duration.
772 WaitTime time.Duration
773
774 // ReceiveBatcherOptions adds constraints to the default batching done for receives.
775 ReceiveBatcherOptions batcher.Options
776
777 // AckBatcherOptions adds constraints to the default batching done for acks.
778 AckBatcherOptions batcher.Options
779 }
780
781 // OpenSubscription opens a subscription based on AWS SQS for the given SQS
782 // queue URL, using AWS SDK V2. The queue is assumed to be subscribed to some SNS topic, though
783 // there is no check for this.
784 func OpenSubscription(ctx context.Context, client *sqs.Client, qURL string, opts *SubscriptionOptions) *pubsub.Subscription {
785 if opts == nil {
786 opts = &SubscriptionOptions{}
787 }
788 rbo := recvBatcherOpts.NewMergedOptions(&opts.ReceiveBatcherOptions)
789 abo := ackBatcherOpts.NewMergedOptions(&opts.AckBatcherOptions)
790 return pubsub.NewSubscription(openSubscription(ctx, client, qURL, opts), rbo, abo)
791 }
792
793 var OpenSubscriptionV2 = OpenSubscription
794
795 // openSubscription returns a driver.Subscription.
796 func openSubscription(ctx context.Context, client *sqs.Client, qURL string, opts *SubscriptionOptions) driver.Subscription {
797 return &subscription{
798 client: client,
799 qURL: qURL,
800 opts: opts,
801 }
802 }
803
804 // ReceiveBatch implements driver.Subscription.ReceiveBatch.
805 func (s *subscription) ReceiveBatch(ctx context.Context, maxMessages int) ([]*driver.Message, error) {
806 var ms []*driver.Message
807 req := &sqs.ReceiveMessageInput{
808 QueueUrl: aws.String(s.qURL),
809 MaxNumberOfMessages: int32(maxMessages),
810 MessageAttributeNames: []string{"All"},
811 AttributeNames: []sqstypes.QueueAttributeName{"All"},
812 }
813 if s.opts.WaitTime != 0 {
814 req.WaitTimeSeconds = int32(s.opts.WaitTime.Seconds())
815 }
816 output, err := s.client.ReceiveMessage(ctx, req)
817 if err != nil {
818 return nil, err
819 }
820 for _, m := range output.Messages {
821 bodyStr := aws.ToString(m.Body)
822 rawAttrs := map[string]string{}
823 for k, v := range m.MessageAttributes {
824 rawAttrs[k] = aws.ToString(v.StringValue)
825 }
826 bodyStr, rawAttrs = extractBody(bodyStr, rawAttrs, s.opts.Raw)
827
828 decodeIt := false
829 attrs := map[string]string{}
830 for k, v := range rawAttrs {
831 // See BodyBase64Encoding for details on when we base64 decode message bodies.
832 if k == base64EncodedKey {
833 decodeIt = true
834 continue
835 }
836 // See the package comments for more details on escaping of metadata
837 // keys & values.
838 attrs[escape.HexUnescape(k)] = escape.URLUnescape(v)
839 }
840
841 var b []byte
842 if decodeIt {
843 var err error
844 b, err = base64.StdEncoding.DecodeString(bodyStr)
845 if err != nil {
846 // Fall back to using the raw message.
847 b = []byte(bodyStr)
848 }
849 } else {
850 b = []byte(bodyStr)
851 }
852
853 m2 := &driver.Message{
854 LoggableID: aws.ToString(m.MessageId),
855 Body: b,
856 Metadata: attrs,
857 AckID: m.ReceiptHandle,
858 AsFunc: func(i any) bool {
859 p, ok := i.(*sqstypes.Message)
860 if !ok {
861 return false
862 }
863 *p = m
864 return true
865 },
866 }
867 ms = append(ms, m2)
868 }
869 if len(ms) == 0 {
870 // When we return no messages and no error, the portable type will call
871 // ReceiveBatch again immediately. Sleep for a bit to avoid hammering SQS
872 // with RPCs.
873 time.Sleep(noMessagesPollDuration)
874 }
875 return ms, nil
876 }
877
878 func extractBody(bodyStr string, rawAttrs map[string]string, raw bool) (body string, attributes map[string]string) {
879 // If the user told us that message bodies are raw, or if there are
880 // top-level MessageAttributes, then it's raw.
881 // (SNS JSON message can have attributes, but they are encoded in
882 // the JSON instead of being at the top level).
883 raw = raw || len(rawAttrs) > 0
884 if raw {
885 // For raw messages, the attributes are at the top level
886 // and we leave bodyStr alone.
887 return bodyStr, rawAttrs
888 }
889
890 // It might be SNS JSON; try to parse the raw body as such.
891 // https://aws.amazon.com/sns/faqs/#Raw_message_delivery
892 // If it parses as JSON and has a TopicArn field, assume it's SNS JSON.
893 var bodyJSON struct {
894 TopicArn string
895 Message string
896 MessageAttributes map[string]struct{ Value string }
897 }
898 if err := json.Unmarshal([]byte(bodyStr), &bodyJSON); err == nil && bodyJSON.TopicArn != "" {
899 // It looks like SNS JSON. Get attributes from the decoded struct,
900 // and update the body to be the JSON Message field.
901 for k, v := range bodyJSON.MessageAttributes {
902 rawAttrs[k] = v.Value
903 }
904 return bodyJSON.Message, rawAttrs
905 }
906 // It doesn't look like SNS JSON, either because it
907 // isn't JSON or because the JSON doesn't have a TopicArn
908 // field. Treat it as raw.
909 //
910 // As above in the other "raw" case, we leave bodyStr
911 // alone. There can't be any top-level attributes (because
912 // then we would have known it was raw earlier).
913 return bodyStr, rawAttrs
914 }
915
916 // SendAcks implements driver.Subscription.SendAcks.
917 func (s *subscription) SendAcks(ctx context.Context, ids []driver.AckID) error {
918 req := &sqs.DeleteMessageBatchInput{QueueUrl: aws.String(s.qURL)}
919 for _, id := range ids {
920 req.Entries = append(req.Entries, sqstypes.DeleteMessageBatchRequestEntry{
921 Id: aws.String(strconv.Itoa(len(req.Entries))),
922 ReceiptHandle: id.(*string),
923 })
924 }
925 resp, err := s.client.DeleteMessageBatch(ctx, req)
926 if err != nil {
927 return err
928 }
929 // Note: DeleteMessageBatch doesn't return failures when you try
930 // to Delete an id that isn't found.
931 if numFailed := len(resp.Failed); numFailed > 0 {
932 first := resp.Failed[0]
933 return fmt.Errorf("sqs.DeleteMessageBatch failed for %d message(s): %s, %s", numFailed, aws.ToString(first.Code), aws.ToString(first.Message))
934 }
935 return nil
936 }
937
938 // CanNack implements driver.CanNack.
939 func (s *subscription) CanNack() bool { return true }
940
941 // SendNacks implements driver.Subscription.SendNacks.
942 func (s *subscription) SendNacks(ctx context.Context, ids []driver.AckID) error {
943 if s.opts.NackLazy {
944 return nil
945 }
946 req := &sqs.ChangeMessageVisibilityBatchInput{QueueUrl: aws.String(s.qURL)}
947 for _, id := range ids {
948 req.Entries = append(req.Entries, sqstypes.ChangeMessageVisibilityBatchRequestEntry{
949 Id: aws.String(strconv.Itoa(len(req.Entries))),
950 ReceiptHandle: id.(*string),
951 VisibilityTimeout: 1,
952 })
953 }
954 resp, err := s.client.ChangeMessageVisibilityBatch(ctx, req)
955 if err != nil {
956 return err
957 }
958 // Note: ChangeMessageVisibilityBatch returns failures when you try to
959 // modify an id that isn't found; drop those.
960 var firstFail sqstypes.BatchResultErrorEntry
961 numFailed := 0
962 for _, fail := range resp.Failed {
963 if aws.ToString(fail.Code) == (&sqstypes.ReceiptHandleIsInvalid{}).ErrorCode() {
964 continue
965 }
966 if numFailed == 0 {
967 firstFail = fail
968 }
969 numFailed++
970 }
971 if numFailed > 0 {
972 return fmt.Errorf("sqs.ChangeMessageVisibilityBatch failed for %d message(s): %s, %s", numFailed, aws.ToString(firstFail.Code), aws.ToString(firstFail.Message))
973 }
974 return nil
975 }
976
977 // IsRetryable implements driver.Subscription.IsRetryable.
978 func (*subscription) IsRetryable(error) bool {
979 // The client handles retries.
980 return false
981 }
982
983 // As implements driver.Subscription.As.
984 func (s *subscription) As(i any) bool {
985 c, ok := i.(**sqs.Client)
986 if !ok {
987 return false
988 }
989 *c = s.client
990 return true
991 }
992
993 // ErrorAs implements driver.Subscription.ErrorAs.
994 func (s *subscription) ErrorAs(err error, i any) bool {
995 return errorAs(err, i)
996 }
997
998 // ErrorCode implements driver.Subscription.ErrorCode.
999 func (s *subscription) ErrorCode(err error) gcerrors.ErrorCode {
1000 return errorCode(err)
1001 }
1002
1003 func errorAs(err error, i any) bool {
1004 return errors.As(err, i)
1005 }
1006
1007 // Close implements driver.Subscription.Close.
1008 func (*subscription) Close() error { return nil }