-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
271 lines (237 loc) · 7.02 KB
/
main.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
package streamsurfer
import (
"context"
"encoding/json"
"fmt"
"strings"
"sync"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/service/kinesis"
"github.com/golang-collections/go-datastructures/queue"
"github.com/google/uuid"
)
type KinesisQueue struct {
q *queue.Queue
maxSizeBytes int
currentSize int
lock *sync.RWMutex
kinesisClient *kinesis.Client
streamName string
streamArn string
originApp string
}
// New creates a new KinesisQueue for sending messages in a batch to a Kinesis stream.
//
// Parameters:
//
// streamName: the name of the Kinesis stream to send messages to.
//
// Returns:
//
// *KinesisQueue: a pointer to the newly created KinesisQueue.
// error: an error, if any occurred during the creation.
func New(streamName string) (*KinesisQueue, error) {
return NewWithOpts(streamName, "sa-east-1", 1024, "", "")
}
// NewWithOrigin creates a new KinesisQueue for sending messages in a batch to a Kinesis stream.
//
// Parameters:
//
// streamName: the name of the Kinesis stream to send messages to.
// origin: the app name that will be used to identify the origin of the messages.
//
// Returns:
//
// *KinesisQueue: a pointer to the newly created KinesisQueue.
// error: an error, if any occurred during the creation.
func NewWithOrigin(streamName string, origin string) (*KinesisQueue, error) {
return NewWithOpts(streamName, "sa-east-1", 1024, origin, "")
}
// NewWithStreamArn creates a new KinesisQueue for sending messages in a batch to a Kinesis stream
// using the stream ARN. This method is useful to send messages to a stream in a different account.
//
// Parameters:
//
// streamArn: the arn of the Kinesis stream to send messages to.
// origin: the app name that will be used to identify the origin of the messages.
//
// Returns:
//
// *KinesisQueue: a pointer to the newly created KinesisQueue.
// error: an error, if any occurred during the creation.
func NewWithStreamArn(streamArn, origin string) (*KinesisQueue, error) {
if streamArn == "" {
return &KinesisQueue{}, fmt.Errorf("streamArn must be provided")
}
streamName, err := extractStreamNameFromARN(streamArn)
if err != nil {
return &KinesisQueue{}, err
}
return NewWithOpts(streamName, "sa-east-1", 1024, origin, streamArn)
}
func extractStreamNameFromARN(arn string) (string, error) {
parts := strings.Split(arn, "/")
if len(parts) != 2 {
return "", fmt.Errorf("invalid ARN format")
}
return parts[1], nil
}
// NewWithOpts creates a new KinesisQueue for sending messages in a batch to a Kinesis stream.
//
// Parameters:
//
// streamName: the name of the Kinesis stream to send messages to.
// region: the aws region. The default is sa-east-1.
// maxSizeKB: the maximum size in kilobytes for the batch.
// origin: the app name that will be used to identify the origin of the messages.
// streamArn: the ARN of the Kinesis stream to send messages to.
//
// Returns:
//
// *KinesisQueue: a pointer to the newly created KinesisQueue.
// error: an error, if any occurred during the creation.
func NewWithOpts(streamName string, region string, maxSizeKB int, origin string, streamArn string) (*KinesisQueue, error) {
if streamName == "" {
return &KinesisQueue{}, fmt.Errorf("streamName must be provided")
}
if region == "" {
region = "sa-east-1"
}
if maxSizeKB == 0 {
return &KinesisQueue{}, fmt.Errorf("maxSizeKB must be provided")
}
kinesisClient, err := connectToKinesis(region)
if err != nil {
return &KinesisQueue{}, err
}
q := &KinesisQueue{
q: queue.New(0),
maxSizeBytes: maxSizeKB,
lock: &sync.RWMutex{},
kinesisClient: kinesisClient,
streamName: streamName,
originApp: origin,
streamArn: streamArn,
}
return q, nil
}
func connectToKinesis(awsRegion string) (*kinesis.Client, error) {
if awsRegion == "" {
awsRegion = "sa-east-1"
}
cfg, err := config.LoadDefaultConfig(context.Background(),
config.WithRetryMaxAttempts(5),
config.WithRegion(awsRegion))
if err != nil {
return &kinesis.Client{}, err
}
return kinesis.NewFromConfig(cfg), nil
}
// Enqueue adds a new data item to the KinesisQueue for batch processing.
//
// Parameters:
//
// data: a map containing the data to be enqueued. It must include an "event" field as a string.
//
// Returns:
//
// error: an error, if any occurred during the enqueue process.
func (q *KinesisQueue) Enqueue(data map[string]interface{}) error {
if _, ok := data["event"].(string); !ok {
return fmt.Errorf("event field is required")
}
q.lock.Lock()
defer q.lock.Unlock()
// Add server timestamp to every event
currentTime := time.Now().UTC()
formattedTime := currentTime.Format("2006-01-02T15:04:05.999Z")
data["server_timestamp"] = formattedTime
// When origin available, add it to the data
if q.originApp != "" {
data["origin"] = q.originApp
}
dataBytes, _ := json.Marshal(data)
itemSize := len(dataBytes)
if q.currentSize+itemSize >= q.maxSizeBytes {
_, err := q.flush()
if err != nil {
return err
}
}
err := q.q.Put(data)
if err != nil {
return err
}
q.currentSize += itemSize
return nil
}
func (q *KinesisQueue) flush() ([]any, error) {
var items []interface{}
for q.currentSize > 0 {
if val, err := q.q.Get(1); err == nil {
items = append(items, val[0])
itemBytes, _ := json.Marshal(val[0])
itemSize := len(itemBytes)
q.currentSize = q.currentSize - itemSize
}
}
if len(items) > 0 {
data, err := q.sendToKinesis(items)
if err != nil {
return data, err
}
}
return nil, nil
}
// Flush sends the accumulated items in the KinesisQueue to the Kinesis stream.
//
// This method locks the KinesisQueue, processes the items, and sends them to the Kinesis stream.
// The items are retrieved from the queue and marshaled into JSON before being sent to Kinesis.
// If there are items in the queue, they are sent to Kinesis using the sendToKinesis method.
//
// Returns:
//
// []interface{}: a slice of items that were sent to Kinesis.
// error: an error, if any occurred during the flushing process.
func (q *KinesisQueue) Flush() ([]any, error) {
q.lock.Lock()
defer q.lock.Unlock()
var items []interface{}
for q.currentSize > 0 {
if val, err := q.q.Get(1); err == nil {
items = append(items, val[0])
itemBytes, _ := json.Marshal(val[0])
itemSize := len(itemBytes)
q.currentSize = q.currentSize - itemSize
}
}
if len(items) > 0 {
data, err := q.sendToKinesis(items)
if err != nil {
return data, err
}
}
return nil, nil
}
func (q *KinesisQueue) sendToKinesis(data []any) ([]any, error) {
itemBytes, err := json.Marshal(data)
if err != nil {
return data, err
}
putRecord := kinesis.PutRecordInput{
Data: itemBytes,
StreamName: &q.streamName,
PartitionKey: aws.String(uuid.New().String()),
}
// When streamArn available, add it to the record input
if q.streamArn != "" {
putRecord.StreamARN = &q.streamArn
}
_, err = q.kinesisClient.PutRecord(context.TODO(), &putRecord)
if err != nil {
return data, fmt.Errorf("failed to put record to kinesis: %v", err)
}
return nil, nil
}