distant_net/client/
shutdown.rs

1use std::io;
2
3use async_trait::async_trait;
4use dyn_clone::DynClone;
5use tokio::sync::{mpsc, oneshot};
6
7/// Interface representing functionality to shut down an active client.
8#[async_trait]
9pub trait Shutdown: DynClone + Send + Sync {
10    /// Attempts to shutdown the client.
11    async fn shutdown(&self) -> io::Result<()>;
12}
13
14#[async_trait]
15impl Shutdown for mpsc::Sender<oneshot::Sender<io::Result<()>>> {
16    async fn shutdown(&self) -> io::Result<()> {
17        let (tx, rx) = oneshot::channel();
18        match self.send(tx).await {
19            Ok(_) => match rx.await {
20                Ok(x) => x,
21                Err(_) => Err(already_shutdown()),
22            },
23            Err(_) => Err(already_shutdown()),
24        }
25    }
26}
27
28#[inline]
29fn already_shutdown() -> io::Error {
30    io::Error::new(io::ErrorKind::Other, "Client already shutdown")
31}
32
33impl Clone for Box<dyn Shutdown> {
34    fn clone(&self) -> Self {
35        dyn_clone::clone_box(&**self)
36    }
37}