perf: optimize backend — HTTP client, DB queries, error handling, and config cleanup
Some checks failed
CI / lint-and-build (push) Failing after 2m55s

This commit is contained in:
2026-04-08 10:50:40 +03:00
parent 28aa4ef8cc
commit 50214fec0f
15 changed files with 126 additions and 32 deletions

1
src-tauri/Cargo.lock generated
View File

@@ -4704,7 +4704,6 @@ dependencies = [
"bytes", "bytes",
"libc", "libc",
"mio", "mio",
"parking_lot",
"pin-project-lite", "pin-project-lite",
"signal-hook-registry", "signal-hook-registry",
"socket2", "socket2",

View File

@@ -21,7 +21,7 @@ tauri-plugin-shell = "2"
tauri-plugin-dialog = "2" tauri-plugin-dialog = "2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
tokio = { version = "1", features = ["full"] } tokio = { version = "1", features = ["rt-multi-thread", "sync", "time", "net", "macros", "process", "io-util"] }
sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres", "json", "chrono", "uuid", "bigdecimal"] } sqlx = { version = "0.8", features = ["runtime-tokio-rustls", "postgres", "json", "chrono", "uuid", "bigdecimal"] }
chrono = { version = "0.4", features = ["serde"] } chrono = { version = "0.4", features = ["serde"] }
uuid = { version = "1", features = ["serde"] } uuid = { version = "1", features = ["serde"] }

View File

@@ -36,7 +36,7 @@ fn get_ai_settings_path(app: &AppHandle) -> TuskResult<std::path::PathBuf> {
let dir = app let dir = app
.path() .path()
.app_data_dir() .app_data_dir()
.map_err(|e| TuskError::Custom(e.to_string()))?; .map_err(|e| TuskError::Config(e.to_string()))?;
fs::create_dir_all(&dir)?; fs::create_dir_all(&dir)?;
Ok(dir.join("ai_settings.json")) Ok(dir.join("ai_settings.json"))
} }
@@ -1037,7 +1037,7 @@ fn simplify_default(raw: &str) -> String {
fn validate_select_statement(sql: &str) -> TuskResult<()> { fn validate_select_statement(sql: &str) -> TuskResult<()> {
let sql_upper = sql.trim().to_uppercase(); let sql_upper = sql.trim().to_uppercase();
if !sql_upper.starts_with("SELECT") { if !sql_upper.starts_with("SELECT") {
return Err(TuskError::Custom( return Err(TuskError::Validation(
"Validation query must be a SELECT statement".to_string(), "Validation query must be a SELECT statement".to_string(),
)); ));
} }
@@ -1047,7 +1047,7 @@ fn validate_select_statement(sql: &str) -> TuskResult<()> {
fn validate_index_ddl(ddl: &str) -> TuskResult<()> { fn validate_index_ddl(ddl: &str) -> TuskResult<()> {
let ddl_upper = ddl.trim().to_uppercase(); let ddl_upper = ddl.trim().to_uppercase();
if !ddl_upper.starts_with("CREATE INDEX") && !ddl_upper.starts_with("DROP INDEX") { if !ddl_upper.starts_with("CREATE INDEX") && !ddl_upper.starts_with("DROP INDEX") {
return Err(TuskError::Custom( return Err(TuskError::Validation(
"Only CREATE INDEX and DROP INDEX statements are allowed".to_string(), "Only CREATE INDEX and DROP INDEX statements are allowed".to_string(),
)); ));
} }

View File

@@ -18,7 +18,7 @@ pub(crate) fn get_connections_path(app: &AppHandle) -> TuskResult<std::path::Pat
let dir = app let dir = app
.path() .path()
.app_data_dir() .app_data_dir()
.map_err(|e| TuskError::Custom(e.to_string()))?; .map_err(|e| TuskError::Config(e.to_string()))?;
fs::create_dir_all(&dir)?; fs::create_dir_all(&dir)?;
Ok(dir.join("connections.json")) Ok(dir.join("connections.json"))
} }

View File

@@ -29,6 +29,7 @@ pub async fn get_table_data(
let mut where_clause = String::new(); let mut where_clause = String::new();
if let Some(ref f) = filter { if let Some(ref f) = filter {
if !f.trim().is_empty() { if !f.trim().is_empty() {
validate_filter(f)?;
where_clause = format!(" WHERE {}", f); where_clause = format!(" WHERE {}", f);
} }
} }
@@ -285,6 +286,75 @@ pub async fn delete_rows(
Ok(total_affected) Ok(total_affected)
} }
/// Rejects filter strings that contain SQL statements capable of mutating data.
/// This blocks writable CTEs and other injection attempts that could bypass
/// SET TRANSACTION READ ONLY (which PostgreSQL does not enforce inside CTEs
/// in all versions).
fn validate_filter(filter: &str) -> TuskResult<()> {
let upper = filter.to_ascii_uppercase();
// Remove string literals to avoid false positives on keywords inside quoted values
let sanitized = remove_string_literals(&upper);
const FORBIDDEN: &[&str] = &[
"INSERT ",
"UPDATE ",
"DELETE ",
"DROP ",
"ALTER ",
"TRUNCATE ",
"CREATE ",
"GRANT ",
"REVOKE ",
"COPY ",
"EXECUTE ",
"CALL ",
];
for kw in FORBIDDEN {
if sanitized.contains(kw) {
return Err(TuskError::Validation(format!(
"Filter contains forbidden SQL keyword: {}",
kw.trim()
)));
}
}
if sanitized.contains("INTO ") && sanitized.contains("SELECT ") {
return Err(TuskError::Validation(
"Filter contains forbidden SELECT INTO clause".into(),
));
}
Ok(())
}
/// Replaces the contents of single-quoted string literals with spaces so that
/// keyword detection does not trigger on values like `status = 'DELETE_PENDING'`.
fn remove_string_literals(s: &str) -> String {
let mut result = String::with_capacity(s.len());
let mut in_quote = false;
let mut chars = s.chars().peekable();
while let Some(ch) = chars.next() {
if ch == '\'' {
if in_quote {
// Check for escaped quote ('')
if chars.peek() == Some(&'\'') {
chars.next();
result.push(' ');
continue;
}
in_quote = false;
result.push('\'');
} else {
in_quote = true;
result.push('\'');
}
} else if in_quote {
result.push(' ');
} else {
result.push(ch);
}
}
result
}
pub(crate) fn bind_json_value<'q>( pub(crate) fn bind_json_value<'q>(
query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>, query: sqlx::query::Query<'q, sqlx::Postgres, sqlx::postgres::PgArguments>,
value: &'q Value, value: &'q Value,

View File

@@ -13,7 +13,7 @@ pub async fn export_csv(
let mut wtr = csv::Writer::from_writer(file); let mut wtr = csv::Writer::from_writer(file);
wtr.write_record(&columns) wtr.write_record(&columns)
.map_err(|e| TuskError::Custom(e.to_string()))?; .map_err(|e| TuskError::Export(e.to_string()))?;
for row in &rows { for row in &rows {
let record: Vec<String> = row let record: Vec<String> = row
@@ -27,10 +27,10 @@ pub async fn export_csv(
}) })
.collect(); .collect();
wtr.write_record(&record) wtr.write_record(&record)
.map_err(|e| TuskError::Custom(e.to_string()))?; .map_err(|e| TuskError::Export(e.to_string()))?;
} }
wtr.flush().map_err(|e| TuskError::Custom(e.to_string()))?; wtr.flush().map_err(|e| TuskError::Export(e.to_string()))?;
Ok(()) Ok(())
} }

View File

@@ -7,7 +7,7 @@ fn get_history_path(app: &AppHandle) -> TuskResult<std::path::PathBuf> {
let dir = app let dir = app
.path() .path()
.app_data_dir() .app_data_dir()
.map_err(|e| TuskError::Custom(e.to_string()))?; .map_err(|e| TuskError::Config(e.to_string()))?;
fs::create_dir_all(&dir)?; fs::create_dir_all(&dir)?;
Ok(dir.join("query_history.json")) Ok(dir.join("query_history.json"))
} }

