-
Notifications
You must be signed in to change notification settings - Fork 21
/
upring.js
355 lines (292 loc) · 8.45 KB
/
upring.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
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
'use strict'
const EE = require('events').EventEmitter
const inherits = require('util').inherits
const net = require('net')
const tentacoli = require('tentacoli')
const pump = require('pump')
const dezalgo = require('fastzalgo')
const networkAddress = require('network-address')
const bloomrun = require('bloomrun')
const pino = require('pino')
const tinysonic = require('tinysonic')
const promisify = require('util.promisify')
const avvio = require('avvio')
const Ajv = require('ajv')
const ajv = new Ajv({ coerceTypes: true })
const serializers = require('./lib/serializers')
const monitoring = require('./lib/monitoring')
const symbolSchema = Symbol('schema')
function UpRing (opts) {
if (!(this instanceof UpRing)) {
return new UpRing(opts)
}
opts = opts || {}
opts.port = opts.port || 0
opts.host = opts.host || networkAddress()
const app = avvio(this)
this._inbound = new Set()
this.log = opts.logger ? opts.logger.child({ serializers }) : pino({ serializers })
this.info = {}
this._fireCallback = fireCallback.bind(this)
this.isReady = false
if (!opts.logger) {
this.log.level = opts.logLevel || 'info'
}
this
.use(require('./lib/tcp-server'), opts)
.use(require('./lib/hashring'), opts)
// for some reasons, ready() will not
// work to set isReady
app.use((i, opts, cb) => {
this.isReady = true
cb()
})
app.on('start', () => {
this.emit('up')
})
this._dispatch = (req, reply) => {
if (!this.isReady) {
this.once('up', this._dispatch.bind(this, req, reply))
return
}
var func
this.emit('prerequest', req)
if (this._router) {
func = this._router.lookup(req)
if (func) {
if (func[symbolSchema]) {
var valid = func[symbolSchema](req)
if (valid !== true) {
return reply(new Error('400'), valid)
}
}
var result = func(req, reply)
if (result && typeof result.then === 'function') {
result
.then(res => process.nextTick(reply, null, res))
.catch(err => process.nextTick(reply, err, null))
}
} else {
reply(new Error('message does not match any pattern'))
}
} else {
this.emit('request', req, reply)
}
}
this._peers = {}
this.onClose(function (that, cb) {
if (that._tracker) {
that._tracker.clear()
}
Object.keys(that._peers).forEach((id) => {
that._peers[id].destroy()
})
that._inbound.forEach((s) => {
s.destroy()
})
that._hashring.close()
that._server.close((err) => {
that.log.info('closed')
that.emit('close')
cb(err)
})
})
}
inherits(UpRing, EE)
UpRing.prototype.whoami = function () {
if (!this.isReady) throw new Error('UpRing not ready yet')
return this._hashring.whoami()
}
UpRing.prototype.join = function (peers, cb) {
if (!this.isReady) {
this.once('up', this.join.bind(this, peers, cb))
return
}
if (!Array.isArray(peers)) {
peers = [peers]
}
return this._hashring.swim.join(peers, cb)
}
UpRing.prototype.allocatedToMe = function (key) {
if (!this.isReady) return null
return this._hashring.allocatedToMe(key)
}
UpRing.prototype.peerConn = function (peer) {
let conn = this._peers[peer.id]
if (!conn) {
this.log.debug({ peer: peer }, 'connecting to peer')
const upring = peer.meta.upring
const stream = net.connect(upring.port, upring.address)
conn = setupConn(this, peer, stream)
}
return conn
}
function setupConn (that, peer, stream, retry) {
const conn = tentacoli()
pump(stream, conn, stream, function () {
that.log.debug({ peer: peer }, 'peer disconnected')
var nustream = null
that._hashring.on('peerDown', onPeerDown)
if (!retry) {
that.log.debug({ peer: peer }, 'reconnecting to peer')
nustream = net.connect(peer.meta.upring.port, peer.meta.upring.address)
nustream.on('connect', onConnect)
nustream.on('error', onError)
}
function onPeerDown (peerDown) {
if (peerDown.id === peer.id) {
that.log.debug({ peer: peer }, 'peer down')
delete that._peers[peer.id]
that._hashring.removeListener('peerDown', onPeerDown)
if (nustream) {
nustream.destroy()
}
}
}
function onConnect () {
that.log.debug({ peer: peer }, 'reconnected')
setupConn(that, peer, nustream, true)
that._hashring.removeListener('peerDown', onPeerDown)
}
function onError () {
// do nothing, let's wait for peerDown
// TODO that might never come, how to signal the hashring?
}
})
setTimeout(function () {
retry = true
}, 10 * 1000).unref() // 10 seconds
that._peers[peer.id] = conn
return conn
}
UpRing.prototype.peers = function (myself) {
return this._hashring.peers(myself)
}
UpRing.prototype.mymeta = function () {
return this._hashring.mymeta()
}
UpRing.prototype.request = function (obj, callback, _count) {
if (!this.isReady) {
this.once('up', this.request.bind(this, obj, callback))
return
}
if (this._hashring.allocatedToMe(obj.key)) {
this.log.trace({ msg: obj }, 'local call')
this._dispatch(obj, dezalgo(callback))
} else {
const peer = this._hashring.lookup(obj.key)
this.log.trace({ msg: obj, peer }, 'remote call')
const upring = peer.meta.upring
if (!upring || !upring.address || !upring.port) {
callback(new Error('peer has invalid upring metadata'))
return
}
// TODO simplify all this logic
// and avoid allocating a closure
if (typeof _count !== 'number') {
_count = 0
} else if (_count === 3) {
callback(new Error('retried three times'))
return
} else {
_count++
}
const conn = this.peerConn(peer)
if (conn.destroyed) {
// TODO make this dependent on the gossip interval
setTimeout(retry, 500, this, 'request', obj, callback, _count)
return
}
conn.request(obj, (err, result) => {
if (err) {
// the peer has changed
if (this._hashring.lookup(obj.key).id !== peer.id || conn.destroyed) {
// TODO make this dependent on the gossip interval
setTimeout(retry, 500, this, 'request', obj, callback, _count)
return
}
}
callback(err, result)
})
}
return this
}
UpRing.prototype.requestp = promisify(UpRing.prototype.request)
UpRing.prototype.fire = function (obj, callback, _count) {
callback = callback || this._fireCallback
if (!this.isReady) {
this.once('up', this.fire.bind(this, obj, callback))
return
}
if (this._hashring.allocatedToMe(obj.key)) {
this.log.trace({ msg: obj }, 'local call')
callback()
this._dispatch(obj, noop)
} else {
const peer = this._hashring.lookup(obj.key)
this.log.trace({ msg: obj, peer }, 'remote call')
const upring = peer.meta.upring
if (!upring || !upring.address || !upring.port) {
callback(new Error('peer has invalid upring metadata'))
return
}
// TODO simplify all this logic
// and avoid allocating a closure
if (typeof _count !== 'number') {
_count = 0
} else if (_count === 3) {
callback(new Error('retried three times'))
return
} else {
_count++
}
const conn = this.peerConn(peer)
if (conn.destroyed) {
// TODO make this dependent on the gossip interval
setTimeout(retry, 500, this, 'fire', obj, callback, _count)
return
}
conn.fire(obj, (err) => {
if (err) {
// the peer has changed
if (this._hashring.lookup(obj.key).id !== peer.id || conn.destroyed) {
// TODO make this dependent on the gossip interval
setTimeout(retry, 500, this, 'fire', obj, callback, _count)
return
}
}
callback(err)
})
}
return this
}
function fireCallback (err) {
if (err) {
this.log.debug(err, 'fire and forget')
}
}
function retry (that, method, obj, callback, _count) {
that[method](obj, callback, _count)
}
UpRing.prototype.add = function (pattern, schema, func) {
if (!this._router) {
this._router = bloomrun()
monitoring(this)
}
if (typeof schema === 'function') {
func = schema
schema = null
}
func[symbolSchema] = schema === null ? null : ajv.compile(schema)
if (typeof pattern === 'string') {
let sonic = tinysonic(pattern)
if (sonic) {
pattern = sonic
} else {
pattern = { cmd: pattern }
}
}
this._router.add(pattern, func)
}
function noop () {}
module.exports = UpRing