//! Code exécuté uniquement côté serveur : base de données et accès au contexte. use crate::{ model::{DEFAULT_INTERVAL, FileSort, FileSummary, ProjectSummary, Settings, Summary}, scanner::Scanner, }; use leptos::prelude::*; use sqlx::{ SqlitePool, sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}, }; use std::{error::Error, fmt::Display, str::FromStr, sync::Arc, time::Duration}; /// Ouvre le pool SQLite (en créant le fichier au besoin), vérifie son intégrité /// et applique les migrations. pub async fn connect_db(url: &str) -> Result> { let options = SqliteConnectOptions::from_str(url)? .create_if_missing(true) .foreign_keys(true) .journal_mode(SqliteJournalMode::Wal) .busy_timeout(Duration::from_secs(5)); let pool = SqlitePoolOptions::new() .max_connections(5) .connect_with(options) .await?; let check: String = sqlx::query_scalar("PRAGMA quick_check") .fetch_one(&pool) .await?; if check != "ok" { return Err(format!("base corrompue : {check}").into()); } sqlx::migrate!().run(&pool).await?; Ok(pool) } /// Récupère le pool fourni en contexte par `main`. pub fn pool() -> Result { use_context::().ok_or_else(|| internal_error("SqlitePool absent du contexte")) } /// Récupère le scanner fourni en contexte par `main`. pub fn scanner() -> Result, ServerFnError> { use_context::>().ok_or_else(|| internal_error("Scanner absent du contexte")) } /// Journalise l'erreur réelle et renvoie au client un message générique. pub fn internal_error(error: impl Display) -> ServerFnError { leptos::logging::error!("erreur interne : {error}"); ServerFnError::new("Une erreur interne est survenue.") } /// Erreur renvoyée quand un projet ou un fichier demandé n'existe plus. pub fn not_found() -> ServerFnError { ServerFnError::new("Élément introuvable, la liste a été rafraîchie.") } /// Horodatage courant, au format stocké en base. pub fn now() -> String { format_ts(time::OffsetDateTime::now_utc()) } pub fn format_ts(ts: time::OffsetDateTime) -> String { use time::macros::format_description; ts.format(format_description!( "[year]-[month]-[day] [hour]:[minute]:[second]" )) .unwrap_or_default() } async fn setting(pool: &SqlitePool, key: &str) -> sqlx::Result> { sqlx::query_scalar("SELECT value FROM settings WHERE key = ?") .bind(key) .fetch_optional(pool) .await } pub async fn set_setting(pool: &SqlitePool, key: &str, value: &str) -> sqlx::Result<()> { sqlx::query( "INSERT INTO settings (key, value) VALUES (?, ?) ON CONFLICT (key) DO UPDATE SET value = excluded.value", ) .bind(key) .bind(value) .execute(pool) .await?; Ok(()) } pub async fn load_settings(pool: &SqlitePool) -> sqlx::Result { let refresh_interval_seconds = setting(pool, "refresh_interval_seconds") .await? .and_then(|v| v.parse().ok()) .unwrap_or(DEFAULT_INTERVAL); let file_sort = setting(pool, "file_sort") .await? .and_then(|v| FileSort::parse(&v)) .unwrap_or_default(); let paused = setting(pool, "paused").await?.as_deref() == Some("1"); Ok(Settings { refresh_interval_seconds, file_sort, paused, }) } /// (id, project_id, relative_path, size, modifié le, manquant, erreur, non-lus) type FileRow = ( i64, i64, String, i64, Option, bool, Option, i64, ); /// Projets, fichiers et compteurs de non-lus. /// /// Un fichier manquant ou un projet introuvable sur le disque ne compte aucun non-lu. pub async fn load_summary(pool: &SqlitePool) -> sqlx::Result { let projects: Vec<(i64, String, String, Option)> = sqlx::query_as( "SELECT id, name, root_path, last_error FROM projects ORDER BY name COLLATE NOCASE, id", ) .fetch_all(pool) .await?; let files: Vec = sqlx::query_as( "SELECT f.id, f.project_id, f.relative_path, f.size, f.modified_at, f.missing_since IS NOT NULL, f.last_error, (SELECT COUNT(*) FROM log_entries_index e WHERE e.log_file_id = f.id AND e.start_offset >= c.read_offset) FROM log_files f JOIN read_cursors c ON c.log_file_id = f.id ORDER BY f.relative_path", ) .fetch_all(pool) .await?; let mut summary = Summary { total: 0, now: time::OffsetDateTime::now_utc().unix_timestamp(), projects: Vec::with_capacity(projects.len()), }; for (id, name, root_path, error) in projects { let project_ok = error.is_none(); let files: Vec = files .iter() .filter(|f| f.1 == id) .map( |(fid, _, rel, size, modified, missing, ferr, unread)| FileSummary { id: *fid, relative_path: rel.clone(), size: *size as u64, modified: *modified, missing: *missing, error: ferr.clone(), unread: if project_ok && !*missing { *unread as u64 } else { 0 }, }, ) .collect(); let unread = files.iter().map(|f| f.unread).sum(); summary.total += unread; summary.projects.push(ProjectSummary { id, name, root_path, error, unread, files, }); } Ok(summary) }