/
send_aws_dynamodb.go
202 lines (162 loc) · 5.28 KB
/
send_aws_dynamodb.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
package transform
import (
"context"
"encoding/json"
"fmt"
"sync"
"github.com/aws/aws-sdk-go/service/dynamodb"
"github.com/aws/aws-sdk-go/service/dynamodb/dynamodbattribute"
"github.com/brexhq/substation/config"
"github.com/brexhq/substation/internal/aggregate"
"github.com/brexhq/substation/internal/aws"
idynamodb "github.com/brexhq/substation/internal/aws/dynamodb"
iconfig "github.com/brexhq/substation/internal/config"
"github.com/brexhq/substation/internal/errors"
"github.com/brexhq/substation/message"
)
// Items greater than 400 KB in size cannot be put into DynamoDB.
const sendAWSDynamoDBItemSizeLimit = 1024 * 400
// errSendAWSDynamoDBItemSizeLimit is returned when data exceeds the
// DynamoDB item size limit. If this error occurs, then drop or reduce
// the size of the data before attempting to write it to DynamoDB.
var errSendAWSDynamoDBItemSizeLimit = fmt.Errorf("data exceeded size limit")
// errSendAWSDynamoDBNonObject is returned when non-object data is sent to the transform.
//
// If this error occurs, then parse the data into an object (or drop invalid objects)
// before attempting to send the data.
var errSendAWSDynamoDBNonObject = fmt.Errorf("input must be object")
type sendAWSDynamoDBConfig struct {
// TableName is the DynamoDB table that items are written to.
TableName string `json:"table_name"`
// AuxTransforms are applied to batched data before it is sent.
AuxTransforms []config.Config `json:"auxiliary_transforms"`
Object iconfig.Object `json:"object"`
Batch iconfig.Batch `json:"batch"`
AWS iconfig.AWS `json:"aws"`
Retry iconfig.Retry `json:"retry"`
}
func (c *sendAWSDynamoDBConfig) Decode(in interface{}) error {
return iconfig.Decode(in, c)
}
func (c *sendAWSDynamoDBConfig) Validate() error {
if c.TableName == "" {
return fmt.Errorf("table_name: %v", errors.ErrMissingRequiredOption)
}
return nil
}
func newSendAWSDynamoDB(_ context.Context, cfg config.Config) (*sendAWSDynamoDB, error) {
conf := sendAWSDynamoDBConfig{}
if err := conf.Decode(cfg.Settings); err != nil {
return nil, fmt.Errorf("transform: send_aws_dynamodb: %v", err)
}
if err := conf.Validate(); err != nil {
return nil, fmt.Errorf("transform: send_aws_dynamodb: %v", err)
}
if conf.Object.SourceKey == "" {
conf.Object.SourceKey = "@this"
}
tf := sendAWSDynamoDB{
conf: conf,
}
tf.client.Setup(aws.Config{
Region: conf.AWS.Region,
RoleARN: conf.AWS.RoleARN,
MaxRetries: conf.Retry.Count,
RetryableErrors: conf.Retry.ErrorMessages,
})
agg, err := aggregate.New(aggregate.Config{
// DynamoDB limits batch operations to 25 records and 16 MiB.
Count: 25,
Size: 1000 * 1000 * 16,
Duration: conf.Batch.Duration,
})
if err != nil {
return nil, err
}
tf.agg = agg
if len(conf.AuxTransforms) > 0 {
tf.tforms = make([]Transformer, len(conf.AuxTransforms))
for i, c := range conf.AuxTransforms {
t, err := New(context.Background(), c)
if err != nil {
return nil, fmt.Errorf("transform: send_aws_kinesis_data_firehose: %v", err)
}
tf.tforms[i] = t
}
}
return &tf, nil
}
type sendAWSDynamoDB struct {
conf sendAWSDynamoDBConfig
// client is safe for concurrent use.
client idynamodb.API
mu sync.Mutex
agg *aggregate.Aggregate
tforms []Transformer
}
func (tf *sendAWSDynamoDB) Transform(ctx context.Context, msg *message.Message) ([]*message.Message, error) {
tf.mu.Lock()
defer tf.mu.Unlock()
if msg.IsControl() {
for key := range tf.agg.GetAll() {
if tf.agg.Count(key) == 0 {
continue
}
if err := tf.send(ctx, key); err != nil {
return nil, fmt.Errorf("transform: send_aws_dynamodb: %v", err)
}
}
tf.agg.ResetAll()
return []*message.Message{msg}, nil
}
if !json.Valid(msg.Data()) {
return nil, fmt.Errorf("transform: send_aws_dynamodb: %v", errSendAWSDynamoDBNonObject)
}
value := msg.GetValue(tf.conf.Object.SourceKey)
if !value.Exists() {
return []*message.Message{msg}, nil
}
if len(value.Bytes()) > sendAWSDynamoDBItemSizeLimit {
return nil, fmt.Errorf("transform: send_aws_dynamodb: %v", errSendAWSDynamoDBItemSizeLimit)
}
// If this value does not exist, then all data is batched together.
key := msg.GetValue(tf.conf.Object.BatchKey).String()
if ok := tf.agg.Add(key, msg.Data()); ok {
return []*message.Message{msg}, nil
}
if err := tf.send(ctx, key); err != nil {
return nil, fmt.Errorf("transform: send_aws_dynamodb: %v", err)
}
// If data cannot be added after reset, then the batch is misconfgured.
tf.agg.Reset(key)
if ok := tf.agg.Add(key, msg.Data()); !ok {
return nil, fmt.Errorf("transform: send_aws_dynamodb: %v", errSendBatchMisconfigured)
}
return []*message.Message{msg}, nil
}
func (tf *sendAWSDynamoDB) String() string {
b, _ := json.Marshal(tf.conf)
return string(b)
}
func (tf *sendAWSDynamoDB) send(ctx context.Context, key string) error {
data, err := withTransforms(ctx, tf.tforms, tf.agg.Get(key))
if err != nil {
return err
}
var items []map[string]*dynamodb.AttributeValue
for _, b := range data {
m := make(map[string]any)
for k, v := range bytesToValue(b).Map() {
m[k] = v.Value()
}
i, err := dynamodbattribute.MarshalMap(m)
if err != nil {
return err
}
items = append(items, i)
}
if _, err := tf.client.BatchPutItem(ctx, tf.conf.TableName, items); err != nil {
return err
}
return nil
}