use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Instant;
use tokio::sync::watch;
use tokio::task::{JoinError, JoinHandle};
use crate::Result;
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub struct BridgeStats {
pub received: u64,
pub sent: u64,
pub dropped: u64,
pub last_received: Option<Instant>,
}
pub struct Bridge {
task: JoinHandle<Result<BridgeStats>>,
stats: watch::Receiver<BridgeStats>,
teardown: Teardown,
bitrate: Option<BitrateControl>,
}
impl Bridge {
pub(crate) fn spawn<F>(run: impl FnOnce(StatsSender) -> F) -> Self
where
F: Future<Output = Result<()>> + Send + 'static,
{
let (sender, stats) = watch::channel(BridgeStats::default());
let counters = StatsSender(sender);
let run = run(counters.clone());
let task = tokio::spawn(async move {
run.await?;
Ok(counters.snapshot())
});
Self {
task,
stats,
teardown: Teardown::default(),
bitrate: None,
}
}
pub(crate) fn with_bitrate_control(mut self, bitrate: BitrateControl) -> Self {
self.bitrate = Some(bitrate);
self
}
pub fn bitrate_control(&self) -> Option<BitrateControl> {
self.bitrate.clone()
}
pub(crate) fn with_teardown(mut self, teardown: Teardown) -> Self {
self.teardown = teardown;
self
}
pub fn take_teardown(&mut self) -> Teardown {
std::mem::take(&mut self.teardown)
}
pub fn stats(&self) -> BridgeStats {
*self.stats.borrow()
}
pub fn watch_stats(&self) -> watch::Receiver<BridgeStats> {
self.stats.clone()
}
pub fn is_finished(&self) -> bool {
self.task.is_finished()
}
pub fn abort(&self) {
self.task.abort();
}
}
impl Future for Bridge {
type Output = std::result::Result<Result<BridgeStats>, JoinError>;
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.task).poll(cx)
}
}
#[derive(Clone, Debug)]
pub struct BitrateControl(watch::Sender<u32>);
impl BitrateControl {
pub(crate) fn new(bitrate: u32) -> (Self, watch::Receiver<u32>) {
let (sender, receiver) = watch::channel(bitrate);
(Self(sender), receiver)
}
pub fn set(&self, bitrate: u32) {
self.0.send_replace(bitrate);
}
pub fn get(&self) -> u32 {
*self.0.borrow()
}
}
#[derive(Default)]
pub struct Teardown(Option<TeardownFn>);
type TeardownFn = Box<dyn FnOnce(&mut r2r::Node) + Send>;
impl Teardown {
pub(crate) fn new(teardown: impl FnOnce(&mut r2r::Node) + Send + 'static) -> Self {
Self(Some(Box::new(teardown)))
}
pub fn run(self, node: &mut r2r::Node) {
if let Some(teardown) = self.0 {
teardown(node);
}
}
}
#[derive(Clone)]
pub(crate) struct StatsSender(watch::Sender<BridgeStats>);
impl StatsSender {
pub(crate) fn received(&self) {
self.0.send_modify(|stats| {
stats.received += 1;
stats.last_received = Some(Instant::now());
});
}
pub(crate) fn sent(&self) {
self.0.send_modify(|stats| stats.sent += 1);
}
pub(crate) fn dropped(&self) {
self.0.send_modify(|stats| stats.dropped += 1);
}
pub(crate) fn snapshot(&self) -> BridgeStats {
*self.0.borrow()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn reports_live_and_final_counts() {
let (go, wait) = tokio::sync::oneshot::channel::<()>();
let bridge = Bridge::spawn(|stats| async move {
stats.received();
stats.sent();
stats.received();
stats.dropped();
wait.await.unwrap();
Ok(())
});
let mut watch = bridge.watch_stats();
watch.wait_for(|stats| stats.dropped == 1).await.unwrap();
let live = bridge.stats();
assert_eq!((live.received, live.sent, live.dropped), (2, 1, 1));
assert!(live.last_received.is_some());
go.send(()).unwrap();
assert_eq!(bridge.await.unwrap().unwrap(), live);
}
#[tokio::test]
async fn abort_cancels_the_task() {
let bridge = Bridge::spawn(|_| std::future::pending());
bridge.abort();
assert!(bridge.await.unwrap_err().is_cancelled());
}
}