1use crate::Error;
2use std::time::Duration;
3use tokio::sync::mpsc;
4
5#[derive(Debug)]
6pub struct SafeSender<T> {
7 tx: mpsc::Sender<T>,
8 timeout: Duration,
9}
10
11impl<T> Clone for SafeSender<T> {
12 fn clone(&self) -> Self {
13 Self {
14 tx: self.tx.clone(),
15 timeout: self.timeout,
16 }
17 }
18}
19
20impl<T> SafeSender<T> {
21 #[must_use]
22 pub fn new(tx: mpsc::Sender<T>, timeout: Duration) -> Self {
23 Self { tx, timeout }
24 }
25
26 pub async fn safe_send(&self, data: T) -> Result<(), Error> {
30 tokio::time::timeout(self.timeout, self.tx.send(data))
31 .await
32 .map_or(Err(Error::timeout()), |res| {
33 res.map_or_else(|e| Err(Error::internal(e)), |()| Ok(()))
34 })
35 }
36}