UNPKG

hamok

Version:

Lightweight Distributed Object Storage on RAFT consensus algorithm

120 lines (119 loc) 3.71 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.RaftAppendEntriesRequest = void 0; class RaftAppendEntriesRequest { _peerId; _term = -1; _leaderId; _prevLogIndex = -1; _prevLogTerm = -1; _leaderCommit = -1; _leaderNextIndex = -1; _entries = new Map(); _ready = false; _endSeq = -1; _created = Date.now(); _received = 0; _entriesList = []; requestId; constructor(requestId) { this.requestId = requestId; } add(requestChunk) { if (requestChunk.requestId !== this.requestId) { throw new Error(`Request id mismatch. Expected ${this.requestId}, got ${requestChunk.requestId}`); } if (this._peerId == null) { this._peerId = requestChunk.peerId; } if (this._term < 0) { this._term = requestChunk.term; } if (this._leaderId == null) { this._leaderId = requestChunk.leaderId; } if (this._prevLogIndex < 0) { this._prevLogIndex = requestChunk.prevLogIndex; } if (this._prevLogTerm < 0) { this._prevLogTerm = requestChunk.prevLogTerm; } if (this._leaderCommit < 0) { this._leaderCommit = requestChunk.leaderCommit; } if (this._leaderNextIndex < 0) { this._leaderNextIndex = requestChunk.leaderNextIndex; } if (requestChunk.entry != undefined) { const removedEntry = this._entries.get(requestChunk.sequence); this._entries.set(requestChunk.sequence, requestChunk.entry); if (removedEntry != null) { throw new Error(`Overwritten log entry for requestChunk: ${requestChunk}. removedEntry: ${removedEntry}`); } } if (requestChunk.lastMessage) { this._endSeq = requestChunk.sequence; } if (this._endSeq == 0) { // in this case the first message is the last, // so its immediately ready this._ready = true; } else if (0 < this._endSeq) { // in this case the saved number of entries have to be equal to the endseq this._ready = (this._entries.size - 1) == this._endSeq; } if (this._ready) { const entriesList = []; for (let index = 0; index < this._entries.size; ++index) { const entry = this._entries.get(index); if (!entry) { continue; } entriesList.push(entry); } this._entriesList = entriesList; } } get peerId() { return this._peerId; } get term() { return this._term; } get leaderId() { return this._leaderId; } get prevLogIndex() { return this._prevLogIndex; } get prevLogTerm() { return this._prevLogTerm; } get leaderCommit() { return this._leaderCommit; } get leaderNextIndex() { return this._leaderNextIndex; } get entries() { return this._entriesList; } get ready() { return this._ready; } toString() { return JSON.stringify({ peerId: this._peerId, term: this._term, leaderId: this._leaderId, prevLogIndex: this._prevLogIndex, prevLogTerm: this._prevLogTerm, leaderCommit: this._leaderCommit, leaderNextIndex: this._leaderNextIndex, endSeq: this._endSeq, ready: this._ready }, null, 2); } } exports.RaftAppendEntriesRequest = RaftAppendEntriesRequest;