Skip to main content

binance/ws/
handle.rs

1use serde::Serialize;
2use std::fmt::Debug;
3use tokio::sync::mpsc;
4
5use crate::ws;
6
7#[derive(Clone)]
8pub struct Handle<C>
9where
10    C: Serialize + Send + Debug + 'static,
11{
12    cmd_tx: mpsc::Sender<ws::Command<C>>,
13}
14
15impl<C> Handle<C>
16where
17    C: Serialize + Send + Debug + 'static,
18{
19    pub fn new(cmd_tx: mpsc::Sender<ws::Command<C>>) -> Self {
20        Self { cmd_tx }
21    }
22
23    pub async fn connect(&self) -> Result<(), ws::Error> {
24        let cmd = ws::Command::Connect;
25        self.cmd_tx
26            .send(cmd)
27            .await
28            .map_err(|_| ws::Error::DriverGone)
29    }
30
31    pub fn try_connect(&self) -> Result<(), ws::Error> {
32        let cmd = ws::Command::Connect;
33        self.cmd_tx.try_send(cmd).map_err(|e| match e {
34            mpsc::error::TrySendError::Full(_) => ws::Error::QueueFull,
35            mpsc::error::TrySendError::Closed(_) => ws::Error::DriverGone,
36        })
37    }
38
39    pub async fn disconnect(&self) -> Result<(), ws::Error> {
40        let cmd = ws::Command::Disconnect;
41        self.cmd_tx
42            .send(cmd)
43            .await
44            .map_err(|_| ws::Error::DriverGone)
45    }
46
47    pub fn try_disconnect(&self) -> Result<(), ws::Error> {
48        let cmd = ws::Command::Disconnect;
49        self.cmd_tx.try_send(cmd).map_err(|e| match e {
50            mpsc::error::TrySendError::Full(_) => ws::Error::QueueFull,
51            mpsc::error::TrySendError::Closed(_) => ws::Error::DriverGone,
52        })
53    }
54
55    pub async fn send_command(&self, msg: C) -> Result<(), ws::Error> {
56        let cmd = ws::Command::Send(msg);
57        self.cmd_tx
58            .send(cmd)
59            .await
60            .map_err(|_| ws::Error::DriverGone)
61    }
62
63    pub fn try_send_command(&self, msg: C) -> Result<(), ws::Error> {
64        let cmd = ws::Command::Send(msg);
65        self.cmd_tx.try_send(cmd).map_err(|e| match e {
66            mpsc::error::TrySendError::Full(_) => ws::Error::QueueFull,
67            mpsc::error::TrySendError::Closed(_) => ws::Error::DriverGone,
68        })
69    }
70}