surmux 0.2.0

极简 SurrealDB WebSocket 客户端 — 单连接 JSON-RPC 多路复用, 极简依赖
Documentation
//! 连接配置.
//!
//! 提供 builder 模式构造连接参数.

use std::time::Duration;

use crate::error::{SurrealError, SurrealResult};

/// WebSocket RPC 协议.
///
/// SurrealDB 通过 `Sec-WebSocket-Protocol` 子协议头协商协议, 整个连接锁定一种格式.
/// CBOR 对 `Bytes` 有原生 byte string 支持, 是二进制文件传输的最优选择 (零膨胀).
/// JSON 兼容老 SDK 但 `Bytes` 会变成 `[byte, byte, ...]` 整数数组 (~4x 膨胀).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum WireProtocol {
    /// CBOR (RFC 8949) Binary 帧. 默认. 高性能, 二进制文件传输零膨胀.
    #[default]
    Cbor,
    /// JSON Text 帧. 兼容性最好, 但 Bytes 字段 ~4x 膨胀, 整体性能差.
    Json,
}

impl WireProtocol {
    /// WS 子协议头名 (用于 `Sec-WebSocket-Protocol` 协商).
    pub fn subprotocol(&self) -> &'static str {
        match self {
            WireProtocol::Cbor => "cbor",
            WireProtocol::Json => "json",
        }
    }
}

/// SurrealDB 连接配置.
///
/// # 示例
///
/// ```rust,no_run
/// let config = SurrealConfig::new("localhost:8000")
///     .user("root")
///     .password("root")
///     .namespace("iot_tool")
///     .database("main");
/// ```
#[derive(Clone, Debug)]
pub struct SurrealConfig {
    /// WebSocket 地址, 格式 `host:port` 或 `wss://host:port`.
    /// 自动补全为 `ws://host:port/rpc`.
    pub url: String,

    /// 认证用户名 (root / namespace 用户).
    pub user: String,

    /// 认证密码.
    pub password: String,

    /// 命名空间.
    pub namespace: String,

    /// 数据库名.
    pub database: String,

    /// WebSocket RPC 协议 (默认 CBOR).
    pub protocol: WireProtocol,

    /// 连接超时 (WebSocket 握手).
    pub connect_timeout: Duration,

    /// 查询默认超时 (单次请求).
    pub query_timeout: Duration,

    /// 重连最大重试次数.
    pub max_reconnect_attempts: u32,

    /// 重连退避基础间隔.
    pub reconnect_base_delay: Duration,

    /// 重连退避最大间隔.
    pub reconnect_max_delay: Duration,
}

impl Default for SurrealConfig {
    fn default() -> Self {
        Self {
            url: String::new(),
            user: String::new(),
            password: String::new(),
            namespace: String::new(),
            database: String::new(),
            protocol: WireProtocol::default(),
            connect_timeout: Duration::from_secs(10),
            query_timeout: Duration::from_secs(30),
            max_reconnect_attempts: 10,
            reconnect_base_delay: Duration::from_millis(100),
            reconnect_max_delay: Duration::from_secs(5),
        }
    }
}

impl SurrealConfig {
    /// 使用地址创建配置 (其余字段用默认值).
    pub fn new(url: impl Into<String>) -> Self {
        Self {
            url: url.into(),
            ..Default::default()
        }
    }

    /// 设置认证信息.
    pub fn user(mut self, user: impl Into<String>) -> Self {
        self.user = user.into();
        self
    }

    /// 设置密码.
    pub fn password(mut self, password: impl Into<String>) -> Self {
        self.password = password.into();
        self
    }

    /// 设置命名空间.
    pub fn namespace(mut self, ns: impl Into<String>) -> Self {
        self.namespace = ns.into();
        self
    }

    /// 设置数据库名.
    pub fn database(mut self, db: impl Into<String>) -> Self {
        self.database = db.into();
        self
    }

    /// 设置 WebSocket RPC 协议 (默认 CBOR).
    pub fn protocol(mut self, protocol: WireProtocol) -> Self {
        self.protocol = protocol;
        self
    }

    /// 设置连接超时.
    pub fn connect_timeout(mut self, timeout: Duration) -> Self {
        self.connect_timeout = timeout;
        self
    }

    /// 设置查询超时.
    pub fn query_timeout(mut self, timeout: Duration) -> Self {
        self.query_timeout = timeout;
        self
    }

    /// 构建完整的 WebSocket URL (补全协议和路径).
    pub fn ws_url(&self) -> SurrealResult<String> {
        let addr = self.url.trim();

        if addr.is_empty() {
            return Err(SurrealError::Config("URL 不能为空".into()));
        }

        // 如果已经有 scheme, 直接使用
        if addr.starts_with("ws://") || addr.starts_with("wss://") {
            // 确保路径包含 /rpc
            if addr.contains("/rpc") {
                Ok(addr.to_string())
            } else {
                Ok(format!("{}/rpc", addr.trim_end_matches('/')))
            }
        } else {
            // 默认 ws://
            Ok(format!("ws://{}/rpc", addr))
        }
    }

    /// 验证配置完整性.
    pub fn validate(&self) -> SurrealResult<()> {
        if self.url.is_empty() {
            return Err(SurrealError::Config("URL 未设置".into()));
        }
        if self.user.is_empty() {
            return Err(SurrealError::Config("用户名未设置".into()));
        }
        if self.password.is_empty() {
            return Err(SurrealError::Config("密码未设置".into()));
        }
        if self.namespace.is_empty() {
            return Err(SurrealError::Config("命名空间未设置".into()));
        }
        if self.database.is_empty() {
            return Err(SurrealError::Config("数据库名未设置".into()));
        }
        Ok(())
    }
}