2023-11-20 19:08:07 +00:00
|
|
|
use crate::cnf;
|
2023-08-16 12:27:53 +00:00
|
|
|
use crate::rpc::connection::Connection;
|
2023-07-19 14:35:56 +00:00
|
|
|
use axum::routing::get;
|
|
|
|
use axum::Extension;
|
|
|
|
use axum::Router;
|
|
|
|
use http_body::Body as HttpBody;
|
2023-08-16 12:27:53 +00:00
|
|
|
use surrealdb::dbs::Session;
|
2023-08-03 14:59:05 +00:00
|
|
|
use tower_http::request_id::RequestId;
|
2023-05-31 22:40:24 +00:00
|
|
|
use uuid::Uuid;
|
2023-07-19 14:35:56 +00:00
|
|
|
|
|
|
|
use axum::{
|
2023-08-16 12:27:53 +00:00
|
|
|
extract::ws::{WebSocket, WebSocketUpgrade},
|
2023-07-19 14:35:56 +00:00
|
|
|
response::IntoResponse,
|
|
|
|
};
|
2022-07-04 01:03:26 +00:00
|
|
|
|
2023-07-19 14:35:56 +00:00
|
|
|
pub(super) fn router<S, B>() -> Router<S, B>
|
|
|
|
where
|
|
|
|
B: HttpBody + Send + 'static,
|
|
|
|
S: Clone + Send + Sync + 'static,
|
|
|
|
{
|
|
|
|
Router::new().route("/rpc", get(handler))
|
|
|
|
}
|
|
|
|
|
2023-08-03 14:59:05 +00:00
|
|
|
async fn handler(
|
|
|
|
ws: WebSocketUpgrade,
|
|
|
|
Extension(sess): Extension<Session>,
|
|
|
|
Extension(req_id): Extension<RequestId>,
|
|
|
|
) -> impl IntoResponse {
|
2023-11-20 19:08:07 +00:00
|
|
|
ws
|
|
|
|
// Set the maximum frame size
|
|
|
|
.max_frame_size(*cnf::WEBSOCKET_MAX_FRAME_SIZE)
|
|
|
|
// Set the maximum message size
|
|
|
|
.max_message_size(*cnf::WEBSOCKET_MAX_MESSAGE_SIZE)
|
|
|
|
// Set the potential WebSocket protocol formats
|
|
|
|
.protocols(["surrealql-binary", "json", "cbor", "messagepack"])
|
|
|
|
// Handle the WebSocket upgrade and process messages
|
|
|
|
.on_upgrade(move |socket| handle_socket(socket, sess, req_id))
|
2022-07-04 01:03:26 +00:00
|
|
|
}
|
|
|
|
|
2023-08-03 14:59:05 +00:00
|
|
|
async fn handle_socket(ws: WebSocket, sess: Session, req_id: RequestId) {
|
2023-11-20 19:08:07 +00:00
|
|
|
// Create a new connection instance
|
2023-08-16 12:27:53 +00:00
|
|
|
let rpc = Connection::new(sess);
|
|
|
|
// Update the WebSocket ID with the Request ID
|
|
|
|
if let Ok(Ok(req_id)) = req_id.header_value().to_str().map(Uuid::parse_str) {
|
|
|
|
// If the ID couldn't be updated, ignore the error and keep the default ID
|
|
|
|
let _ = rpc.write().await.update_ws_id(req_id).await;
|
2022-07-04 01:03:26 +00:00
|
|
|
}
|
2023-11-20 19:08:07 +00:00
|
|
|
// Serve the socket connection requests
|
2023-08-16 12:27:53 +00:00
|
|
|
Connection::serve(rpc, ws).await;
|
2022-07-04 01:03:26 +00:00
|
|
|
}
|