use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll, ready};
use futures_util::stream::FusedStream;
use futures_util::{Sink, SinkExt, Stream, StreamExt};
use http::StatusCode;
use http::header::{self, HeaderValue};
use http::request::Parts;
use hyper::upgrade::{OnUpgrade, Upgraded};
use hyper_util::rt::TokioIo;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::protocol::{Role, WebSocketConfig};
use tokio_tungstenite::tungstenite::{self, error::CapacityError};
use crate::body::Body;
use crate::extract::FromRequestParts;
use crate::response::Response;
mod handshake;
mod message;
pub use crate::extract::rejection::WebSocketRejection;
pub use handshake::{Handshake, origin_allowed};
pub use message::{CloseCode, CloseFrame, Message, Utf8Bytes};
pub const DEFAULT_MAX_FRAME_BYTES: usize = 1024 * 1024;
pub const DEFAULT_MAX_MESSAGE_BYTES: usize = 1024 * 1024;
#[must_use = "a WebSocket opens when the response of `on_upgrade` is returned"]
#[derive(Debug)]
pub struct WebSocketUpgrade {
handshake: Handshake,
config: WebSocketConfig,
protocol: Option<HeaderValue>,
on_upgrade: OnUpgrade,
}
impl WebSocketUpgrade {
pub fn max_frame_size(mut self, bytes: usize) -> Self {
self.config = self.config.max_frame_size(Some(bytes));
self
}
pub fn max_message_size(mut self, bytes: usize) -> Self {
self.config = self.config.max_message_size(Some(bytes));
self
}
pub fn read_buffer_size(mut self, bytes: usize) -> Self {
self.config = self.config.read_buffer_size(bytes);
self
}
pub fn write_buffer_size(mut self, bytes: usize) -> Self {
self.config = self.config.write_buffer_size(bytes);
self
}
pub fn max_write_buffer_size(mut self, bytes: usize) -> Self {
self.config = self.config.max_write_buffer_size(bytes);
self
}
pub fn protocols<I>(mut self, protocols: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
self.protocol = protocols.into_iter().find_map(|protocol| {
let protocol = protocol.as_ref();
self.handshake
.requested_protocols()
.iter()
.find(|offered| offered.as_bytes() == protocol.as_bytes())
.cloned()
});
self
}
pub fn requested_protocols(&self) -> &[HeaderValue] {
self.handshake.requested_protocols()
}
pub fn selected_protocol(&self) -> Option<&HeaderValue> {
self.protocol.as_ref()
}
pub fn origin(&self) -> Option<&str> {
self.handshake.origin()
}
pub fn origin_allowed<S: AsRef<str>>(&self, allowed: &[S]) -> bool {
origin_allowed(self.handshake.origin(), self.handshake.host(), allowed)
}
#[must_use = "the WebSocket opens when this response is returned"]
pub fn on_upgrade<C, F>(self, callback: C) -> Response
where
C: FnOnce(WebSocket) -> F + Send + 'static,
F: Future<Output = ()> + Send + 'static,
{
let Self {
handshake,
config,
protocol,
on_upgrade,
} = self;
let chosen = protocol.clone();
tokio::spawn(async move {
let upgraded = match on_upgrade.await {
Ok(upgraded) => upgraded,
Err(error) => {
tracing::debug!(target: "navree::http", %error, "the WebSocket upgrade failed");
return;
}
};
let inner = WebSocketStream::from_raw_socket(
TokioIo::new(upgraded),
Role::Server,
Some(config),
)
.await;
callback(WebSocket {
inner,
protocol: chosen,
})
.await;
});
let mut response = Response::new(Body::empty());
if let Some(accept) = handshake.accept_key() {
*response.status_mut() = StatusCode::SWITCHING_PROTOCOLS;
let headers = response.headers_mut();
headers.insert(header::CONNECTION, HeaderValue::from_static("upgrade"));
headers.insert(header::UPGRADE, HeaderValue::from_static("websocket"));
headers.insert(header::SEC_WEBSOCKET_ACCEPT, accept);
}
if let Some(protocol) = protocol {
response
.headers_mut()
.insert(header::SEC_WEBSOCKET_PROTOCOL, protocol);
}
response
}
}
impl FromRequestParts for WebSocketUpgrade {
type Rejection = WebSocketRejection;
async fn from_request_parts(parts: &mut Parts) -> Result<Self, Self::Rejection> {
let handshake = Handshake::read(parts)?;
let on_upgrade = parts
.extensions
.remove::<OnUpgrade>()
.ok_or(WebSocketRejection::NotUpgradable)?;
Ok(Self {
handshake,
config: WebSocketConfig::default()
.max_frame_size(Some(DEFAULT_MAX_FRAME_BYTES))
.max_message_size(Some(DEFAULT_MAX_MESSAGE_BYTES)),
protocol: None,
on_upgrade,
})
}
}
#[derive(Debug)]
pub struct WebSocketError(Box<tungstenite::Error>);
impl WebSocketError {
fn new(error: tungstenite::Error) -> Self {
Self(Box::new(error))
}
pub fn is_too_large(&self) -> bool {
matches!(
*self.0,
tungstenite::Error::Capacity(CapacityError::MessageTooLong { .. })
)
}
}
impl std::fmt::Display for WebSocketError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.0.fmt(f)
}
}
impl std::error::Error for WebSocketError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&*self.0)
}
}
#[derive(Debug)]
pub struct WebSocket {
inner: WebSocketStream<TokioIo<Upgraded>>,
protocol: Option<HeaderValue>,
}
impl WebSocket {
pub async fn recv(&mut self) -> Option<Result<Message, WebSocketError>> {
self.next().await
}
pub async fn send(&mut self, message: Message) -> Result<(), WebSocketError> {
self.inner
.send(message.into_tungstenite())
.await
.map_err(WebSocketError::new)
}
pub fn protocol(&self) -> Option<&HeaderValue> {
self.protocol.as_ref()
}
}
impl Stream for WebSocket {
type Item = Result<Message, WebSocketError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
loop {
return Poll::Ready(match ready!(self.inner.poll_next_unpin(cx)) {
Some(Ok(message)) => match Message::from_tungstenite(message) {
Some(message) => Some(Ok(message)),
None => continue,
},
Some(Err(error)) => Some(Err(WebSocketError::new(error))),
None => None,
});
}
}
}
impl FusedStream for WebSocket {
fn is_terminated(&self) -> bool {
self.inner.is_terminated()
}
}
impl Sink<Message> for WebSocket {
type Error = WebSocketError;
fn poll_ready(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner)
.poll_ready(cx)
.map_err(WebSocketError::new)
}
fn start_send(mut self: Pin<&mut Self>, item: Message) -> Result<(), Self::Error> {
Pin::new(&mut self.inner)
.start_send(item.into_tungstenite())
.map_err(WebSocketError::new)
}
fn poll_flush(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner)
.poll_flush(cx)
.map_err(WebSocketError::new)
}
fn poll_close(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Pin::new(&mut self.inner)
.poll_close(cx)
.map_err(WebSocketError::new)
}
}