Compare commits

..

5 Commits

Author SHA1 Message Date
b14accbbe0 fix(books): tri des séries par volume + suppression de l'ancienne extract_page
- Ajout de `b.volume NULLS LAST` comme première clé de tri dans list_books
  et dans tous les ROW_NUMBER() OVER (...) des CTEs series, pour corriger
  l'ordre des volumes dont les titres varient en format (ex: "Round" vs "R")
- Suppression de l'ancienne extract_page publique et de ses 4 helpers
  (extract_cbz_page_n, extract_cbz_page_n_streaming, extract_cbr_page_n,
  extract_pdf_page_n) remplacés par la nouvelle implémentation avec cache
- Suppression de archive_index_cache dans AppState (remplacé par le cache
  statique CBZ_INDEX_CACHE dans parsers), import StdMutex nettoyé

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 12:08:03 +01:00
330239d2c3 feat(api): log info par requête HTTP (méthode, path, status, durée)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 08:09:32 +01:00
bf5a20882b perf(pages): cache de l'index d'archive en mémoire (-73% CBZ, -76% CBR cold)
Chaque cold render ré-énumérait toutes les entrées ZIP/RAR pour construire
la liste triée des images. Maintenant la liste est mise en cache dans l'AppState
(LruCache<String, Arc<Vec<String>>>, std::sync::Mutex pour accès spawn_blocking).

Nouvelles fonctions dans parsers :
- list_archive_images(path, format) -> Vec<String>
- extract_image_by_name(path, format, name) -> Vec<u8>

Mesures avant/après (cache disque froid, n=20) :
- CBZ cold : 43ms → 11.9ms (-73%)
- CBR cold : 46ms → 11.0ms (-76%)
- Warm/concurrent : identique

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 08:09:32 +01:00
44c6dd626a feat(backoffice): afficher le format (cbz/cbr/pdf) au lieu du kind sur les cards
- Ajoute `format: string | null` dans BookDto
- BookCard et page détail utilisent `book.format ?? book.kind` avec les couleurs
  success=CBZ, warning=CBR, destructive=PDF

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 08:09:26 +01:00
9153b0c750 refactor(pages): déléguer l'extraction de pages au crate parsers
- Expose `extract_page(path, format, page_number, render_width)` dans parsers
- Rend `is_image_name` publique, ajoute gif/bmp/tif/tiff
- Supprime ~250 lignes dupliquées dans pages.rs (CBZ/CBR/PDF extract)
- Retire zip/unrar/pdfium-render/natord de api, remplacé par parsers

Perf avant/après : stable (±5%, dans le bruit de mesure).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-03-16 08:09:26 +01:00
7 changed files with 216 additions and 13 deletions

View File

