feat(raft-library): task 3.1 — raft_init validation, state init, raft_snapshot; 12 tests

This commit is contained in:
Rongsong Shen 2026-05-31 05:18:42 +00:00
parent d109155a21
commit 1aa7db4583
4 changed files with 368 additions and 8 deletions

View file

@ -12,8 +12,40 @@ void raft_snapshot(const raft_state_t *s, raft_snapshot_t *snap)
int raft_init(raft_state_t *s, const raft_config_t *cfg)
{
(void)s;
(void)cfg;
/* Validate required callbacks and n_peers before touching *s */
if (cfg->n_peers < 1)
return -EINVAL;
if (!cfg->cbs)
return -EINVAL;
if (!cfg->cbs->on_send_vote_request)
return -EINVAL;
if (!cfg->cbs->on_become_leader)
return -EINVAL;
if (!cfg->cbs->on_become_follower)
return -EINVAL;
if (!cfg->cbs->on_persist)
return -EINVAL;
if (!cfg->cbs->on_schedule_timeout)
return -EINVAL;
if (!cfg->cbs->on_cancel_timeout)
return -EINVAL;
if (!cfg->cbs->on_start_election_after_delay)
return -EINVAL;
s->term = cfg->initial_term;
s->role = RAFT_FOLLOWER;
s->voted_for = cfg->initial_voted_for;
s->voted_for_term = 0;
s->n_peers = cfg->n_peers;
s->self_idx = cfg->self_idx;
s->votes_granted = 0;
s->replies_received = 0;
s->election_decided = 0;
s->election_timeout_ms = cfg->election_timeout_ms ? cfg->election_timeout_ms : 2000;
s->my_priority = cfg->my_priority;
s->cbs = cfg->cbs;
s->ctx = cfg->ctx;
return 0;
}

View file

@ -12,6 +12,9 @@ typedef enum {
RAFT_LEADER = 2,
} raft_role_t;
/* Forward declaration — full definition follows raft_state_t */
typedef struct raft_callbacks_t raft_callbacks_t;
/* raft_state_t: pure Raft consensus state for one node.
*
* Contains only the Raft invariant state. Application-specific fields
@ -29,6 +32,9 @@ typedef struct {
int election_decided; /* 1 once on_become_leader/follower fired */
uint32_t election_timeout_ms;
int my_priority; /* priority index for jitter (0 = highest) */
/* set by raft_init — needed by the state machine to fire callbacks */
const raft_callbacks_t *cbs;
void *ctx;
} raft_state_t;
/* raft_snapshot_t: point-in-time read of all Raft state for logging/debugging */
@ -57,7 +63,7 @@ typedef struct {
* on_vote_eligible — if NULL, all Raft-eligible candidates are granted
* on_trace — if NULL, tracing is suppressed
*/
typedef struct {
typedef struct raft_callbacks_t {
/* REQUIRED: Send a RequestVote RPC to peer peer_idx for the given term.
* The caller encodes config_tag, log_lsn, and any other fields in the wire RPC. */
int (*on_send_vote_request)(void *ctx, int peer_idx, uint64_t term);