aboutsummaryrefslogtreecommitdiff
path: root/net/src/stream/websocket.rs
blob: 9f4da46064d0bd3092aac011e976213b26474197 (plain)
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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
use std::{
    pin::Pin,
    task::{Context, Poll},
};

use async_tungstenite::tungstenite::Message;
use futures_util::{
    stream::{SplitSink, SplitStream},
    Sink, SinkExt, Stream, StreamExt, TryStreamExt,
};
use pin_project_lite::pin_project;

#[cfg(feature = "tokio")]
type WebSocketStream<T> =
    async_tungstenite::WebSocketStream<async_tungstenite::tokio::TokioAdapter<T>>;
#[cfg(feature = "smol")]
use async_tungstenite::WebSocketStream;

use karyon_core::async_runtime::net::TcpStream;

#[cfg(feature = "tls")]
use crate::async_rustls::TlsStream;

use crate::{codec::WebSocketCodec, Error, Result};

pub struct WsStream<C> {
    inner: InnerWSConn,
    codec: C,
}

impl<C> WsStream<C>
where
    C: WebSocketCodec + Clone,
{
    pub fn new_ws(conn: WebSocketStream<TcpStream>, codec: C) -> Self {
        Self {
            inner: InnerWSConn::Plain(conn),
            codec,
        }
    }

    #[cfg(feature = "tls")]
    pub fn new_wss(conn: WebSocketStream<TlsStream<TcpStream>>, codec: C) -> Self {
        Self {
            inner: InnerWSConn::Tls(conn),
            codec,
        }
    }

    pub fn split(self) -> (ReadWsStream<C>, WriteWsStream<C>) {
        let (write, read) = self.inner.split();

        (
            ReadWsStream {
                codec: self.codec.clone(),
                inner: read,
            },
            WriteWsStream {
                inner: write,
                codec: self.codec,
            },
        )
    }
}

pin_project! {
    pub struct ReadWsStream<C> {
        #[pin]
        inner: SplitStream<InnerWSConn>,
        codec: C,
    }
}

pin_project! {
    pub struct WriteWsStream<C> {
        #[pin]
        inner: SplitSink<InnerWSConn, Message>,
        codec: C,
    }
}

impl<C> ReadWsStream<C>
where
    C: WebSocketCodec,
{
    pub async fn recv(&mut self) -> Result<C::Item> {
        match self.inner.next().await {
            Some(msg) => match self.codec.decode(&msg?)? {
                Some(m) => Ok(m),
                None => todo!(),
            },
            None => Err(Error::IO(std::io::ErrorKind::ConnectionAborted.into())),
        }
    }
}

impl<C> WriteWsStream<C>
where
    C: WebSocketCodec,
{
    pub async fn send(&mut self, msg: C::Item) -> Result<()> {
        let ws_msg = self.codec.encode(&msg)?;
        self.inner.send(ws_msg).await
    }
}

impl<C> Sink<Message> for WriteWsStream<C> {
    type Error = Error;

    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        self.project().inner.poll_ready(cx)
    }

    fn start_send(self: Pin<&mut Self>, item: Message) -> Result<()> {
        self.project().inner.start_send(item)
    }

    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        self.project().inner.poll_flush(cx)
    }

    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        self.project().inner.poll_close(cx)
    }
}

impl<C> Stream for ReadWsStream<C> {
    type Item = Result<Message>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        self.inner.try_poll_next_unpin(cx)
    }
}

enum InnerWSConn {
    Plain(WebSocketStream<TcpStream>),
    #[cfg(feature = "tls")]
    Tls(WebSocketStream<TlsStream<TcpStream>>),
}

impl Sink<Message> for InnerWSConn {
    type Error = Error;

    fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        match &mut *self {
            InnerWSConn::Plain(s) => Pin::new(s).poll_ready(cx).map_err(Error::from),
            #[cfg(feature = "tls")]
            InnerWSConn::Tls(s) => Pin::new(s).poll_ready(cx).map_err(Error::from),
        }
    }

    fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<()> {
        match &mut *self {
            InnerWSConn::Plain(s) => Pin::new(s).start_send(item).map_err(Error::from),
            #[cfg(feature = "tls")]
            InnerWSConn::Tls(s) => Pin::new(s).start_send(item).map_err(Error::from),
        }
    }

    fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        match &mut *self {
            InnerWSConn::Plain(s) => Pin::new(s).poll_flush(cx).map_err(Error::from),
            #[cfg(feature = "tls")]
            InnerWSConn::Tls(s) => Pin::new(s).poll_flush(cx).map_err(Error::from),
        }
    }

    fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<()>> {
        match &mut *self {
            InnerWSConn::Plain(s) => Pin::new(s).poll_close(cx).map_err(Error::from),
            #[cfg(feature = "tls")]
            InnerWSConn::Tls(s) => Pin::new(s).poll_close(cx).map_err(Error::from),
        }
        .map_err(Error::from)
    }
}

impl Stream for InnerWSConn {
    type Item = Result<Message>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        match &mut *self {
            InnerWSConn::Plain(s) => Pin::new(s).poll_next(cx).map_err(Error::from),
            #[cfg(feature = "tls")]
            InnerWSConn::Tls(s) => Pin::new(s).poll_next(cx).map_err(Error::from),
        }
    }
}