use alloc::string::{String, ToString};
use core::future::Future;
use axum::extract::State;
use axum::extract::ws::{Message as WsMessage, WebSocket, WebSocketUpgrade};
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::routing::any;
use crate::io::{Error, Received, TextTransport};
use super::store::PairingKey;
use super::routes::Endpoint;
#[derive(Debug)]
pub struct ServerSocket {
socket: WebSocket,
ended: Option<tokio::sync::watch::Receiver<bool>>,
}
impl ServerSocket {
#[must_use]
pub fn new(socket: WebSocket) -> Self {
Self {
socket,
ended: None,
}
}
#[must_use]
pub fn ending_with(mut self, session: &super::LiveSession) -> Self {
self.ended = Some(session.watch());
self
}
}
impl TextTransport for ServerSocket {
async fn send_text(&mut self, text: String) -> Result<(), Error> {
self.socket
.send(WsMessage::Text(text.into()))
.await
.map_err(|e| Error::Transport(e.to_string()))
}
#[allow(clippy::match_same_arms)]
async fn recv_text(&mut self) -> Result<Option<String>, Error> {
loop {
match self.recv().await? {
None => return Ok(None),
Some(Received::Text(text)) => return Ok(Some(text)),
Some(Received::Alive) => {}
}
}
}
async fn recv(&mut self) -> Result<Option<Received>, Error> {
{
let frame = match self.ended.as_mut() {
Some(ended) => {
tokio::select! {
frame = self.socket.recv() => Some(frame),
_ = async { ended.wait_for(|ended| *ended).await.is_ok() } => None,
}
}
None => Some(self.socket.recv().await),
};
let Some(frame) = frame else {
let _ = self.socket.send(WsMessage::Close(None)).await;
return Ok(None);
};
match frame {
None | Some(Ok(WsMessage::Close(_))) => Ok(None),
Some(Err(e)) => Err(Error::Transport(e.to_string())),
Some(Ok(WsMessage::Text(text))) => Ok(Some(Received::Text(text.to_string()))),
Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => Ok(Some(Received::Alive)),
Some(Ok(WsMessage::Binary(_))) => Err(Error::UnexpectedFrame("binary".to_string())),
}
}
}
async fn ping(&mut self) -> Result<(), Error> {
self.socket
.send(WsMessage::Ping(axum::body::Bytes::new()))
.await
.map_err(|e| Error::Transport(e.to_string()))
}
async fn close(&mut self) {
let _ = self.socket.send(WsMessage::Close(None)).await;
}
}
struct WsState<H> {
endpoint: Endpoint,
handler: alloc::sync::Arc<H>,
}
impl<H> Clone for WsState<H> {
fn clone(&self) -> Self {
Self {
endpoint: self.endpoint.clone(),
handler: self.handler.clone(),
}
}
}
pub fn websocket_router<H, Fut>(endpoint: Endpoint, path: &str, on_session: H) -> axum::Router
where
H: Fn(PairingKey, ServerSocket) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
axum::Router::new()
.route(path, any(upgrade::<H, Fut>))
.with_state(WsState {
endpoint,
handler: alloc::sync::Arc::new(on_session),
})
}
async fn upgrade<H, Fut>(
State(state): State<WsState<H>>,
bearer: super::routes::Bearer,
upgrade: WebSocketUpgrade,
) -> Response
where
H: Fn(PairingKey, ServerSocket) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let now = state.endpoint.now();
let Some(key) = state
.endpoint
.session()
.authorize_connection(bearer.as_str(), now)
else {
crate::trace::event!(warn, "refused a WebSocket with an unusable token");
return StatusCode::UNAUTHORIZED.into_response();
};
crate::trace::event!(info, node = %key.remote, "accepted an S2 WebSocket");
let handler = state.handler.clone();
let live = state.endpoint.session().register_session(key);
upgrade
.max_message_size(state.endpoint.max_message_bytes())
.max_frame_size(state.endpoint.max_message_bytes())
.on_upgrade(move |socket| async move {
let socket = ServerSocket::new(socket).ending_with(&live);
handler(key, socket).await;
drop(live);
})
}