From 8bbdda1740efb2daecb939401097ede932041793 Mon Sep 17 00:00:00 2001 From: ZhuchkaTriplesix Date: Sun, 15 Nov 2026 11:05:46 +0300 Subject: [PATCH] refactor(rust): connection registry hygiene before next driver (#1949) Release the sessions map lock before SQLite I/O via Arc sessions, route query IPC through the session API, use invoke-Err-only for stream failures, add From, trim premature DriverKind/password stubs, and gate CI with clippy -D warnings. --- .github/workflows/tauri-ci.yml | 4 + apps/tauri/src-tauri/src/commands.rs | 27 +---- apps/tauri/src-tauri/src/connection/error.rs | 18 +++ apps/tauri/src-tauri/src/connection/id.rs | 6 +- .../tauri/src-tauri/src/connection/manager.rs | 103 ++++++++++++------ apps/tauri/src-tauri/src/connection/mod.rs | 4 - apps/tauri/src-tauri/src/connection/sqlite.rs | 28 ++--- .../src/connection/sqlite_introspect.rs | 12 +- .../src-tauri/src/connection/sqlite_query.rs | 42 +++---- 9 files changed, 140 insertions(+), 104 deletions(-) diff --git a/.github/workflows/tauri-ci.yml b/.github/workflows/tauri-ci.yml index 583af4a8..7e4379aa 100644 --- a/.github/workflows/tauri-ci.yml +++ b/.github/workflows/tauri-ci.yml @@ -82,6 +82,10 @@ jobs: working-directory: apps/tauri/src-tauri run: cargo check --locked + - name: cargo clippy + working-directory: apps/tauri/src-tauri + run: cargo clippy --locked --all-targets -- -D warnings + - name: cargo test working-directory: apps/tauri/src-tauri run: cargo test --locked diff --git a/apps/tauri/src-tauri/src/commands.rs b/apps/tauri/src-tauri/src/commands.rs index f1d17b3b..3e9b4a1d 100644 --- a/apps/tauri/src-tauri/src/commands.rs +++ b/apps/tauri/src-tauri/src/commands.rs @@ -1,6 +1,6 @@ use crate::connection::{ ConnectionConfig, ConnectionError, ConnectionId, ConnectionManager, ConnectionRegistry, - QueryEvent, SchemaObject, TableSchema, + SchemaObject, TableSchema, }; use tauri::ipc::Channel; use tauri::State; @@ -51,35 +51,20 @@ pub fn db_list_columns( registry.with_sqlite(&id, |s| s.list_columns(&table)) } -/// Execute SQL and stream `QueryEvent` batches over `on_event` (not one giant IPC payload). +/// Execute SQL and stream `QueryEvent` batches over `on_event`. +/// Failures return as the invoke `Err` only (no dual channel `Error` event). #[tauri::command] pub fn db_execute_query( id: ConnectionId, sql: String, limit: Option, - on_event: Channel, + on_event: Channel, registry: State<'_, ConnectionRegistry>, ) -> Result<(), ConnectionError> { - let conn_arc = registry.sqlite_connection_arc(&id)?; - let guard = conn_arc - .lock() - .map_err(|_| ConnectionError::io("sqlite connection lock poisoned"))?; - let conn = guard - .as_ref() - .ok_or_else(|| ConnectionError::Disconnected { id: id.clone() })?; - let limit = limit.map(|n| n as usize); - match crate::connection::sqlite_query::execute_streaming(conn, &sql, limit, None, |ev| { + registry.execute_sqlite_query(&id, &sql, limit, |ev| { on_event .send(ev) .map_err(|e| ConnectionError::io(format!("query channel closed: {e}"))) - }) { - Ok(()) => Ok(()), - Err(e) => { - let _ = on_event.send(QueryEvent::Error { - message: e.to_string(), - }); - Err(e) - } - } + }) } diff --git a/apps/tauri/src-tauri/src/connection/error.rs b/apps/tauri/src-tauri/src/connection/error.rs index 8b248258..69bb387b 100644 --- a/apps/tauri/src-tauri/src/connection/error.rs +++ b/apps/tauri/src-tauri/src/connection/error.rs @@ -56,6 +56,12 @@ impl fmt::Display for ConnectionError { impl std::error::Error for ConnectionError {} +impl From for ConnectionError { + fn from(value: rusqlite::Error) -> Self { + Self::driver(DriverKind::Sqlite, value.to_string()) + } +} + /// IPC-friendly result alias. pub type ConnectionResult = Result; @@ -79,4 +85,16 @@ mod tests { let err = ConnectionError::driver(DriverKind::Sqlite, "no such table"); assert_eq!(err.to_string(), "sqlite error: no such table"); } + + #[test] + fn from_rusqlite() { + let err: ConnectionError = rusqlite::Error::InvalidQuery.into(); + assert!(matches!( + err, + ConnectionError::Driver { + driver: DriverKind::Sqlite, + .. + } + )); + } } diff --git a/apps/tauri/src-tauri/src/connection/id.rs b/apps/tauri/src-tauri/src/connection/id.rs index ed9180f1..1679ce1e 100644 --- a/apps/tauri/src-tauri/src/connection/id.rs +++ b/apps/tauri/src-tauri/src/connection/id.rs @@ -41,15 +41,13 @@ impl From<&str> for ConnectionId { } } -/// Driver family — mirrors Flutter connection `type` strings. +/// Driver family wired (or stubbed) in this crate. Redis/Mongo land with their epics. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum DriverKind { Sqlite, Postgres, Mysql, - Redis, - Mongodb, } impl DriverKind { @@ -58,8 +56,6 @@ impl DriverKind { Self::Sqlite => "sqlite", Self::Postgres => "postgres", Self::Mysql => "mysql", - Self::Redis => "redis", - Self::Mongodb => "mongodb", } } } diff --git a/apps/tauri/src-tauri/src/connection/manager.rs b/apps/tauri/src-tauri/src/connection/manager.rs index 60f7115e..663f0596 100644 --- a/apps/tauri/src-tauri/src/connection/manager.rs +++ b/apps/tauri/src-tauri/src/connection/manager.rs @@ -1,5 +1,6 @@ use super::error::{ConnectionError, ConnectionResult}; use super::id::{ConnectionId, DriverKind}; +use super::query::QueryEvent; use super::sqlite::SqliteSession; use serde::{Deserialize, Serialize}; use std::any::Any; @@ -7,6 +8,7 @@ use std::collections::HashMap; use std::sync::{Arc, Mutex}; /// Driver-agnostic connect parameters (tagged for IPC). +/// Secrets are not part of this enum — keyring lands with #1847. #[derive(Debug, Clone, Serialize, Deserialize)] #[serde(tag = "driver", rename_all = "snake_case")] pub enum ConnectionConfig { @@ -14,20 +16,19 @@ pub enum ConnectionConfig { /// Absolute or relative path to a `.db` / `.sqlite` file. path: String, }, + /// Stub until the Postgres adapter epic wires connect. Postgres { host: String, port: u16, database: String, user: String, - /// Secret is resolved via keyring later; optional here for stubs. - password: Option, }, + /// Stub until the MySQL adapter epic wires connect. Mysql { host: String, port: u16, database: String, user: String, - password: Option, }, } @@ -45,7 +46,8 @@ impl ConnectionConfig { pub trait ConnectionSession: Send + Sync { fn id(&self) -> &ConnectionId; fn driver(&self) -> DriverKind; - fn disconnect(&mut self) -> ConnectionResult<()>; + /// Close the underlying driver connection (interior mutability OK). + fn disconnect(&self) -> ConnectionResult<()>; /// Downcast hook for driver-specific APIs (introspection, query). fn as_any(&self) -> &dyn Any; } @@ -58,13 +60,12 @@ pub trait ConnectionManager: Send + Sync { fn driver_of(&self, id: &ConnectionId) -> Option; } -type SessionBox = Box; +type SessionArc = Arc; -/// In-memory registry used by Tauri commands. Drivers register factories later. +/// In-memory registry used by Tauri commands. pub struct ConnectionRegistry { - sessions: Mutex>, - /// Optional opener for tests / driver wiring. Returns a live session. - opener: Option ConnectionResult + Send + Sync>>, + sessions: Mutex>, + opener: Option ConnectionResult + Send + Sync>>, } impl Default for ConnectionRegistry { @@ -81,7 +82,10 @@ impl ConnectionRegistry { /// Registry with SQLite opener wired (PG/MySQL return UnsupportedDriver). pub fn with_builtin_drivers() -> Self { Self::with_opener(|config| match config { - ConnectionConfig::Sqlite { path } => super::sqlite::open_sqlite(path), + ConnectionConfig::Sqlite { path } => { + let session = super::sqlite::open_sqlite(path)?; + Ok(Arc::new(session) as SessionArc) + } other => Err(ConnectionError::UnsupportedDriver { driver: other.driver_kind(), }), @@ -90,7 +94,7 @@ impl ConnectionRegistry { pub fn with_opener(opener: F) -> Self where - F: Fn(ConnectionConfig) -> ConnectionResult + Send + Sync + 'static, + F: Fn(ConnectionConfig) -> ConnectionResult + Send + Sync + 'static, { Self { sessions: Mutex::new(HashMap::new()), @@ -100,22 +104,27 @@ impl ConnectionRegistry { fn lock( &self, - ) -> ConnectionResult>> { + ) -> ConnectionResult>> { self.sessions .lock() .map_err(|_| ConnectionError::io("connection registry lock poisoned")) } - /// Run a closure against a live [`SqliteSession`]. + /// Clone a session Arc under a brief map lock. + fn session_arc(&self, id: &ConnectionId) -> ConnectionResult { + let map = self.lock()?; + map.get(id) + .cloned() + .ok_or_else(|| ConnectionError::NotFound { id: id.clone() }) + } + + /// Run a closure against a live [`SqliteSession`] **outside** the registry map lock. pub fn with_sqlite( &self, id: &ConnectionId, f: impl FnOnce(&SqliteSession) -> ConnectionResult, ) -> ConnectionResult { - let map = self.lock()?; - let session = map - .get(id) - .ok_or_else(|| ConnectionError::NotFound { id: id.clone() })?; + let session = self.session_arc(id)?; let sqlite = session .as_any() .downcast_ref::() @@ -125,12 +134,15 @@ impl ConnectionRegistry { f(sqlite) } - /// Clone the SQLite connection Arc so callers can drop the registry lock. - pub fn sqlite_connection_arc( + /// Stream a query through the SQLite session API (commands stay thin). + pub fn execute_sqlite_query( &self, id: &ConnectionId, - ) -> ConnectionResult>>> { - self.with_sqlite(id, |s| Ok(s.connection_arc())) + sql: &str, + limit: Option, + emit: impl FnMut(QueryEvent) -> ConnectionResult<()>, + ) -> ConnectionResult<()> { + self.with_sqlite(id, |s| s.execute_streaming(sql, limit, emit)) } } @@ -142,6 +154,7 @@ impl ConnectionManager for ConnectionRegistry { .ok_or(ConnectionError::UnsupportedDriver { driver: config.driver_kind(), })?; + // Open outside the map lock (disk I/O). let session = opener(config)?; let id = session.id().clone(); let mut map = self.lock()?; @@ -154,11 +167,11 @@ impl ConnectionManager for ConnectionRegistry { fn disconnect(&self, id: &ConnectionId) -> ConnectionResult<()> { let mut map = self.lock()?; - let mut session = map + let session = map .remove(id) .ok_or_else(|| ConnectionError::NotFound { id: id.clone() })?; - session.disconnect()?; - Ok(()) + drop(map); + session.disconnect() } fn is_connected(&self, id: &ConnectionId) -> bool { @@ -177,7 +190,6 @@ mod tests { struct FakeSession { id: ConnectionId, driver: DriverKind, - closed: bool, } impl ConnectionSession for FakeSession { @@ -187,8 +199,7 @@ mod tests { fn driver(&self) -> DriverKind { self.driver } - fn disconnect(&mut self) -> ConnectionResult<()> { - self.closed = true; + fn disconnect(&self) -> ConnectionResult<()> { Ok(()) } fn as_any(&self) -> &dyn Any { @@ -200,11 +211,10 @@ mod tests { fn registry_connect_disconnect() { let reg = ConnectionRegistry::with_opener(|cfg| { assert!(matches!(cfg, ConnectionConfig::Sqlite { .. })); - Ok(Box::new(FakeSession { + Ok(Arc::new(FakeSession { id: ConnectionId::from("s1"), driver: DriverKind::Sqlite, - closed: false, - })) + }) as SessionArc) }); let id = reg @@ -230,7 +240,6 @@ mod tests { port: 5432, database: "db".into(), user: "u".into(), - password: None, }) .unwrap_err(); assert!(matches!( @@ -240,4 +249,36 @@ mod tests { } )); } + + #[test] + fn execute_sqlite_query_streams_via_session() { + let path = std::env::temp_dir().join(format!( + "querya_reg_query_{}.db", + std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos() + )); + { + let conn = rusqlite::Connection::open(&path).unwrap(); + conn.execute_batch("CREATE TABLE t(n INTEGER); INSERT INTO t VALUES (1),(2),(3);") + .unwrap(); + } + let reg = ConnectionRegistry::with_builtin_drivers(); + let id = reg + .connect(ConnectionConfig::Sqlite { + path: path.to_string_lossy().into(), + }) + .unwrap(); + let mut events = Vec::new(); + reg.execute_sqlite_query(&id, "SELECT n FROM t ORDER BY n", Some(10), |ev| { + events.push(ev); + Ok(()) + }) + .unwrap(); + assert!(matches!(events.first(), Some(QueryEvent::Columns { .. }))); + assert!(matches!(events.last(), Some(QueryEvent::Done { row_count: 3, .. }))); + reg.disconnect(&id).unwrap(); + let _ = std::fs::remove_file(&path); + } } diff --git a/apps/tauri/src-tauri/src/connection/mod.rs b/apps/tauri/src-tauri/src/connection/mod.rs index f8c0facf..a345cd87 100644 --- a/apps/tauri/src-tauri/src/connection/mod.rs +++ b/apps/tauri/src-tauri/src/connection/mod.rs @@ -14,8 +14,4 @@ pub use error::ConnectionError; pub use id::{ConnectionId, DriverKind}; pub use introspect::{ColumnMeta, SchemaObject, SchemaObjectKind, TableSchema}; pub use manager::{ConnectionConfig, ConnectionManager, ConnectionRegistry}; -#[allow(unused_imports)] // public API for later IPC / frontend issues -pub use manager::ConnectionSession; pub use query::QueryEvent; -#[allow(unused_imports)] // public API for later IPC / frontend issues -pub use sqlite::{open_sqlite, SqliteSession}; diff --git a/apps/tauri/src-tauri/src/connection/sqlite.rs b/apps/tauri/src-tauri/src/connection/sqlite.rs index 0bca1460..7c87f8bc 100644 --- a/apps/tauri/src-tauri/src/connection/sqlite.rs +++ b/apps/tauri/src-tauri/src/connection/sqlite.rs @@ -10,8 +10,9 @@ use std::sync::{Arc, Mutex}; pub struct SqliteSession { id: ConnectionId, + /// On-disk path used to open this session (for diagnostics / UI). path: String, - /// Shared so query streaming can drop the registry lock. + /// Shared so query streaming can hold the session Arc without the registry lock. conn: Arc>>, } @@ -20,10 +21,6 @@ impl SqliteSession { &self.path } - pub fn connection_arc(&self) -> Arc>> { - Arc::clone(&self.conn) - } - pub fn with_connection( &self, f: impl FnOnce(&Connection) -> ConnectionResult, @@ -76,14 +73,13 @@ impl ConnectionSession for SqliteSession { DriverKind::Sqlite } - fn disconnect(&mut self) -> ConnectionResult<()> { + fn disconnect(&self) -> ConnectionResult<()> { let mut guard = self .conn .lock() .map_err(|_| ConnectionError::io("sqlite connection lock poisoned"))?; if let Some(conn) = guard.take() { - conn.close() - .map_err(|(_, e)| ConnectionError::driver(DriverKind::Sqlite, e.to_string()))?; + conn.close().map_err(|(_, e)| ConnectionError::from(e))?; } Ok(()) } @@ -94,7 +90,7 @@ impl ConnectionSession for SqliteSession { } /// Open a SQLite database file and return a live session. -pub fn open_sqlite(path: impl AsRef) -> ConnectionResult> { +pub fn open_sqlite(path: impl AsRef) -> ConnectionResult { let path = path.as_ref().trim(); if path.is_empty() { return Err(ConnectionError::invalid_config("sqlite path is empty")); @@ -110,17 +106,14 @@ pub fn open_sqlite(path: impl AsRef) -> ConnectionResult ConnectionResult> { WHERE type IN ('table', 'view') AND name NOT LIKE 'sqlite_%' \ ORDER BY type ASC, name ASC", ) - .map_err(|e| ConnectionError::driver(DriverKind::Sqlite, e.to_string()))?; + ?; let rows = stmt .query_map([], |row| { @@ -26,12 +26,12 @@ pub fn list_tables(conn: &Connection) -> ConnectionResult> { let type_str: String = row.get(1)?; Ok((name, type_str)) }) - .map_err(|e| ConnectionError::driver(DriverKind::Sqlite, e.to_string()))?; + ?; let mut out = Vec::new(); for row in rows { let (name, type_str) = - row.map_err(|e| ConnectionError::driver(DriverKind::Sqlite, e.to_string()))?; + row?; let kind = match type_str.as_str() { "view" => SchemaObjectKind::View, _ => SchemaObjectKind::Table, @@ -60,7 +60,7 @@ pub fn list_columns(conn: &Connection, table: &str) -> ConnectionResult ConnectionResult 0; if is_pk { primary_keys.push(name.clone()); diff --git a/apps/tauri/src-tauri/src/connection/sqlite_query.rs b/apps/tauri/src-tauri/src/connection/sqlite_query.rs index 8aea160b..9fd396a6 100644 --- a/apps/tauri/src-tauri/src/connection/sqlite_query.rs +++ b/apps/tauri/src-tauri/src/connection/sqlite_query.rs @@ -1,7 +1,6 @@ //! SQLite execute + batched row streaming (rusqlite). use super::error::{ConnectionError, ConnectionResult}; -use super::id::DriverKind; use super::query::QueryEvent; use rusqlite::{types::ValueRef, Connection, Statement}; use std::time::Instant; @@ -26,17 +25,12 @@ pub fn execute_streaming( let batch_size = batch_size.unwrap_or(DEFAULT_BATCH).max(1); let started = Instant::now(); - let mut stmt = conn - .prepare(sql) - .map_err(|e| ConnectionError::driver(DriverKind::Sqlite, e.to_string()))?; + let mut stmt = conn.prepare(sql)?; let col_count = stmt.column_count(); if col_count == 0 { // Non-SELECT (DDL/DML): execute and report changes. - let affected = stmt - .execute([]) - .map_err(|e| ConnectionError::driver(DriverKind::Sqlite, e.to_string()))? - as u64; + let affected = stmt.execute([])? as u64; emit(QueryEvent::Done { row_count: 0, truncated: false, @@ -62,9 +56,7 @@ fn stream_rows( started: Instant, emit: &mut impl FnMut(QueryEvent) -> ConnectionResult<()>, ) -> ConnectionResult<()> { - let mut rows = stmt - .query([]) - .map_err(|e| ConnectionError::driver(DriverKind::Sqlite, e.to_string()))?; + let mut rows = stmt.query([])?; let mut batch: Vec> = Vec::with_capacity(batch_size); let mut offset: u64 = 0; @@ -80,16 +72,12 @@ fn stream_rows( let row = match rows.next() { Ok(Some(r)) => r, Ok(None) => break, - Err(e) => { - return Err(ConnectionError::driver(DriverKind::Sqlite, e.to_string())); - } + Err(e) => return Err(e.into()), }; let mut cells = Vec::with_capacity(col_count); for i in 0..col_count { - let v = row - .get_ref(i) - .map_err(|e| ConnectionError::driver(DriverKind::Sqlite, e.to_string()))?; + let v = row.get_ref(i)?; cells.push(value_ref_to_json(v)); } batch.push(cells); @@ -107,13 +95,10 @@ fn stream_rows( } if !batch.is_empty() { - let n = batch.len() as u64; emit(QueryEvent::Rows { rows: batch, offset, })?; - offset += n; - let _ = offset; } emit(QueryEvent::Done { @@ -254,4 +239,21 @@ mod tests { } } } + + #[test] + fn empty_sql_is_invalid_config() { + let conn = Connection::open_in_memory().unwrap(); + let err = execute_streaming(&conn, " ", None, None, |_| Ok(())).unwrap_err(); + assert!(matches!(err, ConnectionError::InvalidConfig { .. })); + } + + #[test] + fn emit_failure_propagates() { + let conn = seed_nums(); + let err = execute_streaming(&conn, "SELECT n FROM nums", Some(2), Some(1), |_| { + Err(ConnectionError::io("channel closed")) + }) + .unwrap_err(); + assert!(matches!(err, ConnectionError::Io { .. })); + } }