/
aws.go
293 lines (252 loc) · 8.82 KB
/
aws.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
package aws
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sns"
"github.com/aws/aws-sdk-go/service/sqs"
"github.com/aws/aws-sdk-go/service/sqs/sqsiface"
"github.com/google/uuid"
"github.com/Orange-Health/pubsublib/helper"
"github.com/Orange-Health/pubsublib/infrastructure"
)
type AWSPubSubAdapter struct {
session *session.Session
snsSvc *sns.SNS
sqsSvc sqsiface.SQSAPI
redisClient *infrastructure.RedisDatabase
}
func NewAWSPubSubAdapter(region, accessKeyId, secretAccessKey, snsEndpoint, redisAddress, redisPassword string, redisDB, redisPoolSize, redisMinIdleConn int) (*AWSPubSubAdapter, error) {
sess, err := session.NewSession(&aws.Config{
Region: aws.String(region),
Endpoint: aws.String(snsEndpoint),
Credentials: credentials.NewStaticCredentials(
accessKeyId,
secretAccessKey,
"", // a token will be created when the session it's used.
),
})
if err != nil {
return nil, err
}
snsSvc := sns.New(sess)
sqsSvc := sqs.New(sess)
redisClient, err := infrastructure.NewRedisDatabase(redisAddress, redisPassword, redisDB, redisPoolSize, redisMinIdleConn)
if err != nil {
return nil, err
}
return &AWSPubSubAdapter{
session: sess,
snsSvc: snsSvc,
sqsSvc: sqsSvc,
redisClient: redisClient,
}, nil
}
/*
Publishes the message with the messageAttributes to the topicARN provided.
source, contains and eventType are necessary keys in messageAttributes.
Returns error if fails to publish message
When the SNS Topic is FIFO type, messageGroupId and messageDeduplicationId are required.
- messageGroupId : SNS orders the messages in a message group into a sequence.
- messageDeduplicationId : SNS uses this to determine whether to create a new message or to use an existing one.
*/
func (ps *AWSPubSubAdapter) Publish(topicARN string, messageGroupId, messageDeduplicationId string, message interface{}, messageAttributes map[string]interface{}) error {
// Check if message is of type map[string]interface{} and then convert all the keys to snake_case
switch message.(type) {
case map[string]interface{}:
message = helper.ConvertBodyToSnakeCase(message.(map[string]interface{}))
}
jsonString, err := json.Marshal(message)
if err != nil {
return err
}
// figure out the message body as required
messageBody := string(jsonString)
if len(messageBody) > 200*1024 {
// body is larger than 200kB. Best to put it in redis with expiry time of 10 days
redisKey := uuid.New().String()
messageAttributes["redis_key"] = redisKey
// Set the message body in redis db
err = ps.redisClient.Set(redisKey, messageBody, 2*60)
if err != nil {
return err
}
messageBody = "body is stored in redis under key PUBSUB:" + redisKey
}
if messageAttributes["source"] == nil {
return fmt.Errorf("should have source key in messageAttributes")
}
if messageAttributes["contains"] == nil {
return fmt.Errorf("should have contains key in messageAttributes")
}
if messageAttributes["event_type"] == nil {
return fmt.Errorf("should have event_type key in messageAttributes")
}
if messageAttributes["trace_id"] == nil {
messageAttributes["trace_id"] = uuid.New().String()
}
awsMessageAttributes := map[string]*sns.MessageAttributeValue{}
if messageAttributes != nil {
awsMessageAttributes, _ = BindAttributes(messageAttributes)
}
pubslishMessage := &sns.PublishInput{
Message: aws.String(messageBody), // Ensures to always send compressed message
TopicArn: aws.String(topicARN),
MessageAttributes: awsMessageAttributes,
}
if messageGroupId != "" {
pubslishMessage.MessageGroupId = aws.String(messageGroupId)
}
if messageDeduplicationId != "" {
pubslishMessage.MessageDeduplicationId = aws.String(messageDeduplicationId)
}
_, err = ps.snsSvc.Publish(pubslishMessage)
if err != nil {
return err
}
return nil
}
/*
Polls messages from SQS with queueURL, using long polling for 20 seconds, visibility timeout of 5 seconds and maximum of 10 messages read at once.
Handler func will be executed for each message individually, if error returned from the handler func is nil, message is deleted from queue, else returns error
*/
func (ps *AWSPubSubAdapter) PollMessages(queueURL string, handler func(message *sqs.Message) error) error {
result, err := ps.sqsSvc.ReceiveMessage(&sqs.ReceiveMessageInput{
QueueUrl: aws.String(queueURL),
MaxNumberOfMessages: aws.Int64(10),
VisibilityTimeout: aws.Int64(5),
WaitTimeSeconds: aws.Int64(20),
MessageAttributeNames: []*string{
aws.String("All"),
},
AttributeNames: []*string{
aws.String("All"),
},
})
if err != nil {
return err
}
for _, message := range result.Messages {
// Verify the message integrity
if !verifyMessageIntegrity(*message.Body, *message.MD5OfBody) {
return fmt.Errorf("message corrupted")
}
if redisKey, ok := message.MessageAttributes["redis_key"]; ok {
if messageBody, err := ps.FetchValueFromRedis(*redisKey.StringValue); err != nil {
return err
} else {
message.Body = aws.String(messageBody)
}
}
err = handler(message)
if err != nil {
return err
}
_, err = ps.sqsSvc.DeleteMessage(&sqs.DeleteMessageInput{
QueueUrl: aws.String(queueURL),
ReceiptHandle: message.ReceiptHandle,
})
if err != nil {
return err
}
}
return nil
}
// Expects the redis key (uuid), fetches the value from redis and returns it as string always. Since all values are stored as string in redis for now.
func (ps *AWSPubSubAdapter) FetchValueFromRedis(redisKey string) (string, error) {
var messageBody string
err := ps.redisClient.Get(redisKey, &messageBody)
if err != nil {
return "", err
}
return messageBody, nil
}
// not using this for v1
// func (ps *AWSPubSubAdapter) Subscribe(topicARN string, handler func(message string) error) error {
// subscribeOutput, err := ps.snsSvc.Subscribe(&sns.SubscribeInput{
// Protocol: aws.String("sqs"),
// Endpoint: aws.String(topicARN),
// TopicArn: aws.String(topicARN),
// })
// if err != nil {
// return err
// }
// subscriptionARN := *subscribeOutput.SubscriptionArn
// go ps.PollMessages(topicARN, handler)
// // Wait for termination signals to unsubscribe and cleanup
// ps.waitForTermination(topicARN, &subscriptionARN)
// return nil
// }
// func (ps *AWSPubSubAdapter) waitForTermination(topicARN string, subscriptionARN *string) {
// sigCh := make(chan os.Signal, 1)
// signal.Notify(sigCh, os.Interrupt, syscall.SIGTERM)
// <-sigCh // Wait for termination signal
// // Unsubscribe from the topic
// _, err := ps.snsSvc.Unsubscribe(&sns.UnsubscribeInput{
// SubscriptionArn: subscriptionARN,
// })
// if err != nil {
// log.Println("Error unsubscribing from the topic:", err)
// }
// // Delete the SQS queue
// _, err = ps.sqsSvc.DeleteQueue(&sqs.DeleteQueueInput{
// QueueUrl: aws.String(topicARN),
// })
// if err != nil {
// log.Println("Error deleting the queue:", err)
// }
// os.Exit(0) // Terminate the program
// }
func BindAttributes(attributes map[string]interface{}) (map[string]*sns.MessageAttributeValue, error) {
boundAttributes := make(map[string]*sns.MessageAttributeValue)
for key, value := range attributes {
attrValue, _ := convertToAttributeValue(value)
boundAttributes[key] = attrValue
}
return boundAttributes, nil
}
func convertToAttributeValue(value interface{}) (*sns.MessageAttributeValue, error) {
// Perform type assertions or conversions based on the expected types of attributes
// and create the appropriate sns.MessageAttributeValue object.
switch v := value.(type) {
case string:
return &sns.MessageAttributeValue{
DataType: aws.String("String"),
StringValue: aws.String(v),
}, nil
case int, int32, int64, uint, uint8, uint16, uint32, uint64, float32, float64:
return &sns.MessageAttributeValue{
DataType: aws.String("Number"),
StringValue: aws.String(fmt.Sprint(v)),
}, nil
case []string:
return &sns.MessageAttributeValue{
DataType: aws.String("String.Array"),
StringValue: aws.String(strings.Join(v, ",")),
}, nil
// Add more cases for other data types as needed
default:
return nil, fmt.Errorf("unsupported attribute value type: %T", value)
}
}
/*
Compares the calculated MD5 hashes with the received MD5 hashes.
If the MD5 hashes match, the message is not corrupted hence returns true
*/
func verifyMessageIntegrity(messageBody, md5OfBody string) bool {
// Calculate the MD5 hash of the message body
calculatedMD5OfBody := calculateMD5Hash(messageBody)
// Compare the calculated MD5 hashes with the received MD5 hashes
return calculatedMD5OfBody == md5OfBody
}
// Calculates the MD5 hash of the data passed
func calculateMD5Hash(data string) string {
hasher := md5.New()
hasher.Write([]byte(data))
return hex.EncodeToString(hasher.Sum(nil))
}