Files
logs_reader/src/server.rs
T
Romulus21andClaude Opus 5.5 e44e0fd162 Rafraîchissement par projet, nom obligatoire et fichiers anciens masqués
- Chaque projet choisit sa fréquence de relecture (jamais, 5 s … 1 h) ; le
  serveur ne relit que les projets dus, le fichier affiché est toujours à
  jour. Le réglage global et sa page disparaissent (migration de l'ancien
  intervalle vers chaque projet).
- Le nom du projet est obligatoire, proposé d'après le chemin.
- Les fichiers non modifiés depuis N jours peuvent être masqués ; ils ne
  comptent plus dans les non-lus et réapparaissent dès qu'ils changent.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 13:24:11 +02:00

218 lines
7.0 KiB
Rust

//! Code exécuté uniquement côté serveur : base de données et accès au contexte.
use crate::{
model::{
FileSort, FileSummary, LogFormat, LogKind, ProjectSummary, Settings, Summary, is_hidden,
parse_log_dirs,
},
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<SqlitePool, Box<dyn Error>> {
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<SqlitePool, ServerFnError> {
use_context::<SqlitePool>().ok_or_else(|| internal_error("SqlitePool absent du contexte"))
}
/// Récupère le scanner fourni en contexte par `main`.
pub fn scanner() -> Result<Arc<Scanner>, ServerFnError> {
use_context::<Arc<Scanner>>().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<Option<String>> {
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<Settings> {
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 { file_sort, paused })
}
/// (id, project_id, relative_path, kind, format, size, modifié le, manquant, erreur, non-lus)
type FileRow = (
i64,
i64,
String,
String,
Option<String>,
i64,
Option<i64>,
bool,
Option<String>,
i64,
);
/// Projets, fichiers et compteurs de non-lus.
///
/// Un fichier manquant ou un projet introuvable sur le disque ne compte aucun non-lu, ni un
/// log d'accès (cf. [`LogFormat::notifies`]). Les fichiers masqués (trop anciens, cf.
/// [`is_hidden`]) ne sont ni listés ni comptés.
pub async fn load_summary(pool: &SqlitePool) -> sqlx::Result<Summary> {
type ProjectRow = (
i64,
String,
String,
i64,
Option<i64>,
String,
Option<String>,
Option<String>,
Option<String>,
);
let projects: Vec<ProjectRow> = sqlx::query_as(
"SELECT id, name, root_path, refresh_seconds, hide_after_days, log_dirs, last_error,
vhost_path, vhost_error
FROM projects ORDER BY name COLLATE NOCASE, id",
)
.fetch_all(pool)
.await?;
let files: Vec<FileRow> = sqlx::query_as(
"SELECT f.id, f.project_id, f.relative_path, f.kind, f.format, 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 now = time::OffsetDateTime::now_utc().unix_timestamp();
let mut summary = Summary {
total: 0,
now,
projects: Vec::with_capacity(projects.len()),
};
for (
id,
name,
root_path,
refresh_seconds,
hide_after_days,
log_dirs,
error,
vhost_path,
vhost_error,
) in projects
{
let project_ok = error.is_none();
let hide_after_days = hide_after_days.map(|d| d as u32);
let (hidden, visible): (Vec<&FileRow>, Vec<&FileRow>) = files
.iter()
.filter(|f| f.1 == id)
.partition(|f| is_hidden(f.6, now, hide_after_days));
let files: Vec<FileSummary> = visible
.into_iter()
.map(
|(fid, _, rel, kind, format, size, modified, missing, ferr, unread)| {
let kind = LogKind::parse(kind).unwrap_or_default();
let notifies = format
.as_deref()
.and_then(LogFormat::parse)
.is_none_or(LogFormat::notifies);
let counted = !*missing && notifies && (project_ok || kind != LogKind::Project);
FileSummary {
id: *fid,
kind,
relative_path: rel.clone(),
size: *size as u64,
modified: *modified,
missing: *missing,
error: ferr.clone(),
unread: if counted { *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,
refresh_seconds: refresh_seconds as u32,
hide_after_days,
hidden_files: hidden.len() as u32,
log_dirs: parse_log_dirs(&log_dirs),
error,
vhost_path,
vhost_error,
unread,
files,
});
}
Ok(summary)
}