feat(raft-library): task 2.1 — raft_role_t, raft_state_t, raft_snapshot_t in raft.h

This commit is contained in:
Rongsong Shen 2026-05-31 04:56:49 +00:00
parent 7f7de013b9
commit 66c9810823
3 changed files with 49 additions and 4 deletions

View file

@ -8,7 +8,7 @@
- _Requirements: 8.3_
- [ ] 2. Public API definition (raft.h)
- [ ] 2.1 Define core data structures: raft_role_t, raft_state_t, raft_snapshot_t
- [x] 2.1 Define core data structures: raft_role_t, raft_state_t, raft_snapshot_t
- `raft_role_t` enum: `FOLLOWER=0`, `CANDIDATE=1`, `LEADER=2`
- `raft_state_t` struct: `term`, `role`, `voted_for`, `voted_for_term`, `n_peers`, `self_idx`, `votes_granted`, `replies_received`, `election_decided`, `election_timeout_ms`, `my_priority`
- `raft_snapshot_t`: point-in-time read of `term`, `role`, `voted_for`, `voted_for_term`, `votes_granted`, `election_decided`; `raft_snapshot()` signature declared

View file

@ -1,3 +1,11 @@
#include "raft.h"
/* raft library — populated in task 2 */
void raft_snapshot(const raft_state_t *s, raft_snapshot_t *snap)
{
snap->term = s->term;
snap->role = s->role;
snap->voted_for = s->voted_for;
snap->voted_for_term = s->voted_for_term;
snap->votes_granted = s->votes_granted;
snap->election_decided = s->election_decided;
}

View file

@ -1,10 +1,47 @@
#ifndef RAFT_H
#define RAFT_H
/* raft library — populated in task 2 */
#include <errno.h>
#include <stdint.h>
#include <string.h>
/* raft_role_t: self-contained role enum (does not depend on ctrl_role_t) */
typedef enum {
RAFT_FOLLOWER = 0,
RAFT_CANDIDATE = 1,
RAFT_LEADER = 2,
} raft_role_t;
/* raft_state_t: pure Raft consensus state for one node.
*
* Contains only the Raft invariant state. Application-specific fields
* (config_tag, log_lsn, heartbeat timestamps, ctrl_role) stay in ha_state_t;
* they are accessed by the caller via the on_vote_eligible callback. */
typedef struct {
uint64_t term; /* current term (monotonically increasing) */
raft_role_t role; /* current role */
int voted_for; /* peer index voted for this term; -1=none; self_idx=self-vote */
uint64_t voted_for_term; /* term in which voted_for was set */
int n_peers; /* total cluster size (including self) */
int self_idx; /* this node's index in [0, n_peers) */
int votes_granted; /* votes collected in current election */
int replies_received; /* total peer replies received (for all-replied-no-quorum, Req 4.4) */
int election_decided; /* 1 once on_become_leader/follower fired */
uint32_t election_timeout_ms;
int my_priority; /* priority index for jitter (0 = highest) */
} raft_state_t;
/* raft_snapshot_t: point-in-time read of all Raft state for logging/debugging */
typedef struct {
uint64_t term;
raft_role_t role;
int voted_for;
uint64_t voted_for_term;
int votes_granted;
int election_decided;
} raft_snapshot_t;
/* Fills snap with current state. Caller must hold lock. */
void raft_snapshot(const raft_state_t *s, raft_snapshot_t *snap);
#endif /* RAFT_H */