Skip to main content

rocket_ws/
duplex.rs

1use std::pin::Pin;
2use std::task::{Context, Poll};
3
4use rocket::data::IoStream;
5use rocket::futures::{ready, StreamExt, SinkExt, Sink};
6use rocket::futures::stream::{Stream, FusedStream};
7
8use crate::frame::{Message, CloseFrame};
9use crate::result::{Result, Error};
10
11/// A readable and writeable WebSocket [`Message`] `async` stream.
12///
13/// This struct implements [`Stream`] and [`Sink`], allowing for `async` reading
14/// and writing of [`Message`]s. The [`StreamExt`] and [`SinkExt`] traits can be
15/// imported to provide additional functionality for streams and sinks:
16///
17/// ```rust
18/// # use rocket::get;
19/// # use rocket_ws as ws;
20/// use rocket::futures::{SinkExt, StreamExt};
21///
22/// #[get("/echo/manual")]
23/// fn echo_manual<'r>(ws: ws::WebSocket) -> ws::Channel<'r> {
24///     ws.channel(move |mut stream| Box::pin(async move {
25///         while let Some(message) = stream.next().await {
26///             let _ = stream.send(message?).await;
27///         }
28///
29///         Ok(())
30///     }))
31/// }
32/// ```
33///
34/// [`StreamExt`]: rocket::futures::StreamExt
35/// [`SinkExt`]: rocket::futures::SinkExt
36pub struct DuplexStream(tokio_tungstenite::WebSocketStream<IoStream>, bool);
37
38impl DuplexStream {
39    /// If `await_close` is `true`, closing the sink also waits for the peer's
40    /// `Close`, discarding any other messages.
41    pub(crate) async fn new(stream: IoStream, config: crate::Config, await_close: bool) -> Self {
42        use tokio_tungstenite::WebSocketStream;
43        use crate::tungstenite::protocol::Role;
44
45        let inner = WebSocketStream::from_raw_socket(stream, Role::Server, Some(config));
46        DuplexStream(inner.await, await_close)
47    }
48
49    /// Close the stream now. This does not typically need to be called.
50    pub async fn close(&mut self, msg: Option<CloseFrame>) -> Result<()> {
51        self.0.close(msg).await
52    }
53}
54
55impl Stream for DuplexStream {
56    type Item = Result<Message>;
57
58    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
59        self.get_mut().0.poll_next_unpin(cx)
60    }
61
62    fn size_hint(&self) -> (usize, Option<usize>) {
63        self.0.size_hint()
64    }
65}
66
67impl FusedStream for DuplexStream {
68    fn is_terminated(&self) -> bool {
69        self.0.is_terminated()
70    }
71}
72
73impl Sink<Message> for DuplexStream {
74    type Error = Error;
75
76    fn poll_ready(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
77        self.get_mut().0.poll_ready_unpin(cx)
78    }
79
80    fn start_send(self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
81        self.get_mut().0.start_send_unpin(item)
82    }
83
84    fn poll_flush(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
85        self.get_mut().0.poll_flush_unpin(cx)
86    }
87
88    fn poll_close(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
89        let this = self.get_mut();
90        ready!(this.0.poll_close_unpin(cx))?;
91        while this.1 {
92            match ready!(this.0.poll_next_unpin(cx)) {
93                Some(Ok(message)) if message.is_close() => break,
94                Some(Ok(_)) => continue,
95                Some(Err(e)) => return Poll::Ready(Err(e)),
96                None => break,
97            }
98        }
99
100        Poll::Ready(Ok(()))
101    }
102}