mirror of
https://github.com/SECTL/SecScore.git
synced 2026-07-19 19:04:23 +08:00
修复安卓端PostgreSQL连接长时间转圈无响应
This commit is contained in:
@@ -3,6 +3,7 @@ use serde::{Deserialize, Serialize};
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use tauri::{AppHandle, Emitter, Manager, State};
|
||||
use tokio::time::{timeout, Duration};
|
||||
|
||||
use crate::db::connection::{create_postgres_connection, create_sqlite_connection};
|
||||
use crate::db::connection::DatabaseType;
|
||||
@@ -15,6 +16,9 @@ use sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter, Set};
|
||||
|
||||
use super::response::IpcResponse;
|
||||
|
||||
const DB_CONNECT_TIMEOUT_SECS: u64 = 15;
|
||||
const DB_MIGRATION_TIMEOUT_SECS: u64 = 20;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct TestConnectionResult {
|
||||
pub success: bool,
|
||||
@@ -775,18 +779,28 @@ pub async fn db_test_connection(
|
||||
} else if connection_string.starts_with("postgres://")
|
||||
|| connection_string.starts_with("postgresql://")
|
||||
{
|
||||
match create_postgres_connection(&connection_string).await {
|
||||
Ok(conn) => {
|
||||
let connection_result = timeout(
|
||||
Duration::from_secs(DB_CONNECT_TIMEOUT_SECS),
|
||||
create_postgres_connection(&connection_string),
|
||||
)
|
||||
.await;
|
||||
|
||||
match connection_result {
|
||||
Err(_) => TestConnectionResult {
|
||||
success: false,
|
||||
error: Some("PostgreSQL 连接超时,请检查网络或连接字符串".to_string()),
|
||||
},
|
||||
Ok(Err(e)) => TestConnectionResult {
|
||||
success: false,
|
||||
error: Some(e.to_string()),
|
||||
},
|
||||
Ok(Ok(conn)) => {
|
||||
let _ = conn.close().await;
|
||||
TestConnectionResult {
|
||||
success: true,
|
||||
error: None,
|
||||
}
|
||||
}
|
||||
Err(e) => TestConnectionResult {
|
||||
success: false,
|
||||
error: Some(e.to_string()),
|
||||
},
|
||||
}
|
||||
} else {
|
||||
let path = connection_string.as_str();
|
||||
@@ -819,12 +833,20 @@ pub async fn db_switch_connection(
|
||||
let (db_type, saved_connection_string, saved_status, conn) = if connection_string.starts_with("postgres://")
|
||||
|| connection_string.starts_with("postgresql://")
|
||||
{
|
||||
let conn = create_postgres_connection(&connection_string)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
run_migration(&conn, DatabaseType::PostgreSQL)
|
||||
.await
|
||||
.map_err(|e| e.to_string())?;
|
||||
let conn = timeout(
|
||||
Duration::from_secs(DB_CONNECT_TIMEOUT_SECS),
|
||||
create_postgres_connection(&connection_string),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| "PostgreSQL 连接超时,请检查网络或连接字符串".to_string())?
|
||||
.map_err(|e| e.to_string())?;
|
||||
timeout(
|
||||
Duration::from_secs(DB_MIGRATION_TIMEOUT_SECS),
|
||||
run_migration(&conn, DatabaseType::PostgreSQL),
|
||||
)
|
||||
.await
|
||||
.map_err(|_| "PostgreSQL 初始化超时,请稍后重试".to_string())?
|
||||
.map_err(|e| e.to_string())?;
|
||||
|
||||
(
|
||||
"postgresql".to_string(),
|
||||
|
||||
@@ -1,9 +1,26 @@
|
||||
use sea_orm::{ConnectOptions, Database, DatabaseConnection, DbErr};
|
||||
use std::time::Duration;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use tracing::{info, warn};
|
||||
|
||||
const DB_MAX_CONNECTIONS: u32 = 20;
|
||||
const DB_MIN_CONNECTIONS: u32 = 1;
|
||||
const DB_CONNECT_TIMEOUT_SECS: u64 = 12;
|
||||
const DB_ACQUIRE_TIMEOUT_SECS: u64 = 12;
|
||||
const DB_IDLE_TIMEOUT_SECS: u64 = 30;
|
||||
|
||||
fn apply_default_connect_options(opt: &mut ConnectOptions) {
|
||||
opt.max_connections(DB_MAX_CONNECTIONS)
|
||||
.min_connections(DB_MIN_CONNECTIONS)
|
||||
.connect_timeout(Duration::from_secs(DB_CONNECT_TIMEOUT_SECS))
|
||||
.acquire_timeout(Duration::from_secs(DB_ACQUIRE_TIMEOUT_SECS))
|
||||
.idle_timeout(Duration::from_secs(DB_IDLE_TIMEOUT_SECS))
|
||||
.sqlx_logging(true)
|
||||
.sqlx_logging_level(tracing::log::LevelFilter::Info);
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum DatabaseType {
|
||||
SQLite,
|
||||
@@ -106,10 +123,7 @@ impl ConnectionManager {
|
||||
);
|
||||
|
||||
let mut opt = ConnectOptions::new(&url);
|
||||
opt.max_connections(100)
|
||||
.min_connections(5)
|
||||
.sqlx_logging(true)
|
||||
.sqlx_logging_level(tracing::log::LevelFilter::Info);
|
||||
apply_default_connect_options(&mut opt);
|
||||
|
||||
let conn = Database::connect(opt).await?;
|
||||
|
||||
@@ -195,20 +209,14 @@ impl ConnectionManager {
|
||||
pub async fn create_sqlite_connection(path: &str) -> Result<DatabaseConnection, DbErr> {
|
||||
let url = format!("sqlite://{}?mode=rwc", path);
|
||||
let mut opt = ConnectOptions::new(&url);
|
||||
opt.max_connections(100)
|
||||
.min_connections(5)
|
||||
.sqlx_logging(true)
|
||||
.sqlx_logging_level(tracing::log::LevelFilter::Info);
|
||||
apply_default_connect_options(&mut opt);
|
||||
|
||||
Database::connect(opt).await
|
||||
}
|
||||
|
||||
pub async fn create_postgres_connection(url: &str) -> Result<DatabaseConnection, DbErr> {
|
||||
let mut opt = ConnectOptions::new(url);
|
||||
opt.max_connections(100)
|
||||
.min_connections(5)
|
||||
.sqlx_logging(true)
|
||||
.sqlx_logging_level(tracing::log::LevelFilter::Info);
|
||||
apply_default_connect_options(&mut opt);
|
||||
|
||||
Database::connect(opt).await
|
||||
}
|
||||
|
||||
+65
-17
@@ -13,6 +13,7 @@ use crate::db::migration::run_migration;
|
||||
use crate::services::settings::{SettingsKey, SettingsValue};
|
||||
use crate::{commands::*, state::AppState};
|
||||
use tauri::{App, Manager};
|
||||
use tokio::time::{timeout, Duration};
|
||||
#[cfg(desktop)]
|
||||
use tauri::{
|
||||
image::Image,
|
||||
@@ -125,6 +126,9 @@ pub fn setup_app(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
}
|
||||
|
||||
fn setup_database(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
const DB_CONNECT_TIMEOUT_SECS: u64 = 15;
|
||||
const DB_MIGRATION_TIMEOUT_SECS: u64 = 20;
|
||||
|
||||
let handle = app.handle().clone();
|
||||
let db_path = if cfg!(all(debug_assertions, desktop)) {
|
||||
std::path::PathBuf::from("data.sql")
|
||||
@@ -166,9 +170,67 @@ fn setup_database(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
};
|
||||
|
||||
if !pg_connection_string.trim().is_empty() {
|
||||
match create_postgres_connection(&pg_connection_string).await {
|
||||
Ok(pg_conn) => {
|
||||
if let Err(e) = run_migration(&pg_conn, DatabaseType::PostgreSQL).await {
|
||||
match timeout(
|
||||
Duration::from_secs(DB_CONNECT_TIMEOUT_SECS),
|
||||
create_postgres_connection(&pg_connection_string),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Err(_) => {
|
||||
let timeout_message = "PostgreSQL auto-connect timeout".to_string();
|
||||
eprintln!(
|
||||
"PostgreSQL auto-connect timed out on startup, fallback to sqlite"
|
||||
);
|
||||
settings
|
||||
.set_value(
|
||||
SettingsKey::PgConnectionStatus,
|
||||
SettingsValue::Json(serde_json::json!({
|
||||
"connected": false,
|
||||
"type": "sqlite",
|
||||
"error": timeout_message
|
||||
})),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("Failed to save pg status: {}", err))?;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
eprintln!("PostgreSQL auto-connect failed, fallback to sqlite: {}", e);
|
||||
settings
|
||||
.set_value(
|
||||
SettingsKey::PgConnectionStatus,
|
||||
SettingsValue::Json(serde_json::json!({
|
||||
"connected": false,
|
||||
"type": "sqlite",
|
||||
"error": e.to_string()
|
||||
})),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("Failed to save pg status: {}", err))?;
|
||||
}
|
||||
Ok(Ok(pg_conn)) => {
|
||||
let migration_result = timeout(
|
||||
Duration::from_secs(DB_MIGRATION_TIMEOUT_SECS),
|
||||
run_migration(&pg_conn, DatabaseType::PostgreSQL),
|
||||
)
|
||||
.await;
|
||||
|
||||
if let Err(_) = migration_result {
|
||||
let timeout_message = "PostgreSQL migration timeout".to_string();
|
||||
eprintln!(
|
||||
"PostgreSQL migration timed out on startup, fallback to sqlite"
|
||||
);
|
||||
settings
|
||||
.set_value(
|
||||
SettingsKey::PgConnectionStatus,
|
||||
SettingsValue::Json(serde_json::json!({
|
||||
"connected": false,
|
||||
"type": "sqlite",
|
||||
"error": timeout_message
|
||||
})),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("Failed to save pg status: {}", err))?;
|
||||
} else if let Ok(Err(e)) = migration_result {
|
||||
eprintln!("PostgreSQL migration failed on startup, fallback to sqlite: {}", e);
|
||||
settings
|
||||
.set_value(
|
||||
@@ -196,20 +258,6 @@ fn setup_database(app: &mut App) -> Result<(), Box<dyn std::error::Error>> {
|
||||
eprintln!("Auto connected to PostgreSQL from saved connection string");
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
eprintln!("PostgreSQL auto-connect failed, fallback to sqlite: {}", e);
|
||||
settings
|
||||
.set_value(
|
||||
SettingsKey::PgConnectionStatus,
|
||||
SettingsValue::Json(serde_json::json!({
|
||||
"connected": false,
|
||||
"type": "sqlite",
|
||||
"error": e.to_string()
|
||||
})),
|
||||
)
|
||||
.await
|
||||
.map_err(|err| format!("Failed to save pg status: {}", err))?;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
settings
|
||||
|
||||
Reference in New Issue
Block a user