use std::future::Future;
use crate::RaftTypeConfig;
use crate::async_runtime::MpscReceiver;
use crate::async_runtime::MpscSender;
use crate::async_runtime::SendError;
use crate::async_runtime::TryRecvError;
use crate::async_runtime::mpsc::PeekableReceiver;
use crate::core::notification::Notification;
use crate::type_config::alias::MpscReceiverOf;
use crate::type_config::alias::MpscSenderOf;
pub(crate) struct NotificationChannel<C>
where C: RaftTypeConfig
{
sender: MpscSenderOf<C, Notification<C>>,
receiver: PeekableReceiver<MpscReceiverOf<C, Notification<C>>, Notification<C>>,
pending: Vec<Notification<C>>,
}
impl<C> NotificationChannel<C>
where C: RaftTypeConfig
{
pub(crate) fn new(sender: MpscSenderOf<C, Notification<C>>, receiver: MpscReceiverOf<C, Notification<C>>) -> Self {
Self {
sender,
receiver: receiver.peekable(),
pending: Vec::new(),
}
}
pub(crate) fn sender(&self) -> MpscSenderOf<C, Notification<C>> {
self.sender.clone()
}
pub(crate) fn enqueue(&mut self, notification: Notification<C>) {
self.pending.push(notification);
}
pub(crate) fn has_pending(&self) -> bool {
!self.pending.is_empty()
}
pub(crate) fn send_pending(&mut self) -> impl Future<Output = Result<(), SendError<Notification<C>>>> + use<C> {
let sender = self.sender();
let pending = std::mem::take(&mut self.pending);
async move {
for notification in pending {
sender.send(notification).await?;
}
Ok(())
}
}
pub(crate) fn try_recv(&mut self) -> Result<Notification<C>, TryRecvError> {
self.receiver.try_recv()
}
pub(crate) async fn recv(&mut self) -> Option<Notification<C>> {
self.receiver.recv().await
}
pub(crate) fn try_peek(&mut self) -> Result<&Notification<C>, TryRecvError> {
self.receiver.try_peek()
}
}
#[cfg(test)]
mod notification_channel_test;