use rama_core::error::{BoxError, BoxErrorExt as _};
use std::{
io::{self, Read, Write},
pin::Pin,
task::{Context, Poll, ready},
};
use rama_core::io::Io;
use rama_core::{
extensions::{Extensions, ExtensionsRef},
futures::{self, SinkExt, StreamExt},
telemetry::tracing::{debug, trace},
};
use rama_http::io::upgrade;
use crate::{
Message, ProtocolError,
protocol::{CloseFrame, Role, WebSocket, WebSocketConfig},
runtime::{
compat::{self, AllowStd, ContextWaker},
handshake::without_handshake,
},
};
#[derive(Debug)]
pub struct AsyncWebSocket<S = upgrade::Upgraded> {
inner: WebSocket<AllowStd<S>>,
closing: bool,
ended: bool,
ready: bool,
}
impl<S> AsyncWebSocket<S> {
pub async fn from_raw_socket(stream: S, role: Role, config: Option<WebSocketConfig>) -> Self
where
S: Io + Unpin + ExtensionsRef,
{
without_handshake(stream, move |allow_std| {
WebSocket::from_raw_socket(allow_std, role, config)
})
.await
}
pub async fn from_partially_read(
stream: S,
part: Vec<u8>,
role: Role,
config: Option<WebSocketConfig>,
) -> Self
where
S: Io + Unpin + ExtensionsRef,
{
without_handshake(stream, move |allow_std| {
WebSocket::from_partially_read(allow_std, part, role, config)
})
.await
}
pub(crate) fn new(ws: WebSocket<AllowStd<S>>) -> Self {
Self {
inner: ws,
closing: false,
ended: false,
ready: true,
}
}
fn with_context<F, R>(&mut self, ctx: Option<(ContextWaker, &mut Context<'_>)>, f: F) -> R
where
S: Unpin,
F: FnOnce(&mut WebSocket<AllowStd<S>>) -> R,
AllowStd<S>: Read + Write,
{
trace!("AsyncWebSocket.with_context");
if let Some((kind, ctx)) = ctx {
self.inner.get_mut().set_waker(kind, ctx.waker());
}
f(&mut self.inner)
}
pub fn into_inner(self) -> S {
self.inner.into_inner().into_inner()
}
pub fn get_ref(&self) -> &S
where
S: Io + Unpin,
{
self.inner.get_ref().get_ref()
}
pub fn get_mut(&mut self) -> &mut S
where
S: Io + Unpin,
{
self.inner.get_mut().get_mut()
}
pub fn get_config(&self) -> &WebSocketConfig {
self.inner.get_config()
}
pub async fn close(&mut self, msg: Option<CloseFrame>) -> Result<(), ProtocolError>
where
S: Io + Unpin,
{
self.send(Message::Close(msg)).await
}
}
impl<S: ExtensionsRef> ExtensionsRef for AsyncWebSocket<S> {
fn extensions(&self) -> &Extensions {
self.inner.extensions()
}
}
impl<S: Io + Unpin> AsyncWebSocket<S> {
#[inline]
pub fn send_message(
&mut self,
msg: Message,
) -> impl Future<Output = Result<(), ProtocolError>> + Send + '_ {
self.send(msg)
}
pub async fn recv_message(&mut self) -> Result<Message, ProtocolError> {
self.next().await.ok_or_else(|| {
ProtocolError::Io(io::Error::new(
io::ErrorKind::ConnectionAborted,
BoxError::from_static_str(
"Connection closed: no messages to be received any longer",
),
))
})?
}
}
impl<T> futures::Stream for AsyncWebSocket<T>
where
T: Io + Unpin,
{
type Item = Result<Message, ProtocolError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
trace!("Stream.poll_next");
if self.ended {
return Poll::Ready(None);
}
match ready!(self.with_context(Some((ContextWaker::Read, cx)), |s| {
trace!("Stream.with_context poll_next -> read()");
compat::cvt(s.read())
})) {
Ok(v) => Poll::Ready(Some(Ok(v))),
Err(e) => {
self.ended = true;
if e.is_connection_error() {
Poll::Ready(None)
} else {
Poll::Ready(Some(Err(e)))
}
}
}
}
}
impl<T> futures::stream::FusedStream for AsyncWebSocket<T>
where
T: Io + Unpin,
{
fn is_terminated(&self) -> bool {
self.ended
}
}
impl<T> futures::Sink<Message> for AsyncWebSocket<T>
where
T: Io + Unpin,
{
type Error = ProtocolError;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
if self.ready {
Poll::Ready(Ok(()))
} else {
(*self)
.with_context(Some((ContextWaker::Write, cx)), |s| compat::cvt(s.flush()))
.map(|r| {
self.ready = true;
r
})
}
}
fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
match (*self).with_context(None, |s| s.write(item)) {
Ok(()) => {
self.ready = true;
Ok(())
}
Err(ProtocolError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {
self.ready = false;
Ok(())
}
Err(e) => {
self.ready = true;
debug!("websocket start_send error: {e}");
Err(e)
}
}
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
(*self)
.with_context(Some((ContextWaker::Write, cx)), |s| compat::cvt(s.flush()))
.map(|r| {
self.ready = true;
match r {
Err(err) if err.is_connection_error() => {
Ok(())
}
other => other,
}
})
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.ready = true;
let res = if self.closing {
(*self).with_context(Some((ContextWaker::Write, cx)), |s| s.flush())
} else {
(*self).with_context(Some((ContextWaker::Write, cx)), |s| s.close(None))
};
match res {
Ok(()) => Poll::Ready(Ok(())),
Err(ProtocolError::Io(err)) if err.kind() == std::io::ErrorKind::WouldBlock => {
trace!("WouldBlock");
self.closing = true;
Poll::Pending
}
Err(err) => {
if err.is_connection_error() {
Poll::Ready(Ok(()))
} else {
debug!("websocket close error: {}", err);
Poll::Ready(Err(err))
}
}
}
}
}
#[cfg(test)]
mod tests {
use crate::runtime::{AsyncWebSocket, compat::AllowStd};
use std::io::{Read, Write};
fn is_read<T: Read>() {}
fn is_write<T: Write>() {}
fn is_unpin<T: Unpin>() {}
#[test]
fn web_socket_stream_has_traits() {
is_read::<AllowStd<tokio::net::TcpStream>>();
is_write::<AllowStd<tokio::net::TcpStream>>();
is_unpin::<AsyncWebSocket<tokio::net::TcpStream>>();
}
}