forked from segmentio/analytics-go
/
s3client.go
295 lines (244 loc) · 6.8 KB
/
s3client.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
package analytics
import (
"bytes"
"compress/gzip"
"encoding/json"
"fmt"
"io"
"sync"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
)
type s3Client struct {
*client
config S3ClientConfig
apiContext *apiContext
uploader *s3manager.Uploader
}
// S3 is a configuration for s3Client.
type S3 struct {
Bucket string
Stage string
// Stream is an arbitrary name of the stream where messages will be delivered.
// Examples: tuna, salmon, haring, etc. Each system receives its own stream.
Stream string
MaxBatchBytes int
KeyConstructor func(now func() Time, uid func() string) string
UploaderOptions []func(*s3manager.Uploader)
}
// S3ClientConfig provides configuration for S3 Client.
type S3ClientConfig struct {
Config
S3 S3
}
// NewS3ClientWithConfig creates S3 client from provided configuration.
// Pass empty S3ClientConfig{} to use default config.
func NewS3ClientWithConfig(config S3ClientConfig) (Client, error) {
cfg, err := makeS3ClientConfig(config)
if err != nil {
return nil, err
}
client, err := newWithConfig("", cfg.Config)
if err != nil {
return nil, err
}
sess := session.Must(session.NewSession())
uploader := s3manager.NewUploader(sess, cfg.S3.UploaderOptions...)
c := &s3Client{
client: client,
config: cfg,
apiContext: &apiContext{
APIID: uid(),
Stage: cfg.S3.Stage,
},
uploader: uploader,
}
go c.loop() // custom implementation
go c.loopMetrics() // reuse client's implementation
return c, nil
}
// a copy of client.loop() function.
func (c *s3Client) loop() {
defer close(c.shutdown)
wg := &sync.WaitGroup{}
defer wg.Wait()
tick := time.NewTicker(c.Interval)
defer tick.Stop()
ex := newExecutor(c.maxConcurrentRequests)
defer ex.close()
mq := messageQueue{
maxBatchSize: c.BatchSize,
maxBatchBytes: c.config.S3.MaxBatchBytes,
}
for {
select {
case msg := <-c.msgs:
c.push(&mq, msg, wg, ex)
case <-tick.C:
c.flush(&mq, wg, ex)
case <-c.quit:
c.debugf("exit requested – draining messages")
// Drain the msg channel, we have to close it first so no more
// messages can be pushed and otherwise the loop would never end.
close(c.msgs)
for msg := range c.msgs {
c.push(&mq, msg, wg, ex)
}
c.flush(&mq, wg, ex)
c.debugf("exit")
return
}
}
}
func (c *s3Client) push(q *messageQueue, m Message, wg *sync.WaitGroup, ex *executor) {
var msg message
var err error
if msg, err = makeTargetMessage(m, maxMessageBytes, c.apiContext, c.now); err != nil {
c.errorf("%s - %v", err, m)
c.notifyFailure([]message{msg}, err)
return
}
c.debugf("buffer (%d/%d) %v", len(q.pending), c.BatchSize, m)
if msgs := q.push(msg); msgs != nil {
c.debugf("exceeded messages batch limit with batch of %d messages – flushing", len(msgs))
c.sendAsync(msgs, wg, ex)
}
}
type apiContext struct {
APIID string `json:"apiId,omitempty"`
RequestID string `json:"requestId,omitempty"`
ResourcePath string `json:"resourcePath,omitempty"`
Stage string `json:"stage,omitempty"`
}
// targetMessage is a single non-batched message delivered to s3 in one row of json.
type targetMessage struct {
APIContext *apiContext `json:"context,omitempty"`
Event Message `json:"event"`
SentAt Time `json:"sentAt"`
ReceivedAt Time `json:"receivedAt"`
json []byte
}
func (m *targetMessage) MarshalJSON() ([]byte, error) {
return m.json, nil
}
func (m *targetMessage) Msg() Message {
return m.Event
}
func (m *targetMessage) size() int {
return len(m.json)
}
// makeTargetMessage constructs targetMessage instance.
func makeTargetMessage(m Message, maxBytes int, apiContext *apiContext, now func() Time) (message, error) {
ts := now()
result := targetMessage{
APIContext: apiContext,
Event: m,
SentAt: ts,
ReceivedAt: ts,
}
type alias targetMessage
b, err := json.Marshal(alias(result))
if err != nil {
return &result, err
}
if len(b) > maxBytes {
return &result, ErrMessageTooBig
}
result.json = b
return &result, nil
}
// Asychronously send a batched requests.
func (c *s3Client) sendAsync(msgs []message, wg *sync.WaitGroup, ex *executor) {
wg.Add(1)
if !ex.do(func() {
defer wg.Done()
defer func() {
// In case a bug is introduced in the send function that triggers
// a panic, we don't want this to ever crash the application so we
// catch it here and log it instead.
if err := recover(); err != nil {
c.errorf("panic - %s", err)
}
}()
c.send(msgs)
}) {
wg.Done()
c.errorf("sending messages failed - %s", ErrTooManyRequests)
c.notifyFailure(msgs, ErrTooManyRequests)
}
}
func (c *s3Client) flush(q *messageQueue, wg *sync.WaitGroup, ex *executor) {
if msgs := q.flush(); msgs != nil {
c.debugf("flushing %d messages", len(msgs))
c.sendAsync(msgs, wg, ex)
}
}
// Send batch request.
func (c *s3Client) send(msgs []message) {
const attempts = 10
var err error
buf := &bytes.Buffer{}
wr := gzip.NewWriter(buf)
encoder := json.NewEncoder(wr)
marshalledMessages := []message{}
failedMessages := []message{}
var lastError error
for _, m := range msgs {
err = encoder.Encode(m)
if err != nil {
failedMessages = append(failedMessages, m)
lastError = err
} else {
marshalledMessages = append(marshalledMessages, m)
}
}
if len(failedMessages) > 0 {
c.errorf("marshalling message - %s", lastError)
c.notifyFailure(failedMessages, lastError)
}
if err = wr.Close(); err != nil {
c.errorf("flushing writer failed: %s", err)
return
}
if buf.Len() == 0 || len(marshalledMessages) == 0 {
c.errorf("empty buffer, send is not possible")
return
}
for i := 0; i != attempts; i++ {
if err = c.upload(buf); err == nil {
c.notifySuccess(marshalledMessages)
return
}
// Wait for either a retry timeout or the client to be closed.
select {
case <-time.After(c.RetryAfter(i)):
err = fmt.Errorf("%d messages dropped because of error: %s", len(msgs), err)
c.errorf(err.Error())
c.notifyFailure(marshalledMessages, err)
return
case <-c.quit:
err = fmt.Errorf("%d messages dropped because they failed to be sent and the client was closed, upload error: %s", len(msgs), err)
c.errorf(err.Error())
c.notifyFailure(marshalledMessages, err)
return
}
}
c.errorf("%d messages dropped because they failed to be sent after %d attempts", len(msgs), attempts)
c.notifyFailure(marshalledMessages, err)
}
// Upload batch to S3.
func (c *s3Client) upload(r io.Reader) error {
key := c.config.S3.KeyConstructor(c.now, uid)
c.debugf("uploading to s3://%s/%s", c.config.S3.Bucket, key)
input := &s3manager.UploadInput{
Body: r,
Bucket: aws.String(c.config.S3.Bucket),
ACL: aws.String("public-read"),
Key: aws.String(key),
}
_, err := c.uploader.Upload(input)
return err
}
func stringPtr(s string) *string { return &s }