use std::{sync::Arc, time::Duration};
use tokio::sync::Semaphore;
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct StreamPolicy {
pub max_in_flight: usize,
pub max_duration: Duration,
pub idle_timeout: Duration,
}
pub(crate) struct StreamingGroup {
prefix: Box<str>,
pub(crate) policy: StreamPolicy,
}
impl StreamingGroup {
pub(crate) fn new(prefix: &str, policy: StreamPolicy) -> Result<Self> {
if !prefix.strip_prefix('/').is_some_and(|path| {
path.split('/').all(|segment| {
!matches!(segment, "" | "." | "..")
&& segment.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b'~')
})
})
}) {
return Err(Error::Registration(
"a streaming prefix must be a non-root absolute path with static segments".into(),
));
}
if !(1..=Semaphore::MAX_PERMITS).contains(&policy.max_in_flight) {
return Err(Error::Registration(
"streaming capacity must be positive and fit the semaphore".into(),
));
}
let now = std::time::Instant::now();
if [policy.max_duration, policy.idle_timeout]
.into_iter()
.any(|duration| duration.is_zero() || now.checked_add(duration).is_none())
{
return Err(Error::Registration(
"streaming budgets must be positive and form monotonic deadlines".into(),
));
}
Ok(Self {
prefix: prefix.into(),
policy,
})
}
pub(crate) fn contains(&self, path: &str) -> bool {
path.strip_prefix(&*self.prefix)
.is_some_and(|suffix| suffix.is_empty() || suffix.starts_with('/'))
}
pub(crate) fn overlaps(&self, other: &Self) -> bool {
self.contains(&other.prefix) || other.contains(&self.prefix)
}
}
pub(super) struct StreamAdmission {
pub(super) group: StreamingGroup,
pub(super) capacity: Arc<Semaphore>,
}
impl StreamAdmission {
pub(super) fn new(group: StreamingGroup) -> Self {
Self {
capacity: Arc::new(Semaphore::new(group.policy.max_in_flight)),
group,
}
}
}