Skip to content

Commit

Permalink
OnRequestVote implemented
Browse files Browse the repository at this point in the history
  • Loading branch information
resetius committed Nov 24, 2023
1 parent 0fc8923 commit bcc2ba6
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
34 changes: 34 additions & 0 deletions src/raft.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,40 @@ TRaft::TRaft(int node, const TNodeDict& nodes, const std::shared_ptr<ITimeSource
{ }

std::unique_ptr<TResult> TRaft::OnRequestVote(TMessageHolder<TRequestVoteRequest> message) {
if (message->Term < State->CurrentTerm) {
auto reply = NewHoldedMessage<TRequestVoteResponse>(static_cast<uint32_t>(EMessageType::REQUEST_VOTE_RESPONSE), sizeof(TRequestVoteResponse));
reply->Src = Id;
reply->Dst = message->Src;
reply->Term = State->CurrentTerm;
reply->VoteGranted = false;
return std::make_unique<TResult>(TResult {
.Message = reply
});
} else if (message->Term == State->CurrentTerm) {
bool accept = false;
if (State->VotedFor == 0) {
accept = true;
} else if (State->VotedFor == message->CandidateId && message->LastLogTerm > State->LogTerm()) {
accept = true;
} else if (State->VotedFor == message->CandidateId && message->LastLogTerm == State->LogTerm() && message->LastLogIndex >= State->Log.size()) {
accept = true;
}

auto reply = NewHoldedMessage<TRequestVoteResponse>(static_cast<uint32_t>(EMessageType::REQUEST_VOTE_RESPONSE), sizeof(TRequestVoteResponse));
reply->Src = Id;
reply->Dst = message->Src;
reply->Term = message->Term;
reply->VoteGranted = accept;

return std::make_unique<TResult>(TResult {
.NextState = std::make_unique<TState>(TState{
.CurrentTerm = message->Term,
.VotedFor = message->CandidateId
}),
.Message = reply,
});
}

return nullptr;
}

Expand Down
6 changes: 3 additions & 3 deletions src/raft.h
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ class TNode: public INode {
};

struct TState {
int CurrentTerm = 1;
int VotedFor = 0;
uint64_t CurrentTerm = 1;
uint32_t VotedFor = 0;
std::vector<TMessageHolder<TLogEntry>> Log;

int LogTerm(int index = -1) const {
Expand Down Expand Up @@ -105,7 +105,7 @@ class TRaft {
TMessageHolder<TRequestVoteRequest> CreateVote();
std::vector<TMessageHolder<TAppendEntriesRequest>> CreateAppendEntries();

int Id;
uint32_t Id;
TNodeDict Nodes;
std::shared_ptr<ITimeSource> TimeSource;
int MinVotes;
Expand Down

0 comments on commit bcc2ba6

Please sign in to comment.