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:
Romulus21andClaude Opus 5.5 committed 2026-10-21 10:52:04 +02:00
commit 818527b758
20 files changed
+6523

No files matched your search

+264
View File
@@ -0,0 +1,264 @@
//! Server functions appelées par l'interface.
use crate::model::{EntriesPage, FileSort, Settings, Summary};
use leptos::{prelude::*, server_fn::codec::Json};
#[cfg(feature = "ssr")]
use crate::server::{internal_error, not_found, now, pool, scanner};
/// Rafraîchit l'index de tous les projets puis renvoie les compteurs de non-lus.
/// Appelée à chaque cycle de polling.
#[server(endpoint = "unread_summary")]
pub async fn unread_summary() -> Result<Summary, ServerFnError> {
let pool = pool()?;
scanner()?.scan_all(&pool).await.map_err(internal_error)?;
crate::server::load_summary(&pool)
.await
.map_err(internal_error)
}
#[server(endpoint = "add_project")]
pub async fn add_project(path: String, name: String) -> Result<(), ServerFnError> {
let root = crate::scanner::validate_project_path(&path).map_err(ServerFnError::new)?;
let root_str = root.to_string_lossy().to_string();
let name = match name.trim() {
"" => root
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_else(|| root_str.clone()),
name => name.to_string(),
};
let pool = pool()?;
let inserted: Result<i64, sqlx::Error> = sqlx::query_scalar(
"INSERT INTO projects (name, root_path, created_at) VALUES (?, ?, ?) RETURNING id",
)
.bind(&name)
.bind(&root_str)
.bind(now())
.fetch_one(&pool)
.await;
let id = match inserted {
Ok(id) => id,
Err(sqlx::Error::Database(e)) if e.is_unique_violation() => {
return Err(ServerFnError::new("Ce projet est déjà enregistré."));
}
Err(e) => return Err(internal_error(e)),
};
scanner()?
.scan_new_project(&pool, id, &root_str)
.await
.map_err(internal_error)
}
#[server(endpoint = "remove_project")]
pub async fn remove_project(project_id: i64) -> Result<(), ServerFnError> {
let result = sqlx::query("DELETE FROM projects WHERE id = ?")
.bind(project_id)
.execute(&pool()?)
.await
.map_err(internal_error)?;
if result.rows_affected() == 0 {
return Err(not_found());
}
Ok(())
}
/// Entrées les plus récentes d'un fichier (du plus récent au plus ancien), filtrées par
/// niveau et par texte (insensible à la casse). Un filtre de niveaux vide ne renvoie rien.
#[server(input = Json, endpoint = "read_entries")]
pub async fn read_entries(
file_id: i64,
limit: u32,
levels: Vec<String>,
query: String,
) -> Result<EntriesPage, ServerFnError> {
use crate::{
model::{Entry, MAX_ENTRIES_LIMIT, MAX_ENTRY_BYTES},
parser::split_entry,
scanner::logs_dir,
};
use std::{
fs::File,
io::{Read, Seek, SeekFrom},
path::PathBuf,
};
let pool = pool()?;
let row: Option<(String, String, String, i64, i64)> = sqlx::query_as(
"SELECT p.root_path, p.name, f.relative_path, f.scan_offset, c.read_offset
FROM log_files f
JOIN projects p ON p.id = f.project_id
JOIN read_cursors c ON c.log_file_id = f.id
WHERE f.id = ?",
)
.bind(file_id)
.fetch_optional(&pool)
.await
.map_err(internal_error)?;
let Some((root, project_name, relative_path, scan_offset, read_offset)) = row else {
return Err(not_found());
};
let path: PathBuf = logs_dir(root.as_ref()).join(&relative_path);
let limit = limit.clamp(1, MAX_ENTRIES_LIMIT) as usize;
let query = query.trim().to_lowercase();
let mut entries = Vec::new();
// Sans recherche texte, une seule requête suffit ; sinon on parcourt l'index par lots.
let batch_size = if query.is_empty() { limit + 1 } else { 500 };
let mut before = i64::MAX;
while !levels.is_empty() && entries.len() <= limit {
let mut select = sqlx::QueryBuilder::new(
"SELECT start_offset, end_offset, logged_at, level FROM log_entries_index WHERE log_file_id = ",
);
select.push_bind(file_id);
select.push(" AND start_offset < ").push_bind(before);
select.push(" AND level IN (");
let mut list = select.separated(", ");
for level in &levels {
list.push_bind(level);
}
select.push(") ORDER BY start_offset DESC LIMIT ");
select.push_bind(batch_size as i64);
let batch: Vec<(i64, i64, String, String)> = select
.build_query_as()
.fetch_all(&pool)
.await
.map_err(internal_error)?;
let Some(last) = batch.last() else { break };
before = last.0;
let fetched = batch.len();
let file_path = path.clone();
let contents = tokio::task::spawn_blocking(move || -> std::io::Result<Vec<_>> {
let mut file = File::open(&file_path)?;
let mut out = Vec::with_capacity(batch.len());
for (start, end, logged_at, level) in batch {
let size = (end - start) as u64;
let mut buf = Vec::with_capacity(size.min(MAX_ENTRY_BYTES) as usize);
file.seek(SeekFrom::Start(start as u64))?;
(&mut file).take(MAX_ENTRY_BYTES).read_to_end(&mut buf)?;
buf.truncate(size.min(MAX_ENTRY_BYTES) as usize);
out.push((
start,
size,
logged_at,
level,
String::from_utf8_lossy(&buf).to_string(),
));
}
Ok(out)
})
.await
.map_err(internal_error)?
.map_err(|e| ServerFnError::new(format!("Impossible de lire le fichier : {e}.")))?;
for (start, size, logged_at, level, content) in contents {
if !query.is_empty() && !content.to_lowercase().contains(&query) {
continue;
}
let (env, message, details) = split_entry(&content);
entries.push(Entry {
start: start as u64,
logged_at,
level,
env,
message,
details,
size,
truncated: size > MAX_ENTRY_BYTES,
});
if entries.len() > limit {
break;
}
}
if fetched < batch_size {
break;
}
}
let has_more = entries.len() > limit;
entries.truncate(limit);
let present: Vec<String> =
sqlx::query_scalar("SELECT DISTINCT level FROM log_entries_index WHERE log_file_id = ?")
.bind(file_id)
.fetch_all(&pool)
.await
.map_err(internal_error)?;
Ok(EntriesPage {
file_id,
project_name,
relative_path,
entries,
has_more,
scan_offset: scan_offset as u64,
read_offset: read_offset as u64,
levels: present,
})
}
/// Avance le curseur de lecture d'un fichier. Un curseur ne recule jamais et ne dépasse
/// jamais la fin de la partie indexée.
#[server(endpoint = "mark_read")]
pub async fn mark_read(file_id: i64, up_to: u64) -> Result<(), ServerFnError> {
let result = sqlx::query(
"UPDATE read_cursors
SET read_offset = MAX(read_offset, MIN(?, (SELECT scan_offset FROM log_files WHERE id = log_file_id))),
updated_at = ?
WHERE log_file_id = ?",
)
.bind(up_to.min(i64::MAX as u64) as i64)
.bind(now())
.bind(file_id)
.execute(&pool()?)
.await
.map_err(internal_error)?;
if result.rows_affected() == 0 {
return Err(not_found());
}
Ok(())
}
/// Marque comme lus tous les fichiers d'un projet, ou de tous les projets.
#[server(endpoint = "mark_all_read")]
pub async fn mark_all_read(project_id: Option<i64>) -> Result<(), ServerFnError> {
sqlx::query(
"UPDATE read_cursors
SET read_offset = (SELECT scan_offset FROM log_files WHERE id = log_file_id),
updated_at = ?
WHERE log_file_id IN (SELECT id FROM log_files WHERE ?2 IS NULL OR project_id = ?2)",
)
.bind(now())
.bind(project_id)
.execute(&pool()?)
.await
.map_err(internal_error)?;
Ok(())
}
#[server(endpoint = "get_settings")]
pub async fn get_settings() -> Result<Settings, ServerFnError> {
crate::server::load_settings(&pool()?)
.await
.map_err(internal_error)
}
#[server(endpoint = "set_refresh_interval")]
pub async fn set_refresh_interval(seconds: String) -> Result<Settings, ServerFnError> {
let seconds = crate::model::parse_interval(&seconds).map_err(ServerFnError::new)?;
let pool = pool()?;
crate::server::set_setting(&pool, "refresh_interval_seconds", &seconds.to_string())
.await
.map_err(internal_error)?;
crate::server::load_settings(&pool)
.await
.map_err(internal_error)
}
/// Ordre des fichiers dans la barre latérale, conservé entre deux sessions.
#[server(input = Json, endpoint = "set_file_sort")]
pub async fn set_file_sort(sort: FileSort) -> Result<(), ServerFnError> {
crate::server::set_setting(&pool()?, "file_sort", sort.as_str())
.await
.map_err(internal_error)
}
+818
View File
@@ -0,0 +1,818 @@
use crate::{
api::{
AddProject, MarkAllRead, MarkRead, RemoveProject, SetFileSort, SetRefreshInterval,
get_settings, read_entries, unread_summary,
},
model::{
DEFAULT_INTERVAL, EntriesPage, Entry, FaviconState, FileSort, LEVELS, PAGE_SIZE,
ProjectSummary, Settings, Summary, UNKNOWN_LEVEL, favicon_data_url, human_size, page_title,
relative_age, sort_files,
},
};
use leptos::{html, prelude::*};
use leptos_meta::{MetaTags, Stylesheet, Title, provide_meta_context};
use leptos_router::{
SsrMode,
components::{A, Route, Router, Routes},
hooks::use_params_map,
path,
};
use std::{collections::HashSet, time::Duration};
pub fn shell(options: LeptosOptions) -> impl IntoView {
view! {
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link id="favicon" rel="icon" href="/favicon.svg" type="image/svg+xml" />
<AutoReload options=options.clone() />
<HydrationScripts options />
<MetaTags />
</head>
<body class="bg-zinc-50 text-zinc-900 antialiased dark:bg-zinc-950 dark:text-zinc-100">
<App />
</body>
</html>
}
}
/// État partagé par toute l'interface : le compteur de rafraîchissement et le résumé des
/// non-lus qui en dépend. Incrémenter `refresh` relance le scan côté serveur.
#[derive(Clone, Copy)]
struct Live {
refresh: RwSignal<u64>,
summary: Resource<Result<Summary, ServerFnError>>,
/// Dernier résumé reçu avec succès, affiché quand le serveur est injoignable.
last_ok: RwSignal<Option<Summary>>,
}
impl Live {
fn bump(&self) {
self.refresh.update(|n| *n += 1);
}
/// Résumé à afficher : le plus récent, ou le dernier connu si le serveur ne répond plus.
fn current(&self) -> Option<Summary> {
match self.summary.get() {
Some(Ok(summary)) => Some(summary),
_ => self.last_ok.get(),
}
}
fn offline(&self) -> bool {
matches!(self.summary.get(), Some(Err(_)))
}
}
#[derive(Clone, Copy)]
struct SettingsCtx {
settings: Resource<Result<Settings, ServerFnError>>,
save: ServerAction<SetRefreshInterval>,
}
/// Extrait le message lisible d'une erreur de server function.
fn error_message(error: &ServerFnError) -> String {
match error {
ServerFnError::ServerError(message) => message.clone(),
_ => "Impossible de joindre le serveur.".to_string(),
}
}
/// Vrai si l'onglet est affiché (toujours vrai côté serveur).
fn page_visible() -> bool {
#[cfg(feature = "hydrate")]
{
document().visibility_state() == web_sys::VisibilityState::Visible
}
#[cfg(not(feature = "hydrate"))]
{
true
}
}
#[component]
pub fn App() -> impl IntoView {
provide_meta_context();
let refresh = RwSignal::new(0u64);
let summary = Resource::new(move || refresh.get(), |_| unread_summary());
let live = Live {
refresh,
summary,
last_ok: RwSignal::new(None),
};
provide_context(live);
let save = ServerAction::<SetRefreshInterval>::new();
let settings = Resource::new(move || save.version().get(), |_| get_settings());
provide_context(SettingsCtx { settings, save });
let interval = move || {
settings
.get()
.and_then(Result::ok)
.map(|s| s.refresh_interval_seconds)
.unwrap_or(DEFAULT_INTERVAL)
};
// Polling : le timer est recréé à chaque changement d'intervalle.
Effect::new(move |previous: Option<Option<IntervalHandle>>| {
if let Some(Some(handle)) = previous {
handle.clear();
}
let seconds = interval();
set_interval_with_handle(move || live.bump(), Duration::from_secs(seconds.into())).ok()
});
// Retour sur l'onglet : rafraîchit tout de suite (et marque lu le fichier ouvert).
Effect::new(move |_| {
let _ = window_event_listener(leptos::ev::focus, move |_| live.bump());
});
Effect::new(move |_| {
if let Some(Ok(summary)) = summary.get() {
live.last_ok.set(Some(summary));
}
});
// Favicon : pastille rouge avec le nombre de non-lus, grise si le serveur est injoignable.
Effect::new(move |_| {
let state = match summary.get() {
Some(Ok(s)) if s.total > 0 => FaviconState::Unread(s.total),
Some(Err(_)) => FaviconState::Offline,
_ => FaviconState::Idle,
};
if let Ok(Some(link)) = document().query_selector("link#favicon") {
let _ = link.set_attribute("href", &favicon_data_url(state));
}
});
let total = move || live.current().map(|s| s.total).unwrap_or(0);
view! {
<Stylesheet id="leptos" href="/pkg/lara_logs_reader.css" />
// Routes en `SsrMode::Async` : le serveur attend le résumé avant d'envoyer `<head>`,
// le titre contient donc déjà le nombre de non-lus.
<Transition>
{move || view! { <Title text=page_title(total()) /> }}
</Transition>
<Router>
<div class="flex h-screen">
<Sidebar />
<main class="flex-1 overflow-y-auto">
<Routes fallback=|| view! { <p class="p-8">"Page introuvable."</p> }>
<Route path=path!("/") view=HomePage ssr=SsrMode::Async />
<Route path=path!("/files/:id") view=FileView ssr=SsrMode::Async />
<Route path=path!("/settings") view=SettingsPage ssr=SsrMode::Async />
</Routes>
</main>
</div>
</Router>
}
}
const INPUT: &str = "w-full rounded-md border border-zinc-700 bg-zinc-800 px-2 py-1.5 text-sm text-zinc-100 placeholder:text-zinc-500 focus:border-red-400 focus:outline-none";
const BUTTON: &str = "rounded-md bg-red-500 px-3 py-1.5 text-sm font-medium text-white hover:bg-red-600 disabled:opacity-50";
const SMALL_BUTTON: &str =
"rounded px-1.5 py-0.5 text-xs text-zinc-400 hover:bg-zinc-800 hover:text-zinc-100";
#[component]
fn Sidebar() -> impl IntoView {
let live = expect_context::<Live>();
let add = ServerAction::<AddProject>::new();
let remove = ServerAction::<RemoveProject>::new();
let mark_all = ServerAction::<MarkAllRead>::new();
let form = NodeRef::<html::Form>::new();
// Projets repliés par l'utilisateur. La liste est reconstruite à chaque rafraîchissement :
// sans cet état, chaque projet se redéplierait.
let collapsed = RwSignal::new(HashSet::<i64>::new());
// Ordre des fichiers : le choix fait ici s'applique tout de suite, sans attendre que
// les réglages soient relus ; sinon, celui enregistré en base.
let SettingsCtx { settings, .. } = expect_context::<SettingsCtx>();
let save_sort = ServerAction::<SetFileSort>::new();
let chosen_sort = RwSignal::new(None::<FileSort>);
let sort = move || {
chosen_sort.get().unwrap_or_else(|| {
settings
.get()
.and_then(Result::ok)
.map(|s| s.file_sort)
.unwrap_or_default()
})
};
let sort_button = move |value: FileSort, label: &'static str| {
view! {
<button
class=move || {
if sort() == value {
"rounded px-1.5 py-0.5 text-xs bg-zinc-700 text-white"
} else {
SMALL_BUTTON
}
}
aria-pressed=move || (sort() == value).to_string()
on:click=move |_| {
chosen_sort.set(Some(value));
save_sort.dispatch(SetFileSort { sort: value });
}
>
{label}
</button>
}
};
Effect::watch(
move || {
(
add.version().get(),
remove.version().get(),
mark_all.version().get(),
)
},
move |_, _, _| live.bump(),
false,
);
// Vide le formulaire quand l'ajout a réussi (`ActionForm` ne le fait pas).
Effect::new(move |_| {
if matches!(add.value().get(), Some(Ok(())))
&& let Some(form) = form.get()
{
form.reset();
}
});
let total = move || live.current().map(|s| s.total).unwrap_or(0);
view! {
<aside class="flex w-80 shrink-0 flex-col gap-4 overflow-y-auto bg-zinc-900 p-4 text-zinc-100">
<header class="flex items-center justify-between">
<A href="/" attr:class="text-lg font-semibold">
"Lara Logs Reader"
</A>
<A href="/settings" attr:class=SMALL_BUTTON attr:title="Réglages">
"Réglages"
</A>
</header>
<ActionForm action=add node_ref=form attr:class="flex flex-col gap-2">
<input
name="path"
required
placeholder="/chemin/vers/projet-laravel"
aria-label="Chemin du projet"
class=INPUT
/>
<input
name="name"
placeholder="Nom (optionnel)"
aria-label="Nom du projet"
class=INPUT
/>
<button type="submit" class=BUTTON disabled=move || add.pending().get()>
"Ajouter le projet"
</button>
{move || {
add.value()
.get()
.and_then(Result::err)
.map(|e| view! { <p class="text-sm text-red-400">{error_message(&e)}</p> })
}}
</ActionForm>
{move || {
remove
.value()
.get()
.and_then(Result::err)
.map(|e| view! { <p class="text-sm text-red-400">{error_message(&e)}</p> })
}}
<Transition fallback=|| view! { <p class="text-sm text-zinc-400">"Chargement…"</p> }>
<Show when=move || live.offline()>
<p class="rounded-md bg-zinc-700 px-2 py-1 text-sm">"Serveur injoignable."</p>
</Show>
<div class="flex items-center justify-between border-t border-zinc-800 pt-3 text-sm">
<span>
{move || match total() {
0 => "Aucun nouveau log".to_string(),
1 => "1 nouveau log".to_string(),
n => format!("{n} nouveaux logs"),
}}
</span>
<Show when=move || { total() > 0 }>
<button
class=SMALL_BUTTON
on:click=move |_| {
mark_all.dispatch(MarkAllRead { project_id: None });
}
>
"Tout marquer lu"
</button>
</Show>
</div>
<div class="flex items-center gap-1 text-xs text-zinc-400">
"Trier les fichiers :" {sort_button(FileSort::Name, "Nom")}
{sort_button(FileSort::Modified, "Date")}
</div>
{move || {
let sort = sort();
live.current()
.map(|summary| {
if summary.projects.is_empty() {
view! {
<p class="text-sm text-zinc-400">"Aucun projet pour l'instant."</p>
}
.into_any()
} else {
let now = summary.now;
summary
.projects
.into_iter()
.map(|project| {
view! { <ProjectItem project remove mark_all collapsed sort now /> }
})
.collect_view()
.into_any()
}
})
}}
</Transition>
</aside>
}
}
#[component]
fn UnreadBadge(count: u64) -> impl IntoView {
(count > 0).then(|| {
view! {
<span class="rounded-full bg-red-500 px-1.5 text-xs font-semibold text-white">
{count}
</span>
}
})
}
#[component]
fn ProjectItem(
project: ProjectSummary,
remove: ServerAction<RemoveProject>,
mark_all: ServerAction<MarkAllRead>,
collapsed: RwSignal<HashSet<i64>>,
sort: FileSort,
/// Heure du serveur, pour l'ancienneté des fichiers.
now: i64,
) -> impl IntoView {
let id = project.id;
// Lu sans suivi : replier un projet ne doit pas reconstruire la liste.
let open = !collapsed.read_untracked().contains(&id);
let on_toggle = move |ev: leptos::ev::Event| {
let is_open = event_target::<leptos::web_sys::Element>(&ev).has_attribute("open");
collapsed.update_untracked(|set| {
if is_open {
set.remove(&id);
} else {
set.insert(id);
}
});
};
let name = project.name.clone();
let confirm_remove = move |_| {
let message =
format!("Retirer le projet « {name} » ? Les fichiers de log ne sont pas modifiés.");
if window().confirm_with_message(&message).unwrap_or(false) {
remove.dispatch(RemoveProject { project_id: id });
}
};
let mut files = project.files;
sort_files(&mut files, sort);
let empty = files.is_empty();
view! {
<details open=open on:toggle=on_toggle class="group">
<summary class="flex cursor-pointer items-center gap-2 rounded px-1 py-1 hover:bg-zinc-800">
<span class="flex-1 truncate font-medium" title=project.root_path.clone()>
{project.name.clone()}
</span>
<UnreadBadge count=project.unread />
<Show when=move || { project.unread > 0 }>
<button
class=SMALL_BUTTON
title="Tout marquer comme lu"
on:click=move |ev| {
ev.prevent_default();
mark_all.dispatch(MarkAllRead { project_id: Some(id) });
}
>
"✓"
</button>
</Show>
<button
class=SMALL_BUTTON
title="Retirer le projet"
on:click=move |ev| {
ev.prevent_default();
confirm_remove(ev);
}
>
"✕"
</button>
</summary>
{project.error.map(|e| view! { <p class="px-1 text-xs text-red-400">{e}</p> })}
{empty.then(|| view! { <p class="px-3 py-1 text-xs text-zinc-500">"Aucun fichier de log pour l'instant."</p> })}
<ul class="mt-1 flex flex-col">
{files
.into_iter()
.map(|file| {
let age = file.modified.map(|m| relative_age(now - m));
let tooltip = match &age {
Some(age) => {
format!("{} — {} — modifié {age}", file.relative_path, human_size(file.size))
}
None => format!("{} — {}", file.relative_path, human_size(file.size)),
};
// Trié par date, l'ancienneté est plus utile que la taille.
let detail = match (sort, age) {
(FileSort::Modified, Some(age)) => age,
_ => human_size(file.size),
};
let label_class = if file.missing {
"flex-1 truncate line-through text-zinc-500"
} else {
"flex-1 truncate"
};
view! {
<li>
<A
href=format!("/files/{}", file.id)
attr:class="flex items-center gap-2 rounded py-1 pl-4 pr-1 text-sm text-zinc-300 hover:bg-zinc-800 aria-[current=page]:bg-zinc-800 aria-[current=page]:text-white"
>
<span class=label_class title=tooltip>
{file.relative_path.clone()}
</span>
{file.missing.then(|| view! { <span class="text-xs text-zinc-500">"manquant"</span> })}
{file
.error
.clone()
.map(|e| view! { <span class="text-xs text-amber-400" title=e>"⚠"</span> })}
<span class="shrink-0 text-xs text-zinc-500">{detail}</span>
<UnreadBadge count=file.unread />
</A>
</li>
}
})
.collect_view()}
</ul>
</details>
}
}
#[component]
fn HomePage() -> impl IntoView {
view! {
<div class="mx-auto max-w-xl p-10 text-zinc-600 dark:text-zinc-400">
<h1 class="mb-4 text-2xl font-semibold text-zinc-900 dark:text-zinc-100">
"Lara Logs Reader"
</h1>
<p class="mb-2">
"Ajoutez un projet Laravel avec son chemin dans la barre latérale : tous les fichiers de "
<code>"storage/logs"</code> " sont suivis."
</p>
<p>
"Les nouveaux logs sont signalés par l'icône de l'onglet, même quand il est en arrière-plan. Choisissez un fichier pour les lire."
</p>
</div>
}
}
fn all_levels() -> Vec<String> {
LEVELS
.iter()
.chain([&UNKNOWN_LEVEL])
.map(|l| l.to_string())
.collect()
}
#[component]
fn FileView() -> impl IntoView {
let live = expect_context::<Live>();
let params = use_params_map();
let file_id = Memo::new(move |_| params.read().get("id").and_then(|s| s.parse::<i64>().ok()));
let pages = RwSignal::new(1u32);
let levels = RwSignal::new(all_levels());
let query = RwSignal::new(String::new());
// Curseur de lecture à l'ouverture du fichier : les entrées au-delà sont surlignées.
let highlight_from = RwSignal::new(None::<(i64, u64)>);
// Niveaux présents dans le fichier affiché. Tenu à part de la ressource : la barre de
// filtres reste en place (et la recherche garde le focus) pendant les rafraîchissements.
let present_levels = RwSignal::new(None::<(i64, Vec<String>)>);
Effect::watch(
move || file_id.get(),
move |_, _, _| {
pages.set(1);
levels.set(all_levels());
query.set(String::new());
},
false,
);
let entries = Resource::new(
move || {
(
file_id.get(),
pages.get(),
levels.get(),
query.get(),
live.refresh.get(),
)
},
|(id, pages, levels, query, _)| async move {
match id {
Some(id) => read_entries(id, pages * PAGE_SIZE, levels, query).await,
None => Err(ServerFnError::new("Fichier introuvable.")),
}
},
);
// Consulter un fichier le marque comme lu, si l'onglet est visible.
let mark = ServerAction::<MarkRead>::new();
Effect::watch(
move || mark.version().get(),
move |_, _, _| live.bump(),
false,
);
Effect::new(move |_| {
if let Some(Ok(page)) = entries.get() {
present_levels.set(Some((page.file_id, page.levels.clone())));
if highlight_from.get_untracked().map(|(id, _)| id) != Some(page.file_id) {
highlight_from.set(Some((page.file_id, page.read_offset)));
}
if page.scan_offset > page.read_offset && page_visible() {
mark.dispatch(MarkRead {
file_id: page.file_id,
up_to: page.scan_offset,
});
}
}
});
let toggle_level = move |level: &'static str| {
levels.update(|selected| {
if let Some(i) = selected.iter().position(|l| l == level) {
selected.remove(i);
} else {
selected.push(level.to_string());
}
});
pages.set(1);
};
// Double-clic : n'afficher que ce niveau ; s'il est déjà le seul, tout réafficher.
// Les deux clics qui précèdent le double-clic ont coché puis décoché la case : sans effet.
let solo_level = move |level: &'static str| {
levels.update(|selected| {
*selected = if selected.len() == 1 && selected[0] == level {
all_levels()
} else {
vec![level.to_string()]
};
});
pages.set(1);
};
view! {
<div class="flex flex-col gap-4 p-6">
<div class="flex flex-wrap items-center gap-3 text-sm">
{LEVELS
.iter()
.chain([&UNKNOWN_LEVEL])
.map(|level| {
let level: &'static str = level;
// Disponible tant que le fichier courant n'est pas encore chargé.
let available = move || {
present_levels
.read()
.as_ref()
.filter(|(id, _)| Some(*id) == file_id.get())
.is_none_or(|(_, present)| present.iter().any(|l| l == level))
};
view! {
<label
class=move || {
if available() {
"flex cursor-pointer select-none items-center gap-1"
} else {
"flex cursor-not-allowed items-center gap-1 opacity-40 grayscale"
}
}
title=move || {
if available() {
"Double-cliquer pour n'afficher que ce niveau"
} else {
"Aucune entrée de ce niveau dans ce fichier"
}
}
on:dblclick=move |_| {
if available() {
solo_level(level);
}
}
>
<input
type="checkbox"
disabled=move || !available()
prop:checked=move || levels.read().iter().any(|l| l == level)
on:change=move |_| toggle_level(level)
/>
<span class=level_badge(level)>{level}</span>
</label>
}
})
.collect_view()}
<input
type="search"
placeholder="Rechercher…"
aria-label="Rechercher dans les entrées"
class="ml-auto w-64 rounded-md border border-zinc-300 bg-white px-2 py-1 dark:border-zinc-700 dark:bg-zinc-900"
prop:value=move || query.get()
on:change=move |ev| {
query.set(event_target_value(&ev));
pages.set(1);
}
/>
</div>
<Transition fallback=|| view! { <p>"Chargement…"</p> }>
{move || {
entries
.get()
.map(|result| match result {
Err(e) => {
view! { <p class="text-red-600">{error_message(&e)}</p> }.into_any()
}
Ok(page) => {
let highlight = highlight_from
.get()
.filter(|(id, _)| *id == page.file_id)
.map(|(_, offset)| offset);
view! { <EntriesList page highlight pages /> }.into_any()
}
})
}}
</Transition>
</div>
}
}
#[component]
fn EntriesList(page: EntriesPage, highlight: Option<u64>, pages: RwSignal<u32>) -> impl IntoView {
let empty = page.entries.is_empty();
view! {
<h1 class="text-lg font-semibold">
{page.project_name} <span class="text-zinc-400">" / "</span> {page.relative_path}
</h1>
{empty.then(|| view! { <p class="text-zinc-500">"Aucune entrée."</p> })}
<ul class="flex flex-col gap-2">
{page
.entries
.into_iter()
.map(|entry| {
let new = highlight.is_some_and(|offset| entry.start >= offset);
view! { <EntryRow entry new /> }
})
.collect_view()}
</ul>
{page
.has_more
.then(|| {
view! {
<button
class="self-center rounded-md border border-zinc-300 px-4 py-1.5 text-sm hover:bg-zinc-100 dark:border-zinc-700 dark:hover:bg-zinc-800"
on:click=move |_| pages.update(|p| *p += 1)
>
"Charger plus"
</button>
}
})}
}
}
fn level_badge(level: &str) -> &'static str {
match level {
"DEBUG" => "rounded px-1.5 text-xs font-semibold bg-zinc-200 text-zinc-700",
"INFO" => "rounded px-1.5 text-xs font-semibold bg-sky-100 text-sky-800",
"NOTICE" => "rounded px-1.5 text-xs font-semibold bg-teal-100 text-teal-800",
"WARNING" => "rounded px-1.5 text-xs font-semibold bg-amber-100 text-amber-800",
"ERROR" => "rounded px-1.5 text-xs font-semibold bg-red-100 text-red-800",
"CRITICAL" | "ALERT" | "EMERGENCY" => {
"rounded px-1.5 text-xs font-semibold bg-red-700 text-white"
}
_ => "rounded px-1.5 text-xs font-semibold bg-zinc-100 text-zinc-500",
}
}
#[component]
fn EntryRow(entry: Entry, new: bool) -> impl IntoView {
let class = if new {
"rounded-md border border-amber-300 bg-amber-50 p-3 dark:border-amber-700 dark:bg-amber-950"
} else {
"rounded-md border border-zinc-200 bg-white p-3 dark:border-zinc-800 dark:bg-zinc-900"
};
let message_class = "font-mono text-sm whitespace-pre-wrap break-all";
let body = if entry.details.is_empty() {
view! { <p class=message_class>{entry.message}</p> }.into_any()
} else {
view! {
<details>
<summary class=format!("cursor-pointer {message_class}")>{entry.message}</summary>
<pre class="mt-2 overflow-x-auto text-xs text-zinc-600 dark:text-zinc-400">{entry.details}</pre>
</details>
}
.into_any()
};
view! {
<li class=class>
<div class="mb-1 flex items-center gap-2">
<span class="font-mono text-xs text-zinc-500">{entry.logged_at}</span>
<span class=level_badge(&entry.level)>{entry.level.clone()}</span>
<span class="text-xs text-zinc-500">{entry.env}</span>
{new.then(|| view! { <span class="text-xs font-semibold text-amber-600">"nouveau"</span> })}
</div>
{body}
{entry
.truncated
.then(|| {
view! {
<p class="mt-1 text-xs text-amber-700">
{format!("Entrée tronquée ({}).", human_size(entry.size))}
</p>
}
})}
</li>
}
}
#[component]
fn SettingsPage() -> impl IntoView {
let SettingsCtx { settings, save } = expect_context::<SettingsCtx>();
view! {
<div class="mx-auto max-w-md p-10">
<h1 class="mb-6 text-2xl font-semibold">"Réglages"</h1>
<Transition fallback=|| view! { <p>"Chargement…"</p> }>
{move || {
settings
.get()
.map(|result| {
let current = result
.map(|s| s.refresh_interval_seconds)
.unwrap_or(DEFAULT_INTERVAL);
view! {
<ActionForm action=save attr:class="flex flex-col gap-3">
<label class="flex flex-col gap-1 text-sm">
"Intervalle de rafraîchissement (secondes, 1 à 3600)"
<input
name="seconds"
inputmode="numeric"
value=current.to_string()
class="rounded-md border border-zinc-300 bg-white px-2 py-1.5 dark:border-zinc-700 dark:bg-zinc-900"
/>
</label>
<button
type="submit"
class=BUTTON
disabled=move || save.pending().get()
>
"Enregistrer"
</button>
</ActionForm>
}
})
}}
</Transition>
{move || {
save.value()
.get()
.map(|result| match result {
Ok(s) => {
view! {
<p class="mt-3 text-sm text-green-700">
{format!(
"Enregistré : rafraîchissement toutes les {} s.",
s.refresh_interval_seconds,
)}
</p>
}
.into_any()
}
Err(e) => {
view! { <p class="mt-3 text-sm text-red-600">{error_message(&e)}</p> }
.into_any()
}
})
}}
</div>
}
}
+17
View File
@@ -0,0 +1,17 @@
pub mod api;
pub mod app;
pub mod model;
#[cfg(feature = "ssr")]
pub mod parser;
#[cfg(feature = "ssr")]
pub mod scanner;
#[cfg(feature = "ssr")]
pub mod server;
#[cfg(feature = "hydrate")]
#[wasm_bindgen::prelude::wasm_bindgen]
pub fn hydrate() {
use crate::app::*;
console_error_panic_hook::set_once();
leptos::mount::hydrate_body(App);
}
+75
View File
@@ -0,0 +1,75 @@
#[cfg(feature = "ssr")]
#[tokio::main]
async fn main() {
use axum::Router;
use lara_logs_reader::{
app::{App, shell},
scanner::Scanner,
server,
};
use leptos::{logging::log, prelude::*};
use leptos_axum::{LeptosRoutes, generate_route_list};
use std::{net::SocketAddr, process::exit, sync::Arc};
let database_url = std::env::var("LLR_DATABASE_URL")
.unwrap_or_else(|_| "sqlite://./lara_logs_reader.sqlite?mode=rwc".into());
let pool = match server::connect_db(&database_url).await {
Ok(pool) => pool,
Err(e) => {
eprintln!("Impossible d'ouvrir la base de données `{database_url}` : {e}");
exit(1);
}
};
let scanner = Arc::new(Scanner::default());
let conf = get_configuration(None).unwrap();
let mut leptos_options = conf.leptos_options;
if let Ok(addr) = std::env::var("LLR_ADDR") {
match addr.parse::<SocketAddr>() {
Ok(addr) => leptos_options.site_addr = addr,
Err(e) => {
eprintln!("LLR_ADDR invalide `{addr}` : {e}");
exit(1);
}
}
}
let addr = leptos_options.site_addr;
let routes = generate_route_list(App);
let app = Router::new()
.leptos_routes_with_context(
&leptos_options,
routes,
{
let pool = pool.clone();
let scanner = scanner.clone();
move || {
provide_context(pool.clone());
provide_context(scanner.clone());
}
},
{
let leptos_options = leptos_options.clone();
move || shell(leptos_options.clone())
},
)
.fallback(leptos_axum::file_and_error_handler(shell))
.with_state(leptos_options);
let listener = match tokio::net::TcpListener::bind(&addr).await {
Ok(listener) => listener,
Err(e) => {
eprintln!("Impossible d'écouter sur `{addr}` : {e}");
exit(1);
}
};
log!("listening on http://{}", &addr);
axum::serve(listener, app.into_make_service())
.await
.unwrap();
}
#[cfg(not(feature = "ssr"))]
pub fn main() {
// Pas de `main` côté client : voir `hydrate()` dans lib.rs.
}
+313
View File
@@ -0,0 +1,313 @@
//! Types partagés entre le serveur et le client, et règles pures (sans E/S).
use serde::{Deserialize, Serialize};
pub const MIN_INTERVAL: u32 = 1;
pub const MAX_INTERVAL: u32 = 3600;
pub const DEFAULT_INTERVAL: u32 = 5;
/// Nombre d'entrées chargées par page dans la vue d'un fichier.
pub const PAGE_SIZE: u32 = 50;
/// Nombre maximal d'entrées renvoyées par un appel à `read_entries`.
pub const MAX_ENTRIES_LIMIT: u32 = 2000;
/// Au-delà, le contenu d'une entrée est tronqué à l'affichage.
pub const MAX_ENTRY_BYTES: u64 = 1024 * 1024;
/// Niveaux PSR-3, plus `UNKNOWN` pour le texte qui précède la première ligne d'en-tête.
pub const LEVELS: [&str; 8] = [
"DEBUG",
"INFO",
"NOTICE",
"WARNING",
"ERROR",
"CRITICAL",
"ALERT",
"EMERGENCY",
];
pub const UNKNOWN_LEVEL: &str = "UNKNOWN";
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Summary {
pub total: u64,
/// Heure du serveur (secondes Unix), pour afficher l'ancienneté des fichiers.
pub now: i64,
pub projects: Vec<ProjectSummary>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ProjectSummary {
pub id: i64,
pub name: String,
pub root_path: String,
pub error: Option<String>,
pub unread: u64,
pub files: Vec<FileSummary>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct FileSummary {
pub id: i64,
pub relative_path: String,
pub size: u64,
/// Date de dernière modification (secondes Unix).
pub modified: Option<i64>,
pub missing: bool,
pub error: Option<String>,
pub unread: u64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EntriesPage {
pub file_id: i64,
pub project_name: String,
pub relative_path: String,
pub entries: Vec<Entry>,
pub has_more: bool,
/// Fin de la dernière entrée complète indexée.
pub scan_offset: u64,
/// Curseur de lecture au moment de l'appel.
pub read_offset: u64,
/// Niveaux présents dans le fichier, indépendamment des filtres.
pub levels: Vec<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Entry {
pub start: u64,
pub logged_at: String,
pub level: String,
pub env: String,
/// Première ligne, sans l'en-tête `[date] env.LEVEL: `.
pub message: String,
/// Lignes suivantes (stack trace…).
pub details: String,
/// Taille réelle de l'entrée en octets.
pub size: u64,
pub truncated: bool,
}
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Settings {
pub refresh_interval_seconds: u32,
pub file_sort: FileSort,
}
/// Ordre des fichiers dans la liste d'un projet.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum FileSort {
/// Par chemin, ordre alphabétique.
#[default]
Name,
/// Le plus récemment modifié en premier.
Modified,
}
impl FileSort {
pub fn as_str(self) -> &'static str {
match self {
FileSort::Name => "name",
FileSort::Modified => "modified",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"name" => Some(FileSort::Name),
"modified" => Some(FileSort::Modified),
_ => None,
}
}
}
/// Trie les fichiers d'un projet. À date égale (ou inconnue), l'ordre alphabétique départage ;
/// les fichiers sans date viennent en dernier.
pub fn sort_files(files: &mut [FileSummary], sort: FileSort) {
match sort {
FileSort::Name => files.sort_by(|a, b| a.relative_path.cmp(&b.relative_path)),
FileSort::Modified => files.sort_by(|a, b| {
b.modified
.cmp(&a.modified)
.then_with(|| a.relative_path.cmp(&b.relative_path))
}),
}
}
/// Ancienneté lisible : « à l'instant », « il y a 5 min », « il y a 3 h », « il y a 2 j ».
pub fn relative_age(seconds: i64) -> String {
match seconds.max(0) {
s if s < 60 => "à l'instant".to_string(),
s if s < 3600 => format!("il y a {} min", s / 60),
s if s < 86_400 => format!("il y a {} h", s / 3600),
s => format!("il y a {} j", s / 86_400),
}
}
/// Valide l'intervalle saisi par l'utilisateur.
pub fn parse_interval(input: &str) -> Result<u32, String> {
input
.trim()
.parse::<u32>()
.ok()
.filter(|s| (MIN_INTERVAL..=MAX_INTERVAL).contains(s))
.ok_or_else(|| {
format!(
"L'intervalle doit être un entier entre {MIN_INTERVAL} et {MAX_INTERVAL} secondes."
)
})
}
/// État affiché par le favicon.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum FaviconState {
Idle,
Unread(u64),
Offline,
}
/// Favicon SVG correspondant à l'état, sous forme d'URL `data:`.
pub fn favicon_data_url(state: FaviconState) -> String {
let badge = match state {
FaviconState::Idle | FaviconState::Unread(0) => String::new(),
FaviconState::Unread(n) => {
let label = if n > 99 {
"99+".to_string()
} else {
n.to_string()
};
let font = match label.len() {
1 => 18,
2 => 15,
_ => 11,
};
format!(
"<circle cx='21' cy='11' r='11' fill='#dc2626'/>\
<text x='21' y='11' dy='.35em' text-anchor='middle' font-family='Arial,sans-serif' \
font-weight='bold' font-size='{font}' fill='#fff'>{label}</text>"
)
}
FaviconState::Offline => "<circle cx='21' cy='11' r='11' fill='#71717a'/>\
<text x='21' y='11' dy='.35em' text-anchor='middle' font-family='Arial,sans-serif' \
font-weight='bold' font-size='18' fill='#fff'>!</text>"
.to_string(),
};
let svg = format!(
"<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 32 32'>\
<rect x='2' y='4' width='24' height='26' rx='4' fill='#18181b'/>\
<rect x='6' y='10' width='16' height='2.5' rx='1' fill='#f87171'/>\
<rect x='6' y='16' width='12' height='2.5' rx='1' fill='#e4e4e7'/>\
<rect x='6' y='22' width='14' height='2.5' rx='1' fill='#e4e4e7'/>\
{badge}</svg>"
);
let mut url = String::from("data:image/svg+xml,");
for c in svg.chars() {
match c {
'#' => url.push_str("%23"),
'<' => url.push_str("%3C"),
'>' => url.push_str("%3E"),
'%' => url.push_str("%25"),
_ => url.push(c),
}
}
url
}
/// Titre de l'onglet selon le nombre de non-lus.
pub fn page_title(unread: u64) -> String {
if unread == 0 {
"Lara Logs Reader".to_string()
} else {
format!("({unread}) Lara Logs Reader")
}
}
/// Taille lisible (o, Kio, Mio, Gio).
pub fn human_size(bytes: u64) -> String {
const UNITS: [&str; 4] = ["o", "Kio", "Mio", "Gio"];
let mut size = bytes as f64;
let mut unit = 0;
while size >= 1024.0 && unit < UNITS.len() - 1 {
size /= 1024.0;
unit += 1;
}
if unit == 0 {
format!("{bytes} o")
} else {
format!("{size:.1} {}", UNITS[unit])
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn interval_bounds() {
assert_eq!(parse_interval("5"), Ok(5));
assert_eq!(parse_interval(" 3600 "), Ok(3600));
for bad in ["0", "3601", "-5", "abc", "", "1.5"] {
assert!(parse_interval(bad).is_err(), "{bad:?} devrait être refusé");
}
}
#[test]
fn favicon_badge_label() {
let decode = |s: String| s.replace("%3C", "<").replace("%3E", ">");
assert!(!decode(favicon_data_url(FaviconState::Idle)).contains("<text"));
assert!(!decode(favicon_data_url(FaviconState::Unread(0))).contains("<text"));
assert!(decode(favicon_data_url(FaviconState::Unread(3))).contains(">3</text>"));
assert!(decode(favicon_data_url(FaviconState::Unread(150))).contains(">99+</text>"));
assert!(decode(favicon_data_url(FaviconState::Offline)).contains(">!</text>"));
assert!(!favicon_data_url(FaviconState::Unread(3)).contains('#'));
}
fn file(name: &str, modified: Option<i64>) -> FileSummary {
FileSummary {
id: 0,
relative_path: name.to_string(),
size: 0,
modified,
missing: false,
error: None,
unread: 0,
}
}
#[test]
fn file_sorting() {
let mut files = vec![
file("b.log", Some(100)),
file("a.log", Some(50)),
file("z.log", None),
file("c.log", Some(100)),
];
sort_files(&mut files, FileSort::Modified);
let names: Vec<_> = files.iter().map(|f| f.relative_path.as_str()).collect();
assert_eq!(names, ["b.log", "c.log", "a.log", "z.log"]);
sort_files(&mut files, FileSort::Name);
let names: Vec<_> = files.iter().map(|f| f.relative_path.as_str()).collect();
assert_eq!(names, ["a.log", "b.log", "c.log", "z.log"]);
}
#[test]
fn sort_round_trip() {
for sort in [FileSort::Name, FileSort::Modified] {
assert_eq!(FileSort::parse(sort.as_str()), Some(sort));
}
assert_eq!(FileSort::parse("size"), None);
}
#[test]
fn ages() {
assert_eq!(relative_age(-3), "à l'instant");
assert_eq!(relative_age(59), "à l'instant");
assert_eq!(relative_age(300), "il y a 5 min");
assert_eq!(relative_age(3 * 3600), "il y a 3 h");
assert_eq!(relative_age(2 * 86_400 + 5), "il y a 2 j");
}
#[test]
fn title() {
assert_eq!(page_title(0), "Lara Logs Reader");
assert_eq!(page_title(150), "(150) Lara Logs Reader");
}
}
+251
View File
@@ -0,0 +1,251 @@
//! Découpage d'un fichier de log Laravel (format Monolog par défaut) en entrées.
use crate::model::UNKNOWN_LEVEL;
use regex::Regex;
use std::{io::BufRead, sync::LazyLock};
static HEADER: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r"^\[(\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2})?)\] (\S+?)\.([A-Za-z]+): ?",
)
.unwrap()
});
#[derive(Debug, PartialEq)]
pub struct Header<'a> {
pub logged_at: &'a str,
pub env: &'a str,
pub level: String,
/// Le texte qui suit l'en-tête sur la même ligne.
pub message: &'a str,
}
/// Reconnaît une ligne d'en-tête `[YYYY-MM-DD HH:MM:SS] env.LEVEL: message`.
pub fn parse_header(line: &str) -> Option<Header<'_>> {
let caps = HEADER.captures(line)?;
Some(Header {
logged_at: caps.get(1).unwrap().as_str(),
env: caps.get(2).unwrap().as_str(),
level: caps.get(3).unwrap().as_str().to_ascii_uppercase(),
message: &line[caps.get(0).unwrap().end()..],
})
}
/// Une entrée repérée dans le fichier, sans son contenu.
#[derive(Clone, Debug, PartialEq)]
pub struct IndexedEntry {
pub start: u64,
pub end: u64,
pub logged_at: String,
pub level: String,
}
/// Résultat de l'indexation d'une portion de fichier.
#[derive(Debug, PartialEq)]
pub struct Indexed {
pub entries: Vec<IndexedEntry>,
/// Fin de la dernière entrée complète : le prochain scan reprendra ici.
pub offset: u64,
}
/// Indexe les entrées complètes lues depuis `reader`, positionné à l'octet `start` du fichier.
///
/// Le fichier est lu ligne par ligne, sans être chargé en mémoire. Une entrée est complète
/// quand une ligne d'en-tête la suit. La dernière entrée du fichier ne l'est que si elle se
/// termine par `\n` **et** que le fichier est `settled` (non modifié depuis un court instant) :
/// sinon on pourrait lire une stack trace à moitié écrite. Une entrée incomplète n'est pas
/// indexée : `offset` s'arrête à son début pour qu'elle soit relue au scan suivant.
/// `fallback_ts` horodate le texte qui ne commence pas par une ligne d'en-tête.
pub fn index_entries(
mut reader: impl BufRead,
start: u64,
fallback_ts: &str,
settled: bool,
) -> std::io::Result<Indexed> {
let mut entries = Vec::new();
let mut current: Option<IndexedEntry> = None;
let mut pos = start;
let mut buf = Vec::new();
loop {
buf.clear();
let n = reader.read_until(b'\n', &mut buf)? as u64;
if n == 0 {
break;
}
if buf.last() != Some(&b'\n') {
// Ligne partielle en fin de fichier. Si elle commence par `[`, c'est
// vraisemblablement une nouvelle entrée : la précédente est donc complète.
// Sinon, c'est la suite de l'entrée courante, qui n'est pas encore finie.
if buf.first() != Some(&b'[')
&& let Some(cur) = current.take()
{
pos = cur.start;
}
break;
}
let line = String::from_utf8_lossy(&buf);
if let Some(header) = parse_header(&line) {
if let Some(mut cur) = current.take() {
cur.end = pos;
entries.push(cur);
}
current = Some(IndexedEntry {
start: pos,
end: 0,
logged_at: header.logged_at.to_string(),
level: header.level,
});
} else if current.is_none() {
current = Some(IndexedEntry {
start: pos,
end: 0,
logged_at: fallback_ts.to_string(),
level: UNKNOWN_LEVEL.to_string(),
});
}
pos += n;
}
if let Some(mut cur) = current {
if settled {
cur.end = pos;
entries.push(cur);
} else {
pos = cur.start;
}
}
Ok(Indexed {
entries,
offset: pos,
})
}
/// Découpe le texte d'une entrée en (env, message, détails).
pub fn split_entry(content: &str) -> (String, String, String) {
let content = content.trim_end_matches(['\n', '\r']);
let (first, rest) = content.split_once('\n').unwrap_or((content, ""));
let first = first.trim_end_matches('\r');
match parse_header(first) {
Some(h) => (h.env.to_string(), h.message.to_string(), rest.to_string()),
None => (String::new(), first.to_string(), rest.to_string()),
}
}
#[cfg(test)]
mod tests {
use super::*;
fn index(s: &str) -> Indexed {
index_entries(s.as_bytes(), 0, "2026-01-01 00:00:00", true).unwrap()
}
#[test]
fn header_variants() {
let h = parse_header("[2026-10-21 10:00:00] local.ERROR: boom\n").unwrap();
assert_eq!(h.logged_at, "2026-10-21 10:00:00");
assert_eq!(h.env, "local");
assert_eq!(h.level, "ERROR");
assert_eq!(h.message, "boom\n");
assert!(parse_header("[2026-10-21T10:00:00.123456+02:00] production.info: x").is_some());
assert!(parse_header("[2026-10-21 10:00:00] local.INFO:").is_some());
assert!(parse_header("#0 /app/vendor/foo.php(12): bar()").is_none());
assert!(parse_header("[2026-10-21] local.INFO: x").is_none());
}
#[test]
fn multiline_entries() {
let log = "[2026-10-21 10:00:00] local.ERROR: boom\n#0 a\n#1 b\n[2026-10-21 10:00:01] local.INFO: ok\n";
let r = index(log);
assert_eq!(r.entries.len(), 2);
assert_eq!(r.entries[0].start, 0);
assert_eq!(r.entries[0].end, r.entries[1].start);
assert_eq!(r.entries[1].level, "INFO");
assert_eq!(r.entries[1].end, log.len() as u64);
assert_eq!(r.offset, log.len() as u64);
}
#[test]
fn partial_header_line_is_not_indexed() {
let done = "[2026-10-21 10:00:00] local.INFO: a\n";
let r = index(&format!("{done}[2026-10-21 10:00:01] local.INFO: b"));
assert_eq!(r.entries.len(), 1);
assert_eq!(r.offset, done.len() as u64);
}
#[test]
fn partial_continuation_keeps_entry_open() {
let first = "[2026-10-21 10:00:00] local.INFO: a\n";
let r = index(&format!(
"{first}[2026-10-21 10:00:01] local.ERROR: b\n#0 trace"
));
assert_eq!(r.entries.len(), 1);
assert_eq!(r.offset, first.len() as u64);
}
#[test]
fn last_entry_waits_until_settled() {
let first = "[2026-10-21 10:00:00] local.INFO: a\n";
let log = format!("{first}[2026-10-21 10:00:01] local.ERROR: b\n#0 trace\n");
let r = index_entries(log.as_bytes(), 0, "x", false).unwrap();
assert_eq!(r.entries.len(), 1);
assert_eq!(r.offset, first.len() as u64);
}
#[test]
fn text_before_first_header_is_unknown() {
let r = index("garbage\n[2026-10-21 10:00:00] local.INFO: a\n");
assert_eq!(r.entries.len(), 2);
assert_eq!(r.entries[0].level, UNKNOWN_LEVEL);
assert_eq!(r.entries[0].logged_at, "2026-01-01 00:00:00");
}
#[test]
fn invalid_utf8_is_tolerated() {
let mut bytes = b"[2026-10-21 10:00:00] local.INFO: caf".to_vec();
bytes.extend_from_slice(&[0xff, 0xfe, b'\n']);
let r = index_entries(&bytes[..], 0, "x", true).unwrap();
assert_eq!(r.entries.len(), 1);
assert_eq!(r.offset, bytes.len() as u64);
}
#[test]
fn incremental_from_offset() {
let a = "[2026-10-21 10:00:00] local.INFO: a\n";
let b = "[2026-10-21 10:00:01] local.INFO: b\n";
let r = index_entries(b.as_bytes(), a.len() as u64, "x", true).unwrap();
assert_eq!(r.entries[0].start, a.len() as u64);
assert_eq!(r.offset, (a.len() + b.len()) as u64);
}
/// Quel que soit le découpage des écritures, l'indexation incrémentale aboutit au même
/// résultat que l'indexation d'un seul coup (pas de doublon ni d'entrée coupée).
#[test]
fn chunked_writes_match_full_index() {
let log = "[2026-10-21 10:00:00] local.ERROR: boom\n#0 a\n#1 b\n\
[2026-10-21 10:00:01] local.INFO: ok\n\
[2026-10-21 10:00:02] local.WARNING: w\nmore\n";
let full = index(log);
for step in 1..log.len() {
let mut offset = 0u64;
let mut entries = Vec::new();
let mut written = 0;
while written < log.len() {
written = (written + step).min(log.len());
let visible = &log.as_bytes()[offset as usize..written];
let settled = written == log.len();
let r = index_entries(visible, offset, "x", settled).unwrap();
entries.extend(r.entries);
offset = r.offset;
}
assert_eq!(entries, full.entries, "découpage par {step} octets");
}
}
#[test]
fn split() {
let (env, msg, details) =
split_entry("[2026-10-21 10:00:00] local.ERROR: boom\n#0 a\n#1 b\n");
assert_eq!(env, "local");
assert_eq!(msg, "boom");
assert_eq!(details, "#0 a\n#1 b");
}
}
+612
View File
@@ -0,0 +1,612 @@
//! Découverte des fichiers de log d'un projet et indexation incrémentale de leurs entrées.
use crate::{
parser::{self, Indexed},
server::{format_ts, now},
};
use sqlx::{QueryBuilder, SqlitePool};
use std::{
collections::HashMap,
fs::{self, File, Metadata},
io::{BufReader, ErrorKind, Read, Seek, SeekFrom},
path::{Path, PathBuf},
time::{Duration, Instant},
};
use tokio::sync::Mutex;
/// Délai sans modification au-delà duquel la dernière entrée d'un fichier est jugée complète.
pub const SETTLE_DELAY: Duration = Duration::from_secs(1);
/// Deux scans complets rapprochés de moins de ce délai n'en font qu'un (plusieurs onglets).
const MIN_SCAN_GAP: Duration = Duration::from_millis(500);
pub fn logs_dir(root: &Path) -> PathBuf {
root.join("storage").join("logs")
}
/// Valide le chemin saisi pour un nouveau projet et renvoie sa forme canonique.
pub fn validate_project_path(input: &str) -> Result<PathBuf, String> {
let input = input.trim();
if input.is_empty() {
return Err("Veuillez saisir un chemin.".into());
}
let expanded = match input.strip_prefix('~') {
Some(rest) if rest.is_empty() || rest.starts_with('/') => {
format!("{}{rest}", std::env::var("HOME").unwrap_or_default())
}
_ => input.to_string(),
};
let path = Path::new(&expanded)
.canonicalize()
.map_err(|e| match e.kind() {
ErrorKind::NotFound => format!("Le chemin « {input} » n'existe pas."),
ErrorKind::PermissionDenied => format!("Accès refusé à « {input} »."),
_ => format!("Le chemin « {input} » est inaccessible : {e}."),
})?;
if !path.is_dir() {
return Err(format!("« {input} » n'est pas un répertoire."));
}
if !path.join("artisan").is_file() {
return Err(format!(
"« {input} » ne semble pas être un projet Laravel (fichier artisan introuvable)."
));
}
let logs = logs_dir(&path);
if !logs.is_dir() {
return Err(format!(
"Répertoire storage/logs introuvable dans « {input} »."
));
}
if let Err(e) = fs::read_dir(&logs) {
return Err(match e.kind() {
ErrorKind::PermissionDenied => format!("Accès refusé à « {} ».", logs.display()),
_ => format!("« {} » est illisible : {e}.", logs.display()),
});
}
Ok(path)
}
/// Fichiers `*.log` sous `dir` (récursivement), avec leur chemin relatif (séparateur `/`).
///
/// Les fichiers et dossiers cachés sont ignorés. Un lien symbolique n'est retenu que s'il
/// pointe vers un fichier situé lui aussi sous `dir` ; les liens vers des dossiers ne sont
/// pas suivis (pas de boucle possible).
pub fn discover(dir: &Path) -> std::io::Result<Vec<(String, PathBuf)>> {
let base = dir.canonicalize()?;
let mut found = Vec::new();
let mut stack = vec![base.clone()];
while let Some(current) = stack.pop() {
let entries = match fs::read_dir(&current) {
Ok(entries) => entries,
Err(e) if current == base => return Err(e),
Err(_) => continue,
};
for entry in entries.flatten() {
let name = entry.file_name();
let name = name.to_string_lossy();
if name.starts_with('.') {
continue;
}
let path = entry.path();
let Ok(file_type) = entry.file_type() else {
continue;
};
if file_type.is_dir() {
stack.push(path);
continue;
}
let is_file = if file_type.is_symlink() {
path.canonicalize()
.is_ok_and(|target| target.starts_with(&base) && target.is_file())
} else {
file_type.is_file()
};
if is_file && name.ends_with(".log") {
let relative = path
.strip_prefix(&base)
.unwrap_or(&path)
.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
found.push((relative, path));
}
}
}
found.sort();
Ok(found)
}
/// Identité physique d'un fichier, pour détecter qu'il a été remplacé (rotation).
fn identity(meta: &Metadata) -> Option<String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
Some(format!("{}:{}", meta.dev(), meta.ino()))
}
#[cfg(not(unix))]
{
let _ = meta;
None
}
}
/// Ce que la base sait d'un fichier avant le scan.
#[derive(Clone, Debug)]
struct Known {
id: i64,
identity: Option<String>,
scan_offset: u64,
missing: bool,
}
#[derive(Debug)]
enum Outcome {
Missing,
Error(String),
Scanned {
size: u64,
modified: Option<i64>,
identity: Option<String>,
/// Le fichier a été tronqué, remplacé ou recréé : on repart de zéro.
reset: bool,
indexed: Indexed,
},
}
/// Lit la partie nouvelle d'un fichier (E/S bloquantes).
fn scan_file(path: &Path, known: &Known) -> Outcome {
let meta = match fs::metadata(path) {
Ok(meta) => meta,
Err(e) if e.kind() == ErrorKind::NotFound => return Outcome::Missing,
Err(e) => return Outcome::Error(e.to_string()),
};
let size = meta.len();
let modified = meta.modified().ok();
let modified_unix = modified
.and_then(|m| m.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs() as i64);
let ident = identity(&meta);
let reset = known.missing
|| size < known.scan_offset
|| (known.identity.is_some() && ident != known.identity);
let from = if reset { 0 } else { known.scan_offset };
if from == size {
return Outcome::Scanned {
size,
modified: modified_unix,
identity: ident,
reset,
indexed: Indexed {
entries: Vec::new(),
offset: from,
},
};
}
let settled = modified
.and_then(|m| m.elapsed().ok())
.is_none_or(|elapsed| elapsed >= SETTLE_DELAY);
let fallback_ts = modified.map(|m| format_ts(m.into())).unwrap_or_else(now);
let read = || -> std::io::Result<Indexed> {
let mut file = File::open(path)?;
file.seek(SeekFrom::Start(from))?;
// Borné à la taille observée : ce qui est écrit pendant la lecture attendra le prochain scan.
let reader = BufReader::with_capacity(64 * 1024, file.take(size - from));
parser::index_entries(reader, from, &fallback_ts, settled)
};
match read() {
Ok(indexed) => Outcome::Scanned {
size,
modified: modified_unix,
identity: ident,
reset,
indexed,
},
Err(e) if e.kind() == ErrorKind::NotFound => Outcome::Missing,
Err(e) => Outcome::Error(e.to_string()),
}
}
/// Enregistre le résultat d'un scan, en une transaction pour un fichier donné.
async fn apply(pool: &SqlitePool, file_id: i64, outcome: Outcome) -> sqlx::Result<()> {
match outcome {
Outcome::Missing => {
sqlx::query(
"UPDATE log_files SET missing_since = COALESCE(missing_since, ?) WHERE id = ?",
)
.bind(now())
.bind(file_id)
.execute(pool)
.await?;
}
Outcome::Error(message) => {
sqlx::query("UPDATE log_files SET last_error = ? WHERE id = ?")
.bind(message)
.bind(file_id)
.execute(pool)
.await?;
}
Outcome::Scanned {
size,
modified,
identity,
reset,
indexed,
} => {
let mut tx = pool.begin().await?;
if reset {
sqlx::query("DELETE FROM log_entries_index WHERE log_file_id = ?")
.bind(file_id)
.execute(&mut *tx)
.await?;
sqlx::query(
"UPDATE read_cursors SET read_offset = 0, updated_at = ? WHERE log_file_id = ?",
)
.bind(now())
.bind(file_id)
.execute(&mut *tx)
.await?;
}
for chunk in indexed.entries.chunks(1000) {
let mut insert = QueryBuilder::new(
"INSERT INTO log_entries_index (log_file_id, start_offset, end_offset, logged_at, level) ",
);
insert.push_values(chunk, |mut row, entry| {
row.push_bind(file_id)
.push_bind(entry.start as i64)
.push_bind(entry.end as i64)
.push_bind(&entry.logged_at)
.push_bind(&entry.level);
});
insert.build().execute(&mut *tx).await?;
}
sqlx::query(
"UPDATE log_files
SET size = ?, modified_at = ?, file_identity = ?, scan_offset = ?,
entries_count = CASE WHEN ? THEN 0 ELSE entries_count END + ?,
missing_since = NULL, last_error = NULL
WHERE id = ?",
)
.bind(size as i64)
.bind(modified)
.bind(identity)
.bind(indexed.offset as i64)
.bind(reset)
.bind(indexed.entries.len() as i64)
.bind(file_id)
.execute(&mut *tx)
.await?;
tx.commit().await?;
}
}
Ok(())
}
/// Découvre et indexe les fichiers d'un projet.
///
/// Avec `mark_existing_read`, les curseurs sont placés en fin de fichier : utilisé à l'ajout
/// du projet, pour que l'historique ne soit pas compté comme non-lu.
async fn scan_project(
pool: &SqlitePool,
project_id: i64,
root: &str,
mark_existing_read: bool,
) -> sqlx::Result<()> {
let root = PathBuf::from(root);
let logs = logs_dir(&root);
let discovered = tokio::task::spawn_blocking(move || {
if !root.is_dir() || !logs.is_dir() {
return Err("Projet introuvable sur le disque.".to_string());
}
discover(&logs).map_err(|e| format!("storage/logs illisible : {e}."))
})
.await
.unwrap_or_else(|e| Err(e.to_string()));
let discovered = match discovered {
Ok(files) => {
sqlx::query("UPDATE projects SET last_error = NULL WHERE id = ?")
.bind(project_id)
.execute(pool)
.await?;
files
}
Err(message) => {
sqlx::query("UPDATE projects SET last_error = ? WHERE id = ?")
.bind(message)
.bind(project_id)
.execute(pool)
.await?;
return Ok(());
}
};
let rows: Vec<(i64, String, Option<String>, i64, bool)> = sqlx::query_as(
"SELECT id, relative_path, file_identity, scan_offset, missing_since IS NOT NULL
FROM log_files WHERE project_id = ?",
)
.bind(project_id)
.fetch_all(pool)
.await?;
let mut known: HashMap<String, Known> = rows
.into_iter()
.map(|(id, rel, identity, offset, missing)| {
(
rel,
Known {
id,
identity,
scan_offset: offset as u64,
missing,
},
)
})
.collect();
for (relative, path) in discovered {
let state = match known.remove(&relative) {
Some(state) => state,
None => {
// Nouveau fichier : tout son contenu est non-lu (curseur à 0).
let ts = now();
let id: i64 = sqlx::query_scalar(
"INSERT INTO log_files (project_id, relative_path, discovered_at)
VALUES (?, ?, ?) RETURNING id",
)
.bind(project_id)
.bind(&relative)
.bind(&ts)
.fetch_one(pool)
.await?;
sqlx::query(
"INSERT INTO read_cursors (log_file_id, read_offset, updated_at) VALUES (?, 0, ?)",
)
.bind(id)
.bind(&ts)
.execute(pool)
.await?;
Known {
id,
identity: None,
scan_offset: 0,
missing: false,
}
}
};
let file_id = state.id;
let outcome = tokio::task::spawn_blocking(move || scan_file(&path, &state))
.await
.unwrap_or_else(|e| Outcome::Error(e.to_string()));
apply(pool, file_id, outcome).await?;
}
// Fichiers connus qui n'ont pas été retrouvés.
for state in known.into_values() {
apply(pool, state.id, Outcome::Missing).await?;
}
if mark_existing_read {
sqlx::query(
"UPDATE read_cursors
SET read_offset = (SELECT scan_offset FROM log_files WHERE id = log_file_id),
updated_at = ?
WHERE log_file_id IN (SELECT id FROM log_files WHERE project_id = ?)",
)
.bind(now())
.bind(project_id)
.execute(pool)
.await?;
}
Ok(())
}
/// Sérialise les scans : un seul à la fois, quel que soit le nombre d'onglets ouverts.
#[derive(Default)]
pub struct Scanner {
last_full_scan: Mutex<Option<Instant>>,
}
impl Scanner {
/// Scanne tous les projets, sauf si un scan complet vient de se terminer.
pub async fn scan_all(&self, pool: &SqlitePool) -> sqlx::Result<()> {
let mut last = self.last_full_scan.lock().await;
if last.is_some_and(|t| t.elapsed() < MIN_SCAN_GAP) {
return Ok(());
}
let projects: Vec<(i64, String)> = sqlx::query_as("SELECT id, root_path FROM projects")
.fetch_all(pool)
.await?;
for (id, root) in projects {
scan_project(pool, id, &root, false).await?;
}
*last = Some(Instant::now());
Ok(())
}
/// Premier scan d'un projet qui vient d'être ajouté.
pub async fn scan_new_project(
&self,
pool: &SqlitePool,
project_id: i64,
root: &str,
) -> sqlx::Result<()> {
let _guard = self.last_full_scan.lock().await;
scan_project(pool, project_id, root, true).await
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::io::Write;
fn laravel_project() -> tempfile::TempDir {
let dir = tempfile::tempdir().unwrap();
fs::write(dir.path().join("artisan"), "").unwrap();
fs::create_dir_all(logs_dir(dir.path())).unwrap();
dir
}
#[test]
fn validation_errors() {
let project = laravel_project();
assert!(validate_project_path(" ").is_err());
assert!(
validate_project_path("/nope/does/not/exist")
.unwrap_err()
.contains("n'existe pas")
);
let file = project.path().join("artisan");
assert!(
validate_project_path(file.to_str().unwrap())
.unwrap_err()
.contains("n'est pas un répertoire")
);
let plain = tempfile::tempdir().unwrap();
assert!(
validate_project_path(plain.path().to_str().unwrap())
.unwrap_err()
.contains("artisan")
);
fs::write(plain.path().join("artisan"), "").unwrap();
assert!(
validate_project_path(plain.path().to_str().unwrap())
.unwrap_err()
.contains("storage/logs")
);
}
#[test]
fn validation_canonicalizes() {
let project = laravel_project();
let canonical = project.path().canonicalize().unwrap();
let with_slash = format!("{}/", project.path().display());
assert_eq!(validate_project_path(&with_slash).unwrap(), canonical);
let dotted = format!("{}/storage/..", project.path().display());
assert_eq!(validate_project_path(&dotted).unwrap(), canonical);
}
#[cfg(unix)]
#[test]
fn discovery_rules() {
let project = laravel_project();
let logs = logs_dir(project.path());
for name in [
"laravel.log",
"laravel-2026-10-20.log",
".hidden.log",
"old.log.gz",
".gitignore",
] {
fs::write(logs.join(name), "").unwrap();
}
fs::create_dir(logs.join("jobs")).unwrap();
fs::write(logs.join("jobs/worker.log"), "").unwrap();
let outside = tempfile::NamedTempFile::new().unwrap();
std::os::unix::fs::symlink(outside.path(), logs.join("ext.log")).unwrap();
std::os::unix::fs::symlink(logs.join("laravel.log"), logs.join("alias.log")).unwrap();
let names: Vec<String> = discover(&logs)
.unwrap()
.into_iter()
.map(|(r, _)| r)
.collect();
assert_eq!(
names,
[
"alias.log",
"jobs/worker.log",
"laravel-2026-10-20.log",
"laravel.log"
]
);
}
/// Recule la date de modification : la dernière entrée est alors jugée complète.
fn settle(path: &Path) {
File::options()
.write(true)
.open(path)
.unwrap()
.set_modified(std::time::SystemTime::now() - Duration::from_secs(10))
.unwrap();
}
fn known(offset: u64, identity: Option<String>) -> Known {
Known {
id: 1,
identity,
scan_offset: offset,
missing: false,
}
}
fn scanned(outcome: Outcome) -> (u64, Option<String>, bool, Indexed) {
match outcome {
Outcome::Scanned {
size,
identity,
reset,
indexed,
..
} => (size, identity, reset, indexed),
other => panic!("scan inattendu : {other:?}"),
}
}
#[test]
fn truncation_and_rotation_reset() {
let project = laravel_project();
let path = logs_dir(project.path()).join("laravel.log");
let line = "[2026-10-21 10:00:00] local.INFO: a\n";
fs::write(&path, line.repeat(3)).unwrap();
settle(&path);
let (_, ident, reset, indexed) = scanned(scan_file(&path, &known(0, None)));
assert!(!reset);
assert_eq!(indexed.entries.len(), 3);
// Tronqué puis réécrit plus court.
fs::write(&path, line).unwrap();
settle(&path);
let (_, _, reset, indexed) = scanned(scan_file(
&path,
&known(3 * line.len() as u64, ident.clone()),
));
assert!(reset);
assert_eq!(indexed.entries.len(), 1);
// Remplacé par un autre fichier plus long (rotation).
fs::rename(&path, path.with_extension("old")).unwrap();
let mut f = File::create(&path).unwrap();
f.write_all(line.repeat(5).as_bytes()).unwrap();
drop(f);
settle(&path);
let (_, _, reset, indexed) = scanned(scan_file(&path, &known(line.len() as u64, ident)));
if cfg!(unix) {
assert!(reset);
assert_eq!(indexed.entries.len(), 5);
}
}
#[test]
fn last_entry_waits_for_settle() {
let project = laravel_project();
let path = logs_dir(project.path()).join("laravel.log");
fs::write(&path, "[2026-10-21 10:00:00] local.INFO: a\n").unwrap();
let (_, _, _, indexed) = scanned(scan_file(&path, &known(0, None)));
assert!(indexed.entries.is_empty());
assert_eq!(indexed.offset, 0);
settle(&path);
let (_, _, _, indexed) = scanned(scan_file(&path, &known(0, None)));
assert_eq!(indexed.entries.len(), 1);
}
#[test]
fn missing_file() {
let project = laravel_project();
let path = logs_dir(project.path()).join("gone.log");
assert!(matches!(
scan_file(&path, &known(0, None)),
Outcome::Missing
));
}
}
+176
View File
@@ -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)
}