use crate::error::{BoxError, Error, ensure};
use std::sync::Arc;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
pub(crate) struct PendingLimit {
permits: Arc<Semaphore>,
broker: &'static str,
}
impl PendingLimit {
pub(crate) fn new(max_pending: usize, broker: &'static str) -> Self {
Self {
permits: Arc::new(Semaphore::new(max_pending.min(Semaphore::MAX_PERMITS))),
broker,
}
}
pub(crate) fn validate(max_pending: usize, broker: &str) -> Result<(), Error> {
ensure!(
(1..=Semaphore::MAX_PERMITS).contains(&max_pending),
Error::config,
"{broker} sink max_pending must be between 1 and {}",
Semaphore::MAX_PERMITS
);
Ok(())
}
pub(crate) async fn acquire(&self) -> Result<OwnedSemaphorePermit, BoxError> {
self.permits
.clone()
.acquire_owned()
.await
.map_err(|_| Error::closed(format!("{} sink is closed", self.broker)).into())
}
pub(crate) fn close(&self) {
self.permits.close();
}
}
#[cfg(test)]
mod tests {
use super::PendingLimit;
#[tokio::test]
async fn closing_fails_waiting_and_later_acquires() {
let limit = PendingLimit::new(1, "Test");
let held = limit.acquire().await.unwrap();
let waiting = limit.acquire();
limit.close();
assert_eq!(
waiting.await.unwrap_err().to_string(),
"Test sink is closed"
);
drop(held);
assert!(limit.acquire().await.is_err());
}
#[test]
fn validation_rejects_zero() {
assert!(PendingLimit::validate(0, "Test").is_err());
assert!(PendingLimit::validate(1, "Test").is_ok());
}
}