use leaky_bucket::RateLimiter;
use log::warn;
use tokio::sync::mpsc;
#[cfg(loom)]
use super::probe::PushHandleProbe;
use super::{
FrameLike,
FrameLimits,
PushError,
PushPolicy,
PushPriority,
dlq::DeadLetterState,
sync::{Arc, Weak},
waits::{PushWaitCounters, PushWaitCounts},
};
mod lane;
pub(crate) struct PushHandleInner<F> {
pub(crate) high_prio_tx: mpsc::Sender<F>,
pub(crate) low_prio_tx: mpsc::Sender<F>,
pub(crate) limiter: Option<RateLimiter>,
pub(crate) dead_letter: DeadLetterState<F>,
pub(crate) waits: PushWaitCounts,
pub(crate) frame_limits: FrameLimits<F>,
}
pub struct PushHandle<F>(Arc<PushHandleInner<F>>);
impl<F> Clone for PushHandle<F> {
fn clone(&self) -> Self { Self(Arc::clone(&self.0)) }
}
impl<F: FrameLike> PushHandle<F> {
pub(crate) const fn from_arc(arc: Arc<PushHandleInner<F>>) -> Self { Self(arc) }
#[cfg(loom)]
#[must_use]
pub fn probe(&self) -> PushHandleProbe<F> { PushHandleProbe::new(self.0.clone()) }
pub async fn push_high_priority(&self, frame: F) -> Result<(), PushError> {
self.push_with_priority(frame, PushPriority::High).await
}
pub async fn push_low_priority(&self, frame: F) -> Result<(), PushError> {
self.push_with_priority(frame, PushPriority::Low).await
}
#[must_use]
pub fn wait_counters(&self) -> PushWaitCounters { self.0.waits.snapshot() }
pub fn try_push(
&self,
frame: F,
priority: PushPriority,
policy: PushPolicy,
) -> Result<(), PushError>
where
F: std::fmt::Debug,
{
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);
}
match tx.try_reserve() {
Ok(permit) => {
if let Some(ref limiter) = self.0.limiter
&& !limiter.try_acquire(1)
{
crate::metrics::inc_push_rate_limited();
drop(permit);
return Err(PushError::RateLimited);
}
permit.send(frame);
Ok(())
}
Err(mpsc::error::TrySendError::Full(())) => {
self.apply_full_policy(frame, priority, policy)
}
Err(mpsc::error::TrySendError::Closed(())) => Err(PushError::Closed),
}
}
fn apply_full_policy(
&self,
frame: F,
priority: PushPriority,
policy: PushPolicy,
) -> Result<(), PushError> {
match policy {
PushPolicy::ReturnErrorIfFull => Err(PushError::QueueFull),
PushPolicy::DropIfFull | PushPolicy::WarnAndDropIfFull => {
if matches!(policy, PushPolicy::WarnAndDropIfFull) {
warn!(
"push queue full: priority={priority:?}, policy={policy:?}, dlq={dlq}",
dlq = self.0.dead_letter.has_queue()
);
}
self.0.dead_letter.route_or_count(frame, priority, policy);
Ok(())
}
}
}
fn check_frame_len(&self, frame: &F) -> Result<(), PushError> {
self.0.frame_limits.check(frame)
}
pub(crate) fn downgrade(&self) -> Weak<PushHandleInner<F>> { Arc::downgrade(&self.0) }
}