This repository has been archived by the owner on Dec 22, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
skiff.js
333 lines (283 loc) · 7.62 KB
/
skiff.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
'use strict'
const debug = require('debug')('skiff.node')
const merge = require('deepmerge')
const EventEmitter = require('events')
const async = require('async')
const Levelup = require('levelup')
const Address = require('./lib/address')
const Network = require('./lib/network')
const IncomingDispatcher = require('./lib/incoming-dispatcher')
const Node = require('./lib/node')
const CommandQueue = require('./lib/command-queue')
const Commands = require('./lib/commands')
const DB = require('./lib/db')
const Leveldown = require('./lib/leveldown')
const Iterator = require('./lib/iterator')
const defaultOptions = require('./lib/default-options')
const importantStateEvents = [
'warning',
'new state',
'election timeout',
'leader',
'rpc latency',
'joined',
'left'
]
class Shell extends EventEmitter {
constructor (id, _options) {
super()
this.id = Address(id)
this._options = merge(defaultOptions, _options || {})
debug('creating node %s with peers %j', id, this._options.peers)
this._ownsNetwork = false
this._db = new DB(this._options.location, this.id, this._options.db, this._options.levelup)
this._dispatcher = new IncomingDispatcher({id})
const connections = {
isConnectedTo: (addr) => this._connections.indexOf(addr) >= 0
}
// connections
this._connections = this._options.peers.filter(addr => addr !== id)
this.on('connect', peer => {
if (this._connections.indexOf(peer) < 0) {
this._connections.push(peer)
}
})
this.on('disconnect', peer => {
this._connections = this._connections.filter(c => c !== peer)
})
this._node = new Node(
this.id,
connections,
this._dispatcher,
this._db,
this.peers.bind(this),
this._options)
// propagate important events
importantStateEvents.forEach(event => this._node.on(event, this.emit.bind(this, event)))
this._commandQueue = new CommandQueue()
this._commands = new Commands(this.id, this._commandQueue, this._node)
this._startState = 'stopped'
// stats
this._stats = {
messagesReceived: 0,
messagesSent: 0,
rpcSent: 0,
rpcReceived: 0,
rpcReceivedByType: {
'AppendEntries': 0,
'RequestVote': 0,
'InstallSnapshot': 0
},
rpcSentByType: {
'AppendEntries': 0,
'RequestVote': 0,
'InstallSnapshot': 0
}
}
this._node.on('message received', () => {
this._stats.messagesReceived ++
})
this._node.on('message sent', () => {
this._stats.messagesSent ++
})
this._node.on('rpc sent', (type) => {
this._stats.rpcSent ++
this._stats.rpcSentByType[type] ++
})
this._node.on('rpc received', (type) => {
this._stats.rpcReceived ++
this._stats.rpcReceivedByType[type] ++
})
}
// ------ Start and stop
start (cb) {
debug('%s: start state is %s', this.id, this._startState)
if (this._startState === 'stopped') {
this._startState = 'starting'
debug('starting node %s', this.id)
async.parallel(
[
this._startNetwork.bind(this),
this._loadPersistedState.bind(this)
],
err => {
debug('%s: done starting', this.id)
if (err) {
this._startState = 'stopped'
} else {
this._startState = 'started'
this.emit('started')
}
this._node._transition('follower')
cb(err)
})
} else if (this._startState === 'started') {
process.nextTick(cb)
} else if (this._startState === 'starting') {
this.once('started', cb)
}
}
_startNetwork (cb) {
const network = this._getNetworkConstructors()
this._network = {
passive: network.passive.node(this.id),
active: network.active.node(this.id)
}
this._network.passive.pipe(this._dispatcher, { end: false })
this._network.active.pipe(this._dispatcher, { end: false })
this._node.passive.pipe(this._network.passive, { end: false })
this._node.active.pipe(this._network.active, { end: false })
this._network.active.on('connect', peer => {
this.emit('connect', peer)
})
this._network.active.on('disconnect', peer => {
this.emit('disconnect', peer)
})
if (cb) {
if (network.passive.listening()) {
process.nextTick(cb)
} else {
network.passive.once('listening', () => {
cb() // do not carry event args into callback
})
}
}
}
_getNetworkConstructors () {
const address = this.id.nodeAddress()
let constructors = this._options.network
if (!constructors) {
this._ownsNetwork = constructors = Network({
passive: {
server: merge(
{
port: address.port,
host: address.address
},
this._options.server
)
}
})
}
return constructors
}
_loadPersistedState (cb) {
this._db.load((err, results) => {
if (err) {
cb(err)
} else {
this._node._log.setEntries(results.log)
if (results.meta.currentTerm) {
this._node._setTerm(results.meta.currentTerm)
}
if (results.meta.votedFor) {
this._node._setVotedFor(results.meta.votedFor)
}
if (results.meta.peers) {
this._node._peers = results.meta.peers
}
cb()
}
})
}
stop (cb) {
if (this._network) {
if (cb) {
if (this._ownsNetwork) {
this._ownsNetwork.passive.once('closed', cb)
} else {
process.nextTick(cb)
}
}
if (this._ownsNetwork) {
this._ownsNetwork.passive.end()
this._ownsNetwork.active.end()
this._ownsNetwork = undefined
}
this._network = undefined
} else if (cb) {
process.nextTick(cb)
}
this._node.stop()
}
// ------ Topology
join (address, done) {
debug('%s: joining %s', this.id, address)
this.start(err => {
if (err) {
done(err)
} else {
this._node.join(address, done)
}
})
}
leave (address, done) {
debug('%s: leaving %s', this.id, address)
this.start(err => {
if (err) {
done(err)
} else {
this._node.leave(address, done)
}
})
}
// ------ Commands
command (command, options, callback) {
if (typeof options === 'function') {
callback = options
options = {}
}
if (this.is('leader')) {
this._commandQueue.write({command, options, callback})
} else {
// bypass the queue if we're not the leader
this._node.command(command, options, callback)
}
}
readConsensus (callback) {
this._node.readConsensus(callback)
}
// ------- State
is (state) {
return this._node.is(state)
}
weaken (duration) {
this._node.weaken(duration)
}
// -------- Level*
leveldown () {
return new Leveldown(this)
}
levelup (options) {
return Levelup(this.id, Object.assign({}, {
db: this.leveldown.bind(this),
valueEncoding: 'json'
}, options))
}
iterator (options) {
return new Iterator(this, this._db.state, options)
}
// -------- Stats
stats () {
return this._stats
}
connections () {
return this._connections
}
peers (done) {
this._node.peers(this._network, done)
}
term () {
return this._node._getTerm()
}
logEntries () {
return this._node.getLogEntries()
}
}
createNodeShell.createNetwork = function createNetwork (options) {
return Network(options)
}
module.exports = createNodeShell
function createNodeShell (id, options) {
return new Shell(id, options)
}