Skip to main content

viser_encoding/
progress.rs

1use std::sync::atomic::{AtomicI64, Ordering};
2use tokio::sync::mpsc;
3use tracing::debug;
4
5/// Non-blocking progress sender. Logs when updates are dropped due to a full channel.
6pub struct ProgressSender<T> {
7    tx: Option<mpsc::Sender<T>>,
8    dropped: AtomicI64,
9}
10
11impl<T> ProgressSender<T> {
12    /// Creates a sender wrapping an optional channel; `None` makes `send` a no-op.
13    pub fn new(tx: Option<mpsc::Sender<T>>) -> Self {
14        Self { tx, dropped: AtomicI64::new(0) }
15    }
16
17    /// Attempts to send a progress update. Non-blocking.
18    pub fn send(&self, value: T) {
19        let Some(ref tx) = self.tx else { return };
20        match tx.try_send(value) {
21            Ok(()) => {}
22            Err(mpsc::error::TrySendError::Full(_)) => {
23                let count = self.dropped.fetch_add(1, Ordering::Relaxed) + 1;
24                if count == 1 || count % 100 == 0 {
25                    debug!("progress update dropped (channel full), total_dropped={count}");
26                }
27            }
28            Err(mpsc::error::TrySendError::Closed(_)) => {}
29        }
30    }
31
32    /// Returns the number of updates dropped so far because the channel was full.
33    pub fn dropped(&self) -> i64 {
34        self.dropped.load(Ordering::Relaxed)
35    }
36}