use crate::cluster::raft::{AppendEntries, RequestVote, VoteResult};
use tokio::sync::{mpsc, oneshot};
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
pub struct Rpc {
pub vote: Option<RequestVote>,
pub append: Option<AppendEntries>,
pub reply: oneshot::Sender<RpcResult>,
}
pub enum RpcResult {
Vote(VoteResult),
Append(bool),
}
#[derive(Clone)]
pub struct MemTransport {
nodes: Arc<Mutex<HashMap<u64, mpsc::UnboundedSender<Rpc>>>>,
}
impl Default for MemTransport {
fn default() -> Self {
Self::new()
}
}
impl MemTransport {
pub fn new() -> Self {
Self {
nodes: Arc::new(Mutex::new(HashMap::new())),
}
}
pub fn register(&self, node_id: u64) -> mpsc::UnboundedReceiver<Rpc> {
let (tx, rx) = mpsc::unbounded_channel();
self.nodes.lock().unwrap().insert(node_id, tx);
rx
}
pub fn send_vote(&self, target: u64, req: RequestVote) -> Option<oneshot::Receiver<RpcResult>> {
let tx = self.nodes.lock().unwrap().get(&target).cloned()?;
let (reply_tx, reply_rx) = oneshot::channel();
tx.send(Rpc {
vote: Some(req),
append: None,
reply: reply_tx,
})
.ok()?;
Some(reply_rx)
}
pub fn send_append(&self, target: u64, req: AppendEntries) -> Option<oneshot::Receiver<RpcResult>> {
let tx = self.nodes.lock().unwrap().get(&target).cloned()?;
let (reply_tx, reply_rx) = oneshot::channel();
tx.send(Rpc {
vote: None,
append: Some(req),
reply: reply_tx,
})
.ok()?;
Some(reply_rx)
}
}