feat(raft-library): task 4.1 — sim data structures, raft_sim_init, dump_log; 2 tests

This commit is contained in:
Rongsong Shen 2026-05-31 06:11:34 +00:00
parent 85a7e325a8
commit d2e2c1ef8a
4 changed files with 349 additions and 2 deletions

View file

@ -192,4 +192,85 @@ int raft_check_and_start_election(raft_state_t *s);
/* Fills snap with current state. Caller must hold lock. */
void raft_snapshot(const raft_state_t *s, raft_snapshot_t *snap);
/* ---------- deterministic simulator (test builds only) ---------- */
#ifdef XCE_TESTING
#include <stdio.h>
#define RAFT_SIM_MAX_NODES 8
/* Buffered RPC entry: one pending vote-request to route */
typedef struct {
int src;
int dst;
uint64_t term;
} raft_sim_rpc_t;
/* One simulated node */
typedef struct {
raft_state_t state;
raft_callbacks_t cbs; /* wired to sim routing functions */
void *ctx; /* points back to raft_sim_cluster_t */
int idx;
int partition; /* 1 = isolated from other nodes */
/* per-node trace event log for test assertions */
char trace_buf[4096];
int trace_len;
} raft_sim_node_t;
/* N-node simulation cluster */
typedef struct {
raft_sim_node_t nodes[RAFT_SIM_MAX_NODES];
int n;
int leader_count; /* incremented by each on_become_leader */
/* buffered RPC queue */
raft_sim_rpc_t pending[64];
int pending_count;
} raft_sim_cluster_t;
/*
* raft_sim_init: initialize an n-node simulation cluster.
* Each node gets index 0..n-1, priority=idx, election_timeout_ms as given.
* Wires on_send_vote_request to buffer RPCs into c->pending.
* Wires on_become_leader to increment c->leader_count.
* All other required callbacks get no-op implementations.
* on_trace appends to the node's trace_buf.
* Returns 0 on success.
*/
int raft_sim_init(raft_sim_cluster_t *c, int n_nodes,
uint32_t election_timeout_ms);
/*
* raft_sim_dump_log: print trace logs for all nodes to fp.
* If RAFT_SIM_VERBOSE env var is set, always prints.
*/
void raft_sim_dump_log(raft_sim_cluster_t *c, FILE *fp);
/*
* raft_sim_deliver_pending: route all buffered RPCs synchronously.
* For each buffered (src, dst, term), calls raft_on_vote_request on dst
* then routes the reply back to src via raft_on_vote_reply.
* Skips delivery if dst has partition=1.
*/
void raft_sim_deliver_pending(raft_sim_cluster_t *c);
/*
* raft_sim_start_all_elections: call raft_start_election on each node 0..n-1.
*/
void raft_sim_start_all_elections(raft_sim_cluster_t *c);
/*
* raft_sim_fire_timeout: call raft_on_election_timeout on node at node_idx.
*/
void raft_sim_fire_timeout(raft_sim_cluster_t *c, int node_idx);
/*
* raft_sim_partition: set/clear partition flag for node_idx.
* Subsequent raft_sim_deliver_pending drops RPCs to/from that node.
*/
void raft_sim_partition(raft_sim_cluster_t *c, int node_idx, int isolated);
#endif /* XCE_TESTING */
#endif /* RAFT_H */