forked from fredriksvensson/go-dynamodb-stream-subscriber
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstream.go
400 lines (355 loc) · 9.82 KB
/
stream.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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
package stream
import (
"context"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/dynamodb"
"github.com/aws/aws-sdk-go-v2/service/dynamodbstreams"
"github.com/aws/aws-sdk-go-v2/service/dynamodbstreams/types"
"github.com/aws/smithy-go"
"github.com/cenkalti/backoff/v4"
"github.com/pkg/errors"
"runtime"
"sort"
"sync"
"time"
)
type Subscriber struct {
table string
dynamoSvc DynamoService
streamSvc StreamService
shards sync.Map
shardCount int
shardProcessQueue chan *shardProcessContext
shutdownCh chan struct{}
recordCh chan *types.Record
errorCh chan error
shardSequenceIteratorType types.ShardIteratorType
shardIteratorType types.ShardIteratorType
shardIteratorInitialInterval time.Duration
shardIteratorMaxInterval time.Duration
shardUpdateInterval time.Duration
shardProcessWorkers int
maximumRecords int32
}
func NewSubscriber(
dynamoSvc DynamoService,
streamSvc StreamService,
table string,
) *Subscriber {
s := &Subscriber{
table: table,
dynamoSvc: dynamoSvc,
streamSvc: streamSvc,
shards: sync.Map{},
shutdownCh: make(chan struct{}),
}
s.applyDefaults()
return s
}
func (r *Subscriber) applyDefaults() {
r.SetShardSequenceIteratorType(types.ShardIteratorTypeAfterSequenceNumber)
r.SetShardIteratorType(types.ShardIteratorTypeTrimHorizon)
r.SetShardIteratorInitialInterval(1 * time.Second)
r.SetShardIteratorMaxInterval(1 * time.Minute)
r.SetShardUpdateInterval(1 * time.Minute)
r.SetShardProcessWorkers(runtime.NumCPU())
r.SetShardProcessQueueSize(8192)
r.SetMaximumRecords(1000)
r.SetRecordBufferSize(8192)
r.SetErrorBufferSize(8192)
}
func (r *Subscriber) SetShardSequences(shardSequences []*ShardSequence) {
if r.shardCount == 0 {
for _, shardSequence := range shardSequences {
if len(shardSequence.SequenceNumber) > 0 {
r.shards.Store(shardSequence.ShardId, shardSequence.SequenceNumber)
}
}
}
}
func (r *Subscriber) SetShardSequenceIteratorType(shardSequenceIteratorType types.ShardIteratorType) {
if len(r.shardSequenceIteratorType) == 0 {
switch shardSequenceIteratorType {
case types.ShardIteratorTypeAtSequenceNumber:
case types.ShardIteratorTypeAfterSequenceNumber:
default:
return
}
r.shardSequenceIteratorType = shardSequenceIteratorType
}
}
func (r *Subscriber) SetShardIteratorType(shardIteratorType types.ShardIteratorType) {
if len(r.shardIteratorType) == 0 {
switch shardIteratorType {
case types.ShardIteratorTypeTrimHorizon:
case types.ShardIteratorTypeLatest:
default:
return
}
r.shardIteratorType = shardIteratorType
}
}
func (r *Subscriber) SetShardIteratorInitialInterval(shardIteratorInitialInterval time.Duration) {
if r.shardIteratorInitialInterval == 0 {
r.shardIteratorInitialInterval = shardIteratorInitialInterval
}
}
func (r *Subscriber) SetShardIteratorMaxInterval(shardIteratorMaxInterval time.Duration) {
if r.shardIteratorMaxInterval == 0 {
r.shardIteratorMaxInterval = shardIteratorMaxInterval
}
}
func (r *Subscriber) SetShardUpdateInterval(shardUpdateInterval time.Duration) {
if r.shardUpdateInterval == 0 {
r.shardUpdateInterval = shardUpdateInterval
}
}
func (r *Subscriber) SetShardProcessWorkers(shardProcessWorkers int) {
if r.shardProcessWorkers == 0 {
r.shardProcessWorkers = shardProcessWorkers
}
}
func (r *Subscriber) SetShardProcessQueueSize(shardProcessQueueSize int) {
if r.shardProcessQueue == nil {
r.shardProcessQueue = make(chan *shardProcessContext, shardProcessQueueSize)
}
}
func (r *Subscriber) SetMaximumRecords(maximumRecords int32) {
if r.maximumRecords == 0 {
r.maximumRecords = maximumRecords
}
}
func (r *Subscriber) SetRecordBufferSize(bufferSize int32) {
if r.recordCh == nil {
r.recordCh = make(chan *types.Record, bufferSize)
}
}
func (r *Subscriber) SetErrorBufferSize(bufferSize int32) {
if r.errorCh == nil {
r.errorCh = make(chan error, bufferSize)
}
}
func (r *Subscriber) ShardSequences() []*ShardSequence {
var shardSequences []*ShardSequence
r.shards.Range(func(key any, value any) bool {
shardId := key.(string)
sequenceNumber := value.(string)
if len(sequenceNumber) > 0 {
shardSequences = append(shardSequences, &ShardSequence{
ShardId: shardId,
SequenceNumber: sequenceNumber,
})
}
return true
})
sort.Slice(shardSequences, func(i, j int) bool {
return shardSequences[i].ShardId < shardSequences[j].ShardId
})
return shardSequences
}
func (r *Subscriber) Shutdown() {
defer func() {
recover()
}()
close(r.shutdownCh)
close(r.errorCh)
}
func (r *Subscriber) Subscribe() (<-chan *types.Record, <-chan error) {
go func() {
for {
select {
case <-r.shutdownCh:
time.Sleep(1 * time.Second)
if len(r.recordCh) == 0 {
close(r.recordCh)
return
}
}
}
}()
go func() {
first := true
after := time.Duration(0)
for {
select {
case <-r.shutdownCh:
return
case <-time.After(after):
after = r.shardUpdateInterval
streamArn, err := r.getLatestStreamArn()
if err != nil {
r.sendError(err)
continue
}
if streamArn == nil {
r.sendError(errors.New("stream arn is nil"))
continue
}
shards, err := r.getShards(streamArn)
if err != nil {
r.sendError(err)
continue
}
for _, shard := range shards {
var sequenceNumber *string
shardIteratorType := r.shardIteratorType
if first {
sqn, ok := r.shards.Load(*shard.ShardId)
if ok {
shardIteratorType = r.shardSequenceIteratorType
sequenceNumberStr := sqn.(string)
sequenceNumber = &sequenceNumberStr
r.shards.Delete(*shard.ShardId)
} else {
shardIteratorType = r.shardIteratorType
}
}
if _, exist := r.shards.LoadOrStore(*shard.ShardId, ""); !exist {
r.shardCount++
r.shardProcessQueue <- newShardProcessContext(
&dynamodbstreams.GetShardIteratorInput{
StreamArn: streamArn,
ShardIteratorType: shardIteratorType,
ShardId: shard.ShardId,
SequenceNumber: sequenceNumber,
},
r.shardIteratorInitialInterval,
r.shardIteratorMaxInterval,
)
}
}
first = false
}
}
}()
go func() {
shardProcessWorkersCh := make(chan struct{}, r.shardProcessWorkers)
for {
select {
case <-r.shutdownCh:
return
case shardProcessCtx := <-r.shardProcessQueue:
shardProcessWorkersCh <- struct{}{}
go func(processCtx *shardProcessContext) {
done, err := r.processShard(processCtx)
if err != nil {
r.sendError(err)
}
if !done {
go func() {
select {
case <-r.shutdownCh:
case <-time.After(processCtx.backoff.NextBackOff()):
r.shardProcessQueue <- processCtx
}
}()
}
<-shardProcessWorkersCh
}(shardProcessCtx)
}
}
}()
return r.recordCh, r.errorCh
}
func (r *Subscriber) sendRecord(record *types.Record) {
select {
case <-r.shutdownCh:
case r.recordCh <- record:
}
}
func (r *Subscriber) sendError(err error) {
select {
case <-r.shutdownCh:
case r.errorCh <- err:
}
}
func (r *Subscriber) getLatestStreamArn() (*string, error) {
tableOutput, err := r.dynamoSvc.DescribeTable(context.Background(), &dynamodb.DescribeTableInput{
TableName: &r.table,
})
if err != nil {
return nil, err
}
return tableOutput.Table.LatestStreamArn, nil
}
func (r *Subscriber) getShards(streamArn *string) (shards []types.Shard, err error) {
des, err := r.streamSvc.DescribeStream(context.Background(), &dynamodbstreams.DescribeStreamInput{
StreamArn: streamArn,
})
if err != nil {
return nil, err
}
return des.StreamDescription.Shards, nil
}
func (r *Subscriber) processShard(processCtx *shardProcessContext) (bool, error) {
if processCtx.iterator == nil {
iterator, err := r.streamSvc.GetShardIterator(context.Background(), processCtx.input)
if err != nil {
var apiErr *smithy.GenericAPIError
if errors.As(err, &apiErr) && apiErr.Code == "ValidationException" {
err = errors.Wrapf(err, "shard=%s, sequenceNumber=%s",
*processCtx.input.ShardId,
*processCtx.input.SequenceNumber)
processCtx.input.SequenceNumber = nil
processCtx.input.ShardIteratorType = r.shardIteratorType
}
return false, err
}
if iterator.ShardIterator == nil {
return true, nil
}
processCtx.iterator = iterator.ShardIterator
}
output, err := r.streamSvc.GetRecords(context.Background(), &dynamodbstreams.GetRecordsInput{
ShardIterator: processCtx.iterator,
Limit: aws.Int32(r.maximumRecords),
})
if err != nil {
var expiredIteratorException *types.ExpiredIteratorException
if errors.As(err, &expiredIteratorException) {
processCtx.iterator = nil
return false, nil
}
var trimmedDataAccessException *types.TrimmedDataAccessException
if errors.As(err, &trimmedDataAccessException) {
return true, nil
}
var resourceNotFoundException *types.ResourceNotFoundException
if errors.As(err, &resourceNotFoundException) {
return true, nil
}
return false, err
}
for _, record := range output.Records {
r.sendRecord(&record)
}
if output.NextShardIterator == nil {
return true, nil
}
processCtx.iterator = output.NextShardIterator
if len(output.Records) > 0 {
processCtx.backoff.Reset()
r.shards.Store(*processCtx.input.ShardId, *output.Records[len(output.Records)-1].Dynamodb.SequenceNumber)
}
return false, nil
}
type shardProcessContext struct {
input *dynamodbstreams.GetShardIteratorInput
iterator *string
backoff *backoff.ExponentialBackOff
}
func newShardProcessContext(
input *dynamodbstreams.GetShardIteratorInput,
initialInterval time.Duration,
maxInterval time.Duration,
) *shardProcessContext {
bo := backoff.NewExponentialBackOff()
bo.RandomizationFactor = 0.1
bo.InitialInterval = initialInterval
bo.MaxInterval = maxInterval
bo.Reset()
return &shardProcessContext{
input: input,
backoff: bo,
}
}