Lecteur de logs Laravel avec notification par favicon
Application web locale (axum, Leptos 0.8, Tailwind v4, SQLite) qui suit les fichiers storage/logs de projets Laravel et signale les nouvelles entrées par le favicon et le titre de l'onglet. - Ajout de projets par chemin (validation, chemin canonique, doublons) - Découverte récursive des *.log et indexation incrémentale en flux, détection de troncature et de rotation - Curseur de lecture par fichier, polling à intervalle configurable - Vue fichier : pagination, filtres par niveau (niveaux absents grisés, double-clic pour isoler un niveau), recherche texte - Tri des fichiers par nom ou date de modification, projets repliables - Spécification complète dans .spec/specification.md Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
818527b758
20 files changed
+6523
No files matched your search
+176
@@ -0,0 +1,176 @@
|
||||
//! 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<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 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();
|
||||
Ok(Settings {
|
||||
refresh_interval_seconds,
|
||||
file_sort,
|
||||
})
|
||||
}
|
||||
|
||||
/// (id, project_id, relative_path, size, modifié le, manquant, erreur, non-lus)
|
||||
type FileRow = (
|
||||
i64,
|
||||
i64,
|
||||
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.
|
||||
pub async fn load_summary(pool: &SqlitePool) -> sqlx::Result<Summary> {
|
||||
let projects: Vec<(i64, String, String, Option<String>)> = 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<FileRow> = 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<FileSummary> = 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)
|
||||
}
|
||||
Reference in new issue
Block a user