-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.go
172 lines (158 loc) · 4.77 KB
/
core.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
package ktail
import (
"fmt"
"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/kinesis"
"github.com/aws/aws-sdk-go/service/kinesis/kinesisiface"
"io"
"log"
"reflect"
"time"
)
type Record struct {
*kinesis.Record
Stream string
Shard string
}
type Follower struct {
api kinesisiface.KinesisAPI
}
func NewFollowerWithAPI(api kinesisiface.KinesisAPI) *Follower {
return &Follower{api}
}
func NewFollower(region string) *Follower {
var configs []*aws.Config
if region != "" {
configs = append(configs, aws.NewConfig().WithRegion(region))
}
return NewFollowerWithAPI(kinesis.New(session.New(), configs...))
}
func (f *Follower) GetShards(stream string) ([]string, error) {
var prevShard *string
var shards []string
for {
params := &kinesis.DescribeStreamInput{
StreamName: &stream,
ExclusiveStartShardId: prevShard,
}
if resp, err := f.api.DescribeStream(params); err != nil {
return nil, err
} else if len(resp.StreamDescription.Shards) == 0 {
return shards, nil
} else {
for _, s := range resp.StreamDescription.Shards {
shards = append(shards, *s.ShardId)
prevShard = s.ShardId
}
}
}
}
func (f *Follower) getShardIterator(stream, shard, iterType string) (string, error) {
params := &kinesis.GetShardIteratorInput{
ShardId: &shard,
ShardIteratorType: &iterType,
StreamName: &stream,
}
if resp, err := f.api.GetShardIterator(params); err != nil {
return "", err
} else {
return *resp.ShardIterator, nil
}
}
func (f *Follower) getRecords(iter string) (records []*kinesis.Record, nextIter *string, lag time.Duration, err error) {
var resp *kinesis.GetRecordsOutput
if resp, err = f.api.GetRecords(&kinesis.GetRecordsInput{ShardIterator: &iter}); err == nil {
records, nextIter, lag = resp.Records, resp.NextShardIterator, time.Duration(*resp.MillisBehindLatest)*time.Millisecond
}
return
}
// ReaderResult indicates the outcome of shard reading procedure.
// Shard reading may end gracefully when a closed shard's last batch
// of records was read. In that case, Err will be set to io.EOF.
type ReaderResult struct {
Stream, Shard string
Err error
}
// String causes ReaderResult to satisfy fmt.Stringer interface.
func (rr *ReaderResult) String() string { return fmt.Sprintf("%s(%s): %v", rr.Stream, rr.Shard, rr.Err) }
func (rr *ReaderResult) setError(err error) *ReaderResult {
rr.Err = err
return rr
}
func (f *Follower) ReadRecords(dst chan<- *Record, stream, shard, iterType string, rest time.Duration) <-chan *ReaderResult {
rrc := make(chan *ReaderResult, 1)
go func() {
defer close(rrc)
rr := &ReaderResult{stream, shard, io.EOF}
startIter, err := f.getShardIterator(stream, shard, iterType)
if err != nil {
rrc <- rr.setError(err)
} else {
var records []*kinesis.Record
var lag time.Duration
const maxAttempts = 5
attempt := 1
for iter := &startIter; iter != nil; {
time.Sleep(rest)
attemptedIter := iter
if records, iter, lag, err = f.getRecords(*attemptedIter); err != nil {
if err, ok := err.(awserr.Error); ok && err.Code() == "ProvisionedThroughputExceededException" && attempt < maxAttempts {
attempt, iter = attempt+1, attemptedIter
log.Print(err.Message())
log.Printf("Will make attempt %v in a bit...", attempt)
continue
}
rrc <- rr.setError(err)
return
}
attempt = 1
for _, r := range records {
dst <- &Record{r, stream, shard}
}
if lag > 5*time.Second {
log.Printf("Reader for %s(%s) is %v behind", stream, shard, lag)
}
}
rrc <- rr
}
}()
return rrc
}
// merge, well, merges results from input channels (chans) onto the
// output channel (the one returned) until all of inputs are
// closed. It closes the output channel when done, too.
// Credit: remixed from https://godoc.org/github.com/eapache/channels#Multiplex
func merge(chans []<-chan *ReaderResult) <-chan *ReaderResult {
out := make(chan *ReaderResult)
go func() {
defer close(out)
n := len(chans)
cases := make([]reflect.SelectCase, n)
for i := range cases {
cases[i].Dir, cases[i].Chan = reflect.SelectRecv, reflect.ValueOf(chans[i])
}
for n > 0 {
chosen, recv, recvOK := reflect.Select(cases)
if recvOK {
out <- recv.Interface().(*ReaderResult)
} else {
cases[chosen].Chan = reflect.ValueOf(nil)
n--
}
}
}()
return out
}
func (f *Follower) Tail(dst chan<- *Record, stream, iterType string, rest time.Duration) (<-chan *ReaderResult, error) {
shards, err := f.GetShards(stream)
if err != nil {
return nil, err
}
results := make([]<-chan *ReaderResult, len(shards))
for i, s := range shards {
results[i] = f.ReadRecords(dst, stream, s, iterType, rest)
}
return merge(results), nil
}