feat(raft-library): task 3.4 — raft_on_vote_reply quorum tracking; 6 tests + review fixes
This commit is contained in:
parent
e0bcb35554
commit
f81054930f
3 changed files with 328 additions and 7 deletions
|
|
@ -163,11 +163,63 @@ int raft_on_vote_request(raft_state_t *s, int from_idx, uint64_t term,
|
|||
|
||||
int raft_on_vote_reply(raft_state_t *s, int from_idx, int granted, uint64_t term)
|
||||
{
|
||||
(void)s;
|
||||
(void)from_idx;
|
||||
(void)granted;
|
||||
(void)term;
|
||||
return 0;
|
||||
|
||||
if (s->cbs->on_trace)
|
||||
s->cbs->on_trace(s->ctx, "vote_reply_in", NULL);
|
||||
|
||||
/* Step 1: term upgrade — higher term means we lost the election */
|
||||
if (term > s->term) {
|
||||
s->term = term;
|
||||
s->role = RAFT_FOLLOWER;
|
||||
s->election_decided = 1;
|
||||
s->cbs->on_become_follower(s->ctx, s->term, -1);
|
||||
s->cbs->on_cancel_timeout(s->ctx);
|
||||
if (s->cbs->on_trace)
|
||||
s->cbs->on_trace(s->ctx, "became_follower", NULL);
|
||||
return RAFT_BECAME_FOLLOWER;
|
||||
}
|
||||
|
||||
/* Step 2: no-op guard — election already decided */
|
||||
if (s->election_decided) {
|
||||
if (s->cbs->on_trace)
|
||||
s->cbs->on_trace(s->ctx, "vote_reply_noop", NULL);
|
||||
return RAFT_PENDING;
|
||||
}
|
||||
|
||||
/* Step 3: count this reply */
|
||||
s->replies_received++;
|
||||
|
||||
/* Step 4: accumulate grant */
|
||||
if (granted)
|
||||
s->votes_granted++;
|
||||
|
||||
/* Step 5: quorum check */
|
||||
int quorum = (s->n_peers / 2) + 1;
|
||||
if (s->votes_granted >= quorum) {
|
||||
s->role = RAFT_LEADER;
|
||||
s->election_decided = 1;
|
||||
s->cbs->on_become_leader(s->ctx, s->term);
|
||||
s->cbs->on_cancel_timeout(s->ctx);
|
||||
if (s->cbs->on_trace)
|
||||
s->cbs->on_trace(s->ctx, "quorum_reached", NULL);
|
||||
if (s->cbs->on_trace)
|
||||
s->cbs->on_trace(s->ctx, "became_leader", NULL);
|
||||
return RAFT_BECAME_LEADER;
|
||||
}
|
||||
|
||||
/* Step 6: all-replied-no-quorum */
|
||||
if (s->replies_received == s->n_peers - 1 && s->votes_granted < quorum) {
|
||||
s->role = RAFT_FOLLOWER;
|
||||
s->election_decided = 1;
|
||||
s->cbs->on_become_follower(s->ctx, s->term, -1);
|
||||
if (s->cbs->on_trace)
|
||||
s->cbs->on_trace(s->ctx, "became_follower", NULL);
|
||||
return RAFT_BECAME_FOLLOWER;
|
||||
}
|
||||
|
||||
/* Step 7: still waiting */
|
||||
return RAFT_PENDING;
|
||||
}
|
||||
|
||||
void raft_on_election_timeout(raft_state_t *s)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue