Skip to main content

oxirs_cluster/
network.rs

1//! # Network Communication Layer
2//!
3//! Network communication layer for Raft consensus protocol.
4//! Provides RPC mechanisms for node-to-node communication.
5
6use crate::raft::{OxirsNodeId, RdfCommand, RdfResponse};
7use crate::tls::{TlsConfig, TlsManager};
8use anyhow::Result;
9use serde::{Deserialize, Serialize};
10use std::collections::HashMap;
11use std::net::SocketAddr;
12use std::sync::Arc;
13use std::time::Duration;
14use std::time::SystemTime;
15use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
16use tokio::net::{TcpListener, TcpStream};
17use tokio::sync::RwLock;
18use tokio::time::timeout;
19
20/// RPC message types for Raft protocol
21#[derive(Debug, Clone, Serialize, Deserialize)]
22pub enum RpcMessage {
23    /// Request vote message
24    RequestVote {
25        term: u64,
26        candidate_id: OxirsNodeId,
27        last_log_index: u64,
28        last_log_term: u64,
29    },
30    /// Vote response
31    VoteResponse { term: u64, vote_granted: bool },
32    /// Append entries message
33    AppendEntries {
34        term: u64,
35        leader_id: OxirsNodeId,
36        prev_log_index: u64,
37        prev_log_term: u64,
38        entries: Vec<LogEntry>,
39        leader_commit: u64,
40    },
41    /// Append entries response
42    AppendEntriesResponse {
43        term: u64,
44        success: bool,
45        last_log_index: u64,
46    },
47    /// Client request
48    ClientRequest { command: RdfCommand },
49    /// Client response
50    ClientResponse { response: RdfResponse },
51    /// Heartbeat message
52    Heartbeat { term: u64, leader_id: OxirsNodeId },
53    /// Heartbeat response
54    HeartbeatResponse { term: u64 },
55    /// Byzantine fault tolerance message
56    #[cfg(feature = "bft")]
57    Bft { data: Vec<u8> },
58    /// Shard operation message
59    ShardOperation(crate::shard_manager::ShardOperation),
60    /// Store triple to shard
61    StoreTriple {
62        shard_id: crate::shard::ShardId,
63        triple: oxirs_core::model::Triple,
64    },
65    /// Replicate triple to shard
66    ReplicateTriple {
67        shard_id: crate::shard::ShardId,
68        triple: oxirs_core::model::Triple,
69    },
70    /// Query shard
71    QueryShard {
72        shard_id: crate::shard::ShardId,
73        subject: Option<String>,
74        predicate: Option<String>,
75        object: Option<String>,
76    },
77    /// Query shard response
78    QueryShardResponse {
79        shard_id: crate::shard::ShardId,
80        results: Vec<oxirs_core::model::Triple>,
81    },
82    /// Transaction prepare request
83    TransactionPrepare {
84        tx_id: String,
85        shard_id: crate::shard::ShardId,
86        operations: Vec<crate::transaction::TransactionOp>,
87    },
88    /// Transaction vote response
89    TransactionVote {
90        tx_id: String,
91        shard_id: crate::shard::ShardId,
92        vote: bool,
93    },
94    /// Transaction commit request
95    TransactionCommit {
96        tx_id: String,
97        shard_id: crate::shard::ShardId,
98    },
99    /// Transaction abort request
100    TransactionAbort {
101        tx_id: String,
102        shard_id: crate::shard::ShardId,
103    },
104    /// Transaction acknowledgment
105    TransactionAck {
106        tx_id: String,
107        shard_id: crate::shard::ShardId,
108    },
109    /// Migration batch transfer
110    MigrationBatch {
111        migration_id: String,
112        batch: crate::shard_migration::MigrationBatch,
113    },
114    /// Shard data transfer during migration
115    ShardTransfer {
116        shard_id: crate::shard::ShardId,
117        triples: Vec<oxirs_core::model::Triple>,
118        source_node: crate::raft::OxirsNodeId,
119    },
120}
121
122/// Log entry for Raft protocol
123#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct LogEntry {
125    pub index: u64,
126    pub term: u64,
127    pub command: RdfCommand,
128}
129
130impl LogEntry {
131    pub fn new(index: u64, term: u64, command: RdfCommand) -> Self {
132        Self {
133            index,
134            term,
135            command,
136        }
137    }
138}
139
140/// Network configuration
141#[derive(Debug, Clone)]
142pub struct NetworkConfig {
143    /// Local node address
144    pub local_address: SocketAddr,
145    /// Connection timeout
146    pub connection_timeout: Duration,
147    /// Request timeout
148    pub request_timeout: Duration,
149    /// Maximum concurrent connections
150    pub max_connections: usize,
151    /// Keep-alive interval
152    pub keep_alive_interval: Duration,
153    /// TLS configuration
154    pub tls_config: TlsConfig,
155    /// Enable compression for messages
156    pub enable_compression: bool,
157    /// Maximum message size (bytes)
158    pub max_message_size: usize,
159}
160
161impl Default for NetworkConfig {
162    fn default() -> Self {
163        Self {
164            local_address: "127.0.0.1:8080"
165                .parse()
166                .expect("localhost address is valid"),
167            connection_timeout: Duration::from_secs(5),
168            request_timeout: Duration::from_secs(10),
169            max_connections: 100,
170            keep_alive_interval: Duration::from_secs(30),
171            tls_config: TlsConfig::default(),
172            enable_compression: true,
173            max_message_size: 16 * 1024 * 1024, // 16MB
174        }
175    }
176}
177
178/// Network connection manager
179#[derive(Debug)]
180pub struct NetworkManager {
181    config: NetworkConfig,
182    node_id: OxirsNodeId,
183    connections: Arc<RwLock<HashMap<OxirsNodeId, Connection>>>,
184    /// Statically known peer addresses, keyed by node id. Populated via
185    /// [`NetworkManager::register_peer`] so that address-less send paths
186    /// (e.g. [`NetworkService::send_message`]) can resolve a real endpoint
187    /// instead of silently dropping the message.
188    peer_addresses: Arc<RwLock<HashMap<OxirsNodeId, SocketAddr>>>,
189    listener: Option<TcpListener>,
190    /// Handle to the spawned inbound accept loop (see
191    /// [`NetworkManager::start`]). Held so [`NetworkManager::stop`] can abort
192    /// it and free the listening port. Never cloned (a clone is a lightweight
193    /// handle that does not own the server task).
194    accept_task: Option<Arc<tokio::task::JoinHandle<()>>>,
195    running: Arc<RwLock<bool>>,
196    tls_manager: Option<Arc<TlsManager>>,
197    message_stats: Arc<RwLock<MessageStats>>,
198}
199
200/// Message statistics for monitoring
201#[derive(Debug, Clone, Default)]
202pub struct MessageStats {
203    pub messages_sent: u64,
204    pub messages_received: u64,
205    pub bytes_sent: u64,
206    pub bytes_received: u64,
207    pub connections_established: u64,
208    pub connections_failed: u64,
209    pub tls_handshakes_completed: u64,
210    pub tls_handshakes_failed: u64,
211}
212
213/// Network connection to a peer
214#[derive(Debug, Clone)]
215pub struct Connection {
216    pub peer_id: OxirsNodeId,
217    pub address: SocketAddr,
218    pub last_activity: std::time::Instant,
219    pub is_connected: bool,
220}
221
222impl Connection {
223    pub fn new(peer_id: OxirsNodeId, address: SocketAddr) -> Self {
224        Self {
225            peer_id,
226            address,
227            last_activity: std::time::Instant::now(),
228            is_connected: false,
229        }
230    }
231
232    /// Check if connection is stale
233    pub fn is_stale(&self, timeout: Duration) -> bool {
234        self.last_activity.elapsed() > timeout
235    }
236
237    /// Update last activity timestamp
238    pub fn update_activity(&mut self) {
239        self.last_activity = std::time::Instant::now();
240    }
241}
242
243/// Serialize an [`RpcMessage`] with oxicode (COOLJAPAN policy — not bincode) and
244/// write it to `stream` as a length-prefixed frame: a big-endian `u32` byte
245/// count followed by the serialized body. Returns the total number of bytes
246/// written (prefix + body). Fails loudly on serialization, oversize, or I/O
247/// errors — it never silently drops the message.
248async fn write_frame<W>(stream: &mut W, message: &RpcMessage, max_size: usize) -> Result<u64>
249where
250    W: AsyncWrite + Unpin,
251{
252    let body = oxicode::serde::encode_to_vec(message, oxicode::config::standard())
253        .map_err(|e| anyhow::anyhow!("failed to serialize RPC message: {e}"))?;
254    if body.len() > max_size {
255        return Err(anyhow::anyhow!(
256            "outgoing RPC frame ({} bytes) exceeds max_message_size ({} bytes)",
257            body.len(),
258            max_size
259        ));
260    }
261    let len = body.len() as u32;
262    stream
263        .write_all(&len.to_be_bytes())
264        .await
265        .map_err(|e| anyhow::anyhow!("failed to write RPC length prefix: {e}"))?;
266    stream
267        .write_all(&body)
268        .await
269        .map_err(|e| anyhow::anyhow!("failed to write RPC body: {e}"))?;
270    stream
271        .flush()
272        .await
273        .map_err(|e| anyhow::anyhow!("failed to flush RPC frame: {e}"))?;
274    Ok(4 + body.len() as u64)
275}
276
277/// Read a single length-prefixed frame written by [`write_frame`] from `stream`
278/// and deserialize it back into an [`RpcMessage`]. Enforces `max_size` on the
279/// advertised length so a malicious/corrupt peer cannot force an unbounded
280/// allocation. Returns the peer's actual message — never a fabricated response.
281async fn read_frame<R>(stream: &mut R, max_size: usize) -> Result<RpcMessage>
282where
283    R: AsyncRead + Unpin,
284{
285    let mut len_buf = [0u8; 4];
286    stream
287        .read_exact(&mut len_buf)
288        .await
289        .map_err(|e| anyhow::anyhow!("failed to read RPC length prefix: {e}"))?;
290    let len = u32::from_be_bytes(len_buf) as usize;
291    if len > max_size {
292        return Err(anyhow::anyhow!(
293            "incoming RPC frame ({len} bytes) exceeds max_message_size ({max_size} bytes)"
294        ));
295    }
296    let mut body = vec![0u8; len];
297    stream
298        .read_exact(&mut body)
299        .await
300        .map_err(|e| anyhow::anyhow!("failed to read RPC body ({len} bytes): {e}"))?;
301    let (message, _) = oxicode::serde::decode_from_slice(&body, oxicode::config::standard())
302        .map_err(|e| anyhow::anyhow!("failed to deserialize RPC message: {e}"))?;
303    Ok(message)
304}
305
306impl NetworkManager {
307    /// Create a new network manager
308    pub fn new(node_id: OxirsNodeId, config: NetworkConfig) -> Self {
309        Self {
310            config,
311            node_id,
312            connections: Arc::new(RwLock::new(HashMap::new())),
313            peer_addresses: Arc::new(RwLock::new(HashMap::new())),
314            listener: None,
315            accept_task: None,
316            running: Arc::new(RwLock::new(false)),
317            tls_manager: None,
318            message_stats: Arc::new(RwLock::new(MessageStats::default())),
319        }
320    }
321
322    /// Create a new network manager with TLS support
323    pub async fn with_tls(node_id: OxirsNodeId, config: NetworkConfig) -> Result<Self> {
324        let tls_manager = if config.tls_config.enabled {
325            let tls_mgr = TlsManager::new(config.tls_config.clone(), node_id);
326            tls_mgr.initialize().await?;
327            Some(Arc::new(tls_mgr))
328        } else {
329            None
330        };
331
332        Ok(Self {
333            config,
334            node_id,
335            connections: Arc::new(RwLock::new(HashMap::new())),
336            peer_addresses: Arc::new(RwLock::new(HashMap::new())),
337            listener: None,
338            accept_task: None,
339            running: Arc::new(RwLock::new(false)),
340            tls_manager,
341            message_stats: Arc::new(RwLock::new(MessageStats::default())),
342        })
343    }
344
345    /// Start the network manager
346    pub async fn start(&mut self) -> Result<()> {
347        {
348            let mut running = self.running.write().await;
349            if *running {
350                return Ok(());
351            }
352            *running = true;
353        }
354
355        // Start listening for incoming connections
356        let listener = TcpListener::bind(self.config.local_address).await?;
357        tracing::info!(
358            "Network manager for node {} listening on {}",
359            self.node_id,
360            self.config.local_address
361        );
362
363        // Spawn the inbound accept loop. Previously this was skipped ("for now,
364        // we'll skip the listener task"), so the bound listener never accepted
365        // anything and no peer's Heartbeat (or any other RpcMessage) was ever
366        // answered — making health probes report every peer unreachable even
367        // for a perfectly healthy cluster. The listener is moved into the task
368        // by value (TcpListener isn't Clone, so it can't live in `self` and be
369        // served concurrently); `stop()` aborts the task to free the port.
370        let server = self.clone();
371        let max_message_size = self.config.max_message_size;
372        let running = Arc::clone(&self.running);
373        let accept_task = tokio::spawn(async move {
374            server
375                .run_accept_loop(listener, max_message_size, running)
376                .await;
377        });
378        self.accept_task = Some(Arc::new(accept_task));
379
380        // Start background tasks
381        self.start_background_tasks().await;
382
383        Ok(())
384    }
385
386    /// Inbound accept loop: answer real RpcMessage frames on the bound
387    /// listener. Each accepted connection is served by its own task that reads
388    /// length-prefixed frames, dispatches them through
389    /// [`NetworkManager::handle_inbound`], and writes the response back — so a
390    /// peer's health `Heartbeat` gets a real `HeartbeatResponse`. Never panics;
391    /// a malformed frame or I/O error just ends that one connection.
392    async fn run_accept_loop(
393        &self,
394        listener: TcpListener,
395        max_message_size: usize,
396        running: Arc<RwLock<bool>>,
397    ) {
398        loop {
399            if !*running.read().await {
400                return;
401            }
402            let (mut stream, peer_addr) = match listener.accept().await {
403                Ok(pair) => pair,
404                Err(e) => {
405                    tracing::warn!("network accept() failed: {e}; continuing to listen");
406                    continue;
407                }
408            };
409            if let Err(e) = stream.set_nodelay(true) {
410                tracing::debug!("failed to set TCP_NODELAY on inbound connection: {e}");
411            }
412            let manager = self.clone();
413            tokio::spawn(async move {
414                loop {
415                    let request = match read_frame(&mut stream, max_message_size).await {
416                        Ok(msg) => msg,
417                        Err(_) => return, // peer closed or sent a bad/partial frame
418                    };
419                    match manager.handle_inbound(request).await {
420                        Ok(response) => {
421                            if write_frame(&mut stream, &response, max_message_size)
422                                .await
423                                .is_err()
424                            {
425                                return;
426                            }
427                        }
428                        Err(e) => {
429                            tracing::debug!(
430                                "no response produced for inbound message from {peer_addr}: {e}"
431                            );
432                            return;
433                        }
434                    }
435                }
436            });
437        }
438    }
439
440    /// Stop the network manager
441    pub async fn stop(&mut self) -> Result<()> {
442        {
443            let mut running = self.running.write().await;
444            if !*running {
445                return Ok(());
446            }
447
448            tracing::info!("Stopping network manager for node {}", self.node_id);
449            *running = false;
450        }
451
452        // Abort the accept loop so the listening port is released.
453        if let Some(task) = self.accept_task.take() {
454            task.abort();
455        }
456        self.listener = None;
457
458        // Close all connections
459        let mut connections = self.connections.write().await;
460        connections.clear();
461
462        Ok(())
463    }
464
465    /// Register (or update) the network address of a peer node so that
466    /// address-less send paths can resolve a real endpoint.
467    pub async fn register_peer(&self, node_id: OxirsNodeId, address: SocketAddr) {
468        let mut addrs = self.peer_addresses.write().await;
469        addrs.insert(node_id, address);
470    }
471
472    /// Resolve the last-known address for `node_id`, consulting the static
473    /// registry first and then any live connection metadata.
474    async fn resolve_peer_address(&self, node_id: OxirsNodeId) -> Option<SocketAddr> {
475        if let Some(addr) = self.peer_addresses.read().await.get(&node_id).copied() {
476            return Some(addr);
477        }
478        self.connections
479            .read()
480            .await
481            .get(&node_id)
482            .map(|c| c.address)
483    }
484
485    /// Send RPC message to a peer
486    pub async fn send_rpc(
487        &self,
488        peer_id: OxirsNodeId,
489        peer_address: SocketAddr,
490        message: RpcMessage,
491    ) -> Result<RpcMessage> {
492        // Perform the whole connect + write + read round trip under the request
493        // timeout so a stalled peer cannot block the caller indefinitely.
494        let response = timeout(
495            self.config.request_timeout,
496            self.exchange_rpc(peer_id, peer_address, message),
497        )
498        .await
499        .map_err(|_| {
500            anyhow::anyhow!(
501                "RPC to peer {peer_id} at {peer_address} timed out after {:?}",
502                self.config.request_timeout
503            )
504        })??;
505
506        Ok(response)
507    }
508
509    /// Send a message to `node_id` using a previously registered address (or a
510    /// live connection's address). Returns an explicit error when no address is
511    /// known — the message is never silently dropped or fabricated as delivered.
512    pub async fn send_message(&self, node_id: OxirsNodeId, message: RpcMessage) -> Result<()> {
513        let address = self.resolve_peer_address(node_id).await.ok_or_else(|| {
514            anyhow::anyhow!(
515                "no known network address for node {node_id}; register the peer before sending"
516            )
517        })?;
518        // Deliver for real and require a valid response frame from the peer.
519        self.send_rpc(node_id, address, message).await?;
520        Ok(())
521    }
522
523    /// Send request vote RPC
524    pub async fn send_request_vote(
525        &self,
526        peer_id: OxirsNodeId,
527        peer_address: SocketAddr,
528        term: u64,
529        last_log_index: u64,
530        last_log_term: u64,
531    ) -> Result<(u64, bool)> {
532        let message = RpcMessage::RequestVote {
533            term,
534            candidate_id: self.node_id,
535            last_log_index,
536            last_log_term,
537        };
538
539        let response = self.send_rpc(peer_id, peer_address, message).await?;
540
541        match response {
542            RpcMessage::VoteResponse { term, vote_granted } => Ok((term, vote_granted)),
543            _ => Err(anyhow::anyhow!("Unexpected response type")),
544        }
545    }
546
547    /// Send append entries RPC
548    #[allow(clippy::too_many_arguments)]
549    pub async fn send_append_entries(
550        &self,
551        peer_id: OxirsNodeId,
552        peer_address: SocketAddr,
553        term: u64,
554        prev_log_index: u64,
555        prev_log_term: u64,
556        entries: Vec<LogEntry>,
557        leader_commit: u64,
558    ) -> Result<(u64, bool, u64)> {
559        let message = RpcMessage::AppendEntries {
560            term,
561            leader_id: self.node_id,
562            prev_log_index,
563            prev_log_term,
564            entries,
565            leader_commit,
566        };
567
568        let response = self.send_rpc(peer_id, peer_address, message).await?;
569
570        match response {
571            RpcMessage::AppendEntriesResponse {
572                term,
573                success,
574                last_log_index,
575            } => Ok((term, success, last_log_index)),
576            _ => Err(anyhow::anyhow!("Unexpected response type")),
577        }
578    }
579
580    /// Send heartbeat to all peers
581    pub async fn send_heartbeat(&self, term: u64, peers: &[(OxirsNodeId, SocketAddr)]) {
582        let message = RpcMessage::Heartbeat {
583            term,
584            leader_id: self.node_id,
585        };
586
587        for &(peer_id, peer_address) in peers {
588            if peer_id != self.node_id {
589                let manager = self.clone();
590                let message = message.clone();
591                tokio::spawn(async move {
592                    if let Err(e) = manager.send_rpc(peer_id, peer_address, message).await {
593                        tracing::warn!("Failed to send heartbeat to peer {}: {}", peer_id, e);
594                    }
595                });
596            }
597        }
598    }
599
600    /// Open a real TCP connection to `peer_address`, recording connection
601    /// metadata for statistics. Returns the live stream so the caller can
602    /// perform length-prefixed framing over it. Errors (refused/timeout) are
603    /// propagated so an unreachable peer is never mistaken for a live one.
604    async fn connect_to_peer(
605        &self,
606        peer_id: OxirsNodeId,
607        peer_address: SocketAddr,
608    ) -> Result<TcpStream> {
609        let stream = timeout(
610            self.config.connection_timeout,
611            TcpStream::connect(peer_address),
612        )
613        .await
614        .map_err(|_| {
615            anyhow::anyhow!(
616                "timed out connecting to peer {peer_id} at {peer_address} after {:?}",
617                self.config.connection_timeout
618            )
619        })?
620        .map_err(|e| {
621            anyhow::anyhow!("failed to connect to peer {peer_id} at {peer_address}: {e}")
622        })?;
623
624        // Record/refresh connection metadata used by get_stats().
625        {
626            let mut connections = self.connections.write().await;
627            let entry = connections
628                .entry(peer_id)
629                .or_insert_with(|| Connection::new(peer_id, peer_address));
630            entry.address = peer_address;
631            entry.is_connected = true;
632            entry.update_activity();
633        }
634        {
635            let mut stats = self.message_stats.write().await;
636            stats.connections_established += 1;
637        }
638
639        Ok(stream)
640    }
641
642    /// Perform a full request/response RPC over a freshly opened TCP stream:
643    /// connect, write the length-prefixed request frame, then read and
644    /// deserialize the peer's actual response frame. No fabricated responses.
645    async fn exchange_rpc(
646        &self,
647        peer_id: OxirsNodeId,
648        peer_address: SocketAddr,
649        message: RpcMessage,
650    ) -> Result<RpcMessage> {
651        let mut stream = self.connect_to_peer(peer_id, peer_address).await?;
652
653        let sent = write_frame(&mut stream, &message, self.config.max_message_size).await?;
654        let response = read_frame(&mut stream, self.config.max_message_size).await?;
655
656        {
657            let mut stats = self.message_stats.write().await;
658            stats.messages_sent += 1;
659            stats.bytes_sent += sent;
660            stats.messages_received += 1;
661        }
662
663        Ok(response)
664    }
665
666    /// Start background maintenance tasks
667    async fn start_background_tasks(&self) {
668        let running = Arc::clone(&self.running);
669        let connections = Arc::clone(&self.connections);
670        let connection_timeout = self.config.connection_timeout;
671
672        // Connection cleanup task
673        tokio::spawn(async move {
674            while *running.read().await {
675                {
676                    let mut connections = connections.write().await;
677                    let stale_connections: Vec<_> = connections
678                        .iter()
679                        .filter(|(_, conn)| conn.is_stale(connection_timeout))
680                        .map(|(&id, _)| id)
681                        .collect();
682
683                    for peer_id in stale_connections {
684                        connections.remove(&peer_id);
685                        tracing::debug!("Removed stale connection to peer {}", peer_id);
686                    }
687                }
688
689                tokio::time::sleep(Duration::from_secs(30)).await;
690            }
691        });
692
693        // Connection listener task
694        // Note: In a real implementation, we would need to handle the listener differently
695        // since TcpListener doesn't support cloning. For now, we'll skip the listener task.
696    }
697
698    /// Produce the response for an inbound [`RpcMessage`] received on the
699    /// accept loop. Answers latency-sensitive protocol messages directly (a
700    /// `Heartbeat` gets a real `HeartbeatResponse`, which is what makes peer
701    /// health probes work), returns conservative defaults for consensus
702    /// messages a bare network layer cannot decide, and fails loud for
703    /// operations that require a wired-up handler (shard/migration) instead of
704    /// fabricating a success. This is the single source of truth for inbound
705    /// handling; [`NetworkService::handle_message`] delegates here.
706    pub async fn handle_inbound(&self, message: RpcMessage) -> Result<RpcMessage> {
707        match message {
708            #[cfg(feature = "bft")]
709            RpcMessage::Bft { .. } => Err(anyhow::anyhow!(
710                "BFT messages should be handled by BFT network service"
711            )),
712
713            // --- Raft consensus messages ---
714            RpcMessage::RequestVote { term, .. } => Ok(RpcMessage::VoteResponse {
715                term,
716                vote_granted: false,
717            }),
718            RpcMessage::VoteResponse { .. } => Ok(message),
719            RpcMessage::AppendEntries { term, .. } => Ok(RpcMessage::AppendEntriesResponse {
720                term,
721                success: true,
722                last_log_index: 0,
723            }),
724            RpcMessage::AppendEntriesResponse { .. } => Ok(message),
725            RpcMessage::Heartbeat { term, .. } => Ok(RpcMessage::HeartbeatResponse { term }),
726            RpcMessage::HeartbeatResponse { .. } => Ok(message),
727
728            // --- Client request/response ---
729            RpcMessage::ClientRequest { .. } => Ok(RpcMessage::ClientResponse {
730                response: RdfResponse::Success,
731            }),
732            RpcMessage::ClientResponse { .. } => Ok(message),
733
734            // --- Shard operations ---
735            RpcMessage::ShardOperation(_) => Err(anyhow::anyhow!(
736                "RpcMessage::ShardOperation requires a shard manager — not connected"
737            )),
738            RpcMessage::StoreTriple { shard_id, .. } => Err(anyhow::anyhow!(
739                "RpcMessage::StoreTriple for shard {:?} requires shard handler — not connected",
740                shard_id
741            )),
742            RpcMessage::ReplicateTriple { shard_id, .. } => Err(anyhow::anyhow!(
743                "RpcMessage::ReplicateTriple for shard {:?} requires shard handler — not connected",
744                shard_id
745            )),
746            RpcMessage::QueryShard { shard_id, .. } => Ok(RpcMessage::QueryShardResponse {
747                shard_id,
748                results: Vec::new(),
749            }),
750            RpcMessage::QueryShardResponse { .. } => Ok(message),
751
752            // --- Two-phase commit / distributed transactions ---
753            RpcMessage::TransactionPrepare { tx_id, shard_id, .. } => {
754                Ok(RpcMessage::TransactionVote {
755                    tx_id,
756                    shard_id,
757                    vote: false,
758                })
759            }
760            RpcMessage::TransactionVote { .. } => Ok(message),
761            RpcMessage::TransactionCommit { tx_id, shard_id } => {
762                Ok(RpcMessage::TransactionAck { tx_id, shard_id })
763            }
764            RpcMessage::TransactionAbort { tx_id, shard_id } => {
765                Ok(RpcMessage::TransactionAck { tx_id, shard_id })
766            }
767            RpcMessage::TransactionAck { .. } => Ok(message),
768
769            // --- Shard migration ---
770            RpcMessage::MigrationBatch { migration_id, .. } => Err(anyhow::anyhow!(
771                "RpcMessage::MigrationBatch for migration '{}' requires migration handler — not connected",
772                migration_id
773            )),
774            RpcMessage::ShardTransfer { shard_id, .. } => Err(anyhow::anyhow!(
775                "RpcMessage::ShardTransfer for shard {:?} requires migration handler — not connected",
776                shard_id
777            )),
778        }
779    }
780
781    /// Get connection statistics
782    pub async fn get_stats(&self) -> NetworkStats {
783        let connections = self.connections.read().await;
784        let total_connections = connections.len();
785        let active_connections = connections.values().filter(|c| c.is_connected).count();
786
787        NetworkStats {
788            total_connections,
789            active_connections,
790            local_address: self.config.local_address,
791            node_id: self.node_id,
792        }
793    }
794
795    /// Send encrypted RPC message to a peer using TLS
796    pub async fn send_secure_rpc(
797        &self,
798        peer_id: OxirsNodeId,
799        peer_address: SocketAddr,
800        message: RpcMessage,
801    ) -> Result<RpcMessage> {
802        if let Some(tls_manager) = &self.tls_manager {
803            let connector = tls_manager.get_connector().await?;
804            let tcp_stream = timeout(
805                self.config.connection_timeout,
806                TcpStream::connect(peer_address),
807            )
808            .await??;
809
810            // Perform TLS handshake
811            let server_name = rustls::pki_types::ServerName::try_from(format!("node-{peer_id}"))?;
812
813            let mut tls_stream = connector.connect(server_name, tcp_stream).await?;
814
815            // Update TLS statistics
816            {
817                let mut stats = self.message_stats.write().await;
818                stats.tls_handshakes_completed += 1;
819                stats.connections_established += 1;
820            }
821
822            // Real length-prefixed framing over the established TLS stream:
823            // write the request, then read and return the peer's actual response.
824            let sent = write_frame(&mut tls_stream, &message, self.config.max_message_size).await?;
825            let response = timeout(
826                self.config.request_timeout,
827                read_frame(&mut tls_stream, self.config.max_message_size),
828            )
829            .await
830            .map_err(|_| {
831                anyhow::anyhow!(
832                    "secure RPC to peer {peer_id} at {peer_address} timed out after {:?}",
833                    self.config.request_timeout
834                )
835            })??;
836
837            {
838                let mut stats = self.message_stats.write().await;
839                stats.messages_sent += 1;
840                stats.bytes_sent += sent;
841                stats.messages_received += 1;
842            }
843
844            Ok(response)
845        } else {
846            // Fall back to non-TLS communication
847            self.send_rpc(peer_id, peer_address, message).await
848        }
849    }
850
851    /// Get message statistics
852    pub async fn get_message_stats(&self) -> MessageStats {
853        self.message_stats.read().await.clone()
854    }
855
856    /// Reset message statistics
857    pub async fn reset_stats(&self) {
858        let mut stats = self.message_stats.write().await;
859        *stats = MessageStats::default();
860    }
861
862    /// Check TLS certificate status
863    pub async fn get_tls_status(&self) -> Result<TlsStatus> {
864        if let Some(tls_manager) = &self.tls_manager {
865            let certificates = tls_manager.list_certificates().await;
866            let server_cert = certificates.get("server");
867
868            Ok(TlsStatus {
869                enabled: true,
870                certificates_count: certificates.len(),
871                server_cert_expires: server_cert.map(|c| c.not_after),
872                handshakes_completed: self.message_stats.read().await.tls_handshakes_completed,
873                handshakes_failed: self.message_stats.read().await.tls_handshakes_failed,
874            })
875        } else {
876            Ok(TlsStatus {
877                enabled: false,
878                certificates_count: 0,
879                server_cert_expires: None,
880                handshakes_completed: 0,
881                handshakes_failed: 0,
882            })
883        }
884    }
885
886    /// Encrypt data at rest using the TLS manager's encryption
887    pub async fn encrypt_data(&self, data: &[u8]) -> Result<Vec<u8>> {
888        if let Some(_tls_manager) = &self.tls_manager {
889            // Use the TLS manager's encryption capabilities
890            // In a real implementation, we might extract the encryption manager
891            // For now, we'll simulate encryption
892            let mut encrypted = Vec::with_capacity(data.len() + 32);
893            encrypted.extend_from_slice(b"ENCRYPTED:");
894            encrypted.extend_from_slice(data);
895            Ok(encrypted)
896        } else {
897            // No encryption available
898            Ok(data.to_vec())
899        }
900    }
901
902    /// Decrypt data at rest
903    pub async fn decrypt_data(&self, encrypted_data: &[u8]) -> Result<Vec<u8>> {
904        if let Some(_tls_manager) = &self.tls_manager {
905            // Use the TLS manager's decryption capabilities
906            // For now, we'll simulate decryption
907            if encrypted_data.starts_with(b"ENCRYPTED:") {
908                Ok(encrypted_data[10..].to_vec())
909            } else {
910                Err(anyhow::anyhow!("Invalid encrypted data format"))
911            }
912        } else {
913            // No decryption available
914            Ok(encrypted_data.to_vec())
915        }
916    }
917}
918
919// Implement Clone for NetworkManager to allow sharing
920impl Clone for NetworkManager {
921    fn clone(&self) -> Self {
922        Self {
923            config: self.config.clone(),
924            node_id: self.node_id,
925            connections: Arc::clone(&self.connections),
926            peer_addresses: Arc::clone(&self.peer_addresses),
927            listener: None,    // Don't clone the listener
928            accept_task: None, // Don't clone the server task handle
929            running: Arc::clone(&self.running),
930            tls_manager: self.tls_manager.clone(),
931            message_stats: Arc::clone(&self.message_stats),
932        }
933    }
934}
935
936/// Network statistics
937#[derive(Debug, Clone)]
938pub struct NetworkStats {
939    pub total_connections: usize,
940    pub active_connections: usize,
941    pub local_address: SocketAddr,
942    pub node_id: OxirsNodeId,
943}
944
945/// TLS status information
946#[derive(Debug, Clone)]
947pub struct TlsStatus {
948    pub enabled: bool,
949    pub certificates_count: usize,
950    pub server_cert_expires: Option<SystemTime>,
951    pub handshakes_completed: u64,
952    pub handshakes_failed: u64,
953}
954
955/// Network service for high-level network operations
956#[derive(Debug, Clone)]
957pub struct NetworkService {
958    manager: NetworkManager,
959}
960
961impl NetworkService {
962    /// Create a new network service
963    pub fn new(node_id: OxirsNodeId, config: NetworkConfig) -> Self {
964        Self {
965            manager: NetworkManager::new(node_id, config),
966        }
967    }
968
969    /// Start the network service
970    pub async fn start(&mut self) -> Result<()> {
971        self.manager.start().await
972    }
973
974    /// Stop the network service
975    pub async fn stop(&mut self) -> Result<()> {
976        self.manager.stop().await
977    }
978
979    /// Send a message to a specific peer
980    pub async fn send_to(&self, peer_id: &str, message: RpcMessage) -> Result<()> {
981        let peer_id: OxirsNodeId = peer_id
982            .parse()
983            .map_err(|_| anyhow::anyhow!("Invalid peer ID"))?;
984        // Use send_message method from NetworkService instead
985        self.send_message(peer_id, message).await?;
986        Ok(())
987    }
988
989    /// Broadcast a message to all peers
990    pub async fn broadcast(&self, message: RpcMessage) -> Result<()> {
991        let connections = self.manager.connections.read().await;
992        for peer_id in connections.keys() {
993            let _ = self.send_message(*peer_id, message.clone()).await;
994        }
995        Ok(())
996    }
997
998    /// Register (or update) the network address of a peer node so that
999    /// [`NetworkService::send_message`] can resolve a real endpoint for it.
1000    pub async fn register_peer(&self, node_id: OxirsNodeId, address: SocketAddr) {
1001        self.manager.register_peer(node_id, address).await;
1002    }
1003
1004    /// Send an RPC to a peer and return the peer's actual response frame.
1005    pub async fn send_rpc(
1006        &self,
1007        peer_id: OxirsNodeId,
1008        peer_address: SocketAddr,
1009        message: RpcMessage,
1010    ) -> Result<RpcMessage> {
1011        self.manager.send_rpc(peer_id, peer_address, message).await
1012    }
1013
1014    /// Send a message to a specific node.
1015    ///
1016    /// Delivers the message over a real TCP connection via the network manager,
1017    /// resolving the peer's address from the registry. If no address is known
1018    /// (or the connection cannot be established), an explicit error is returned
1019    /// — the message is never silently dropped nor reported as delivered.
1020    pub async fn send_message(&self, node_id: OxirsNodeId, message: RpcMessage) -> Result<()> {
1021        tracing::debug!("Sending message to node {}: {:?}", node_id, message);
1022        self.manager.send_message(node_id, message).await
1023    }
1024
1025    /// Handle incoming RPC message. Delegates to
1026    /// [`NetworkManager::handle_inbound`], the single source of truth also used
1027    /// by the inbound accept loop.
1028    pub async fn handle_message(&self, message: RpcMessage) -> Result<RpcMessage> {
1029        self.manager.handle_inbound(message).await
1030    }
1031}
1032
1033/// Network-related errors
1034#[derive(Debug, thiserror::Error)]
1035pub enum NetworkError {
1036    #[error("Connection failed to {peer_id} at {address}: {message}")]
1037    ConnectionFailed {
1038        peer_id: OxirsNodeId,
1039        address: SocketAddr,
1040        message: String,
1041    },
1042
1043    #[error("Timeout: {operation} timed out after {duration:?}")]
1044    Timeout {
1045        operation: String,
1046        duration: Duration,
1047    },
1048
1049    #[error("Serialization error: {message}")]
1050    Serialization { message: String },
1051
1052    #[error("Protocol error: {message}")]
1053    Protocol { message: String },
1054
1055    #[error("IO error: {0}")]
1056    Io(#[from] std::io::Error),
1057}
1058
1059#[cfg(test)]
1060mod tests {
1061    use super::*;
1062    use std::net::{IpAddr, Ipv4Addr};
1063
1064    #[test]
1065    fn test_network_config_default() {
1066        let config = NetworkConfig::default();
1067        assert_eq!(config.connection_timeout, Duration::from_secs(5));
1068        assert_eq!(config.request_timeout, Duration::from_secs(10));
1069        assert_eq!(config.max_connections, 100);
1070        assert_eq!(config.keep_alive_interval, Duration::from_secs(30));
1071    }
1072
1073    #[test]
1074    fn test_log_entry_creation() {
1075        let command = RdfCommand::Insert {
1076            subject: "s".to_string(),
1077            predicate: "p".to_string(),
1078            object: "o".to_string(),
1079        };
1080        let entry = LogEntry::new(1, 1, command.clone());
1081
1082        assert_eq!(entry.index, 1);
1083        assert_eq!(entry.term, 1);
1084        assert_eq!(entry.command, command);
1085    }
1086
1087    #[test]
1088    fn test_connection_creation() {
1089        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
1090        let connection = Connection::new(1, addr);
1091
1092        assert_eq!(connection.peer_id, 1);
1093        assert_eq!(connection.address, addr);
1094        assert!(!connection.is_connected);
1095    }
1096
1097    #[test]
1098    fn test_connection_staleness() {
1099        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
1100        let connection = Connection::new(1, addr);
1101
1102        // Fresh connection should not be stale
1103        assert!(!connection.is_stale(Duration::from_secs(10)));
1104
1105        // Connection should be stale with very short timeout after some time passes
1106        std::thread::sleep(Duration::from_millis(1));
1107        assert!(connection.is_stale(Duration::from_nanos(1)));
1108    }
1109
1110    #[test]
1111    fn test_connection_activity_update() {
1112        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
1113        let mut connection = Connection::new(1, addr);
1114
1115        let old_activity = connection.last_activity;
1116        std::thread::sleep(Duration::from_millis(1));
1117        connection.update_activity();
1118
1119        assert!(connection.last_activity > old_activity);
1120    }
1121
1122    #[tokio::test]
1123    async fn test_network_manager_creation() {
1124        let config = NetworkConfig::default();
1125        let manager = NetworkManager::new(1, config);
1126
1127        assert_eq!(manager.node_id, 1);
1128        assert!(!*manager.running.read().await);
1129
1130        let stats = manager.get_stats().await;
1131        assert_eq!(stats.node_id, 1);
1132        assert_eq!(stats.total_connections, 0);
1133        assert_eq!(stats.active_connections, 0);
1134    }
1135
1136    #[tokio::test]
1137    async fn test_rpc_message_serialization() {
1138        let message = RpcMessage::RequestVote {
1139            term: 1,
1140            candidate_id: 1,
1141            last_log_index: 0,
1142            last_log_term: 0,
1143        };
1144
1145        let serialized = serde_json::to_string(&message).unwrap();
1146        let deserialized: RpcMessage = serde_json::from_str(&serialized).unwrap();
1147
1148        match deserialized {
1149            RpcMessage::RequestVote {
1150                term,
1151                candidate_id,
1152                last_log_index,
1153                last_log_term,
1154            } => {
1155                assert_eq!(term, 1);
1156                assert_eq!(candidate_id, 1);
1157                assert_eq!(last_log_index, 0);
1158                assert_eq!(last_log_term, 0);
1159            }
1160            _ => panic!("Unexpected message type"),
1161        }
1162    }
1163
1164    #[test]
1165    fn test_network_error_display() {
1166        let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 8080);
1167        let err = NetworkError::ConnectionFailed {
1168            peer_id: 1,
1169            address: addr,
1170            message: "refused".to_string(),
1171        };
1172        assert!(err
1173            .to_string()
1174            .contains("Connection failed to 1 at 127.0.0.1:8080: refused"));
1175
1176        let err = NetworkError::Timeout {
1177            operation: "connect".to_string(),
1178            duration: Duration::from_secs(5),
1179        };
1180        assert!(err
1181            .to_string()
1182            .contains("Timeout: connect timed out after 5s"));
1183
1184        let err = NetworkError::Serialization {
1185            message: "invalid json".to_string(),
1186        };
1187        assert!(err
1188            .to_string()
1189            .contains("Serialization error: invalid json"));
1190
1191        let err = NetworkError::Protocol {
1192            message: "unknown message".to_string(),
1193        };
1194        assert!(err.to_string().contains("Protocol error: unknown message"));
1195    }
1196
1197    // --- handle_message dispatch tests ---
1198
1199    #[tokio::test]
1200    async fn test_handle_request_vote_returns_vote_response() {
1201        let config = NetworkConfig::default();
1202        let svc = NetworkService::new(1, config);
1203
1204        let msg = RpcMessage::RequestVote {
1205            term: 5,
1206            candidate_id: 2,
1207            last_log_index: 10,
1208            last_log_term: 4,
1209        };
1210
1211        let resp = svc
1212            .handle_message(msg)
1213            .await
1214            .expect("handle_message failed");
1215        match resp {
1216            RpcMessage::VoteResponse { term, vote_granted } => {
1217                assert_eq!(term, 5);
1218                assert!(!vote_granted, "conservative default should deny vote");
1219            }
1220            other => panic!("unexpected response: {:?}", other),
1221        }
1222    }
1223
1224    #[tokio::test]
1225    async fn test_handle_append_entries_returns_success() {
1226        let config = NetworkConfig::default();
1227        let svc = NetworkService::new(1, config);
1228
1229        let msg = RpcMessage::AppendEntries {
1230            term: 3,
1231            leader_id: 2,
1232            prev_log_index: 0,
1233            prev_log_term: 0,
1234            entries: Vec::new(),
1235            leader_commit: 0,
1236        };
1237
1238        let resp = svc
1239            .handle_message(msg)
1240            .await
1241            .expect("handle_message failed");
1242        match resp {
1243            RpcMessage::AppendEntriesResponse { term, success, .. } => {
1244                assert_eq!(term, 3);
1245                assert!(success);
1246            }
1247            other => panic!("unexpected response: {:?}", other),
1248        }
1249    }
1250
1251    #[tokio::test]
1252    async fn test_handle_heartbeat_returns_heartbeat_response() {
1253        let config = NetworkConfig::default();
1254        let svc = NetworkService::new(1, config);
1255
1256        let msg = RpcMessage::Heartbeat {
1257            term: 7,
1258            leader_id: 2,
1259        };
1260        let resp = svc
1261            .handle_message(msg)
1262            .await
1263            .expect("handle_message failed");
1264        match resp {
1265            RpcMessage::HeartbeatResponse { term } => assert_eq!(term, 7),
1266            other => panic!("unexpected response: {:?}", other),
1267        }
1268    }
1269
1270    #[tokio::test]
1271    async fn test_handle_client_request_returns_success() {
1272        let config = NetworkConfig::default();
1273        let svc = NetworkService::new(1, config);
1274
1275        let cmd = crate::raft::RdfCommand::Clear;
1276        let msg = RpcMessage::ClientRequest { command: cmd };
1277        let resp = svc
1278            .handle_message(msg)
1279            .await
1280            .expect("handle_message failed");
1281        match resp {
1282            RpcMessage::ClientResponse {
1283                response: crate::raft::RdfResponse::Success,
1284            } => {}
1285            other => panic!("unexpected response: {:?}", other),
1286        }
1287    }
1288
1289    #[tokio::test]
1290    async fn test_handle_query_shard_returns_empty_results() {
1291        let config = NetworkConfig::default();
1292        let svc = NetworkService::new(1, config);
1293
1294        let msg = RpcMessage::QueryShard {
1295            shard_id: 42,
1296            subject: None,
1297            predicate: None,
1298            object: None,
1299        };
1300        let resp = svc
1301            .handle_message(msg)
1302            .await
1303            .expect("handle_message failed");
1304        match resp {
1305            RpcMessage::QueryShardResponse { shard_id, results } => {
1306                assert_eq!(shard_id, 42);
1307                assert!(results.is_empty());
1308            }
1309            other => panic!("unexpected response: {:?}", other),
1310        }
1311    }
1312
1313    #[tokio::test]
1314    async fn test_handle_transaction_prepare_votes_no() {
1315        let config = NetworkConfig::default();
1316        let svc = NetworkService::new(1, config);
1317
1318        let msg = RpcMessage::TransactionPrepare {
1319            tx_id: "tx-001".to_string(),
1320            shard_id: 1,
1321            operations: Vec::new(),
1322        };
1323        let resp = svc
1324            .handle_message(msg)
1325            .await
1326            .expect("handle_message failed");
1327        match resp {
1328            RpcMessage::TransactionVote {
1329                tx_id,
1330                shard_id,
1331                vote,
1332            } => {
1333                assert_eq!(tx_id, "tx-001");
1334                assert_eq!(shard_id, 1);
1335                assert!(!vote, "conservative default should vote no");
1336            }
1337            other => panic!("unexpected response: {:?}", other),
1338        }
1339    }
1340
1341    #[tokio::test]
1342    async fn test_handle_transaction_commit_returns_ack() {
1343        let config = NetworkConfig::default();
1344        let svc = NetworkService::new(1, config);
1345
1346        let msg = RpcMessage::TransactionCommit {
1347            tx_id: "tx-002".to_string(),
1348            shard_id: 5,
1349        };
1350        let resp = svc
1351            .handle_message(msg)
1352            .await
1353            .expect("handle_message failed");
1354        match resp {
1355            RpcMessage::TransactionAck { tx_id, shard_id } => {
1356                assert_eq!(tx_id, "tx-002");
1357                assert_eq!(shard_id, 5);
1358            }
1359            other => panic!("unexpected response: {:?}", other),
1360        }
1361    }
1362
1363    #[tokio::test]
1364    async fn test_handle_transaction_abort_returns_ack() {
1365        let config = NetworkConfig::default();
1366        let svc = NetworkService::new(1, config);
1367
1368        let msg = RpcMessage::TransactionAbort {
1369            tx_id: "tx-003".to_string(),
1370            shard_id: 9,
1371        };
1372        let resp = svc
1373            .handle_message(msg)
1374            .await
1375            .expect("handle_message failed");
1376        match resp {
1377            RpcMessage::TransactionAck { tx_id, shard_id } => {
1378                assert_eq!(tx_id, "tx-003");
1379                assert_eq!(shard_id, 9);
1380            }
1381            other => panic!("unexpected response: {:?}", other),
1382        }
1383    }
1384
1385    #[tokio::test]
1386    async fn test_handle_store_triple_returns_descriptive_error() {
1387        use oxirs_core::model::{Literal, NamedNode, Triple};
1388
1389        let config = NetworkConfig::default();
1390        let svc = NetworkService::new(1, config);
1391
1392        let triple = Triple::new(
1393            NamedNode::new("http://example.org/s").expect("valid IRI"),
1394            NamedNode::new("http://example.org/p").expect("valid IRI"),
1395            Literal::new("object-value"),
1396        );
1397        let msg = RpcMessage::StoreTriple {
1398            shard_id: 3,
1399            triple,
1400        };
1401        let err = svc
1402            .handle_message(msg)
1403            .await
1404            .expect_err("should return Err");
1405        let msg_str = err.to_string();
1406        assert!(
1407            msg_str.contains("StoreTriple") || msg_str.contains("shard"),
1408            "error should mention StoreTriple or shard, got: {}",
1409            msg_str
1410        );
1411        assert!(
1412            !msg_str.contains("not yet implemented"),
1413            "stub message should be gone, got: {}",
1414            msg_str
1415        );
1416    }
1417
1418    #[tokio::test]
1419    async fn test_handle_shard_transfer_returns_descriptive_error() {
1420        let config = NetworkConfig::default();
1421        let svc = NetworkService::new(1, config);
1422
1423        let msg = RpcMessage::ShardTransfer {
1424            shard_id: 7,
1425            triples: Vec::new(),
1426            source_node: 2,
1427        };
1428        let err = svc
1429            .handle_message(msg)
1430            .await
1431            .expect_err("should return Err");
1432        let msg_str = err.to_string();
1433        assert!(
1434            !msg_str.contains("not yet implemented"),
1435            "stub message should be gone, got: {}",
1436            msg_str
1437        );
1438    }
1439
1440    #[tokio::test]
1441    async fn test_handle_terminal_responses_echo_back() {
1442        let config = NetworkConfig::default();
1443        let svc = NetworkService::new(1, config);
1444
1445        // VoteResponse echoed back
1446        let msg = RpcMessage::VoteResponse {
1447            term: 2,
1448            vote_granted: true,
1449        };
1450        let resp = svc.handle_message(msg).await.expect("should succeed");
1451        match resp {
1452            RpcMessage::VoteResponse {
1453                term: 2,
1454                vote_granted: true,
1455            } => {}
1456            other => panic!("unexpected: {:?}", other),
1457        }
1458
1459        // HeartbeatResponse echoed back
1460        let msg = RpcMessage::HeartbeatResponse { term: 8 };
1461        let resp = svc.handle_message(msg).await.expect("should succeed");
1462        match resp {
1463            RpcMessage::HeartbeatResponse { term: 8 } => {}
1464            other => panic!("unexpected: {:?}", other),
1465        }
1466    }
1467
1468    // --- length-prefixed framing tests ---
1469
1470    #[tokio::test]
1471    async fn test_frame_round_trip_identity() {
1472        // encode -> decode must yield an identical RpcMessage, proving real
1473        // oxicode (not bincode) serialization over the wire framing.
1474        let original = RpcMessage::AppendEntries {
1475            term: 42,
1476            leader_id: 7,
1477            prev_log_index: 3,
1478            prev_log_term: 2,
1479            entries: vec![LogEntry::new(
1480                4,
1481                42,
1482                RdfCommand::Insert {
1483                    subject: "s".to_string(),
1484                    predicate: "p".to_string(),
1485                    object: "o".to_string(),
1486                },
1487            )],
1488            leader_commit: 3,
1489        };
1490
1491        let (mut a, mut b) = tokio::io::duplex(64 * 1024);
1492        let to_send = original.clone();
1493        let writer = tokio::spawn(async move {
1494            write_frame(&mut a, &to_send, 16 * 1024 * 1024)
1495                .await
1496                .expect("write_frame failed");
1497        });
1498
1499        let decoded = read_frame(&mut b, 16 * 1024 * 1024)
1500            .await
1501            .expect("read_frame failed");
1502        writer.await.expect("writer task panicked");
1503
1504        match decoded {
1505            RpcMessage::AppendEntries {
1506                term,
1507                leader_id,
1508                prev_log_index,
1509                prev_log_term,
1510                entries,
1511                leader_commit,
1512            } => {
1513                assert_eq!(term, 42);
1514                assert_eq!(leader_id, 7);
1515                assert_eq!(prev_log_index, 3);
1516                assert_eq!(prev_log_term, 2);
1517                assert_eq!(leader_commit, 3);
1518                assert_eq!(entries.len(), 1);
1519                assert_eq!(entries[0].index, 4);
1520                assert_eq!(entries[0].term, 42);
1521            }
1522            other => panic!("frame round trip changed the message: {:?}", other),
1523        }
1524    }
1525
1526    #[tokio::test]
1527    async fn test_frame_rejects_oversize_message() {
1528        let msg = RpcMessage::Heartbeat {
1529            term: 1,
1530            leader_id: 1,
1531        };
1532        let (mut a, _b) = tokio::io::duplex(1024);
1533        // max_size of 1 byte forces the oversize guard to trip.
1534        let err = write_frame(&mut a, &msg, 1)
1535            .await
1536            .expect_err("oversize frame must be rejected");
1537        assert!(
1538            err.to_string().contains("exceeds max_message_size"),
1539            "unexpected error: {}",
1540            err
1541        );
1542    }
1543
1544    #[tokio::test]
1545    async fn test_send_rpc_round_trip_returns_peer_response() {
1546        // Stand up a loopback server that reads the request frame and replies
1547        // with a distinctive VoteResponse. The old fabricating transport always
1548        // returned vote_granted:false regardless of the peer; a real transport
1549        // must surface the peer's actual (vote_granted:true) response.
1550        let listener = TcpListener::bind("127.0.0.1:0")
1551            .await
1552            .expect("failed to bind loopback listener");
1553        let addr = listener.local_addr().expect("no local addr");
1554
1555        let server = tokio::spawn(async move {
1556            let (mut socket, _peer) = listener.accept().await.expect("accept failed");
1557            let request = read_frame(&mut socket, 16 * 1024 * 1024)
1558                .await
1559                .expect("server read_frame failed");
1560            let term = match request {
1561                RpcMessage::RequestVote { term, .. } => term,
1562                other => panic!("server got unexpected request: {:?}", other),
1563            };
1564            let response = RpcMessage::VoteResponse {
1565                term,
1566                vote_granted: true,
1567            };
1568            write_frame(&mut socket, &response, 16 * 1024 * 1024)
1569                .await
1570                .expect("server write_frame failed");
1571        });
1572
1573        let manager = NetworkManager::new(1, NetworkConfig::default());
1574        let (term, granted) = manager
1575            .send_request_vote(2, addr, 99, 5, 4)
1576            .await
1577            .expect("send_request_vote failed");
1578
1579        assert_eq!(term, 99, "response term must echo the request term");
1580        assert!(
1581            granted,
1582            "must return the peer's actual vote (true), not a fabricated default"
1583        );
1584
1585        server.await.expect("server task panicked");
1586
1587        // Connection metadata + byte counters must reflect a real exchange.
1588        let stats = manager.get_message_stats().await;
1589        assert_eq!(stats.messages_sent, 1);
1590        assert_eq!(stats.messages_received, 1);
1591        assert!(stats.bytes_sent > 0);
1592    }
1593
1594    #[tokio::test]
1595    async fn test_send_message_errors_without_known_address() {
1596        // With no registered address and no live connection, delivery must fail
1597        // loudly rather than silently reporting success.
1598        let svc = NetworkService::new(1, NetworkConfig::default());
1599        let err = svc
1600            .send_message(
1601                99,
1602                RpcMessage::Heartbeat {
1603                    term: 1,
1604                    leader_id: 1,
1605                },
1606            )
1607            .await
1608            .expect_err("send_message must error when the peer address is unknown");
1609        assert!(
1610            err.to_string().contains("no known network address"),
1611            "unexpected error: {}",
1612            err
1613        );
1614    }
1615
1616    #[tokio::test]
1617    async fn test_send_message_delivers_to_registered_peer() {
1618        let listener = TcpListener::bind("127.0.0.1:0")
1619            .await
1620            .expect("failed to bind loopback listener");
1621        let addr = listener.local_addr().expect("no local addr");
1622
1623        let server = tokio::spawn(async move {
1624            let (mut socket, _peer) = listener.accept().await.expect("accept failed");
1625            let request = read_frame(&mut socket, 16 * 1024 * 1024)
1626                .await
1627                .expect("server read_frame failed");
1628            let term = match request {
1629                RpcMessage::Heartbeat { term, .. } => term,
1630                other => panic!("server got unexpected request: {:?}", other),
1631            };
1632            write_frame(
1633                &mut socket,
1634                &RpcMessage::HeartbeatResponse { term },
1635                16 * 1024 * 1024,
1636            )
1637            .await
1638            .expect("server write_frame failed");
1639        });
1640
1641        let svc = NetworkService::new(1, NetworkConfig::default());
1642        svc.register_peer(2, addr).await;
1643        svc.send_message(
1644            2,
1645            RpcMessage::Heartbeat {
1646                term: 11,
1647                leader_id: 1,
1648            },
1649        )
1650        .await
1651        .expect("send_message to a registered, reachable peer must succeed");
1652
1653        server.await.expect("server task panicked");
1654    }
1655
1656    /// Regression: a *started* NetworkManager must actually accept inbound
1657    /// connections and answer a `Heartbeat` with a `HeartbeatResponse`.
1658    /// Previously `start_background_tasks` skipped spawning any accept loop
1659    /// ("for now, we'll skip the listener task"), so the bound listener never
1660    /// answered and health probes reported every peer unreachable even for a
1661    /// healthy cluster.
1662    #[tokio::test]
1663    async fn regression_network_accept_loop_answers_heartbeat() {
1664        // Reserve a free port, then release it so the manager can bind it.
1665        let probe = TcpListener::bind("127.0.0.1:0")
1666            .await
1667            .expect("failed to reserve a port");
1668        let addr = probe.local_addr().expect("no local addr");
1669        drop(probe);
1670
1671        let mut cfg = NetworkConfig::default();
1672        cfg.local_address = addr;
1673
1674        let mut server = NetworkManager::new(1, cfg.clone());
1675        server.start().await.expect("server start failed");
1676
1677        // A separate manager acts as the client and issues a real heartbeat RPC.
1678        let client = NetworkManager::new(2, cfg);
1679        let response = client
1680            .send_rpc(
1681                1,
1682                addr,
1683                RpcMessage::Heartbeat {
1684                    term: 5,
1685                    leader_id: 2,
1686                },
1687            )
1688            .await
1689            .expect("heartbeat RPC to a started server must get a real answer");
1690
1691        match response {
1692            RpcMessage::HeartbeatResponse { term } => assert_eq!(term, 5),
1693            other => panic!("expected HeartbeatResponse, got {other:?}"),
1694        }
1695
1696        server.stop().await.expect("server stop failed");
1697    }
1698}