Skip to main content

karyon_net/layers/
ws.rs

1use std::io;
2
3use async_tungstenite::tungstenite::{
4    Bytes as TungBytes, Message as TungMessage, protocol::WebSocketConfig,
5};
6use async_tungstenite::{WebSocketReceiver, WebSocketSender, WebSocketStream};
7use futures_util::StreamExt;
8
9#[cfg(feature = "tokio")]
10use async_tungstenite::tokio::{TokioAdapter, accept_async_with_config, client_async_with_config};
11#[cfg(feature = "smol")]
12use async_tungstenite::{accept_async_with_config, client_async_with_config};
13
14use crate::{
15    ByteStream, Endpoint, Error, Result,
16    codec::Codec,
17    layer::{ClientLayer, ServerLayer},
18    message::{MessageRx, MessageTx},
19};
20
21#[cfg(feature = "tokio")]
22type WsInner = TokioAdapter<Box<dyn ByteStream>>;
23#[cfg(feature = "smol")]
24type WsInner = Box<dyn ByteStream>;
25
26/// Default max WS message size, the same as the built-in codecs.
27const DEFAULT_MAX_MSG_SIZE: usize = 4 * 1024 * 1024; // 4MB
28
29/// WebSocket message types. Wraps the underlying WS protocol
30/// message kinds without exposing the third-party library.
31#[derive(Debug, Clone)]
32pub enum Message {
33    Text(String),
34    Binary(Vec<u8>),
35    Ping(Vec<u8>),
36    Pong(Vec<u8>),
37    Close,
38}
39
40impl Message {
41    /// Get the message payload as bytes.
42    pub fn into_bytes(self) -> Vec<u8> {
43        match self {
44            Message::Text(s) => s.into_bytes(),
45            Message::Binary(b) => b,
46            Message::Ping(b) => b,
47            Message::Pong(b) => b,
48            Message::Close => Vec::new(),
49        }
50    }
51
52    pub fn is_text(&self) -> bool {
53        matches!(self, Message::Text(_))
54    }
55
56    pub fn is_binary(&self) -> bool {
57        matches!(self, Message::Binary(_))
58    }
59
60    pub fn is_ping(&self) -> bool {
61        matches!(self, Message::Ping(_))
62    }
63
64    pub fn is_pong(&self) -> bool {
65        matches!(self, Message::Pong(_))
66    }
67
68    pub fn is_close(&self) -> bool {
69        matches!(self, Message::Close)
70    }
71}
72
73/// WebSocket layer. Upgrades a byte stream to a WsConn.
74///
75/// Takes a `Codec<Message>` to encode/decode WS messages directly.
76#[derive(Clone)]
77pub struct WsLayer<C> {
78    url: Option<String>,
79    codec: C,
80    /// Max size of one WS message or frame. Bigger ones are rejected
81    /// before they are buffered.
82    max_msg_size: usize,
83}
84
85impl<C> WsLayer<C>
86where
87    C: Codec<Message> + Clone,
88{
89    /// Create a client WS layer with the target URL and codec.
90    pub fn client(url: &str, codec: C) -> Self {
91        Self {
92            url: Some(url.to_string()),
93            codec,
94            max_msg_size: DEFAULT_MAX_MSG_SIZE,
95        }
96    }
97
98    /// Create a server WS layer with codec.
99    pub fn server(codec: C) -> Self {
100        Self {
101            url: None,
102            codec,
103            max_msg_size: DEFAULT_MAX_MSG_SIZE,
104        }
105    }
106
107    /// Set the max size of one WS message. Defaults to 4MB.
108    pub fn with_max_msg_size(mut self, size: usize) -> Self {
109        self.max_msg_size = size;
110        self
111    }
112
113    fn config(&self) -> WebSocketConfig {
114        WebSocketConfig::default()
115            .max_message_size(Some(self.max_msg_size))
116            .max_frame_size(Some(self.max_msg_size))
117    }
118}
119
120impl<C> ClientLayer<Box<dyn ByteStream>, WsConn<C>> for WsLayer<C>
121where
122    C: Codec<Message> + Clone + Send + Sync + 'static,
123    C::Message: Send + Sync + 'static,
124    C::Error: From<io::Error> + Into<Error> + Send + Sync,
125{
126    async fn handshake(&self, stream: Box<dyn ByteStream>) -> Result<WsConn<C>> {
127        let url = self
128            .url
129            .as_ref()
130            .ok_or_else(|| Error::MissingConfig("WS client layer requires a URL".into()))?;
131
132        let peer = stream.peer_endpoint();
133        let local = stream.local_endpoint();
134
135        let (ws, _) = client_async_with_config(url.as_str(), stream, Some(self.config()))
136            .await
137            .map_err(|e| Error::IO(io::Error::other(e)))?;
138
139        Ok(WsConn::new(ws, self.codec.clone(), peer, local))
140    }
141}
142
143impl<C> ServerLayer<Box<dyn ByteStream>, WsConn<C>> for WsLayer<C>
144where
145    C: Codec<Message> + Clone + Send + Sync + 'static,
146    C::Message: Send + Sync + 'static,
147    C::Error: From<io::Error> + Into<Error> + Send + Sync,
148{
149    async fn handshake(&self, stream: Box<dyn ByteStream>) -> Result<WsConn<C>> {
150        let peer = stream.peer_endpoint();
151        let local = stream.local_endpoint();
152
153        let ws = accept_async_with_config(stream, Some(self.config()))
154            .await
155            .map_err(|e| Error::IO(io::Error::other(e)))?;
156
157        Ok(WsConn::new(ws, self.codec.clone(), peer, local))
158    }
159}
160
161// -- Convert between ws::Message and tungstenite Message --
162
163// Move the payload out instead of copying it. `Vec::from` reuses the
164// buffer when it is not shared.
165fn from_tung(msg: TungMessage) -> Message {
166    match msg {
167        TungMessage::Text(t) => {
168            let bytes = Vec::from(TungBytes::from(t));
169            // Already checked as UTF-8 by tungstenite, so this does not fail.
170            Message::Text(String::from_utf8(bytes).unwrap_or_default())
171        }
172        TungMessage::Binary(b) => Message::Binary(Vec::from(b)),
173        TungMessage::Ping(b) => Message::Ping(Vec::from(b)),
174        TungMessage::Pong(b) => Message::Pong(Vec::from(b)),
175        TungMessage::Close(_) => Message::Close,
176        _ => Message::Close,
177    }
178}
179
180fn into_tung(msg: Message) -> TungMessage {
181    match msg {
182        Message::Text(s) => TungMessage::Text(s.into()),
183        Message::Binary(b) => TungMessage::Binary(b.into()),
184        Message::Ping(b) => TungMessage::Ping(b.into()),
185        Message::Pong(b) => TungMessage::Pong(b.into()),
186        Message::Close => TungMessage::Close(None),
187    }
188}
189
190/// WebSocket message connection.
191pub struct WsConn<C> {
192    reader: WsReader<C>,
193    writer: WsWriter<C>,
194}
195
196impl<C: Clone> WsConn<C> {
197    fn new(
198        ws: WebSocketStream<WsInner>,
199        codec: C,
200        peer_endpoint: Option<Endpoint>,
201        local_endpoint: Option<Endpoint>,
202    ) -> Self {
203        let (sender, receiver) = ws.split();
204        Self {
205            reader: WsReader {
206                receiver,
207                codec: codec.clone(),
208                peer_endpoint: peer_endpoint.clone(),
209                local_endpoint: local_endpoint.clone(),
210            },
211            writer: WsWriter {
212                sender,
213                codec,
214                peer_endpoint,
215                local_endpoint,
216            },
217        }
218    }
219}
220
221impl<C> WsConn<C>
222where
223    C: Codec<Message> + Clone + Send + Sync + 'static,
224    C::Message: Send + Sync + 'static,
225    C::Error: From<io::Error> + Into<Error> + Send + Sync,
226{
227    /// Receive one complete message.
228    pub async fn recv_msg(&mut self) -> Result<C::Message> {
229        self.reader.recv_msg().await
230    }
231
232    /// Send one complete message.
233    pub async fn send_msg(&mut self, msg: C::Message) -> Result<()> {
234        self.writer.send_msg(msg).await
235    }
236
237    /// Remote peer address.
238    pub fn peer_endpoint(&self) -> Option<Endpoint> {
239        self.reader.peer_endpoint.clone()
240    }
241
242    /// Local address.
243    pub fn local_endpoint(&self) -> Option<Endpoint> {
244        self.reader.local_endpoint.clone()
245    }
246
247    /// Split into independent reader and writer halves.
248    pub fn split(self) -> (WsReader<C>, WsWriter<C>) {
249        (self.reader, self.writer)
250    }
251}
252
253/// Read half of a WebSocket connection.
254pub struct WsReader<C> {
255    receiver: WebSocketReceiver<WsInner>,
256    codec: C,
257    peer_endpoint: Option<Endpoint>,
258    local_endpoint: Option<Endpoint>,
259}
260
261impl<C> WsReader<C>
262where
263    C: Codec<Message> + Send + Sync,
264    C::Message: Send + Sync,
265    C::Error: From<io::Error> + Into<Error> + Send + Sync,
266{
267    /// Receive one complete message.
268    pub async fn recv_msg(&mut self) -> Result<C::Message> {
269        loop {
270            let raw = self
271                .receiver
272                .next()
273                .await
274                .ok_or(Error::ConnectionClosed)?
275                .map_err(|e| Error::IO(io::Error::other(e)))?;
276
277            let mut ws_msg = from_tung(raw);
278            match self.codec.decode(&mut ws_msg).map_err(Into::into)? {
279                Some((_, item)) => return Ok(item),
280                None => continue,
281            }
282        }
283    }
284
285    /// Remote peer address.
286    pub fn peer_endpoint(&self) -> Option<Endpoint> {
287        self.peer_endpoint.clone()
288    }
289
290    /// Local address.
291    pub fn local_endpoint(&self) -> Option<Endpoint> {
292        self.local_endpoint.clone()
293    }
294}
295
296impl<C> MessageRx for WsReader<C>
297where
298    C: Codec<Message> + Send + Sync,
299    C::Message: Send + Sync,
300    C::Error: From<io::Error> + Into<Error> + Send + Sync,
301{
302    type Message = C::Message;
303
304    fn recv_msg(&mut self) -> impl std::future::Future<Output = Result<Self::Message>> + Send {
305        WsReader::recv_msg(self)
306    }
307
308    fn peer_endpoint(&self) -> Option<Endpoint> {
309        WsReader::peer_endpoint(self)
310    }
311}
312
313/// Write half of a WebSocket connection.
314pub struct WsWriter<C> {
315    sender: WebSocketSender<WsInner>,
316    codec: C,
317    peer_endpoint: Option<Endpoint>,
318    local_endpoint: Option<Endpoint>,
319}
320
321impl<C> WsWriter<C>
322where
323    C: Codec<Message> + Send + Sync,
324    C::Message: Send + Sync,
325    C::Error: From<io::Error> + Into<Error> + Send + Sync,
326{
327    /// Send one complete message.
328    pub async fn send_msg(&mut self, msg: C::Message) -> Result<()> {
329        let mut ws_msg = Message::Binary(Vec::new());
330        self.codec.encode(&msg, &mut ws_msg).map_err(Into::into)?;
331
332        self.sender
333            .send(into_tung(ws_msg))
334            .await
335            .map_err(|e| Error::IO(io::Error::other(e)))?;
336        Ok(())
337    }
338
339    /// Remote peer address.
340    pub fn peer_endpoint(&self) -> Option<Endpoint> {
341        self.peer_endpoint.clone()
342    }
343
344    /// Local address.
345    pub fn local_endpoint(&self) -> Option<Endpoint> {
346        self.local_endpoint.clone()
347    }
348}
349
350impl<C> MessageTx for WsWriter<C>
351where
352    C: Codec<Message> + Send + Sync,
353    C::Message: Send + Sync,
354    C::Error: From<io::Error> + Into<Error> + Send + Sync,
355{
356    type Message = C::Message;
357
358    fn send_msg(
359        &mut self,
360        msg: Self::Message,
361    ) -> impl std::future::Future<Output = Result<()>> + Send {
362        WsWriter::send_msg(self, msg)
363    }
364
365    fn peer_endpoint(&self) -> Option<Endpoint> {
366        WsWriter::peer_endpoint(self)
367    }
368}