-
Notifications
You must be signed in to change notification settings - Fork 5
/
sns.go
2801 lines (2342 loc) · 92.2 KB
/
sns.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
package sns
/*
* Copyright 2020-2021 Aldelo, LP
*
* 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
*
* http://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.
*/
// =================================================================================================================
// AWS CREDENTIAL:
// use $> aws configure (to set aws access key and secret to target machine)
// Store AWS Access ID and Secret Key into Default Profile Using '$ aws configure' cli
//
// To Install & Setup AWS CLI on Host:
// 1) https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2-linux.html
// On Ubuntu, if host does not have zip and unzip:
// $> sudo apt install zip
// $> sudo apt install unzip
// On Ubuntu, to install AWS CLI v2:
// $> curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
// $> unzip awscliv2.zip
// $> sudo ./aws/install
// 2) $> aws configure set region awsRegionName --profile default
// 3) $> aws configure
// follow prompts to enter Access ID and Secret Key
//
// AWS Region Name Reference:
// us-west-2, us-east-1, ap-northeast-1, etc
// See: https://docs.aws.amazon.com/general/latest/gr/rande.html
// =================================================================================================================
import (
"context"
"errors"
util "github.com/aldelo/common"
awshttp2 "github.com/aldelo/common/wrapper/aws"
awsregion "github.com/aldelo/common/wrapper/aws/awsregion"
"github.com/aldelo/common/wrapper/sns/snsapplicationplatform"
"github.com/aldelo/common/wrapper/sns/snscreatetopicattribute"
"github.com/aldelo/common/wrapper/sns/snsendpointattribute"
"github.com/aldelo/common/wrapper/sns/snsgetsubscriptionattribute"
"github.com/aldelo/common/wrapper/sns/snsgettopicattribute"
"github.com/aldelo/common/wrapper/sns/snsplatformapplicationattribute"
"github.com/aldelo/common/wrapper/sns/snsprotocol"
"github.com/aldelo/common/wrapper/sns/snssubscribeattribute"
"github.com/aldelo/common/wrapper/xray"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
awsxray "github.com/aws/aws-xray-sdk-go/xray"
"net/http"
"time"
)
// ================================================================================================================
// STRUCTS
// ================================================================================================================
// SNS struct encapsulates the AWS SNS access functionality
type SNS struct {
// define the AWS region that SNS is located at
AwsRegion awsregion.AWSRegion
// custom http2 client options
HttpOptions *awshttp2.HttpClientSettings
// optional, sms sender name info
SMSSenderName string
// optional, indicates if sms message sent is transaction or promotional
SMSTransactional bool
// store sns client object
snsClient *sns.SNS
_parentSegment *xray.XRayParentSegment
}
// SubscribedTopic struct encapsulates the AWS SNS subscribed topic data
type SubscribedTopic struct {
SubscriptionArn string
TopicArn string
Protocol snsprotocol.SNSProtocol
Endpoint string
Owner string
}
// ================================================================================================================
// STRUCTS FUNCTIONS
// ================================================================================================================
// ----------------------------------------------------------------------------------------------------------------
// utility functions
// ----------------------------------------------------------------------------------------------------------------
// Connect will establish a connection to the SNS service
func (s *SNS) Connect(parentSegment ...*xray.XRayParentSegment) (err error) {
if xray.XRayServiceOn() {
if len(parentSegment) > 0 {
s._parentSegment = parentSegment[0]
}
seg := xray.NewSegment("SNS-Connect", s._parentSegment)
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("SNS-AWS-Region", s.AwsRegion)
_ = seg.Seg.AddMetadata("SNS-SMS-Sender-Name", s.SMSSenderName)
_ = seg.Seg.AddMetadata("SNS-SMS-Transactional", s.SMSTransactional)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
err = s.connectInternal()
if err == nil {
awsxray.AWS(s.snsClient.Client)
}
return err
} else {
return s.connectInternal()
}
}
// Connect will establish a connection to the SNS service
func (s *SNS) connectInternal() error {
// clean up prior object
s.snsClient = nil
if !s.AwsRegion.Valid() || s.AwsRegion == awsregion.UNKNOWN {
return errors.New("Connect To SNS Failed: (AWS Session Error) " + "Region is Required")
}
// create custom http2 client if needed
var httpCli *http.Client
var httpErr error
if s.HttpOptions == nil {
s.HttpOptions = new(awshttp2.HttpClientSettings)
}
// use custom http2 client
h2 := &awshttp2.AwsHttp2Client{
Options: s.HttpOptions,
}
if httpCli, httpErr = h2.NewHttp2Client(); httpErr != nil {
return errors.New("Connect to SNS Failed: (AWS Session Error) " + "Create Custom Http2 Client Errored = " + httpErr.Error())
}
// establish aws session connection and keep session object in struct
if sess, err := session.NewSession(
&aws.Config{
Region: aws.String(s.AwsRegion.Key()),
HTTPClient: httpCli,
}); err != nil {
// aws session error
return errors.New("Connect To SNS Failed: (AWS Session Error) " + err.Error())
} else {
// create cached objects for shared use
s.snsClient = sns.New(sess)
if s.snsClient == nil {
return errors.New("Connect To SNS Client Failed: (New SNS Client Connection) " + "Connection Object Nil")
}
// session stored to struct
return nil
}
}
// Disconnect will disjoin from aws session by clearing it
func (s *SNS) Disconnect() {
s.snsClient = nil
}
// UpdateParentSegment updates this struct's xray parent segment, if no parent segment, set nil
func (s *SNS) UpdateParentSegment(parentSegment *xray.XRayParentSegment) {
s._parentSegment = parentSegment
}
// ----------------------------------------------------------------------------------------------------------------
// internal helper methods
// ----------------------------------------------------------------------------------------------------------------
// toAwsCreateTopicAttributes will convert from strongly typed to aws accepted map
func (s *SNS) toAwsCreateTopicAttributes(attributes map[snscreatetopicattribute.SNSCreateTopicAttribute]string) (newMap map[string]*string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[string]*string)
for k, v := range attributes {
if k.Valid() && k != snscreatetopicattribute.UNKNOWN {
newMap[k.Key()] = aws.String(v)
}
}
return newMap
}
// fromAwsCreateTopicAttributes will convert from aws map to strongly typed map
func (s *SNS) fromAwsCreateTopicAttributes(attributes map[string]*string) (newMap map[snscreatetopicattribute.SNSCreateTopicAttribute]string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[snscreatetopicattribute.SNSCreateTopicAttribute]string)
var conv snscreatetopicattribute.SNSCreateTopicAttribute
for k, v := range attributes {
if util.LenTrim(k) > 0 {
v1 := aws.StringValue(v)
if k1, err := conv.ParseByKey(k); err == nil {
newMap[k1] = v1
}
}
}
return newMap
}
// toAwsGetTopicAttributes will convert from strongly typed to aws accepted map
func (s *SNS) toAwsGetTopicAttributes(attributes map[snsgettopicattribute.SNSGetTopicAttribute]string) (newMap map[string]*string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[string]*string)
for k, v := range attributes {
if k.Valid() && k != snsgettopicattribute.UNKNOWN {
newMap[k.Key()] = aws.String(v)
}
}
return newMap
}
// fromAwsGetTopicAttributes will convert from aws map to strongly typed map
func (s *SNS) fromAwsGetTopicAttributes(attributes map[string]*string) (newMap map[snsgettopicattribute.SNSGetTopicAttribute]string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[snsgettopicattribute.SNSGetTopicAttribute]string)
var conv snsgettopicattribute.SNSGetTopicAttribute
for k, v := range attributes {
if util.LenTrim(k) > 0 {
v1 := aws.StringValue(v)
if k1, err := conv.ParseByKey(k); err == nil {
newMap[k1] = v1
}
}
}
return newMap
}
// toAwsSubscribeAttributes will convert from strongly typed to aws accepted map
func (s *SNS) toAwsSubscribeAttributes(attributes map[snssubscribeattribute.SNSSubscribeAttribute]string) (newMap map[string]*string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[string]*string)
for k, v := range attributes {
if k.Valid() && k != snssubscribeattribute.UNKNOWN {
newMap[k.Key()] = aws.String(v)
}
}
return newMap
}
// fromAwsSubscribeAttributes will convert from aws map to strongly typed map
func (s *SNS) fromAwsSubscribeAttributes(attributes map[string]*string) (newMap map[snssubscribeattribute.SNSSubscribeAttribute]string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[snssubscribeattribute.SNSSubscribeAttribute]string)
var conv snssubscribeattribute.SNSSubscribeAttribute
for k, v := range attributes {
if util.LenTrim(k) > 0 {
v1 := aws.StringValue(v)
if k1, err := conv.ParseByKey(k); err == nil {
newMap[k1] = v1
}
}
}
return newMap
}
// toAwsGetSubscriptionAttributes will convert from strongly typed to aws accepted map
func (s *SNS) toAwsGetSubscriptionAttributes(attributes map[snsgetsubscriptionattribute.SNSGetSubscriptionAttribute]string) (newMap map[string]*string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[string]*string)
for k, v := range attributes {
if k.Valid() && k != snsgetsubscriptionattribute.UNKNOWN {
newMap[k.Key()] = aws.String(v)
}
}
return newMap
}
// fromAwsGetSubscriptionAttributes will convert from aws map to strongly typed map
func (s *SNS) fromAwsGetSubscriptionAttributes(attributes map[string]*string) (newMap map[snsgetsubscriptionattribute.SNSGetSubscriptionAttribute]string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[snsgetsubscriptionattribute.SNSGetSubscriptionAttribute]string)
var conv snsgetsubscriptionattribute.SNSGetSubscriptionAttribute
for k, v := range attributes {
if util.LenTrim(k) > 0 {
v1 := aws.StringValue(v)
if k1, err := conv.ParseByKey(k); err == nil {
newMap[k1] = v1
}
}
}
return newMap
}
// toAwsPlatformApplicationAttributes will convert from strongly typed to aws accepted map
func (s *SNS) toAwsPlatformApplicationAttributes(attributes map[snsplatformapplicationattribute.SNSPlatformApplicationAttribute]string) (newMap map[string]*string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[string]*string)
for k, v := range attributes {
if k.Valid() && k != snsplatformapplicationattribute.UNKNOWN {
newMap[k.Key()] = aws.String(v)
}
}
return newMap
}
// fromAwsPlatformApplicationAttributes will convert from aws map to strongly typed map
func (s *SNS) fromAwsPlatformApplicationAttributes(attributes map[string]*string) (newMap map[snsplatformapplicationattribute.SNSPlatformApplicationAttribute]string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[snsplatformapplicationattribute.SNSPlatformApplicationAttribute]string)
var conv snsplatformapplicationattribute.SNSPlatformApplicationAttribute
for k, v := range attributes {
if util.LenTrim(k) > 0 {
v1 := aws.StringValue(v)
if k1, err := conv.ParseByKey(k); err == nil {
newMap[k1] = v1
}
}
}
return newMap
}
// toAwsEndpointAttributes will convert from strongly typed to aws accepted map
func (s *SNS) toAwsEndpointAttributes(attributes map[snsendpointattribute.SNSEndpointAttribute]string) (newMap map[string]*string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[string]*string)
for k, v := range attributes {
if k.Valid() && k != snsendpointattribute.UNKNOWN {
newMap[k.Key()] = aws.String(v)
}
}
return newMap
}
// fromAwsEndpointAttributes will convert from aws map to strongly typed map
func (s *SNS) fromAwsEndpointAttributes(attributes map[string]*string) (newMap map[snsendpointattribute.SNSEndpointAttribute]string) {
// validate
if attributes == nil {
return nil
}
// make map
newMap = make(map[snsendpointattribute.SNSEndpointAttribute]string)
var conv snsendpointattribute.SNSEndpointAttribute
for k, v := range attributes {
if util.LenTrim(k) > 0 {
v1 := aws.StringValue(v)
if k1, err := conv.ParseByKey(k); err == nil {
newMap[k1] = v1
}
}
}
return newMap
}
// ----------------------------------------------------------------------------------------------------------------
// topic methods
// ----------------------------------------------------------------------------------------------------------------
// CreateTopic will create a new topic in SNS for clients to subscribe,
// once topic is created, the topicArn is returned for subsequent uses
//
// Parameters:
// 1) topicName = required, the name of the topic to create in SNS
// 2) attributes = optional, topic attributes to further customize the topic
// 3) timeOutDuration = optional, indicates timeout value for context
//
// Topic Attributes: (Key = Expected Value)
// 1) DeliveryPolicy = The JSON serialization of the topic's delivery policy
// 2) DisplayName = The human-readable name used in the From field for notifications to email and email-json endpoints
// 3) Policy = The JSON serialization of the topic's access control policy
//
// The following attribute applies only to server-side-encryption (https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html):
// a) KmsMasterKeyId = The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK.
// For more information, see Key Terms (https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html#sse-key-terms)
// For more examples, see KeyId (https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestParameters) in the AWS Key Management Service API Reference
func (s *SNS) CreateTopic(topicName string, attributes map[snscreatetopicattribute.SNSCreateTopicAttribute]string, timeOutDuration ...time.Duration) (topicArn string, err error){
segCtx := context.Background()
segCtxSet := false
seg := xray.NewSegmentNullable("SNS-CreateTopic", s._parentSegment)
if seg != nil {
segCtx = seg.Ctx
segCtxSet = true
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("SNS-CreateTopic-TopicName", topicName)
_ = seg.Seg.AddMetadata("SNS-CreateTopic-Attributes", attributes)
_ = seg.Seg.AddMetadata("SNS-CreateTopic-Result-TopicArn", topicArn)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validation
if s.snsClient == nil {
err = errors.New("CreateTopic Failed: " + "SNS Client is Required")
return "", err
}
if util.LenTrim(topicName) <= 0 {
err = errors.New("CreateTopic Failed: " + "Topic Name is Required")
return "", err
}
// create input object
input := &sns.CreateTopicInput{
Name: aws.String(topicName),
}
if attributes != nil {
input.Attributes = s.toAwsCreateTopicAttributes(attributes)
}
// perform action
var output *sns.CreateTopicOutput
if len(timeOutDuration) > 0 {
ctx, cancel := context.WithTimeout(segCtx, timeOutDuration[0])
defer cancel()
output, err = s.snsClient.CreateTopicWithContext(ctx, input)
} else {
if segCtxSet {
output, err = s.snsClient.CreateTopicWithContext(segCtx, input)
} else {
output, err = s.snsClient.CreateTopic(input)
}
}
// evaluate result
if err != nil {
err = errors.New("CreateTopic Failed: (Create Action) " + err.Error())
return "", err
}
topicArn = *output.TopicArn
return topicArn, nil
}
// DeleteTopic will delete an existing SNS topic by topicArn,
// returns nil if successful
func (s *SNS) DeleteTopic(topicArn string, timeOutDuration ...time.Duration) (err error) {
segCtx := context.Background()
segCtxSet := false
seg := xray.NewSegmentNullable("SNS-DeleteTopic", s._parentSegment)
if seg != nil {
segCtx = seg.Ctx
segCtxSet = true
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("SNS-DeleteTopic-TopicArn", topicArn)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validation
if s.snsClient == nil {
err = errors.New("DeleteTopic Failed: " + "SNS Client is Required")
return err
}
if util.LenTrim(topicArn) <= 0 {
err = errors.New("DeleteTopic Failed: " + "Topic ARN is Required")
return err
}
// create input object
input := &sns.DeleteTopicInput{
TopicArn: aws.String(topicArn),
}
// perform action
if len(timeOutDuration) > 0 {
ctx, cancel := context.WithTimeout(segCtx, timeOutDuration[0])
defer cancel()
_, err = s.snsClient.DeleteTopicWithContext(ctx, input)
} else {
if segCtxSet {
_, err = s.snsClient.DeleteTopicWithContext(segCtx, input)
} else {
_, err = s.snsClient.DeleteTopic(input)
}
}
// evaluate result
if err != nil {
err = errors.New("DeleteTopic Failed: (Delete Action) " + err.Error())
return err
} else {
return nil
}
}
// ListTopics will list SNS topics, with optional nextToken for retrieving more list from a prior call
//
// Parameters:
// 1) nextToken = optional, if prior call returned more...token, pass in here to retrieve the related list
// 2) timeOutDuration = optional, indicates timeout value for context
//
// Return Values:
// 1) topicArnsList = string slice of topic ARNs, nil if not set
// 2) moreTopicArnsNextToken = if there are more topics, this token is filled, to query more, use the token as input parameter, blank if no more
// 3) err = error info if any
func (s *SNS) ListTopics(nextToken string, timeOutDuration ...time.Duration) (topicArnsList []string, moreTopicArnsNextToken string, err error) {
segCtx := context.Background()
segCtxSet := false
seg := xray.NewSegmentNullable("SNS-ListTopics", s._parentSegment)
if seg != nil {
segCtx = seg.Ctx
segCtxSet = true
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("SNS-ListTopics-NextToken", nextToken)
_ = seg.Seg.AddMetadata("SNS-ListTopics-Result-TopicArnsList", topicArnsList)
_ = seg.Seg.AddMetadata("SNS-ListTopics-Result-NextToken", moreTopicArnsNextToken)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validation
if s.snsClient == nil {
err = errors.New("ListTopics Failed: " + "SNS Client is Required")
return nil, "", err
}
// create input object
input := &sns.ListTopicsInput{}
if util.LenTrim(nextToken) > 0 {
input.NextToken = aws.String(nextToken)
}
// perform action
var output *sns.ListTopicsOutput
if len(timeOutDuration) > 0 {
ctx, cancel := context.WithTimeout(segCtx, timeOutDuration[0])
defer cancel()
output, err = s.snsClient.ListTopicsWithContext(ctx, input)
} else {
if segCtxSet {
output, err = s.snsClient.ListTopicsWithContext(segCtx, input)
} else {
output, err = s.snsClient.ListTopics(input)
}
}
// evaluate result
if err != nil {
err = errors.New("ListTopics Failed: (List Action) " + err.Error())
return nil, "", err
}
moreTopicArnsNextToken = aws.StringValue(output.NextToken)
for _, v := range output.Topics {
buf := aws.StringValue(v.TopicArn)
if util.LenTrim(buf) > 0 {
topicArnsList = append(topicArnsList, buf)
}
}
return topicArnsList, moreTopicArnsNextToken, nil
}
// GetTopicAttributes will retrieve a map of topic attributes based on topicArn
//
// Parameters:
// 1) topicArn = required, specify the topicArn to retrieve related topic attributes
// 2) timeOutDuration = optional, indicates timeout value for context
//
// Return Values:
// 1) attributes = map of sns get topic attributes key value pairs related to teh topic ARN being queried
// 2) err = error info if any
//
// Topic Attributes: (Key = Expected Value)
// 1) DeliveryPolicy = The JSON serialization of the topic's delivery policy (See Subscribe DeliveryPolicy Json Format)
// 2) DisplayName = The human-readable name used in the From field for notifications to email and email-json endpoints
// 3) Owner = The AWS account ID of the topic's owner
// 4) Policy = The JSON serialization of the topic's access control policy
// 5) SubscriptionsConfirmed = The number of confirmed subscriptions for the topic
// 6) SubscriptionsDeleted = The number of deleted subscriptions for the topic
// 7) SubscriptionsPending = The number of subscriptions pending confirmation for the topic
// 8) TopicArn = The topic's ARN
// 9) EffectiveDeliveryPolicy = Yhe JSON serialization of the effective delivery policy, taking system defaults into account
//
// The following attribute applies only to server-side-encryption (https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html):
// a) KmsMasterKeyId = The ID of an AWS-managed customer master key (CMK) for Amazon SNS or a custom CMK.
// For more information, see Key Terms (https://docs.aws.amazon.com/sns/latest/dg/sns-server-side-encryption.html#sse-key-terms)
// For more examples, see KeyId (https://docs.aws.amazon.com/kms/latest/APIReference/API_DescribeKey.html#API_DescribeKey_RequestParameters) in the AWS Key Management Service API Reference
func (s *SNS) GetTopicAttributes(topicArn string, timeOutDuration ...time.Duration) (attributes map[snsgettopicattribute.SNSGetTopicAttribute]string, err error) {
segCtx := context.Background()
segCtxSet := false
seg := xray.NewSegmentNullable("SNS-GetTopicAttributes", s._parentSegment)
if seg != nil {
segCtx = seg.Ctx
segCtxSet = true
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("SNS-GetTopicAttributes-TopicArn", topicArn)
_ = seg.Seg.AddMetadata("SNS-GetTopicAttributes-Result-Attributes", attributes)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validation
if s.snsClient == nil {
err = errors.New("GetTopicAttributes Failed: " + "SNS Client is Required")
return nil, err
}
if util.LenTrim(topicArn) <= 0 {
err = errors.New("GetTopicAttributes Failed: " + "Topic ARN is Required")
return nil, err
}
// create input object
input := &sns.GetTopicAttributesInput{
TopicArn: aws.String(topicArn),
}
// perform action
var output *sns.GetTopicAttributesOutput
if len(timeOutDuration) > 0 {
ctx, cancel := context.WithTimeout(segCtx, timeOutDuration[0])
defer cancel()
output, err = s.snsClient.GetTopicAttributesWithContext(ctx, input)
} else {
if segCtxSet {
output, err = s.snsClient.GetTopicAttributesWithContext(segCtx, input)
} else {
output, err = s.snsClient.GetTopicAttributes(input)
}
}
// evaluate result
if err != nil {
err = errors.New("GetTopicAttributes Failed: (Get Action) " + err.Error())
return nil, err
}
attributes = s.fromAwsGetTopicAttributes(output.Attributes)
return attributes, nil
}
// SetTopicAttribute will set or update a topic attribute,
// For attribute value or Json format, see corresponding notes in CreateTopic where applicable
func (s *SNS) SetTopicAttribute(topicArn string,
attributeName snscreatetopicattribute.SNSCreateTopicAttribute,
attributeValue string,
timeOutDuration ...time.Duration) (err error) {
segCtx := context.Background()
segCtxSet := false
seg := xray.NewSegmentNullable("SNS-SetTopicAttribute", s._parentSegment)
if seg != nil {
segCtx = seg.Ctx
segCtxSet = true
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("SNS-SetTopicAttribute-TopicArn", topicArn)
_ = seg.Seg.AddMetadata("SNS-SetTopicAttribute-AttributeName", attributeName)
_ = seg.Seg.AddMetadata("SNS-SetTopicAttribute-AttributeValue", attributeValue)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validation
if s.snsClient == nil {
err = errors.New("SetTopicAttribute Failed: " + "SNS Client is Required")
return err
}
if util.LenTrim(topicArn) <= 0 {
err = errors.New("SetTopicAttribute Failed: " + "Topic ARN is Required")
return err
}
if !attributeName.Valid() || attributeName == snscreatetopicattribute.UNKNOWN {
err = errors.New("SetTopicAttribute Failed: " + "Attribute Name is Required")
return err
}
// create input object
input := &sns.SetTopicAttributesInput{
TopicArn: aws.String(topicArn),
AttributeName: aws.String(attributeName.Key()),
AttributeValue: aws.String(attributeValue),
}
// perform action
if len(timeOutDuration) > 0 {
ctx, cancel := context.WithTimeout(segCtx, timeOutDuration[0])
defer cancel()
_, err = s.snsClient.SetTopicAttributesWithContext(ctx, input)
} else {
if segCtxSet {
_, err = s.snsClient.SetTopicAttributesWithContext(segCtx, input)
} else {
_, err = s.snsClient.SetTopicAttributes(input)
}
}
// evaluate result
if err != nil {
err = errors.New("SetTopicAttribute Failed: (Set Action) " + err.Error())
return err
} else {
return nil
}
}
// ----------------------------------------------------------------------------------------------------------------
// subscriber methods
// ----------------------------------------------------------------------------------------------------------------
// Subscribe will allow client to subscribe to a SNS topic (previously created with CreateTopic method),
// the subscriptionArn is returned upon success,
// if subscription needs client confirmation, then the string 'pending confirmation' is returned instead
//
// Parameters:
// 1) topicArn = required, subscribe to this topic ARN
// 2) protocol = required, SNS callback protocol, so that when publish to the topic occurs, this protocol is used as callback
// 3) endPoint = required, SNS callback endpoint, so that when publish to the topic occurs, this endpoint is triggered by the callback
// 4) attributes = optional, map of sns subscribe attribute key value pairs
// 5) timeOutDuration = optional, indicates timeout value for context
//
// Protocols: (Key = Expected Value)
// 1) http = delivery of JSON-encoded message via HTTP POST
// 2) https = delivery of JSON-encoded message via HTTPS POST
// 3) email = delivery of message via SMTP
// 4) email-json = delivery of JSON-encoded message via SMTP
// 5) sms = delivery of message via SMS
// 6) sqs = delivery of JSON-encoded message to an Amazon SQS queue
// 7) application = delivery of JSON-encoded message to an EndpointArn for a mobile app and device
// 8) lambda = delivery of JSON-encoded message to an Amazon Lambda function
//
// Endpoint To Receive Notifications: (Based on Protocol)
// 1) http protocol = the endpoint is an URL beginning with http://
// 2) https protocol = the endpoint is a URL beginning with https://
// 3) email protocol = the endpoint is an email address
// 4) email-json protocol = the endpoint is an email address
// 5) sms protocol = the endpoint is a phone number of an SMS-enabled device
// 6) sqs protocol = the endpoint is the ARN of an Amazon SQS queue
// 7) application protocol = the endpoint is the EndpointArn of a mobile app and device
// 8) lambda protocol = the endpoint is the ARN of an Amazon Lambda function
//
// Subscribe Attributes: (Key = Expected Value)
// 1) DeliveryPolicy = The policy that defines how Amazon SNS retries failed deliveries to HTTP/S endpoints
// *) example to set delivery policy to 5 retries:
// {
// "healthyRetryPolicy": {
// "minDelayTarget": <intValue>,
// "maxDelayTarget": <intValue>,
// "numRetries": <intValue>,
// "numMaxDelayRetries": <intValue>,
// "backoffFunction": "<linear|arithmetic|geometric|exponential>"
// },
// "throttlePolicy": {
// "maxReceivesPerSecond": <intValue>
// }
// }
// *) Not All Json Elements Need To Be Filled in Policy, Use What is Needed, such as:
// { "healthyRetryPolicy": { "numRetries": 5 } }
// 2) FilterPolicy = The simple JSON object that lets your subscriber receive only a subset of messages,
// rather than receiving every message published to the topic:
// *) subscriber attribute controls filter allowance,
// publish attribute indicates attributes contained in message
// *) if any single attribute in this policy doesn't match an attribute assigned to message, this policy rejects the message:
// {
// "store": ["example_corp"],
// "event": [{"anything-but": "order_cancelled"}],
// "customer_interests": ["rugby", "football", "baseball"],
// "price_usd": [{"numeric": [">=", 100]}]
// }
// *) "xyz": [{"anything-but": ...}] keyword indicates to match anything but the defined value ... Json element (... may be string or numeric)
// *) "xyz": [{"prefix": ...}] keyword indicates to match value prefixed from the defined value ... in Json element
// *) "xyz": [{"numeric": ["=", ...]}] keyword indicates numeric equal matching as indicated by numeric and =
// *) "xyz": [{"numeric": [">", ...]}] keyword indicates numeric compare matching as indicated by numeric and >, <, >=, <=
// *) "xyz": [{"numeric": [">", 0, "<", 100]}] keyword indicates numeric ranged compare matching as indicated by numeric and >, <, in parts
// *) "xyz": [{"exists": true}] keyword indicates attribute xyz exists matching
// 3) RawMessageDelivery = When set to true, enables raw message delivery to Amazon SQS or HTTP/S endpoints.
// This eliminates the need for the endpoints to process JSON formatting, which is otherwise created for Amazon SNS metadata
// 4) RedrivePolicy = When specified, sends undeliverable messages to the specified Amazon SQS dead-letter queue.
// Messages that can't be delivered due to client errors (for example, when the subscribed endpoint is unreachable),
// or server errors (for example, when the service that powers the subscribed endpoint becomes unavailable),
// are held in the dead-letter queue for further analysis or reprocessing
// *) example of RedrivePolicy to route failed messages to Dead Letter Queue (DLQ):
// {
// "deadLetterTargetArn": "dead letter sns queue arn such as arn:aws:sqs:us-east-2:12345678021:MyDeadLetterQueue"
// }
//
// Subscription Confirmation Support:
// 1) Http / Https Endpoints Requires Subscription Confirmation Support, See Details in URL Below:
// a) https://docs.aws.amazon.com/sns/latest/dg/sns-http-https-endpoint-as-subscriber.html
// 2) Once Subscribe action is performed, SNS sends confirmation notification to the HTTP/s Endpoint:
// b) Client Upon Receipt of the SNS Notification, Retrieve Token and Respond via ConfirmSubscription method
func (s *SNS) Subscribe(topicArn string,
protocol snsprotocol.SNSProtocol,
endPoint string,
attributes map[snssubscribeattribute.SNSSubscribeAttribute]string,
timeOutDuration ...time.Duration) (subscriptionArn string, err error) {
segCtx := context.Background()
segCtxSet := false
seg := xray.NewSegmentNullable("SNS-Subscribe", s._parentSegment)
if seg != nil {
segCtx = seg.Ctx
segCtxSet = true
defer seg.Close()
defer func() {
_ = seg.Seg.AddMetadata("SNS-Subscribe-TopicArn", topicArn)
_ = seg.Seg.AddMetadata("SNS-Subscribe-Protocol", protocol)
_ = seg.Seg.AddMetadata("SNS-Subscribe-Endpoint", endPoint)
_ = seg.Seg.AddMetadata("SNS-Subscribe-Attributes", attributes)
_ = seg.Seg.AddMetadata("SNS-Subscribe-Result-SubscriptionArn", subscriptionArn)
if err != nil {
_ = seg.Seg.AddError(err)
}
}()
}
// validation
if s.snsClient == nil {
err = errors.New("Subscribe Failed: " + "SNS Client is Required")
return "", err
}
if util.LenTrim(topicArn) <= 0 {
err = errors.New("Subscribe Failed: " + "Topic ARN is Required")
return "", err
}
if !protocol.Valid() || protocol == snsprotocol.UNKNOWN {
err = errors.New("Subscribe Failed: " + "Protocol is Required")
return "", err
}
if util.LenTrim(endPoint) <= 0 {
err = errors.New("Subscribe Failed: " + "Endpoint is Required")
return "", err
}
// create input object
input := &sns.SubscribeInput{
TopicArn: aws.String(topicArn),
Protocol: aws.String(protocol.Key()),
Endpoint: aws.String(endPoint),
}
if attributes != nil {
input.Attributes = s.toAwsSubscribeAttributes(attributes)
}
// perform action
var output *sns.SubscribeOutput
if len(timeOutDuration) > 0 {
ctx, cancel := context.WithTimeout(segCtx, timeOutDuration[0])
defer cancel()
output, err = s.snsClient.SubscribeWithContext(ctx, input)
} else {