1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
use std::io;
use std::io::Read;
use std::io::Write;
#[cfg(not(feature = "tokio"))]
use std::sync::mpsc;
#[cfg(not(feature = "tokio"))]
use std::sync::watch;
#[cfg(feature = "tokio")]
use tokio::sync::mpsc;
#[cfg(feature = "tokio")]
use tokio::sync::watch;
#[allow(unused_imports, dead_code)]
use tracing::{debug, error, info, trace, warn};

use crate::abi::*;
use crate::backend::ws::*;

#[derive(Debug)]
pub struct WebSocket {
    pub(super) task: Call,
    pub(super) rx: mpsc::Receiver<Received>,
    pub(super) state: watch::Receiver<SocketState>,
}

impl WebSocket {
    pub fn split(self) -> (SendHalf, RecvHalf) {
        (
            SendHalf {
                task: self.task,
                state: self.state,
            },
            RecvHalf { rx: self.rx },
        )
    }
}

#[derive(Debug, Clone)]
pub struct SendHalf {
    task: Call,
    state: watch::Receiver<SocketState>,
}

impl SendHalf {
    pub async fn wait_till_opened(&self) -> SocketState {
        let mut state = self.state.clone();
        while *state.borrow() == SocketState::Opening {
            if let Err(_) = state.changed().await {
                return SocketState::Closed;
            }
        }
        let ret = (*state.borrow()).clone();
        ret
    }

    pub async fn send(&self, data: Vec<u8>) -> io::Result<usize> {
        if self.wait_till_opened().await != SocketState::Opened {
            return Err(io::Error::new(
                io::ErrorKind::ConnectionReset,
                "connection is not open",
            ));
        }
        self.task
            .call(Send { data })
            .invoke()
            .join()
            .await
            .map_err(|err| err.into_io_error())
            .map(|ret| match ret {
                SendResult::Success(a) => Ok(a),
                SendResult::Failed(err) => Err(io::Error::new(io::ErrorKind::Other, err)),
            })?
    }

    pub fn blocking_send(&self, data: Vec<u8>) -> io::Result<usize> {
        if *self.state.borrow() != SocketState::Opened {
            return Err(io::Error::new(
                io::ErrorKind::ConnectionReset,
                "connection is not open",
            ));
        }
        self.task
            .call(Send { data })
            .invoke()
            .join()
            .wait()
            .map_err(|err| err.into_io_error())
            .map(|ret| match ret {
                SendResult::Success(a) => Ok(a),
                SendResult::Failed(err) => Err(io::Error::new(io::ErrorKind::Other, err)),
            })?
    }
}

#[derive(Debug)]
pub struct RecvHalf {
    rx: mpsc::Receiver<Received>,
}

#[cfg(feature = "tokio")]
impl RecvHalf {
    pub async fn recv(&mut self) -> Option<Vec<u8>> {
        self.rx.recv().await.map(|a| a.data)
    }

    pub fn blocking_recv(&mut self) -> Option<Vec<u8>> {
        self.rx.blocking_recv().map(|a| a.data)
    }
}

#[cfg(not(feature = "tokio"))]
impl RecvHalf {
    pub async fn recv(&mut self) -> Option<Vec<u8>> {
        self.rx.recv().ok().map(|a| a.data)
    }

    pub fn blocking_recv(&mut self) -> Option<Vec<u8>> {
        self.rx.recv().ok().map(|a| a.data)
    }
}