forked from royaltm/node-zmq-raft
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstate_machine_writer.js
48 lines (41 loc) · 1.42 KB
/
state_machine_writer.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
/*
* Copyright (c) 2016-2017 Rafał Michalski <[email protected]>
*/
"use strict";
const { Writable } = require('stream');
/**
* Creates stateMachine stream writer
*
* Writer expects each written chunk to be an array of buffers
* representing log entries starting from index `firstIndex`.
*
* @param {StateMachineBase} stateMachine
* @param {number} firstIndex
* @param {number} currentTerm
* @param {SnapshotFile} [snapshot]
* @return {Promise}
**/
class StateMachineWriter extends Writable {
constructor(stateMachine, firstIndex, currentTerm, snapshot) {
super({objectMode: true, highWaterMark: 2});
this.stateMachine = stateMachine;
this.currentTerm = currentTerm;
this.index = firstIndex;
this._applying = snapshot ? stateMachine.applyEntries([], firstIndex, currentTerm, snapshot)
.catch(err => this.emit('error', err))
: Promise.resolve();
}
_write(entries, encoding, callback) {
this._applying.then(() => {
var nextIndex = this.index;
return this._applying = this.stateMachine.applyEntries(entries, nextIndex, this.currentTerm)
.then(lastApplied => {
nextIndex += entries.length;
this.index = nextIndex;
if (lastApplied !== nextIndex - 1) throw new Error("applying entries failed");
callback();
});
}).catch(err => callback(err));
}
}
module.exports = StateMachineWriter;