View File

@@ -110,11 +110,8 @@ pub async fn drop_database(
.ok_or(TuskError::NotConnected(connection_id))?; .ok_or(TuskError::NotConnected(connection_id))?;
// Terminate active connections to the target database // Terminate active connections to the target database
let terminate_sql = format!( sqlx::query("SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = $1::name AND pid <> pg_backend_pid()")
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE datname = '{}' AND pid <> pg_backend_pid()", .bind(&name)
name.replace('\'', "''")
);
sqlx::query(&terminate_sql)
.execute(pool) .execute(pool)
.await .await
.map_err(TuskError::Database)?; .map_err(TuskError::Database)?;

View File

@@ -7,7 +7,7 @@ fn get_saved_queries_path(app: &AppHandle) -> TuskResult<std::path::PathBuf> {
let dir = app let dir = app
.path() .path()
.app_data_dir() .app_data_dir()
.map_err(|e| TuskError::Custom(e.to_string()))?; .map_err(|e| TuskError::Config(e.to_string()))?;
fs::create_dir_all(&dir)?; fs::create_dir_all(&dir)?;
Ok(dir.join("saved_queries.json")) Ok(dir.join("saved_queries.json"))
} }

View File

@@ -10,7 +10,7 @@ fn get_settings_path(app: &AppHandle) -> TuskResult<std::path::PathBuf> {
let dir = app let dir = app
.path() .path()
.app_data_dir() .app_data_dir()
.map_err(|e| TuskError::Custom(e.to_string()))?; .map_err(|e| TuskError::Config(e.to_string()))?;
fs::create_dir_all(&dir)?; fs::create_dir_all(&dir)?;
Ok(dir.join("app_settings.json")) Ok(dir.join("app_settings.json"))
} }
@@ -61,7 +61,7 @@ pub async fn save_app_settings(
let connections_path = app let connections_path = app
.path() .path()
.app_data_dir() .app_data_dir()
.map_err(|e| TuskError::Custom(e.to_string()))? .map_err(|e| TuskError::Config(e.to_string()))?
.join("connections.json"); .join("connections.json");
let mcp_state = state.inner().clone(); let mcp_state = state.inner().clone();

View File

@@ -26,6 +26,15 @@ pub enum TuskError {
#[error("Docker error: {0}")] #[error("Docker error: {0}")]
Docker(String), Docker(String),
#[error("Configuration error: {0}")]
Config(String),
#[error("Validation error: {0}")]
Validation(String),
#[error("Export error: {0}")]
Export(String),
#[error("{0}")] #[error("{0}")]
Custom(String), Custom(String),
} }

