//! gRPC implementation of the `Transport` trait: every outbound RPC to a peer goes through here. use async_trait::async_trait; use d_engine_core::BackgroundSnapshotTransfer; use d_engine_core::BackoffPolicy; use d_engine_core::MembershipError; use d_engine_core::NetworkError; use d_engine_core::RaftNodeConfig; use d_engine_core::ReplicationStream; use d_engine_core::Result; use d_engine_core::RetryPolicies; use d_engine_core::SnapshotConfig; use d_engine_core::Transport; use d_engine_core::grpc_task_with_timeout_and_exponential_backoff; use d_engine_proto::server::cluster::JoinResponse; use d_engine_proto::server::cluster::LeaderDiscoveryRequest; use d_engine_proto::server::cluster::LeaderDiscoveryResponse; use d_engine_proto::server::cluster::NodeMeta; use d_engine_proto::server::cluster::cluster_management_service_client::ClusterManagementServiceClient; use d_engine_proto::server::election::VoteRequest; use d_engine_proto::server::election::VoteResponse; use d_engine_proto::server::election::raft_election_service_client::RaftElectionServiceClient; use d_engine_proto::server::replication::AppendEntriesRequest; use d_engine_proto::server::replication::raft_replication_service_client::RaftReplicationServiceClient; use d_engine_proto::server::storage::SnapshotChunk; use futures::StreamExt; use futures::stream::BoxStream; use futures::stream::FuturesUnordered; use tokio::sync::mpsc; use tokio_stream::wrappers::ReceiverStream; use tonic::codec::CompressionEncoding; use tonic::transport::Channel; use tracing::debug; use tracing::error; use tracing::info; use tracing::warn; use crate::network::ConnectionCache; use crate::network::ConnectionType; use crate::network::HealthChecker; use crate::network::HealthCheckerApis; use crate::network::HealthMonitor; use crate::network::RaftHealthMonitor; use crate::utils::async_task::task_with_timeout_and_exponential_backoff; use crate::utils::cluster::majority_count; use crate::utils::net::address_str; use super::ElectionRpc; /// Sends Raft RPCs to peers over gRPC. /// /// Owns everything about reaching a peer: the cached connections and the count of failed RPCs per peer. pub struct GrpcTransport { pub(crate) my_id: u32, config: RaftNodeConfig, /// Open connections, reused across RPCs; keyed by peer and connection type. pub(crate) connection_cache: ConnectionCache, /// Counts consecutive failed RPCs per peer. pub(crate) health_monitor: RaftHealthMonitor, } #[async_trait] impl Transport for GrpcTransport { async fn pre_warm_connections( &self, peers: Vec, ) -> Result<()> { if peers.is_empty() { info!("No replication peers found"); return Ok(()); } let conn_types = ConnectionType::all(); // Materialize task futures to a Vec let mut tasks = Vec::new(); for peer in &peers { for conn_type in &conn_types { let peer_id = peer.id; let addr = &peer.address; let conn_type = *conn_type; let fut = async move { match self.get_or_create_channel(peer_id, conn_type, addr).await { Ok(channel) => { info!("Pre-warmed {:?} connection to node {}", conn_type, peer_id); Ok(channel) } Err(e) => { debug!( "Failed to pre-warm {:?} connection to node {}: {}", conn_type, peer_id, e ); Err(()) } } }; tasks.push(fut); } } // Rate-limit concurrent futures futures::stream::iter(tasks) .buffer_unordered(10) .for_each(|result| async move { if result.is_err() { // Use debug level - pre-warming failures during startup are expected debug!("Connection pre-warming failed for one or more peers"); } }) .await; info!("Connection pre-warming completed"); Ok(()) } async fn check_cluster_is_ready( &self, voters: Vec, ) -> Result<()> { info!("check_cluster_is_ready..."); let mut tasks = FuturesUnordered::new(); let settings = self.config.network.clone(); let raft = self.config.raft.clone(); let retry = self.config.retry.clone(); let startup_quorum_timeout = raft.membership.startup_quorum_timeout; let mut peer_ids = Vec::new(); for peer in voters { let peer_id = peer.id; debug!("check_cluster_is_ready for peer: {}", peer_id); peer_ids.push(peer_id); let addr: String = peer.address.clone(); let settings = settings.clone(); let cluster_healthcheck_probe_service_name = raft.membership.cluster_healthcheck_probe_service_name.clone(); tasks.push(async move { match task_with_timeout_and_exponential_backoff( move || { HealthChecker::check_peer_is_ready( addr.clone(), settings.clone(), cluster_healthcheck_probe_service_name.clone(), ) }, retry.membership, ) .await { Ok(response) => { debug!("healthcheck: {:?} response: {:?}", peer.address, response); Ok(response) } Err(e) => { warn!("Received RPC error: {}", e); Err(e) } } }); } // This node counts as one member of the cluster, so the peers still needed for a // majority are `majority - 1`. Return as soon as that many are healthy: a peer that is // slow or down must not hold back a cluster that can already elect and commit. let majority = majority_count(peer_ids.len() + 1); let peers_needed = majority - 1; let mut healthy_peers = 0; let reached = tokio::select! { reached = async { if peers_needed == 0 { return true; } while let Some(result) = tasks.next().await { match result { Ok(_) => { healthy_peers += 1; if healthy_peers >= peers_needed { return true; } } Err(e) => error!("Peer check failed: {:?}", e), } } false } => reached, _ = tokio::time::sleep(startup_quorum_timeout) => { warn!( "check_cluster_is_ready timed out after {:?}: {} of {} needed peer(s) healthy", startup_quorum_timeout, healthy_peers, peers_needed ); false } }; if reached { info!( "Startup health check passed: {} healthy peer(s) plus this node reach a majority of {}", healthy_peers, majority ); Ok(()) } else { error!( "CLUSTER IS NOT READY: {} healthy peer(s) of {} needed for a majority", healthy_peers, peers_needed ); Err(MembershipError::ClusterIsNotReady.into()) } } async fn send_pre_vote_request( &self, peer_id: u32, peer_address: &str, request: VoteRequest, retry: &RetryPolicies, ) -> Result { self.send_election_rpc( ElectionRpc::PreVote, peer_id, peer_address, request, retry.election, ) .await } async fn send_vote_request( &self, peer_id: u32, peer_address: &str, request: VoteRequest, retry: &RetryPolicies, ) -> Result { self.send_election_rpc( ElectionRpc::Vote, peer_id, peer_address, request, retry.election, ) .await } async fn join_cluster( &self, leader_id: u32, leader_address: &str, request: d_engine_proto::server::cluster::JoinRequest, retry: BackoffPolicy, ) -> Result { debug!("Initiating cluster join via leader {}", leader_id); // Real-time connection fetch for control operations let channel = self .get_peer_channel(leader_id, ConnectionType::Control, leader_address) .await .ok_or(NetworkError::PeerConnectionNotFound(leader_id))?; let closure = move || { let channel = channel.clone(); let mut client = ClusterManagementServiceClient::new(channel) .send_compressed(CompressionEncoding::Gzip) .accept_compressed(CompressionEncoding::Gzip); let req = request.clone(); async move { client.join_cluster(tonic::Request::new(req)).await } }; let my_id = self.my_id; let response = grpc_task_with_timeout_and_exponential_backoff("join_cluster", closure, retry).await?; debug!( "[join_cluster | {my_id}->{leader_id}]Join cluster response: {:?}", response ); Ok(response.into_inner()) } async fn discover_leader( &self, request: LeaderDiscoveryRequest, voters: Vec, rpc_enable_compression: bool, ) -> Result> { debug!("Starting leader discovery for node {}", request.node_id); let request = &request; let tasks = voters.into_iter().map(|voter| async move { self.process_member( voter.id, &voter.address, request.clone(), rpc_enable_compression, ) .await }); let my_id = self.my_id; let results = futures::stream::iter(tasks).buffer_unordered(10).collect::>().await; debug!("[discover_leader | {my_id} ] Discover leader results."); Ok(results.into_iter().flatten().collect()) } async fn send_snapshot( &self, peer_id: u32, peer_address: &str, chunks: BoxStream<'static, Result>, config: SnapshotConfig, ) -> Result<()> { debug!(%peer_id, "Pushing snapshot to lagging peer"); let bulk_channel = self .get_peer_channel(peer_id, ConnectionType::Bulk, peer_address) .await .ok_or(NetworkError::PeerConnectionNotFound(peer_id))?; BackgroundSnapshotTransfer::run_push_transfer(peer_id, chunks, bulk_channel, config).await } fn forget_peer( &self, peer_id: u32, ) { self.connection_cache.remove_node(peer_id); } async fn open_replication_stream( &self, peer_id: u32, peer_address: &str, compress: bool, send_queue_capacity: usize, ) -> Result { debug!(%peer_id, "Opening persistent bidi replication stream"); let channel = self .get_peer_channel(peer_id, ConnectionType::Data, peer_address) .await .ok_or(NetworkError::PeerConnectionNotFound(peer_id))?; // Bounded send channel provides natural backpressure to the Raft loop. let (req_tx, req_rx) = mpsc::channel::(send_queue_capacity); let req_stream = ReceiverStream::new(req_rx); let mut client = RaftReplicationServiceClient::new(channel); if compress { client = client .send_compressed(CompressionEncoding::Gzip) .accept_compressed(CompressionEncoding::Gzip); } let response = match client.stream_append_entries(tonic::Request::new(req_stream)).await { Ok(r) => { self.health_monitor.record_success(peer_id).await; r } Err(e) => { // Actual TCP failure: drop the stale connection so the next attempt opens a // fresh one, and toward the unreachable-peer warning self.on_peer_stream_failed(peer_id).await; return Err(NetworkError::TonicStatusError(Box::new(e)).into()); } }; let receiver = response.into_inner().boxed(); Ok(ReplicationStream { sender: req_tx, receiver, }) } } impl GrpcTransport { pub(crate) fn new( node_id: u32, config: RaftNodeConfig, ) -> Self { let zombie = &config.raft.membership.zombie; Self { my_id: node_id, connection_cache: ConnectionCache::new(config.network.clone()), health_monitor: RaftHealthMonitor::new_with_grace( zombie.threshold, zombie.startup_grace, ), config, } } /// Called when a peer's replication stream breaks. Drops the cached connections to /// the peer, so the next attempt opens a fresh one, and counts a failure toward the unreachable-peer warning. pub(crate) async fn on_peer_stream_failed( &self, node_id: u32, ) { self.connection_cache.remove_node(node_id); self.health_monitor.record_failure(node_id).await; } /// Sends one election RPC to `peer_id`, retrying per `policy`. async fn send_election_rpc( &self, rpc: ElectionRpc, peer_id: u32, peer_address: &str, request: VoteRequest, policy: BackoffPolicy, ) -> Result { let channel = self .get_peer_channel(peer_id, ConnectionType::Control, peer_address) .await .ok_or(NetworkError::PeerConnectionNotFound(peer_id))?; let call = move || { let mut client = RaftElectionServiceClient::new(channel.clone()) .send_compressed(CompressionEncoding::Gzip) .accept_compressed(CompressionEncoding::Gzip); async move { let request = tonic::Request::new(request); match rpc { ElectionRpc::PreVote => client.pre_vote(request).await, ElectionRpc::Vote => client.request_vote(request).await, } } }; let my_id = self.my_id; grpc_task_with_timeout_and_exponential_backoff(rpc.name(), call, policy) .await .map(tonic::Response::into_inner) .inspect(|res| debug!("[{} | {my_id}->{peer_id}] response: {:?}", rpc.name(), res)) // Debug, not error: a failed election RPC is routinely a peer that is not // ready yet (cluster bootstrap race) and resolves on the next round (#428). .inspect_err(|e| debug!("[{} | {my_id}->{peer_id}] RPC error: {}", rpc.name(), e)) } async fn process_member( &self, member_id: u32, addr: &str, request: LeaderDiscoveryRequest, rpc_enable_compression: bool, ) -> Option { match self.get_peer_channel(member_id, ConnectionType::Control, addr).await { Some(channel) => { let mut client = ClusterManagementServiceClient::new(channel); if rpc_enable_compression { client = client .send_compressed(CompressionEncoding::Gzip) .accept_compressed(CompressionEncoding::Gzip); } client.discover_leader(request).await.ok().map(|res| res.into_inner()) } None => { error!(%member_id, "Cannot get a channel to the member"); None } } } /// Returns a connection to `node_id`, reusing the cached one if `addr` is unchanged. /// /// A missing address or a failed connection counts as one failure toward the /// unreachable-peer warning. A successful connection does not reset the count: tonic connects /// lazily, so only an RPC result says the peer is healthy. pub(crate) async fn get_peer_channel( &self, node_id: u32, conn_type: ConnectionType, addr: &str, ) -> Option { match self.get_or_create_channel(node_id, conn_type, addr).await { Ok(channel) => Some(channel), Err(e) => { self.health_monitor.record_failure(node_id).await; // Use debug level - connection failures during startup are expected debug!("Connection to node {} failed: {}", node_id, e); None } } } /// Fetches (or creates) the cached channel for `node_id`, evicting the cache /// entry if the attempt fails. No health-monitor side effects — callers that /// need failure counting wrap this (see `get_peer_channel`). async fn get_or_create_channel( &self, node_id: u32, conn_type: ConnectionType, addr: &str, ) -> Result { let addr = address_str(addr); match self.connection_cache.get_channel(node_id, conn_type, &addr).await { Ok(channel) => Ok(channel), Err(e) => { // Remove failed connection from cache self.connection_cache.remove_node(node_id); Err(e) } } } }