Skip to main content

bybit/ws/
handle.rs

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