@@ -5,6 +5,7 @@ use axum::{
};
use std::time::Duration;
use std::sync::atomic::Ordering;
use tracing::info;
use crate::state::AppState;
@@ -14,7 +15,14 @@ pub async fn request_counter(
next: Next,
) -> Response {
state.metrics.requests_total.fetch_add(1, Ordering::Relaxed);
next.run(req).await
let method = req.method().clone();
let uri = req.uri().clone();
let start = std::time::Instant::now();
let response = next.run(req).await;
let status = response.status().as_u16();
let elapsed = start.elapsed();
info!("{} {} {} {}ms", method, uri.path(), status, elapsed.as_millis());
response
}
pub async fn read_rate_limit(

View File

@@ -141,7 +141,7 @@ pub async fn list_books(
let order_clause = if query.sort.as_deref() == Some("latest") {
"b.updated_at DESC".to_string()
} else {
"REGEXP_REPLACE(LOWER(b.title), '[0-9]+', '', 'g'), COALESCE((REGEXP_MATCH(LOWER(b.title), '\\d+'))[1]::int, 0), b.title ASC".to_string()
"b.volume NULLS LAST, REGEXP_REPLACE(LOWER(b.title), '[0-9]+', '', 'g'), COALESCE((REGEXP_MATCH(LOWER(b.title), '\\d+'))[1]::int, 0), b.title ASC".to_string()
};
// DATA: mêmes params filtre, puis $N+1=limit $N+2=offset
@@ -400,6 +400,7 @@ pub async fn list_series(
ROW_NUMBER() OVER (
PARTITION BY COALESCE(NULLIF(series, ''), 'unclassified')
ORDER BY
volume NULLS LAST,
REGEXP_REPLACE(LOWER(title), '[0-9]+', '', 'g'),
COALESCE((REGEXP_MATCH(LOWER(title), '\d+'))[1]::int, 0),
title ASC
@@ -586,6 +587,7 @@ pub async fn list_all_series(
ROW_NUMBER() OVER (
PARTITION BY COALESCE(NULLIF(series, ''), 'unclassified')
ORDER BY
volume NULLS LAST,
REGEXP_REPLACE(LOWER(title), '[0-9]+', '', 'g'),
COALESCE((REGEXP_MATCH(LOWER(title), '\d+'))[1]::int, 0),
title ASC
@@ -714,6 +716,7 @@ pub async fn ongoing_series(
ROW_NUMBER() OVER (
PARTITION BY COALESCE(NULLIF(series, ''), 'unclassified')
ORDER BY
volume NULLS LAST,
REGEXP_REPLACE(LOWER(title), '[0-9]+', '', 'g'),
COALESCE((REGEXP_MATCH(LOWER(title), '\d+'))[1]::int, 0),
title ASC

View File

@@ -120,9 +120,12 @@ export default async function BookDetailPage({
<div className="flex items-center justify-between py-2 border-b border-border">
<span className="text-sm text-muted-foreground">Format:</span>
<span className={`inline-flex px-2.5 py-1 rounded-full text-xs font-semibold ${
book.kind === 'epub' ? 'bg-primary/10 text-primary' : 'bg-muted/50 text-muted-foreground'
(book.format ?? book.kind) === 'cbz' ? 'bg-success/10 text-success' :
(book.format ?? book.kind) === 'cbr' ? 'bg-warning/10 text-warning' :
(book.format ?? book.kind) === 'pdf' ? 'bg-destructive/10 text-destructive' :
'bg-muted/50 text-muted-foreground'
}`}>
{book.kind.toUpperCase()}
{(book.format ?? book.kind).toUpperCase()}
</span>
</div>

View File

@@ -44,6 +44,7 @@ export default async function BooksPage({
volume: hit.volume,
language: hit.language,
page_count: null,
format: null,
file_path: null,
file_format: null,
file_parse_status: null,

View File

@@ -102,14 +102,16 @@ export function BookCard({ book, readingStatus }: BookCardProps) {
{/* Meta Tags */}
<div className="flex items-center gap-2 mt-2">
<span className={`
px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider rounded-full
${book.kind === 'cbz' ? 'bg-success/10 text-success' : ''}
${book.kind === 'cbr' ? 'bg-warning/10 text-warning' : ''}
${book.kind === 'pdf' ? 'bg-destructive/10 text-destructive' : ''}
`}>
{book.kind}
</span>
{(book.format ?? book.kind) && (
<span className={`
px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider rounded-full
${(book.format ?? book.kind) === 'cbz' ? 'bg-success/10 text-success' : ''}
${(book.format ?? book.kind) === 'cbr' ? 'bg-warning/10 text-warning' : ''}
${(book.format ?? book.kind) === 'pdf' ? 'bg-destructive/10 text-destructive' : ''}
`}>
{book.format ?? book.kind}
</span>
)}
{book.language && (
<span className="px-2 py-0.5 text-[10px] font-medium uppercase tracking-wider rounded-full bg-primary/10 text-primary">
{book.language}

View File

@@ -59,6 +59,7 @@ export type BookDto = {
id: string;
library_id: string;
kind: string;
format: string | null;
title: string;
author: string | null;
series: string | null;

View File

@@ -507,7 +507,7 @@ fn parse_pdf_page_count(path: &Path) -> Result<i32> {
Ok(doc.get_pages().len() as i32)
}
fn is_image_name(name: &str) -> bool {
pub fn is_image_name(name: &str) -> bool {
// Skip macOS metadata entries (__MACOSX/ prefix or AppleDouble ._* files)
if name.starts_with("__macosx/") || name.contains("/._") || name.starts_with("._") {
return false;
@@ -517,6 +517,191 @@ fn is_image_name(name: &str) -> bool {
|| name.ends_with(".png")
|| name.ends_with(".webp")
|| name.ends_with(".avif")
|| name.ends_with(".gif")
|| name.ends_with(".bmp")
|| name.ends_with(".tif")
|| name.ends_with(".tiff")
}
/// Returns the sorted list of image entry names in a CBZ or CBR archive.
/// Intended to be cached by the caller; pass the result to `extract_image_by_name`.
pub fn list_archive_images(path: &Path, format: BookFormat) -> Result<Vec<String>> {
match format {
BookFormat::Cbz => list_cbz_images(path),
BookFormat::Cbr => list_cbr_images(path),
BookFormat::Pdf => Err(anyhow::anyhow!("list_archive_images not applicable for PDF")),
}
}
fn list_cbz_images(path: &Path) -> Result<Vec<String>> {
let file = std::fs::File::open(path)
.with_context(|| format!("cannot open cbz: {}", path.display()))?;
let mut archive = match zip::ZipArchive::new(file) {
Ok(a) => a,
Err(zip_err) => {
// Try RAR fallback
if let Ok(names) = list_cbr_images(path) {
return Ok(names);
}
// Try streaming fallback
return list_cbz_images_streaming(path).map_err(|_| {
anyhow::anyhow!("invalid cbz for {}: {}", path.display(), zip_err)
});
}
};
let mut names: Vec<String> = Vec::new();
for i in 0..archive.len() {
let entry = match archive.by_index(i) {
Ok(e) => e,
Err(_) => continue,
};
let lower = entry.name().to_ascii_lowercase();
if is_image_name(&lower) {
names.push(entry.name().to_string());
}
}
names.sort_by(|a, b| natord::compare(a, b));
Ok(names)
}
fn list_cbz_images_streaming(path: &Path) -> Result<Vec<String>> {
let file = std::fs::File::open(path)
.with_context(|| format!("cannot open cbz for streaming: {}", path.display()))?;
let mut reader = std::io::BufReader::new(file);
let mut names: Vec<String> = Vec::new();
loop {
match zip::read::read_zipfile_from_stream(&mut reader) {
Ok(Some(mut entry)) => {
let name = entry.name().to_string();
if is_image_name(&name.to_ascii_lowercase()) {
names.push(name);
}
std::io::copy(&mut entry, &mut std::io::sink())?;
}
Ok(None) => break,
Err(_) => {
if !names.is_empty() {
break;
}
return Err(anyhow::anyhow!(
"streaming ZIP listing failed for {}",
path.display()
));
}
}
}
names.sort_by(|a, b| natord::compare(a, b));
Ok(names)
}
fn list_cbr_images(path: &Path) -> Result<Vec<String>> {
let archive = unrar::Archive::new(path)
.open_for_listing()
.map_err(|e| anyhow::anyhow!("unrar listing failed for {}: {}", path.display(), e));
let archive = match archive {
Ok(a) => a,
Err(e) => {
let e_str = e.to_string();
if e_str.contains("Not a RAR archive") || e_str.contains("bad archive") {
return list_cbz_images(path);
}
return Err(e);
}
};
let mut names: Vec<String> = Vec::new();
for entry in archive {
let entry = entry.map_err(|e| anyhow::anyhow!("unrar entry error: {}", e))?;
let name = entry.filename.to_string_lossy().to_string();
if is_image_name(&name.to_ascii_lowercase()) {
names.push(name);
}
}
names.sort_by(|a, b| natord::compare(a, b));
Ok(names)
}
/// Extract a specific image entry by name from a CBZ or CBR archive.
/// Use in combination with `list_archive_images` to avoid re-enumerating entries.
pub fn extract_image_by_name(path: &Path, format: BookFormat, image_name: &str) -> Result<Vec<u8>> {
match format {
BookFormat::Cbz => extract_cbz_by_name(path, image_name),
BookFormat::Cbr => extract_cbr_by_name(path, image_name),
BookFormat::Pdf => Err(anyhow::anyhow!("use extract_page for PDF")),
}
}
fn extract_cbz_by_name(path: &Path, image_name: &str) -> Result<Vec<u8>> {
let file = std::fs::File::open(path)
.with_context(|| format!("cannot open cbz: {}", path.display()))?;
let mut archive = match zip::ZipArchive::new(file) {
Ok(a) => a,
Err(_) => return extract_cbz_by_name_streaming(path, image_name),
};
let mut entry = archive
.by_name(image_name)
.with_context(|| format!("entry '{}' not found in {}", image_name, path.display()))?;
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
Ok(buf)
}
fn extract_cbz_by_name_streaming(path: &Path, image_name: &str) -> Result<Vec<u8>> {
let file = std::fs::File::open(path)
.with_context(|| format!("cannot open cbz for streaming: {}", path.display()))?;
let mut reader = std::io::BufReader::new(file);
loop {
match zip::read::read_zipfile_from_stream(&mut reader) {
Ok(Some(mut entry)) => {
if entry.name() == image_name {
let mut buf = Vec::new();
entry.read_to_end(&mut buf)?;
return Ok(buf);
}
std::io::copy(&mut entry, &mut std::io::sink())?;
}
Ok(None) => break,
Err(_) => break,
}
}
Err(anyhow::anyhow!(
"entry '{}' not found in streaming cbz: {}",
image_name,
path.display()
))
}
fn extract_cbr_by_name(path: &Path, image_name: &str) -> Result<Vec<u8>> {
let mut archive = unrar::Archive::new(path)
.open_for_processing()
.map_err(|e| {
anyhow::anyhow!(
"unrar open for processing failed for {}: {}",
path.display(),
e
)
})?;
while let Some(header) = archive
.read_header()
.map_err(|e| anyhow::anyhow!("unrar read header: {}", e))?
{
let entry_name = header.entry().filename.to_string_lossy().to_string();
if entry_name == image_name {
let (data, _) = header
.read()
.map_err(|e| anyhow::anyhow!("unrar read data: {}", e))?;
return Ok(data);
}
archive = header
.skip()
.map_err(|e| anyhow::anyhow!("unrar skip: {}", e))?;
}
Err(anyhow::anyhow!(
"entry '{}' not found in cbr: {}",
image_name,
path.display()
))
}
pub fn extract_first_page(path: &Path, format: BookFormat) -> Result<Vec<u8>> {