use std::collections::HashMap;
use futures_util::{SinkExt, StreamExt};
use serde_json::Value;
use tokio::net::TcpStream;
use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender};
use tokio::sync::oneshot;
use tokio_tungstenite::MaybeTlsStream;
use tokio_tungstenite::WebSocketStream;
use tokio_tungstenite::tungstenite::Message;
use tokio_tungstenite::tungstenite::client::IntoClientRequest;
use tokio_tungstenite::tungstenite::http::HeaderValue;
use tokio_tungstenite::tungstenite::http::header::SEC_WEBSOCKET_PROTOCOL;
use crate::codec;
use crate::config::{SurrealConfig, WireProtocol};
use crate::error::{SurrealError, SurrealResult};
use crate::protocol::RpcResponse;
#[allow(dead_code)]
pub(crate) struct RawRpcBytes {
pub id: u64,
pub protocol: WireProtocol,
pub bytes: Vec<u8>,
}
pub(crate) struct RouterCommand {
pub method: String,
pub params: Value,
pub response_tx: oneshot::Sender<Result<RawRpcBytes, SurrealError>>,
}
pub(crate) fn router_channel() -> (
UnboundedSender<RouterCommand>,
UnboundedReceiver<RouterCommand>,
) {
tokio::sync::mpsc::unbounded_channel()
}
type WsStream = WebSocketStream<MaybeTlsStream<TcpStream>>;
type WsSink = futures_util::stream::SplitSink<WsStream, Message>;
type WsSource = futures_util::stream::SplitStream<WsStream>;
pub(crate) fn spawn_router(
request_rx: UnboundedReceiver<RouterCommand>,
config: SurrealConfig,
) -> tokio::task::JoinHandle<()> {
tokio::spawn(async move {
run_router_loop(request_rx, config).await;
})
}
async fn run_router_loop(mut request_rx: UnboundedReceiver<RouterCommand>, config: SurrealConfig) {
let mut attempt: u32 = 0;
loop {
match serve_connection(&mut request_rx, &config).await {
Ok(()) => {
log::debug!("[surreal] Router 正常退出");
break;
}
Err(e) => {
attempt += 1;
if attempt > config.max_reconnect_attempts {
log::error!("[surreal] Router 重连失败 (已尝试 {attempt} 次), 退出: {e}");
let reason = format!("重连失败 ({attempt} 次): {e}");
while let Ok(cmd) = request_rx.try_recv() {
let _ = cmd.response_tx.send(Err(SurrealError::ReconnectFailed(reason.clone())));
}
break;
}
let delay = backoff_delay(attempt, &config);
log::warn!(
"[surreal] Router 断开 (attempt {attempt}/{max}): {e}, {delay:?} 后重连...",
max = config.max_reconnect_attempts,
);
tokio::time::sleep(delay).await;
}
}
}
}
async fn serve_connection(
request_rx: &mut UnboundedReceiver<RouterCommand>,
config: &SurrealConfig,
) -> Result<(), SurrealError> {
let ws_url = config.ws_url()?;
log::debug!("[surreal] 连接 ({}): {ws_url}", config.protocol.subprotocol());
let mut http_request = ws_url
.into_client_request()
.map_err(|e| SurrealError::ConnectionFailed(format!("无效的 WS URL: {e}")))?;
http_request
.headers_mut()
.insert(
SEC_WEBSOCKET_PROTOCOL,
HeaderValue::from_static(config.protocol.subprotocol()),
);
let (ws_stream, _response) = tokio::time::timeout(
config.connect_timeout,
tokio_tungstenite::connect_async(http_request),
)
.await
.map_err(|_| SurrealError::Timeout("WebSocket 连接超时".into()))?
.map_err(|e| SurrealError::ConnectionFailed(format!("WebSocket 连接失败: {e}")))?;
let (mut ws_sink, mut ws_stream) = ws_stream.split();
authenticate(&mut ws_sink, &mut ws_stream, config).await?;
log::debug!(
"[surreal] 认证成功 ({}), 进入多路复用模式",
config.protocol.subprotocol()
);
let mut pending: HashMap<u64, oneshot::Sender<Result<RawRpcBytes, SurrealError>>> =
HashMap::new();
let mut next_id: u64 = 0;
loop {
tokio::select! {
cmd = request_rx.recv() => {
match cmd {
Some(cmd) => {
let id = next_id;
next_id = next_id.wrapping_add(1);
let msg = encode_message(config.protocol, id, &cmd.method, &cmd.params)?;
let send_result = ws_sink.send(msg).await;
if let Err(e) = send_result {
let _ = cmd.response_tx.send(Err(SurrealError::ConnectionLost));
fail_all_pending(&mut pending);
return Err(SurrealError::ConnectionFailed(
format!("WS 写入失败: {e}")
));
}
pending.insert(id, cmd.response_tx);
}
None => {
fail_all_pending(&mut pending);
return Ok(());
}
}
}
msg = ws_stream.next() => {
let frame_data = match decode_inbound_frame(msg, config.protocol) {
Ok(Some(data)) => data,
Ok(None) => continue, Err(e) => {
fail_all_pending(&mut pending);
return Err(e);
}
};
let id = peek_id(config.protocol, &frame_data)?;
if let Some(tx) = pending.remove(&id) {
let _ = tx.send(Ok(RawRpcBytes {
id,
protocol: config.protocol,
bytes: frame_data,
}));
} else {
log::debug!("[surreal] 收到未知 id 的响应: {id}");
}
}
}
}
}
fn encode_message(
protocol: WireProtocol,
id: u64,
method: &str,
params: &Value,
) -> Result<Message, SurrealError> {
match protocol {
WireProtocol::Cbor => {
let bytes = codec::encode_request_cbor(id, method, params)?;
Ok(Message::Binary(bytes.into()))
}
WireProtocol::Json => {
let text = codec::encode_request_json(id, method, params)?;
Ok(Message::Text(text.into()))
}
}
}
fn peek_id(protocol: WireProtocol, data: &[u8]) -> SurrealResult<u64> {
match protocol {
WireProtocol::Cbor => codec::peek_response_id_cbor(data),
WireProtocol::Json => codec::peek_response_id_json(data),
}
}
fn decode_inbound_frame(
msg: Option<Result<Message, tokio_tungstenite::tungstenite::Error>>,
protocol: WireProtocol,
) -> Result<Option<Vec<u8>>, SurrealError> {
let msg = match msg {
Some(m) => m.map_err(|e| SurrealError::ConnectionFailed(format!("WS 读取错误: {e}")))?,
None => return Err(SurrealError::ConnectionLost),
};
match msg {
Message::Binary(data) if protocol == WireProtocol::Cbor => Ok(Some(data.to_vec())),
Message::Binary(_) => {
log::error!("[surreal] 协议 {:?} 期望 Text 帧, 但收到 Binary", protocol);
Err(SurrealError::ConnectionFailed("协议不匹配: 收到 Binary 帧".into()))
}
Message::Text(text) if protocol == WireProtocol::Json => {
Ok(Some(text.as_bytes().to_vec()))
}
Message::Text(_) => {
log::error!("[surreal] 协议 {:?} 期望 Binary 帧, 但收到 Text", protocol);
Err(SurrealError::ConnectionFailed("协议不匹配: 收到 Text 帧".into()))
}
Message::Close(frame) => {
log::info!("[surreal] 收到 Close 帧: {frame:?}");
Err(SurrealError::ConnectionLost)
}
_ => Ok(None), }
}
async fn authenticate(
ws_sink: &mut WsSink,
ws_stream: &mut WsSource,
config: &SurrealConfig,
) -> Result<(), SurrealError> {
let signin_params = crate::protocol::signin_params(&config.user, &config.password);
auth_send_recv(ws_sink, ws_stream, 0, "signin", &signin_params, config.protocol)
.await
.map_err(|e| SurrealError::AuthFailed(format!("signin 失败: {e}")))?;
let use_params = crate::protocol::use_params(&config.namespace, &config.database);
auth_send_recv(ws_sink, ws_stream, 1, "use", &use_params, config.protocol)
.await
.map_err(|e| SurrealError::AuthFailed(format!("use ns/db 失败: {e}")))?;
Ok(())
}
async fn auth_send_recv(
ws_sink: &mut WsSink,
ws_stream: &mut WsSource,
id: u64,
method: &str,
params: &Value,
protocol: WireProtocol,
) -> Result<RpcResponse, SurrealError> {
let msg = encode_message(protocol, id, method, params)?;
ws_sink
.send(msg)
.await
.map_err(|e| SurrealError::ConnectionFailed(format!("WS 发送失败: {e}")))?;
loop {
let msg = ws_stream
.next()
.await
.ok_or(SurrealError::ConnectionLost)?
.map_err(|e| SurrealError::ConnectionFailed(format!("WS 读取错误: {e}")))?;
let data: Vec<u8> = match msg {
Message::Binary(data) => {
if protocol != WireProtocol::Cbor {
return Err(SurrealError::ConnectionFailed(
"协议不匹配: 认证阶段收到 Binary".into(),
));
}
data.to_vec()
}
Message::Text(text) => {
if protocol != WireProtocol::Json {
return Err(SurrealError::ConnectionFailed(
"协议不匹配: 认证阶段收到 Text".into(),
));
}
text.as_bytes().to_vec()
}
Message::Close(frame) => {
return Err(SurrealError::ConnectionFailed(format!(
"认证期间连接关闭: {frame:?}"
)));
}
_ => continue, };
let resp = match protocol {
WireProtocol::Cbor => codec::decode_response_cbor(&data)?,
WireProtocol::Json => codec::decode_response_json(&data)?,
};
if resp.id == id {
return if resp.is_success() {
Ok(resp)
} else {
let msg = resp
.error
.map(|e| e.message)
.unwrap_or_else(|| "未知认证错误".into());
Err(SurrealError::AuthFailed(msg))
};
}
log::debug!(
"[surreal] 认证阶段收到非预期响应 (id={}, expected={})",
resp.id,
id
);
}
}
fn fail_all_pending(
pending: &mut HashMap<u64, oneshot::Sender<Result<RawRpcBytes, SurrealError>>>,
) {
for (_, tx) in pending.drain() {
let _ = tx.send(Err(SurrealError::ConnectionLost));
}
}
fn backoff_delay(attempt: u32, config: &SurrealConfig) -> std::time::Duration {
let base = config.reconnect_base_delay.as_millis() as u64;
let max = config.reconnect_max_delay.as_millis() as u64;
let shift = (attempt.saturating_sub(1)).min(6);
let delay_ms = base.saturating_mul(1u64 << shift);
std::time::Duration::from_millis(delay_ms.min(max))
}