use std::fs::OpenOptions;
use std::io::ErrorKind;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use log::{error, info};
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
use sqlx::{Pool, Sqlite};
use crate::error_handling::DatabaseError;
use crate::utils::{ensure_parent_dir_secure, IoErrorContext};
pub type DbPool = Arc<Pool<Sqlite>>;
pub(crate) const SQLITE_POOL_CONNECTION_CAP: u32 = 32;
pub(crate) const SQLITE_POOL_CONNECTION_FLOOR: u32 = 2;
#[must_use]
pub(crate) fn sqlite_pool_size(max_concurrency: usize) -> u32 {
u32::try_from(max_concurrency)
.unwrap_or(SQLITE_POOL_CONNECTION_CAP)
.clamp(SQLITE_POOL_CONNECTION_FLOOR, SQLITE_POOL_CONNECTION_CAP)
}
pub async fn init_db_pool_with_path(
db_path: &std::path::Path,
max_connections: u32,
) -> Result<DbPool, DatabaseError> {
let db_path_str = db_path.to_string_lossy().to_string();
ensure_parent_dir_secure(db_path).map_err(|e| DatabaseError::FileCreationError {
context: format!(
"Failed to create database directory for {}",
db_path.display()
),
source: Box::new(e),
})?;
let path_for_task = db_path_str.clone();
let file_creation_result = tokio::task::spawn_blocking(move || {
OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(&path_for_task)
.with_path(&path_for_task)
.map(|_| ())
})
.await
.map_err(|e| {
error!("Task panicked while creating database file: {e}");
DatabaseError::FileCreationError {
context: format!("Background task panicked while creating database file {db_path_str}"),
source: Box::new(e),
}
})?;
match file_creation_result {
Ok(()) => info!("Database file created successfully."),
Err(ref e) if e.io_error.kind() == ErrorKind::AlreadyExists => {
info!("Database file already exists.");
}
Err(e) => {
error!("Failed to create database file: {e}");
return Err(DatabaseError::FileCreationError {
context: format!("Failed to open database file {db_path_str}"),
source: Box::new(e),
});
}
}
let db_url = format!("sqlite:{db_path_str}");
let options = SqliteConnectOptions::from_str(&db_url)
.map_err(|e| {
error!("Failed to parse database URL: {e}");
DatabaseError::FileCreationError {
context: format!("Invalid database path: {db_path_str}"),
source: Box::new(e),
}
})?
.create_if_missing(true)
.pragma("foreign_keys", "ON")
.pragma("synchronous", "NORMAL")
.pragma("wal_autocheckpoint", "1000")
.pragma("busy_timeout", "5000");
let pool = SqlitePoolOptions::new()
.max_connections(max_connections)
.acquire_timeout(Duration::from_secs(5)) .idle_timeout(Some(Duration::from_secs(60))) .connect_with(options)
.await
.map_err(|e| {
error!("Failed to connect to database: {e}");
DatabaseError::SqlError(e)
})?;
sqlx::query("PRAGMA journal_mode=WAL")
.execute(&pool)
.await
.map_err(|e| {
error!("Failed to set WAL mode: {e}");
DatabaseError::SqlError(e)
})?;
Ok(Arc::new(pool))
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::{NamedTempFile, TempDir};
#[tokio::test]
async fn test_init_db_pool_with_path_success() {
let temp_file = NamedTempFile::new().expect("Failed to create temp file");
let db_path = temp_file.path();
let result = init_db_pool_with_path(db_path, 5).await;
assert!(result.is_ok(), "Pool initialization should succeed");
let pool = result.unwrap();
assert!(!pool.is_closed(), "Pool should be open");
}
#[tokio::test]
async fn test_init_db_pool_with_path_existing_file() {
let temp_file = NamedTempFile::new().expect("Failed to create temp file");
let db_path = temp_file.path();
std::fs::File::create(db_path).expect("Failed to create file");
let result = init_db_pool_with_path(db_path, 5).await;
assert!(
result.is_ok(),
"Pool initialization should succeed with existing file"
);
}
#[tokio::test]
async fn test_init_db_pool_with_path_wal_mode_enabled() {
let temp_file = NamedTempFile::new().expect("Failed to create temp file");
let db_path = temp_file.path();
let pool = init_db_pool_with_path(db_path, 5)
.await
.expect("Failed to initialize pool");
let result: String = sqlx::query_scalar("PRAGMA journal_mode")
.fetch_one(pool.as_ref())
.await
.expect("Failed to query journal mode");
assert_eq!(
result.to_uppercase(),
"WAL",
"WAL mode should be enabled, got: {}",
result
);
}
#[tokio::test]
async fn test_init_db_pool_with_path_foreign_keys_enabled() {
let temp_file = NamedTempFile::new().expect("Failed to create temp file");
let db_path = temp_file.path();
let pool = init_db_pool_with_path(db_path, 5)
.await
.expect("Failed to initialize pool");
let result: i64 = sqlx::query_scalar("PRAGMA foreign_keys")
.fetch_one(pool.as_ref())
.await
.expect("Failed to query foreign keys");
assert_eq!(result, 1, "Foreign keys should be enabled");
}
#[tokio::test]
async fn test_init_db_pool_with_path_busy_timeout_enabled() {
let temp_file = NamedTempFile::new().expect("Failed to create temp file");
let db_path = temp_file.path();
let pool = init_db_pool_with_path(db_path, 5)
.await
.expect("Failed to initialize pool");
let result: i64 = sqlx::query_scalar("PRAGMA busy_timeout")
.fetch_one(pool.as_ref())
.await
.expect("Failed to query busy_timeout");
assert_eq!(result, 5000, "busy_timeout should be 5000 ms");
}
#[test]
fn sqlite_pool_size_caps_and_floors_concurrency() {
assert_eq!(sqlite_pool_size(1), SQLITE_POOL_CONNECTION_FLOOR);
assert_eq!(sqlite_pool_size(2), 2);
assert_eq!(sqlite_pool_size(30), 30);
assert_eq!(sqlite_pool_size(32), SQLITE_POOL_CONNECTION_CAP);
assert_eq!(sqlite_pool_size(10_000), SQLITE_POOL_CONNECTION_CAP);
}
#[tokio::test]
async fn test_init_db_pool_unwritable_parent_is_file_creation_error() {
let tmp = TempDir::new().expect("tempdir");
let blocker = tmp.path().join("not_a_directory");
std::fs::write(&blocker, b"x").expect("write blocker");
let dest = blocker.join("domain_status.db");
let err = init_db_pool_with_path(&dest, 2)
.await
.expect_err("file-as-parent must fail");
match err {
DatabaseError::FileCreationError { context, .. } => {
assert!(
context.contains(&dest.display().to_string()),
"FileCreationError context must name the dest path, got: {context}"
);
}
other => panic!("expected FileCreationError, got {other:?}"),
}
}
#[tokio::test]
#[cfg(unix)]
async fn test_init_db_pool_unwritable_dest_is_file_creation_error() {
use std::os::unix::fs::PermissionsExt;
let tmp = TempDir::new().expect("tempdir");
let parent = tmp.path().join("locked");
std::fs::create_dir(&parent).expect("parent");
let dest = parent.join("domain_status.db");
std::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o555))
.expect("lock parent");
let result = init_db_pool_with_path(&dest, 2).await;
let _ = std::fs::set_permissions(&parent, std::fs::Permissions::from_mode(0o755));
let err = result.expect_err("unwritable dest must fail");
match err {
DatabaseError::FileCreationError { context, .. } => {
assert!(
context.contains(&dest.display().to_string()),
"FileCreationError context must name the dest path, got: {context}"
);
}
other => panic!("expected FileCreationError, got {other:?}"),
}
}
}