forked from mhart/kinesis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
216 lines (163 loc) · 6.02 KB
/
index.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
var util = require('util'),
stream = require('stream'),
http = require('http'),
https = require('https'),
once = require('once'),
aws4 = require('aws4')
exports.listStreams = listStreams
exports.createReadStream = createReadStream
exports.createWriteStream = createWriteStream
exports.KinesisReadStream = KinesisReadStream
exports.KinesisWriteStream = KinesisWriteStream
exports.request = request
function listStreams(options, cb) {
if (!cb) { cb = options; options = {} }
request('ListStreams', {}, options, function(err, res) {
if (err) return cb(err)
return cb(null, res.StreamNames)
})
}
function createReadStream(name, options) {
return new KinesisReadStream(name, options)
}
function createWriteStream(name, options) {
return new KinesisWriteStream(name, options)
}
util.inherits(KinesisReadStream, stream.Readable)
function KinesisReadStream(name, options) {
stream.Readable.call(this, options)
this.name = name
this.options = options
}
KinesisReadStream.prototype._read = function() {
var self = this
// Firstly we need to know what shards we have
// TODO: Cache this (and allow it to be passed in as options too)
request('DescribeStream', {StreamName: self.name}, self.options, function(err, res) {
if (err) return self.emit('error', err)
var shardIds = res.StreamDescription.Shards.map(function(shard) { return shard.ShardId }),
shardCount = shardIds.length
// Read from all shards in parallel
shardIds.forEach(function(shardId) {
// TODO: Allow reading from a particular position
// TODO: Cache the shard iterator so we don't need to look it up
var data = {StreamName: self.name, ShardId: shardId, ShardIteratorType: 'LATEST'}
request('GetShardIterator', data, self.options, function(err, res) {
if (err) return self.emit('error', err)
var data = {StreamName: self.name, ShardId: shardId, ShardIterator: res.ShardIterator}
self.getNextRecords(data, function(err) {
if (err) return self.emit('error', err)
// If all shards are done, push null to signal we're finished
if (!--shardCount)
self.push(null)
})
})
})
})
}
// `data` should contain at least: StreamName, ShardId, ShardIterator
KinesisReadStream.prototype.getNextRecords = function(data, cb) {
var self = this
request('GetNextRecords', data, self.options, function(err, res) {
if (err) return cb(err)
// If the shard has been closed the requested iterator will not return any more data
if (res.NextShardIterator == null)
return cb()
res.Records.forEach(function(record) {
// TODO: convert data as we push - can always just pipe too
self.push(record.Data, 'base64')
})
// Recurse until we're done
data.ShardIterator = res.NextShardIterator
self.getNextRecords(data, cb)
})
}
util.inherits(KinesisWriteStream, stream.Writable)
function KinesisWriteStream(name, options) {
stream.Writable.call(this, options)
this.name = name
this.options = options
this.resolvePartitionKey = options.resolvePartitionKey || function() { return 'partition-1' }
}
KinesisReadStream.prototype._write = function(chunk, encoding, cb) {
// TODO: Allow ExplicitHashKey
// Determine PartitionKey
var self = this,
partitionKey = self.resolvePartitionKey(chunk, encoding),
data = {StreamName: self.name, PartitionKey: partitionKey, Data: chunk.toString('base64')}
request('PutRecord', data, self.options, cb)
}
function request(action, data, options, cb) {
if (!cb) { cb = options; options = {} }
if (!cb) { cb = data; data = {} }
options = resolveOptions(options)
cb = once(cb)
var httpModule = options.https ? https : http,
httpOptions = {},
body = JSON.stringify(data || {}),
req
httpOptions.host = options.host
httpOptions.port = options.port
httpOptions.agent = options.agent
httpOptions.method = 'POST'
httpOptions.path = '/'
httpOptions.headers = {
'Host': httpOptions.host,
'Date': new Date().toUTCString(),
'Content-Length': Buffer.byteLength(body),
'Content-Type': 'application/x-amz-json-1.1',
'X-Amz-Target': 'Kinesis_' + options.version + '.' + action,
}
aws4.sign(httpOptions, options.credentials)
req = httpModule.request(httpOptions, function(res) {
var json = ''
res.setEncoding('utf8')
res.on('error', cb)
res.on('data', function(chunk){ json += chunk })
res.on('end', function() {
var response, error
try { response = JSON.parse(json) } catch (e) { }
if (res.statusCode == 200 && response != null)
return cb(null, response)
error = new Error
error.statusCode = res.statusCode
if (response != null) {
error.name = (response.__type || '').split('#').pop()
error.message = response.message || response.Message || JSON.stringify(response)
} else {
if (res.statusCode == 413) json = 'Request Entity Too Large'
error.message = 'HTTP/1.1 ' + res.statusCode + ' ' + json
}
cb(error)
})
}).on('error', cb)
req.write(body)
req.end()
}
function resolveOptions(options) {
var region = options.region
options = Object.keys(options).reduce(function(clone, key) {
clone[key] = options[key]
return clone
}, {})
if (typeof region === 'object') {
options.host = region.host
options.port = region.port
options.region = region.region
options.version = region.version
options.agent = region.agent
options.https = region.https
options.credentials = region.credentials
} else {
if (/^[a-z]{2}\-[a-z]+\-\d$/.test(region))
options.region = region
else
// Backwards compatibility for when 1st param was host
options.host = region
}
if (!options.region) options.region = (options.host || '').split('.', 2)[1] || 'us-east-1'
if (!options.host) options.host = 'kinesis.' + options.region + '.amazonaws.com'
if (!options.version) options.version = '20130901'
if (!options.credentials) options.credentials = options.credentials
return options
}