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        self.send(Command::Connect).await
17    }
18
19    pub fn try_connect(&self) -> Result<(), ws::Error> {
20        self.try_send(Command::Connect)
21    }
22
23    pub async fn disconnect(&self) -> Result<(), ws::Error> {
24        self.send(Command::Disconnect).await
25    }
26
27    pub fn try_disconnect(&self) -> Result<(), ws::Error> {
28        self.try_send(Command::Disconnect)
29    }
30
31    pub async fn send_command(&self, msg: OutgoingMessage) -> Result<(), ws::Error> {
32        self.send(Command::Send(msg)).await
33    }
34
35    pub fn try_send_command(&self, msg: OutgoingMessage) -> Result<(), ws::Error> {
36        self.try_send(Command::Send(msg))
37    }
38
39    async fn send(&self, cmd: Command) -> Result<(), ws::Error> {
40        self.cmd_tx
41            .send(cmd)
42            .await
43            .map_err(|_| ws::Error::DriverGone)
44    }
45
46    fn try_send(&self, cmd: Command) -> Result<(), ws::Error> {
47        self.cmd_tx.try_send(cmd).map_err(map_try_send_err)
48    }
49}
50
51fn map_try_send_err(e: mpsc::error::TrySendError<Command>) -> ws::Error {
52    match e {
53        mpsc::error::TrySendError::Full(_) => ws::Error::QueueFull,
54        mpsc::error::TrySendError::Closed(_) => ws::Error::DriverGone,
55    }
56}