use std::time::Duration;
use crate::error::{SurrealError, SurrealResult};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum WireProtocol {
#[default]
Cbor,
Json,
}
impl WireProtocol {
pub fn subprotocol(&self) -> &'static str {
match self {
WireProtocol::Cbor => "cbor",
WireProtocol::Json => "json",
}
}
}
#[derive(Clone, Debug)]
pub struct SurrealConfig {
pub url: String,
pub user: String,
pub password: String,
pub namespace: String,
pub database: String,
pub protocol: WireProtocol,
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
}
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
}
pub fn ws_url(&self) -> SurrealResult<String> {
let addr = self.url.trim();
if addr.is_empty() {
return Err(SurrealError::Config("URL 不能为空".into()));
}
if addr.starts_with("ws://") || addr.starts_with("wss://") {
if addr.contains("/rpc") {
Ok(addr.to_string())
} else {
Ok(format!("{}/rpc", addr.trim_end_matches('/')))
}
} else {
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(())
}
}