forked from mattatcha/go-kinesis
/
kinesis.go
210 lines (168 loc) · 4.54 KB
/
kinesis.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
// Package kinesis implements a batch producer built on top of the official AWS SDK.
package kinesis
import (
"errors"
"time"
"github.com/apex/log"
k "github.com/aws/aws-sdk-go/service/kinesis"
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
"github.com/jpillora/backoff"
)
// Size limits as defined by http://docs.aws.amazon.com/kinesis/latest/APIReference/API_PutRecords.html.
const (
maxRecordSize = 1 << 20 // 1MiB
maxRequestSize = 5 << 20 // 5MiB
maxRecordsPerRequest = 500
)
// Errors.
var (
ErrRecordSizeExceeded = errors.New("kinesis: record size exceeded")
)
type Config struct {
// StreamName is the Kinesis stream.
StreamName string
// FlushInterval is a regular interval for flushing the buffer. Defaults to 1s.
FlushInterval time.Duration
// BufferSize determines the batch request size. Must not exceed 500. Defaults to 500.
BufferSize int
// BacklogSize determines the channel capacity before Put() will begin blocking. Defaults to 500.
BacklogSize int
// Backoff determines the backoff strategy for record failures.
Backoff backoff.Backoff
// Logger is the logger used. Defaults to log.Log.
Logger log.Interface
// Client is the Kinesis API implementation.
Client kinesisiface.KinesisAPI
}
// defaults for configuration.
func (c *Config) defaults() {
if c.Logger == nil {
c.Logger = log.Log
}
c.Logger = c.Logger.WithFields(log.Fields{
"package": "kinesis",
"stream": c.StreamName,
})
if c.BufferSize == 0 {
c.BufferSize = maxRecordsPerRequest
}
if c.BufferSize > maxRecordsPerRequest {
panic("kinesis: BufferSize exceeds 500")
}
if c.BacklogSize == 0 {
c.BacklogSize = maxRecordsPerRequest
}
if c.FlushInterval == 0 {
c.FlushInterval = time.Second
}
}
// Producer batches records.
type KinesisProducer struct {
Config
records chan *k.PutRecordsRequestEntry
done chan struct{}
}
// New producer with the given config.
func New(config Config) *KinesisProducer {
config.defaults()
return &KinesisProducer{
Config: config,
records: make(chan *k.PutRecordsRequestEntry, config.BacklogSize),
done: make(chan struct{}),
}
}
// Put record `data` using `partitionKey`. This method is thread-safe.
func (p *KinesisProducer) Put(data []byte, partitionKey string) error {
if len(data) > maxRecordSize {
return ErrRecordSizeExceeded
}
p.records <- &k.PutRecordsRequestEntry{
Data: data,
PartitionKey: &partitionKey,
}
return nil
}
// Start the producer.
func (p *KinesisProducer) Start() {
go p.loop()
}
// Stop the producer. Flushes any in-flight data.
func (p *KinesisProducer) Stop() {
p.Logger.WithField("backlog", len(p.records)).Info("stopping producer")
// drain
p.done <- struct{}{}
close(p.records)
// wait
<-p.done
p.Logger.Info("stopped producer")
}
// loop and flush at the configured interval, or when the buffer is exceeded.
func (p *KinesisProducer) loop() {
buf := make([]*k.PutRecordsRequestEntry, 0, p.BufferSize)
tick := time.NewTicker(p.FlushInterval)
drain := false
defer tick.Stop()
defer close(p.done)
for {
select {
case record := <-p.records:
buf = append(buf, record)
if len(buf) >= p.BufferSize {
p.flush(buf, "buffer size")
buf = nil
}
if drain && len(p.records) == 0 {
p.Logger.Info("drained")
return
}
case <-tick.C:
if len(buf) > 0 {
p.flush(buf, "interval")
buf = nil
}
case <-p.done:
drain = true
if len(p.records) == 0 {
return
}
}
}
}
// flush records and retry failures if necessary.
func (p *KinesisProducer) flush(records []*k.PutRecordsRequestEntry, reason string) {
p.Logger.WithFields(log.Fields{
"records": len(records),
"reason": reason,
}).Info("flush")
out, err := p.Client.PutRecords(&k.PutRecordsInput{
StreamName: &p.StreamName,
Records: records,
})
if err != nil {
// TODO(tj): confirm that the AWS SDK handles retries of request-level errors
// otherwise we need to backoff here as well.
p.Logger.WithError(err).Error("flush")
p.Backoff.Reset()
return
}
failed := *out.FailedRecordCount
if failed == 0 {
return
}
backoff := p.Backoff.Duration()
p.Logger.WithFields(log.Fields{
"failures": failed,
"backoff": backoff,
}).Warn("put failures")
time.Sleep(backoff)
p.flush(failures(records, out.Records), "retry")
}
// failures returns the failed records as indicated in the response.
func failures(records []*k.PutRecordsRequestEntry, response []*k.PutRecordsResultEntry) (out []*k.PutRecordsRequestEntry) {
for i, record := range response {
if record.ErrorCode != nil {
out = append(out, records[i])
}
}
return
}