diff --git a/apps/tauri/src-tauri/Cargo.lock b/apps/tauri/src-tauri/Cargo.lock index 0b1775c9..9784e3ea 100644 --- a/apps/tauri/src-tauri/Cargo.lock +++ b/apps/tauri/src-tauri/Cargo.lock @@ -2736,6 +2736,7 @@ dependencies = [ "tauri", "tauri-build", "tauri-plugin-opener", + "uuid", ] [[package]] diff --git a/apps/tauri/src-tauri/Cargo.toml b/apps/tauri/src-tauri/Cargo.toml index 593d4f4e..c43ac14b 100644 --- a/apps/tauri/src-tauri/Cargo.toml +++ b/apps/tauri/src-tauri/Cargo.toml @@ -17,6 +17,7 @@ tauri = { version = "2", features = [] } tauri-plugin-opener = "2" serde = { version = "1", features = ["derive"] } serde_json = "1" +uuid = { version = "1", features = ["v4", "serde"] } [profile.release] codegen-units = 1 diff --git a/apps/tauri/src-tauri/src/connection/error.rs b/apps/tauri/src-tauri/src/connection/error.rs new file mode 100644 index 00000000..8b248258 --- /dev/null +++ b/apps/tauri/src-tauri/src/connection/error.rs @@ -0,0 +1,82 @@ +use super::id::{ConnectionId, DriverKind}; +use serde::Serialize; +use std::fmt; + +/// Typed connection failures exposed over Tauri IPC. +#[derive(Debug, Clone, Serialize)] +#[serde(tag = "kind", rename_all = "snake_case")] +pub enum ConnectionError { + NotFound { id: ConnectionId }, + AlreadyConnected { id: ConnectionId }, + Disconnected { id: ConnectionId }, + InvalidConfig { message: String }, + UnsupportedDriver { driver: DriverKind }, + Io { message: String }, + Driver { driver: DriverKind, message: String }, +} + +impl ConnectionError { + pub fn invalid_config(message: impl Into) -> Self { + Self::InvalidConfig { + message: message.into(), + } + } + + pub fn io(message: impl Into) -> Self { + Self::Io { + message: message.into(), + } + } + + pub fn driver(driver: DriverKind, message: impl Into) -> Self { + Self::Driver { + driver, + message: message.into(), + } + } +} + +impl fmt::Display for ConnectionError { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::NotFound { id } => write!(f, "connection not found: {id}"), + Self::AlreadyConnected { id } => write!(f, "already connected: {id}"), + Self::Disconnected { id } => write!(f, "connection closed: {id}"), + Self::InvalidConfig { message } => write!(f, "invalid config: {message}"), + Self::UnsupportedDriver { driver } => { + write!(f, "unsupported driver: {driver}") + } + Self::Io { message } => write!(f, "io error: {message}"), + Self::Driver { driver, message } => { + write!(f, "{driver} error: {message}") + } + } + } +} + +impl std::error::Error for ConnectionError {} + +/// IPC-friendly result alias. +pub type ConnectionResult = Result; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn display_and_serde_not_found() { + let err = ConnectionError::NotFound { + id: ConnectionId::from("c1"), + }; + assert_eq!(err.to_string(), "connection not found: c1"); + let json = serde_json::to_value(&err).unwrap(); + assert_eq!(json["kind"], "not_found"); + assert_eq!(json["id"], "c1"); + } + + #[test] + fn display_driver() { + let err = ConnectionError::driver(DriverKind::Sqlite, "no such table"); + assert_eq!(err.to_string(), "sqlite error: no such table"); + } +} diff --git a/apps/tauri/src-tauri/src/connection/id.rs b/apps/tauri/src-tauri/src/connection/id.rs new file mode 100644 index 00000000..ed9180f1 --- /dev/null +++ b/apps/tauri/src-tauri/src/connection/id.rs @@ -0,0 +1,91 @@ +use serde::{Deserialize, Serialize}; +use std::fmt; +use uuid::Uuid; + +/// Opaque live-connection handle shared across IPC and drivers. +#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(transparent)] +pub struct ConnectionId(String); + +impl ConnectionId { + pub fn new() -> Self { + Self(Uuid::new_v4().to_string()) + } + + pub fn as_str(&self) -> &str { + &self.0 + } +} + +impl Default for ConnectionId { + fn default() -> Self { + Self::new() + } +} + +impl fmt::Display for ConnectionId { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(&self.0) + } +} + +impl From for ConnectionId { + fn from(value: String) -> Self { + Self(value) + } +} + +impl From<&str> for ConnectionId { + fn from(value: &str) -> Self { + Self(value.to_owned()) + } +} + +/// Driver family — mirrors Flutter connection `type` strings. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +#[serde(rename_all = "snake_case")] +pub enum DriverKind { + Sqlite, + Postgres, + Mysql, + Redis, + Mongodb, +} + +impl DriverKind { + pub fn as_str(self) -> &'static str { + match self { + Self::Sqlite => "sqlite", + Self::Postgres => "postgres", + Self::Mysql => "mysql", + Self::Redis => "redis", + Self::Mongodb => "mongodb", + } + } +} + +impl fmt::Display for DriverKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(self.as_str()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn connection_id_round_trips_json() { + let id = ConnectionId::from("abc-123"); + let json = serde_json::to_string(&id).unwrap(); + assert_eq!(json, "\"abc-123\""); + let back: ConnectionId = serde_json::from_str(&json).unwrap(); + assert_eq!(back, id); + } + + #[test] + fn driver_kind_serde() { + let json = serde_json::to_string(&DriverKind::Sqlite).unwrap(); + assert_eq!(json, "\"sqlite\""); + } +} diff --git a/apps/tauri/src-tauri/src/connection/manager.rs b/apps/tauri/src-tauri/src/connection/manager.rs new file mode 100644 index 00000000..98fe494b --- /dev/null +++ b/apps/tauri/src-tauri/src/connection/manager.rs @@ -0,0 +1,190 @@ +use super::error::{ConnectionError, ConnectionResult}; +use super::id::{ConnectionId, DriverKind}; +use serde::{Deserialize, Serialize}; +use std::collections::HashMap; +use std::sync::{Arc, Mutex}; + +/// Driver-agnostic connect parameters (tagged for IPC). +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(tag = "driver", rename_all = "snake_case")] +pub enum ConnectionConfig { + Sqlite { + /// Absolute or relative path to a `.db` / `.sqlite` file. + path: String, + }, + Postgres { + host: String, + port: u16, + database: String, + user: String, + /// Secret is resolved via keyring later; optional here for stubs. + password: Option, + }, + Mysql { + host: String, + port: u16, + database: String, + user: String, + password: Option, + }, +} + +impl ConnectionConfig { + pub fn driver_kind(&self) -> DriverKind { + match self { + Self::Sqlite { .. } => DriverKind::Sqlite, + Self::Postgres { .. } => DriverKind::Postgres, + Self::Mysql { .. } => DriverKind::Mysql, + } + } +} + +/// Live session handle — drivers implement this behind the registry. +pub trait ConnectionSession: Send + Sync { + fn id(&self) -> &ConnectionId; + fn driver(&self) -> DriverKind; + fn disconnect(&mut self) -> ConnectionResult<()>; +} + +/// Opens and tracks live DB sessions. +pub trait ConnectionManager: Send + Sync { + fn connect(&self, config: ConnectionConfig) -> ConnectionResult; + fn disconnect(&self, id: &ConnectionId) -> ConnectionResult<()>; + fn is_connected(&self, id: &ConnectionId) -> bool; + fn driver_of(&self, id: &ConnectionId) -> Option; +} + +type SessionBox = Box; + +/// In-memory registry used by Tauri commands. Drivers register factories later. +#[derive(Default)] +pub struct ConnectionRegistry { + sessions: Mutex>, + /// Optional opener for tests / driver wiring. Returns a live session. + opener: Option ConnectionResult + Send + Sync>>, +} + +impl ConnectionRegistry { + pub fn new() -> Self { + Self::default() + } + + pub fn with_opener(opener: F) -> Self + where + F: Fn(ConnectionConfig) -> ConnectionResult + Send + Sync + 'static, + { + Self { + sessions: Mutex::new(HashMap::new()), + opener: Some(Arc::new(opener)), + } + } + + fn lock( + &self, + ) -> ConnectionResult>> { + self.sessions + .lock() + .map_err(|_| ConnectionError::io("connection registry lock poisoned")) + } +} + +impl ConnectionManager for ConnectionRegistry { + fn connect(&self, config: ConnectionConfig) -> ConnectionResult { + let opener = self + .opener + .as_ref() + .ok_or(ConnectionError::UnsupportedDriver { + driver: config.driver_kind(), + })?; + let session = opener(config)?; + let id = session.id().clone(); + let mut map = self.lock()?; + if map.contains_key(&id) { + return Err(ConnectionError::AlreadyConnected { id }); + } + map.insert(id.clone(), session); + Ok(id) + } + + fn disconnect(&self, id: &ConnectionId) -> ConnectionResult<()> { + let mut map = self.lock()?; + let mut session = map + .remove(id) + .ok_or_else(|| ConnectionError::NotFound { id: id.clone() })?; + session.disconnect()?; + Ok(()) + } + + fn is_connected(&self, id: &ConnectionId) -> bool { + self.lock().map(|m| m.contains_key(id)).unwrap_or(false) + } + + fn driver_of(&self, id: &ConnectionId) -> Option { + self.lock().ok()?.get(id).map(|s| s.driver()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + struct FakeSession { + id: ConnectionId, + driver: DriverKind, + closed: bool, + } + + impl ConnectionSession for FakeSession { + fn id(&self) -> &ConnectionId { + &self.id + } + fn driver(&self) -> DriverKind { + self.driver + } + fn disconnect(&mut self) -> ConnectionResult<()> { + self.closed = true; + Ok(()) + } + } + + #[test] + fn registry_connect_disconnect() { + let reg = ConnectionRegistry::with_opener(|cfg| { + assert!(matches!(cfg, ConnectionConfig::Sqlite { .. })); + Ok(Box::new(FakeSession { + id: ConnectionId::from("s1"), + driver: DriverKind::Sqlite, + closed: false, + })) + }); + + let id = reg + .connect(ConnectionConfig::Sqlite { + path: "/tmp/x.db".into(), + }) + .unwrap(); + assert_eq!(id.as_str(), "s1"); + assert!(reg.is_connected(&id)); + assert_eq!(reg.driver_of(&id), Some(DriverKind::Sqlite)); + reg.disconnect(&id).unwrap(); + assert!(!reg.is_connected(&id)); + let err = reg.disconnect(&id).unwrap_err(); + assert!(matches!(err, ConnectionError::NotFound { .. })); + } + + #[test] + fn registry_without_opener_is_unsupported() { + let reg = ConnectionRegistry::new(); + let err = reg + .connect(ConnectionConfig::Sqlite { + path: "a.db".into(), + }) + .unwrap_err(); + assert!(matches!( + err, + ConnectionError::UnsupportedDriver { + driver: DriverKind::Sqlite + } + )); + } +} diff --git a/apps/tauri/src-tauri/src/connection/mod.rs b/apps/tauri/src-tauri/src/connection/mod.rs new file mode 100644 index 00000000..d2025a23 --- /dev/null +++ b/apps/tauri/src-tauri/src/connection/mod.rs @@ -0,0 +1,9 @@ +//! Shared connection layer for Querya drivers (SQLite first, then PG/MySQL/…). + +mod error; +mod id; +mod manager; + +pub use error::ConnectionError; +pub use id::{ConnectionId, DriverKind}; +pub use manager::{ConnectionConfig, ConnectionManager, ConnectionRegistry}; diff --git a/apps/tauri/src-tauri/src/lib.rs b/apps/tauri/src-tauri/src/lib.rs index b3fecdb7..da0a4df0 100644 --- a/apps/tauri/src-tauri/src/lib.rs +++ b/apps/tauri/src-tauri/src/lib.rs @@ -1,3 +1,10 @@ +mod connection; + +pub use connection::{ + ConnectionConfig, ConnectionError, ConnectionId, ConnectionManager, ConnectionRegistry, + DriverKind, +}; + #[tauri::command] fn app_info() -> serde_json::Value { serde_json::json!({ @@ -23,6 +30,7 @@ fn host_platform() -> String { pub fn run() { tauri::Builder::default() .plugin(tauri_plugin_opener::init()) + .manage(ConnectionRegistry::new()) .invoke_handler(tauri::generate_handler![app_info, host_platform]) .run(tauri::generate_context!()) .expect("error while running tauri application");