-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathDynamoStream.js
237 lines (218 loc) · 6.69 KB
/
DynamoStream.js
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
require('rubico/global')
const Transducer = require('rubico/Transducer')
const DynamoDBStreams = require('aws-sdk/clients/dynamodbstreams')
const rubicox = require('rubico/x')
const has = require('./internal/has')
const RetryAwsErrors = require('./internal/RetryAwsErrors')
const HttpAgent = require('./HttpAgent')
const Dynamo = require('./Dynamo')
const Mux = require('rubico/monad/Mux')
const { identity, differenceWith } = rubicox
/**
* @name DynamoStream
*
* @synopsis
* ```coffeescript [specscript]
* DynamoStream(options {
* table: string,
* accessKeyId: string,
* secretAccessKey: string,
* region: string,
* endpoint: string,
* streamViewType?: 'NEW_AND_OLD_IMAGES'|'NEW_IMAGE'|'OLD_IMAGE'|'KEYS_ONLY',
* shardIteratorType?: 'TRIM_HORIZON'|'LATEST'|'AT_SEQUENCE_NUMBER'|'AFTER_SEQUENCE_NUMBER',
* })
* ```
*
* @description
* https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDBStreams.html
*
* DynamoStream -> Stream Headers -> Stream ARNs
*
* `eventName` enumeration: `INSERT`, `MODIFY`, `REMOVE`
*/
const DynamoStream = function (options) {
if (this == null || this.constructor != DynamoStream) {
return new DynamoStream(options)
}
const awsCreds = pick(options, [
'accessKeyId',
'secretAccessKey',
'region',
'endpoint',
])
this.table = options.table
this.getRecordsLimit = options.getRecordsLimit ?? 1000
this.getRecordsInterval = options.getRecordsInterval ?? 1000
this.shardIteratorType = options.shardIteratorType ?? 'LATEST'
this.shardUpdatePeriod = options.shardUpdatePeriod ?? 15000
this.listStreamsLimit = options.listStreamsLimit ?? 100
this.client = new DynamoDBStreams({
apiVersion: '2012-08-10',
accessKeyId: 'id',
secretAccessKey: 'secret',
region: 'x-x-x',
...awsCreds,
})
this.retryListStreams = RetryAwsErrors(
this.client.listStreams,
this.client,
)
this.retryDescribeStream = RetryAwsErrors(
this.client.describeStream,
this.client,
)
this.retryGetShardIterator = RetryAwsErrors(
this.client.getShardIterator,
this.client,
)
this.retryGetRecords = RetryAwsErrors(
this.client.getRecords,
this.client,
)
const dynamo = new Dynamo(awsCreds)
this.ready = dynamo.describeTable(this.table).then(pipe([
get('Table.StreamSpecification'),
streamSpec => streamSpec == null ? dynamo.enableStreams(this.table, {
streamViewType: get('streamViewType', 'NEW_AND_OLD_IMAGES')(options)
}) : {},
]))
return this
}
// () => ()
DynamoStream.prototype.close = function close() {
this.closed = true
}
// () => AsyncGenerator<Stream>
DynamoStream.prototype.getStreams = async function* getStreams() {
let streams = await this.retryListStreams({
Limit: this.listStreamsLimit,
TableName: this.table
})
if (streams.Streams.length > 0) {
yield* streams.Streams
}
while (!this.closed && streams.LastEvaluatedStreamArn != null) {
streams = await this.retryListStreams({
Limit: this.listStreamsLimit,
TableName: this.table,
ExclusiveStartStreamArn: streams.LastEvaluatedStreamArn,
})
if (streams.Streams.length > 0) {
yield* streams.Streams
}
}
}
// Stream => AsyncGenerator<Shard>
DynamoStream.prototype.getShards = async function* getShards(
Stream,
) {
let shards = await this.retryDescribeStream({
StreamArn: Stream.StreamArn,
Limit: 100,
}).then(get('StreamDescription'))
if (shards.Shards.length > 0) {
yield* shards.Shards.map(assign({ Stream: always(Stream) }))
}
while (!this.closed && shards.LastEvaluatedShardId != null) {
shards = await this.retryDescribeStream({
StreamArn: Stream.StreamArn,
Limit: 100,
ExclusiveStartShardId: shards.LastEvaluatedShardId,
}).then(get('StreamDescription'))
if (shards.Shards.length > 0) {
yield* shards.Shards.map(assign({ Stream: always(Stream) }))
}
}
}
// Shard => AsyncGenerator<Record>
DynamoStream.prototype.getRecords = async function* getRecords(
Shard,
) {
const startingShardIterator = await this.retryGetShardIterator({
ShardId: Shard.ShardId,
StreamArn: Shard.Stream.StreamArn,
ShardIteratorType: Shard.ShardIteratorType,
/*
...(
Shard.ShardIteratorType == 'AFTER_SEQUENCE_NUMBER'
|| Shard.ShardIteratorType == 'AT_SEQUENCE_NUMBER'
) ? { SequenceNumber: Shard.SequenceNumber } : {},
*/
}).then(get('ShardIterator'))
let records = await this.retryGetRecords({
ShardIterator: startingShardIterator,
Limit: this.getRecordsLimit
})
if (records.Records.length > 0) {
yield* records.Records.map(assign({
table: always(this.table),
shardId: always(Shard.ShardId),
}))
}
await new Promise(resolve => setTimeout(resolve, this.getRecordsInterval))
while (!this.closed && records.NextShardIterator != null) {
records = await this.retryGetRecords({
ShardIterator: records.NextShardIterator,
Limit: this.getRecordsLimit
})
if (records.Records.length > 0) {
yield* records.Records.map(assign({
table: always(this.table),
shardId: always(Shard.ShardId),
}))
}
await new Promise(resolve => setTimeout(resolve, this.getRecordsInterval))
}
}
const SymbolUpdateShards = Symbol('UpdateShards')
DynamoStream.prototype[Symbol.asyncIterator] = async function* () {
let shards = await pipe(this.getStreams(), [
flatMap(Stream => this.getShards(Stream)),
map(assign({
ShardIteratorType: always(this.shardIteratorType),
})),
transform(Transducer.passthrough, []),
])
let muxAsyncIterator = Mux.race([
...shards.map(Shard => this.getRecords(Shard)),
(async function* UpdateShardsGenerator() {
while (true) {
await new Promise(resolve => {
setTimeout(resolve, this.shardUpdatePeriod)
})
yield SymbolUpdateShards
}
}).call(this),
])
while (!this.closed) {
const { value, done } = await muxAsyncIterator.next()
if (value == SymbolUpdateShards) {
const latestShards = await pipe(this.getStreams(), [
flatMap(Stream => this.getShards(Stream)),
transform(Transducer.passthrough, []),
])
const newShards = pipe(shards, [
differenceWith(
(ShardA, ShardB) => ShardA.ShardId == ShardB.ShardId,
latestShards,
),
map(assign({
ShardIteratorType: always('TRIM_HORIZON'),
})),
])
shards = latestShards
if (newShards.length > 0) {
muxAsyncIterator = Mux.race([
...newShards.map(Shard => this.getRecords(Shard)),
muxAsyncIterator,
])
}
} else if (done) {
await new Promise(resolve => setTimeout(resolve, 1000))
} else {
yield value
}
}
}
module.exports = DynamoStream