use std::fmt;
use std::future::Future;
use std::sync::Arc;
use std::time::Duration;
use futures_util::FutureExt;
use crate::Config;
use crate::OptionalSend;
use crate::RaftTypeConfig;
use crate::async_runtime::watch::WatchReceiver;
use crate::core::heartbeat::errors::RaftCoreClosed;
use crate::core::heartbeat::event::HeartbeatEvent;
use crate::core::heartbeat::failure_log::FailureLog;
use crate::core::heartbeat::heartbeat_send::HeartbeatSend;
use crate::core::notification::Notification;
use crate::network::NetStreamAppend;
use crate::progress::stream_id::StreamId;
use crate::raft::AppendError;
use crate::raft::AppendResult;
use crate::replication::Progress;
use crate::replication::response::ReplicationResult;
use crate::type_config::TypeConfigExt;
use crate::type_config::alias::CancelHandleOf;
use crate::type_config::alias::CommittedVoteOf;
use crate::type_config::alias::MpscSenderOf;
use crate::type_config::alias::WatchReceiverOf;
use crate::type_config::async_runtime::mpsc::MpscSender;
pub struct HeartbeatWorker<C, N>
where
C: RaftTypeConfig,
N: NetStreamAppend<C>,
{
pub(crate) id: C::NodeId,
pub(crate) leader_vote: CommittedVoteOf<C>,
pub(crate) stream_id: StreamId,
pub(crate) rx: WatchReceiverOf<C, Option<HeartbeatEvent<C>>>,
pub(crate) network: N,
pub(crate) target: C::NodeId,
#[allow(dead_code)]
pub(crate) node: C::Node,
pub(crate) config: Arc<Config>,
pub(crate) tx_notification: MpscSenderOf<C, Notification<C>>,
}
impl<C, N> fmt::Display for HeartbeatWorker<C, N>
where
C: RaftTypeConfig,
N: NetStreamAppend<C>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "HeartbeatWorker(id={}, target={})", self.id, self.target)
}
}
impl<C, N> HeartbeatWorker<C, N>
where
C: RaftTypeConfig,
N: NetStreamAppend<C>,
{
pub(crate) fn run(self) -> (CancelHandleOf<C>, impl Future<Output = ()> + OptionalSend) {
let (cancel, stopped) = C::cancellable(std::future::pending::<()>());
let task = self.do_run(stopped).map(|res| {
tracing::info!("HeartbeatWorker finished with result: {:?}", res);
});
(cancel, task)
}
async fn do_run<Stop>(mut self, stopped: Stop) -> Result<(), RaftCoreClosed>
where Stop: Future + OptionalSend {
let mut stopped = std::pin::pin!(stopped);
let mut failed_in_row: u64 = 0;
loop {
tracing::debug!("{} is waiting for a new heartbeat event.", self);
let changed = C::cancellable_by(self.rx.changed(), stopped.as_mut()).await;
let Some(Ok(())) = changed else {
return Ok(());
};
let heartbeat: Option<HeartbeatEvent<C>> = self.rx.borrow_and_update().clone();
let Some(heartbeat) = heartbeat else {
continue;
};
let send = HeartbeatSend {
network: &mut self.network,
leader_vote: &self.leader_vote,
interval: Duration::from_millis(self.config.heartbeat_interval),
log: FailureLog {
id: &self.id,
target: &self.target,
failed_in_row: &mut failed_in_row,
},
};
let reply = send.send(&heartbeat).await;
tracing::debug!("{} sent a heartbeat: {}, reply: {:?}", self, heartbeat, reply);
if let Some(reply) = reply {
let handled = C::cancellable_by(self.handle_stream_result(reply, &heartbeat), stopped.as_mut()).await;
let Some(handled) = handled else {
return Ok(());
};
handled?;
}
}
}
async fn handle_stream_result(
&self,
result: AppendResult<C>,
heartbeat: &HeartbeatEvent<C>,
) -> Result<(), RaftCoreClosed> {
match result {
Ok(_) => {
self.send_heartbeat_progress(heartbeat).await?;
}
Err(AppendError::HigherVote(vote)) => {
tracing::debug!(
"seen a higher vote({vote}) from {}; when:(sending heartbeat)",
self.target
);
let noti = Notification::HigherVote {
target: self.target.clone(),
higher: vote,
leader_vote: self.leader_vote.clone(),
};
self.send_notification(noti, "Seeing higher Vote").await?;
}
Err(AppendError::Conflict { .. }) => {
let conflict_log_id = heartbeat.matching.clone().unwrap();
let noti = Notification::ReplicationProgress {
stream_id: self.stream_id,
progress: Progress {
target: self.target.clone(),
result: Ok(ReplicationResult(Err(conflict_log_id))),
hint: None,
},
inflight_id: None,
};
self.send_notification(noti, "Seeing conflict").await?;
self.send_heartbeat_progress(heartbeat).await?;
}
}
Ok(())
}
async fn send_heartbeat_progress(&self, heartbeat: &HeartbeatEvent<C>) -> Result<(), RaftCoreClosed> {
let noti = Notification::HeartbeatProgress {
stream_id: self.stream_id,
sending_time: heartbeat.time,
target: self.target.clone(),
};
self.send_notification(noti, "send HeartbeatProgress").await
}
async fn send_notification(
&self,
notification: Notification<C>,
when: impl fmt::Display,
) -> Result<(), RaftCoreClosed> {
let res = self.tx_notification.send(notification).await;
if let Err(e) = res {
let notification = e.0;
tracing::error!("{self} failed to send {notification} to RaftCore; when:({when})");
return Err(RaftCoreClosed);
}
Ok(())
}
}
#[cfg(test)]
mod worker_test;