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;
}