diff --git a/crates/core/src/storage/mod.rs b/crates/core/src/storage/mod.rs index 727850816..03a0a07fa 100644 --- a/crates/core/src/storage/mod.rs +++ b/crates/core/src/storage/mod.rs @@ -1687,6 +1687,8 @@ pub struct Storage { applied_migrations: Mutex>>, } +const REQUEST_BUSY_TIMEOUT: Duration = Duration::from_secs(3); + impl Storage { /// Shares the existing database pool without opening a new database or /// checking out a connection. Async completion tasks can own this handle @@ -1699,8 +1701,6 @@ impl Storage { } fn configure_connection(conn: &Connection) -> Result<()> { - // 中文注释:并发写入时给 SQLite 一点等待时间,避免瞬时 lock 导致请求直接失败。 - conn.busy_timeout(Duration::from_millis(3000))?; // 中文注释:复杂筛选/聚合的临时 B-tree 优先走内存,减少报表查询落盘开销。 // journal_size_limit caps the WAL file left behind after a checkpoint, so // a large purge does not keep a multi-GB WAL file around afterwards. @@ -1710,15 +1710,18 @@ impl Storage { Ok(()) } - fn configure_file_connection(conn: &Connection) -> Result<()> { - Self::configure_connection(conn)?; + fn from_file_connection(conn: Connection) -> Result { + Self::configure_connection(&conn)?; // 中文注释:文件库启用 WAL + NORMAL,可明显降低并发读写互斥开销; // 仅在 open(path) 上设置,避免影响 open_in_memory 的行为预期。 conn.execute_batch( "PRAGMA journal_mode=WAL; PRAGMA synchronous=NORMAL;", )?; - Ok(()) + Ok(Self { + conn, + applied_migrations: Mutex::new(None), + }) } /// 函数 `open` @@ -1734,11 +1737,13 @@ impl Storage { /// 返回函数执行结果 pub fn open(path: impl AsRef) -> Result { let conn = Connection::open(path)?; - Self::configure_file_connection(&conn)?; - Ok(Self { - conn, - applied_migrations: Mutex::new(None), - }) + conn.busy_timeout(REQUEST_BUSY_TIMEOUT)?; + Self::from_file_connection(conn) + } + + /// Apply the caller's busy timeout from the initial WAL negotiation onward. + pub fn open_with_busy_timeout(path: impl AsRef, timeout: Duration) -> Result { + Self::from_file_connection(Connection::open_with_busy_timeout(path, timeout)?) } /// 函数 `open_in_memory` @@ -1754,6 +1759,7 @@ impl Storage { /// 返回函数执行结果 pub fn open_in_memory() -> Result { let conn = Connection::open_in_memory()?; + conn.busy_timeout(REQUEST_BUSY_TIMEOUT)?; Self::configure_connection(&conn)?; Ok(Self { conn, diff --git a/crates/rusqlite/src/lib.rs b/crates/rusqlite/src/lib.rs index ec491c829..5416d9a9e 100644 --- a/crates/rusqlite/src/lib.rs +++ b/crates/rusqlite/src/lib.rs @@ -78,16 +78,29 @@ struct ActiveTransaction { impl Connection { pub fn open>(path: P) -> Result { - let path = path.as_ref().to_path_buf(); + Self::open_file(path.as_ref(), SqliteConnectOptions::new()) + } + + pub fn open_with_busy_timeout(path: impl AsRef, timeout: Duration) -> Result { + Self::open_file( + path.as_ref(), + SqliteConnectOptions::new().busy_timeout(timeout), + ) + } + + fn open_file(path: &Path, options: SqliteConnectOptions) -> Result { let rt = sqlite_runtime()?; - let options = sqlite_options_for_path(&path)?; + let options = options + .filename(path) + .create_if_missing(true) + .journal_mode(SqliteJournalMode::Wal); let pool = block_on_runtime(&rt, async { single_handle_pool_options().connect_with(options).await })?; Ok(Self { rt, pool, - path: Some(path), + path: Some(path.to_path_buf()), active_transaction: Arc::new(StdMutex::new(None)), last_known_rowid: Arc::new(AtomicI64::new(0)), }) @@ -365,13 +378,6 @@ fn single_handle_pool_options() -> SqlitePoolOptions { .idle_timeout(None) } -fn sqlite_options_for_path(path: &Path) -> Result { - Ok(SqliteConnectOptions::new() - .filename(path) - .create_if_missing(true) - .journal_mode(SqliteJournalMode::Wal)) -} - #[derive(Debug)] pub struct Statement<'c> { conn: &'c Connection, diff --git a/crates/service/src/storage/storage_helpers.rs b/crates/service/src/storage/storage_helpers.rs index d70b49025..26adb1875 100644 --- a/crates/service/src/storage/storage_helpers.rs +++ b/crates/service/src/storage/storage_helpers.rs @@ -16,6 +16,9 @@ use std::time::{SystemTime, UNIX_EPOCH}; const DEFAULT_STORAGE_MAX_CONNECTIONS: usize = 32; const DEFAULT_STORAGE_MAX_IDLE_CONNECTIONS: usize = 16; const DEFAULT_STORAGE_ACQUIRE_TIMEOUT_MS: u64 = 30_000; +// The service and web processes share SQLite. Startup can wait longer for a +// live writer than a request can, without replaying a partially applied migration. +const SQLITE_STARTUP_BUSY_TIMEOUT: Duration = Duration::from_secs(30); // Legacy domain helper signatures still carry a core Storage reference. In // remote mode this uninitialized memory handle is only a type boundary; it // must never open or modify the user's SQLite database. @@ -676,7 +679,7 @@ fn model_catalog_v2_migration_needed(db_path: &Path) -> Result { if !db_path.exists() || db_path.metadata().map(|meta| meta.len()).unwrap_or(0) == 0 { return Ok(true); } - let conn = Connection::open(db_path) + let conn = Connection::open_with_busy_timeout(db_path, SQLITE_STARTUP_BUSY_TIMEOUT) .map_err(|err| format!("open database for migration inspection failed: {err}"))?; if !sqlite_table_exists(&conn, "schema_migrations")? { return Ok(true); @@ -708,7 +711,7 @@ fn preflight_model_catalog_v2(db_path: &Path) -> Result<(), String> { if !db_path.exists() || db_path.metadata().map(|meta| meta.len()).unwrap_or(0) == 0 { return Ok(()); } - let conn = Connection::open(db_path) + let conn = Connection::open_with_busy_timeout(db_path, SQLITE_STARTUP_BUSY_TIMEOUT) .map_err(|err| format!("open database for model catalog preflight failed: {err}"))?; if sqlite_table_exists(&conn, "model_catalog_models")? { let duplicates: i64 = conn @@ -783,7 +786,7 @@ fn backup_model_catalog_database(db_path: &Path) -> Result, Stri db_path.display(), unix_timestamp() )); - let source = Connection::open(db_path) + let source = Connection::open_with_busy_timeout(db_path, SQLITE_STARTUP_BUSY_TIMEOUT) .map_err(|err| format!("open model catalog backup source failed: {err}"))?; let mut target = Connection::open(&backup_path) .map_err(|err| format!("open model catalog backup target failed: {err}"))?; @@ -798,7 +801,7 @@ fn backup_model_catalog_database(db_path: &Path) -> Result, Stri fn restore_model_catalog_database(db_path: &Path, backup_path: &Path) -> Result<(), String> { let source = Connection::open(backup_path) .map_err(|err| format!("open model catalog restore source failed: {err}"))?; - let mut target = Connection::open(db_path) + let mut target = Connection::open_with_busy_timeout(db_path, SQLITE_STARTUP_BUSY_TIMEOUT) .map_err(|err| format!("open model catalog restore target failed: {err}"))?; let backup = Backup::new(&source, &mut target) .map_err(|err| format!("create model catalog restore backup failed: {err}"))?; @@ -828,16 +831,20 @@ pub(crate) fn initialize_storage() -> Result<(), String> { } let path = std::env::var("CODEXMANAGER_DB_PATH") .map_err(|_| "CODEXMANAGER_DB_PATH not set".to_string())?; + initialize_sqlite_storage(&path) +} + +fn initialize_sqlite_storage(path: &str) -> Result<(), String> { { let initialized = crate::lock_utils::lock_recover( initialized_storage_paths(), "initialized_storage_paths", ); - if initialized.contains_key(&path) { + if initialized.contains_key(path) { return Ok(()); } } - let db_path = Path::new(&path); + let db_path = Path::new(path); if !db_path.exists() { log::warn!("storage path missing: {}", path); } @@ -851,8 +858,8 @@ pub(crate) fn initialize_storage() -> Result<(), String> { } else { None }; - let storage = - Storage::open(&path).map_err(|err| format!("open storage failed: {} ({})", path, err))?; + let storage = Storage::open_with_busy_timeout(path, SQLITE_STARTUP_BUSY_TIMEOUT) + .map_err(|err| format!("open storage failed: {} ({})", path, err))?; let initialization = storage .init() .and_then(|_| storage.smoke_check_model_catalog_v2()); @@ -869,7 +876,7 @@ pub(crate) fn initialize_storage() -> Result<(), String> { } drop(migration_lock); crate::lock_utils::lock_recover(initialized_storage_paths(), "initialized_storage_paths") - .insert(path, ()); + .insert(path.to_owned(), ()); Ok(()) } diff --git a/crates/service/src/storage/tests/storage_helpers_tests.rs b/crates/service/src/storage/tests/storage_helpers_tests.rs index ced179a88..419e53851 100644 --- a/crates/service/src/storage/tests/storage_helpers_tests.rs +++ b/crates/service/src/storage/tests/storage_helpers_tests.rs @@ -143,6 +143,26 @@ fn pending_model_catalog_data_migration_requires_backup() { let _ = std::fs::remove_file(&db_path); } +#[test] +fn initialize_storage_waits_for_an_existing_sqlite_writer() { + let db_path = unique_db_path("codexmanager-startup-write-lock"); + let storage = codexmanager_core::storage::Storage::open(&db_path).unwrap(); + storage.init().unwrap(); + drop(storage); + + let writer = Connection::open(&db_path).unwrap(); + writer.execute_batch("BEGIN IMMEDIATE").unwrap(); + let release = thread::spawn(move || { + // A live service can hold the writer past the normal request timeout. + thread::sleep(Duration::from_secs(5)); + writer.execute_batch("COMMIT").unwrap(); + }); + let result = super::initialize_sqlite_storage(&db_path); + release.join().unwrap(); + let _ = std::fs::remove_file(&db_path); + result.expect("startup should finish when the existing writer releases its lock"); +} + #[test] fn model_catalog_preflight_allows_case_conflicting_legacy_slugs() { let db_path = unique_db_path("codexmanager-model-catalog-duplicate-slugs");