Skip to main content

node_device_session/webrtc/
budget.rs

1//! One allocation budget shared by WebRTC DataChannel queues and HTTP bodies.
2use std::sync::Arc;
3use tokio::sync::{OwnedSemaphorePermit, Semaphore};
4
5/// Soft cap on in-flight session bytes (DC queues + HTTP request decode).
6pub const SESSION_BYTES: usize = 24 * 1024 * 1024;
7
8/// Shared byte budget for one WebRTC answerer session.
9#[derive(Clone)]
10pub struct ByteBudget(Arc<Semaphore>);
11
12impl Default for ByteBudget {
13    fn default() -> Self {
14        Self(Arc::new(Semaphore::new(SESSION_BYTES)))
15    }
16}
17
18impl ByteBudget {
19    /// Reserve `bytes` from the session budget, or `None` when exhausted.
20    pub fn reserve(&self, bytes: usize) -> Option<OwnedSemaphorePermit> {
21        self.0
22            .clone()
23            .try_acquire_many_owned(bytes.try_into().ok()?)
24            .ok()
25    }
26}