use std::{
future::{Future, poll_fn},
time::Duration,
};
use leaky_bucket::RateLimiter;
use log::debug;
use tokio::{sync::mpsc, time::sleep};
use super::{
super::{FrameLike, PushError, PushPriority, waits::record_first_pending},
PushHandle,
};
impl<F: FrameLike> PushHandle<F> {
pub(super) async fn push_with_priority(
&self,
frame: F,
priority: PushPriority,
) -> Result<(), PushError> {
self.check_frame_len(&frame)?;
let tx = match priority {
PushPriority::High => &self.0.high_prio_tx,
PushPriority::Low => &self.0.low_prio_tx,
};
if tx.is_closed() {
return Err(PushError::Closed);
}
self.0.waits.record_capacity_probe();
let permit = match tx.try_reserve() {
Ok(permit) => permit,
Err(mpsc::error::TrySendError::Full(())) => self.reserve_capacity(tx).await?,
Err(mpsc::error::TrySendError::Closed(())) => return Err(PushError::Closed),
};
if let Some(ref limiter) = self.0.limiter {
self.wait_for_permit(limiter, tx).await?;
}
if tx.is_closed() {
return Err(PushError::Closed);
}
permit.send(frame);
debug!("frame pushed: priority={priority:?}");
Ok(())
}
const PERMIT_POLL_INTERVAL: Duration = Duration::from_millis(10);
async fn reserve_capacity<'a>(
&self,
sender: &'a mpsc::Sender<F>,
) -> Result<mpsc::Permit<'a, F>, PushError> {
let mut reserve = std::pin::pin!(sender.reserve());
let mut is_wait_recorded = false;
poll_fn(|cx| {
let polled = reserve.as_mut().poll(cx);
record_first_pending(&polled, &mut is_wait_recorded, &self.0.waits);
polled
})
.await
.map_err(|_| PushError::Closed)
}
async fn wait_for_permit(
&self,
limiter: &RateLimiter,
sender: &mpsc::Sender<F>,
) -> Result<(), PushError> {
loop {
if sender.is_closed() {
return Err(PushError::Closed);
}
if limiter.try_acquire(1) {
return Ok(());
}
sleep(Self::PERMIT_POLL_INTERVAL).await;
}
}
}