/
client.go
182 lines (155 loc) · 5.28 KB
/
client.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
package sqs
import (
"context"
"encoding/json"
"regexp"
"strings"
"fmt"
"strconv"
fthealth "github.com/Financial-Times/go-fthealth/v1_1"
"github.com/Financial-Times/go-logger"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sqs"
)
var keyMatcher = regexp.MustCompile("^[0-9a-f]{8}/[0-9a-f]{4}/[0-9a-f]{4}/[0-9a-f]{4}/[0-9a-f]{12}$")
type Client interface {
ListenAndServeQueue(ctx context.Context) []ConceptUpdate
SendEvents(ctx context.Context, messages []Event) error
RemoveMessageFromQueue(ctx context.Context, receiptHandle *string) error
Healthcheck() fthealth.Check
}
type NotificationClient struct {
sqs *sqs.SQS
listenParams sqs.ReceiveMessageInput
queueUrl string
}
func NewClient(awsRegion string, queueUrl string, messagesToProcess int, visibilityTimeout int, waitTime int) (Client, error) {
if queueUrl == "" {
return &NotificationClient{
queueUrl: queueUrl,
}, nil
}
listenParams := sqs.ReceiveMessageInput{
QueueUrl: aws.String(queueUrl),
MaxNumberOfMessages: aws.Int64(int64(messagesToProcess)),
VisibilityTimeout: aws.Int64(int64(visibilityTimeout)),
WaitTimeSeconds: aws.Int64(int64(waitTime)),
}
sess, err := session.NewSession(&aws.Config{
Region: aws.String(awsRegion),
MaxRetries: aws.Int(3),
})
if err != nil {
logger.WithError(err).Error("Unable to create an SQS client")
return &NotificationClient{}, err
}
client := sqs.New(sess)
return &NotificationClient{
sqs: client,
listenParams: listenParams,
queueUrl: queueUrl,
}, err
}
func (c *NotificationClient) ListenAndServeQueue(ctx context.Context) []ConceptUpdate {
messages, err := c.sqs.ReceiveMessageWithContext(ctx, &c.listenParams)
if err != nil {
logger.WithError(err).Error("Error whilst listening for messages")
}
return getNotificationsFromMessages(messages.Messages)
}
func (c *NotificationClient) SendEvents(ctx context.Context, messages []Event) error {
if c.queueUrl == "" {
return nil
}
var entries []*sqs.SendMessageBatchRequestEntry
for i, msg := range messages {
jsonBytes, _ := json.Marshal(msg)
entries = append(entries, &sqs.SendMessageBatchRequestEntry{
MessageBody: aws.String(string(jsonBytes)),
Id: aws.String(string(msg.ConceptUUID + "_" + strconv.Itoa(i))),
})
}
input := &sqs.SendMessageBatchInput{
QueueUrl: aws.String(c.queueUrl),
Entries: entries,
}
output, err := c.sqs.SendMessageBatchWithContext(ctx, input)
if err != nil {
if _, ok := err.(awserr.Error); ok {
// We've got an AWS error, so handle accordingly.
logger.WithError(err.(awserr.Error).OrigErr()).Errorf("SQS send error: %s", err.(awserr.Error).Message())
return err.(awserr.Error).OrigErr()
}
return err
}
for _, v := range output.Failed {
logger.WithError(fmt.Errorf("SQS Error Code %d", v.Code)).Error(*v.Message)
}
return nil
}
func (c *NotificationClient) RemoveMessageFromQueue(ctx context.Context, receiptHandle *string) error {
deleteParams := sqs.DeleteMessageInput{
QueueUrl: aws.String(c.queueUrl),
ReceiptHandle: receiptHandle,
}
if _, err := c.sqs.DeleteMessageWithContext(ctx, &deleteParams); err != nil {
logger.WithError(err).Error("Error deleting message from SQS")
return err
}
return nil
}
func getNotificationsFromMessages(messages []*sqs.Message) []ConceptUpdate {
notifications := []ConceptUpdate{}
for _, message := range messages {
var err error
receiptHandle := message.ReceiptHandle
messageBody := Body{}
if err = json.Unmarshal([]byte(*message.Body), &messageBody); err != nil {
logger.WithError(err).Error("Failed to unmarshal SQS message")
continue
}
msgRecord := Message{}
if err = json.Unmarshal([]byte(messageBody.Message), &msgRecord); err != nil {
logger.WithError(err).Error("Failed to unmarshal S3 notification")
continue
}
if msgRecord.Records == nil {
logger.Error("Cannot map message to expected JSON format - skipping")
continue
}
key := msgRecord.Records[0].S3.Object.Key
if keyMatcher.MatchString(key) != true {
logger.WithField("key", key).Error("Key in message is not a valid UUID")
continue
}
bookmark := msgRecord.Records[0].Bookmark
notifications = append(notifications, ConceptUpdate{
UUID: strings.Replace(key, "/", "-", 4),
Bookmark: bookmark, //no need to verify via regex, because neo4j might change the pattern..
ReceiptHandle: receiptHandle,
})
}
return notifications
}
func (c *NotificationClient) Healthcheck() fthealth.Check {
return fthealth.Check{
BusinessImpact: "Editorial updates of concepts will not be written into UPP",
Name: "Check connectivity to SQS queue",
PanicGuide: "https://runbooks.in.ft.com/aggregate-concept-transformer",
Severity: 3,
TechnicalSummary: `Cannot connect to SQS queue. If this check fails, check that Amazon SQS is available`,
Checker: func() (string, error) {
params := &sqs.GetQueueAttributesInput{
QueueUrl: aws.String(c.queueUrl),
AttributeNames: []*string{aws.String("ApproximateNumberOfMessages")},
}
if _, err := c.sqs.GetQueueAttributes(params); err != nil {
logger.WithError(err).Error("Got error running SQS health check")
return "", err
}
return "", nil
},
}
}