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::connect::proto::NodeId;
use crate::io::{Error, TextTransport};
use super::routes::Endpoint;
#[derive(Debug)]
pub struct ServerSocket {
socket: WebSocket,
}
impl ServerSocket {
#[must_use]
pub fn new(socket: WebSocket) -> Self {
Self { socket }
}
}
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.socket.recv().await {
None => return Ok(None),
Some(Err(e)) => return Err(Error::Transport(e.to_string())),
Some(Ok(WsMessage::Text(text))) => return Ok(Some(text.to_string())),
Some(Ok(WsMessage::Close(_))) => return Ok(None),
Some(Ok(WsMessage::Ping(_) | WsMessage::Pong(_))) => {}
Some(Ok(WsMessage::Binary(_))) => {
return 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(NodeId, 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(NodeId, ServerSocket) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let now = state.endpoint.now();
let Some(node) = 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 = %node, "accepted an S2 WebSocket");
let handler = state.handler.clone();
upgrade
.max_message_size(state.endpoint.max_message_bytes())
.max_frame_size(state.endpoint.max_message_bytes())
.on_upgrade(move |socket| async move {
handler(node, ServerSocket::new(socket)).await;
})
}