View File

@@ -31,6 +31,7 @@ pub struct AppState {
} }
const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(300); // 5 minutes const SCHEMA_CACHE_TTL: Duration = Duration::from_secs(300); // 5 minutes
const SCHEMA_CACHE_MAX_SIZE: usize = 100;
impl AppState { impl AppState {
pub fn new() -> Self { pub fn new() -> Self {
@@ -80,6 +81,16 @@ impl AppState {
let mut cache = self.schema_cache.write().await; let mut cache = self.schema_cache.write().await;
// Evict stale entries to prevent unbounded memory growth // Evict stale entries to prevent unbounded memory growth
cache.retain(|_, entry| entry.cached_at.elapsed() < SCHEMA_CACHE_TTL); cache.retain(|_, entry| entry.cached_at.elapsed() < SCHEMA_CACHE_TTL);
// If still at capacity, remove the oldest entry
if cache.len() >= SCHEMA_CACHE_MAX_SIZE {
if let Some(oldest_key) = cache
.iter()
.min_by_key(|(_, e)| e.cached_at)
.map(|(k, _)| k.clone())
{
cache.remove(&oldest_key);
}
}
cache.insert( cache.insert(
connection_id, connection_id,
SchemaCacheEntry { SchemaCacheEntry {

View File

@@ -1,4 +1,4 @@
use std::collections::{HashMap, HashSet}; use std::collections::{HashMap, HashSet, VecDeque};
pub fn escape_ident(name: &str) -> String { pub fn escape_ident(name: &str) -> String {
format!("\"{}\"", name.replace('"', "\"\"")) format!("\"{}\"", name.replace('"', "\"\""))
@@ -44,27 +44,33 @@ pub fn topological_sort_tables(
} }
// Kahn's algorithm // Kahn's algorithm
let mut queue: Vec<(String, String)> = in_degree let mut initial: Vec<(String, String)> = in_degree
.iter() .iter()
.filter(|(_, &deg)| deg == 0) .filter(|(_, &deg)| deg == 0)
.map(|(k, _)| k.clone()) .map(|(k, _)| k.clone())
.collect(); .collect();
queue.sort(); // deterministic order initial.sort(); // deterministic order
let mut queue: VecDeque<(String, String)> = VecDeque::from(initial);
let mut result = Vec::new(); let mut result = Vec::new();
while let Some(node) = queue.pop() { while let Some(node) = queue.pop_front() {
result.push(node.clone()); result.push(node.clone());
if let Some(neighbors) = graph.get(&node) { if let Some(neighbors) = graph.get(&node) {
for neighbor in neighbors { let mut new_ready: Vec<(String, String)> = neighbors
if let Some(deg) = in_degree.get_mut(neighbor) { .iter()
.filter(|neighbor| {
if let Some(deg) = in_degree.get_mut(*neighbor) {
*deg -= 1; *deg -= 1;
if *deg == 0 { *deg == 0
queue.push(neighbor.clone()); } else {
queue.sort(); false
}
}
} }
})
.cloned()
.collect();
new_ready.sort();
queue.extend(new_ready);
} }
} }

View File

@@ -22,7 +22,7 @@
} }
], ],
"security": { "security": {
"csp": null "csp": "default-src 'self'; style-src 'self' 'unsafe-inline'"
} }
}, },
"bundle": { "bundle": {

View File

@@ -103,7 +103,9 @@ export function useReconnect() {
setPgVersion(version); setPgVersion(version);
setDbFlavor(id, flavor); setDbFlavor(id, flavor);
setCurrentDatabase(database); setCurrentDatabase(database);
queryClient.invalidateQueries(); queryClient.invalidateQueries({ queryKey: ["databases"] });
queryClient.invalidateQueries({ queryKey: ["schemas"] });
queryClient.invalidateQueries({ queryKey: ["completion-schema"] });
}, },
}); });
} }