proper error handling

This commit is contained in:
Sebastian Hugentobler 2024-05-06 09:09:40 +02:00
parent 687c33829f
commit ac7b0e7e88
Signed by: shu
GPG Key ID: BB32CF3CA052C2F0
15 changed files with 245 additions and 25 deletions

4
Cargo.lock generated
View File

@ -295,10 +295,14 @@ dependencies = [
"once_cell", "once_cell",
"poem", "poem",
"rust-embed", "rust-embed",
"serde",
"serde_json",
"tera", "tera",
"thiserror", "thiserror",
"tokio", "tokio",
"tracing",
"tracing-subscriber", "tracing-subscriber",
"uuid",
] ]
[[package]] [[package]]

View File

@ -3,7 +3,9 @@ use std::path::Path;
use r2d2::Pool; use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager; use r2d2_sqlite::SqliteConnectionManager;
use crate::data::{author::Author, book::Book, error::DataStoreError, pagination::SortOrder}; use crate::data::{
author::Author, book::Book, error::DataStoreError, pagination::SortOrder, series::Series,
};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Calibre { pub struct Calibre {
@ -25,7 +27,7 @@ impl Calibre {
sort_order: SortOrder, sort_order: SortOrder,
) -> Result<Vec<Book>, DataStoreError> { ) -> Result<Vec<Book>, DataStoreError> {
let conn = self.pool.get()?; let conn = self.pool.get()?;
Book::books(&conn, limit, cursor, sort_order) Book::multiple(&conn, limit, cursor, sort_order)
} }
pub fn authors( pub fn authors(
@ -35,7 +37,7 @@ impl Calibre {
sort_order: SortOrder, sort_order: SortOrder,
) -> Result<Vec<Author>, DataStoreError> { ) -> Result<Vec<Author>, DataStoreError> {
let conn = self.pool.get()?; let conn = self.pool.get()?;
Author::authors(&conn, limit, cursor, sort_order) Author::multiple(&conn, limit, cursor, sort_order)
} }
pub fn author_books( pub fn author_books(
@ -58,6 +60,26 @@ impl Calibre {
let conn = self.pool.get()?; let conn = self.pool.get()?;
Book::scalar_book(&conn, id) Book::scalar_book(&conn, id)
} }
pub fn book_author(&self, id: u64) -> Result<Author, DataStoreError> {
let conn = self.pool.get()?;
Author::book_author(&conn, id)
}
pub fn series(
&self,
limit: u64,
cursor: Option<&str>,
sort_order: SortOrder,
) -> Result<Vec<Series>, DataStoreError> {
let conn = self.pool.get()?;
Series::multiple(&conn, limit, cursor, sort_order)
}
pub fn book_series(&self, id: u64) -> Result<Option<(Series, f64)>, DataStoreError> {
let conn = self.pool.get()?;
Series::book_series(&conn, id)
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -1,4 +1,4 @@
use rusqlite::{Connection, Row}; use rusqlite::{named_params, Connection, Row};
use serde::Serialize; use serde::Serialize;
use super::{ use super::{
@ -8,7 +8,7 @@ use super::{
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
pub struct Author { pub struct Author {
pub id: i32, pub id: u64,
pub name: String, pub name: String,
pub sort: String, pub sort: String,
} }
@ -22,12 +22,12 @@ impl Author {
}) })
} }
pub fn authors( pub fn multiple(
conn: &Connection, conn: &Connection,
limit: u64, limit: u64,
cursor: Option<&str>, cursor: Option<&str>,
sort_order: SortOrder, sort_order: SortOrder,
) -> Result<Vec<Author>, DataStoreError> { ) -> Result<Vec<Self>, DataStoreError> {
let pagination = Pagination::new("sort", cursor, limit, sort_order); let pagination = Pagination::new("sort", cursor, limit, sort_order);
pagination.paginate( pagination.paginate(
conn, conn,
@ -36,4 +36,14 @@ impl Author {
Self::from_row, Self::from_row,
) )
} }
pub fn book_author(conn: &Connection, id: u64) -> Result<Self, DataStoreError> {
let mut stmt = conn.prepare(
"SELECT authors.id, authors.name, authors.sort FROM authors \
INNER JOIN books_authors_link ON authors.id = books_authors_link.author \
WHERE books_authors_link.book = (:id)",
)?;
let params = named_params! { ":id": id };
Ok(stmt.query_row(params, Self::from_row)?)
}
} }

View File

@ -8,7 +8,7 @@ use super::{
#[derive(Debug, Serialize)] #[derive(Debug, Serialize)]
pub struct Book { pub struct Book {
pub id: i32, pub id: u64,
pub title: String, pub title: String,
pub sort: String, pub sort: String,
pub path: String, pub path: String,
@ -24,12 +24,12 @@ impl Book {
}) })
} }
pub fn books( pub fn multiple(
conn: &Connection, conn: &Connection,
limit: u64, limit: u64,
cursor: Option<&str>, cursor: Option<&str>,
sort_order: SortOrder, sort_order: SortOrder,
) -> Result<Vec<Book>, DataStoreError> { ) -> Result<Vec<Self>, DataStoreError> {
let pagination = Pagination::new("sort", cursor, limit, sort_order); let pagination = Pagination::new("sort", cursor, limit, sort_order);
pagination.paginate( pagination.paginate(
conn, conn,
@ -45,7 +45,7 @@ impl Book {
limit: u64, limit: u64,
cursor: Option<&str>, cursor: Option<&str>,
sort_order: SortOrder, sort_order: SortOrder,
) -> Result<Vec<Book>, DataStoreError> { ) -> Result<Vec<Self>, DataStoreError> {
let pagination = Pagination::new("books.sort", cursor, limit, sort_order); let pagination = Pagination::new("books.sort", cursor, limit, sort_order);
pagination.paginate( pagination.paginate(
conn, conn,
@ -57,7 +57,7 @@ impl Book {
) )
} }
pub fn recents(conn: &Connection, limit: u64) -> Result<Vec<Book>, DataStoreError> { pub fn recents(conn: &Connection, limit: u64) -> Result<Vec<Self>, DataStoreError> {
let mut stmt = conn.prepare( let mut stmt = conn.prepare(
"SELECT id, title, sort, path FROM books ORDER BY timestamp DESC LIMIT (:limit)", "SELECT id, title, sort, path FROM books ORDER BY timestamp DESC LIMIT (:limit)",
)?; )?;
@ -66,7 +66,7 @@ impl Book {
Ok(iter.filter_map(Result::ok).collect()) Ok(iter.filter_map(Result::ok).collect())
} }
pub fn scalar_book(conn: &Connection, id: u64) -> Result<Book, DataStoreError> { pub fn scalar_book(conn: &Connection, id: u64) -> Result<Self, DataStoreError> {
let mut stmt = conn.prepare("SELECT id, title, sort, path FROM books WHERE id = (:id)")?; let mut stmt = conn.prepare("SELECT id, title, sort, path FROM books WHERE id = (:id)")?;
let params = named_params! { ":id": id }; let params = named_params! { ":id": id };
Ok(stmt.query_row(params, Self::from_row)?) Ok(stmt.query_row(params, Self::from_row)?)

View File

@ -1,9 +1,21 @@
use thiserror::Error; use thiserror::Error;
#[derive(Error, Debug)] #[derive(Error, Debug)]
#[error("data store error")]
pub enum DataStoreError { pub enum DataStoreError {
#[error("no results")]
NoResults(rusqlite::Error),
#[error("sqlite error")] #[error("sqlite error")]
SqliteError(#[from] rusqlite::Error), SqliteError(rusqlite::Error),
#[error("connection error")] #[error("connection error")]
ConnectionError(#[from] r2d2::Error), ConnectionError(#[from] r2d2::Error),
} }
impl From<rusqlite::Error> for DataStoreError {
fn from(error: rusqlite::Error) -> Self {
match error {
rusqlite::Error::QueryReturnedNoRows => DataStoreError::NoResults(error),
_ => DataStoreError::SqliteError(error),
}
}
}

View File

@ -0,0 +1,64 @@
use rusqlite::{named_params, Connection, Row};
use serde::Serialize;
use super::{
error::DataStoreError,
pagination::{Pagination, SortOrder},
};
#[derive(Debug, Serialize)]
pub struct Series {
pub id: u64,
pub name: String,
pub sort: String,
}
impl Series {
fn from_row(row: &Row<'_>) -> Result<Self, rusqlite::Error> {
Ok(Self {
id: row.get(0)?,
name: row.get(1)?,
sort: row.get(2)?,
})
}
pub fn multiple(
conn: &Connection,
limit: u64,
cursor: Option<&str>,
sort_order: SortOrder,
) -> Result<Vec<Self>, DataStoreError> {
let pagination = Pagination::new("sort", cursor, limit, sort_order);
pagination.paginate(
conn,
"SELECT id, title, sort, path FROM series",
&[],
Self::from_row,
)
}
pub fn book_series(
conn: &Connection,
book_id: u64,
) -> Result<Option<(Self, f64)>, DataStoreError> {
let mut stmt = conn.prepare(
"SELECT series.id, series.name, series.sort, books.series_index FROM series \
INNER JOIN books_series_link ON series.id = books_series_link.series \
INNER JOIN books ON books.id = books_series_link.book \
WHERE books_series_link.book = (:id)",
)?;
let params = named_params! { ":id": book_id };
let from_row = |row: &Row<'_>| {
let series = Self::from_row(row)?;
let series_idx = row.get(3)?;
Ok((series, series_idx))
};
match stmt.query_row(params, from_row) {
Ok(series) => Ok(Some(series)),
Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
Err(e) => Err(DataStoreError::SqliteError(e)),
}
}
}

View File

@ -4,4 +4,5 @@ pub mod data {
pub mod book; pub mod book;
pub mod error; pub mod error;
pub mod pagination; pub mod pagination;
pub mod series;
} }

View File

@ -9,7 +9,11 @@ clap = { version = "4.5.4", features = ["derive"] }
once_cell = "1.19.0" once_cell = "1.19.0"
poem = { version = "3.0.0", features = ["embed", "static-files"] } poem = { version = "3.0.0", features = ["embed", "static-files"] }
rust-embed = "8.3.0" rust-embed = "8.3.0"
serde = { workspace = true }
serde_json = "1.0.116"
tera = "1.19.1" tera = "1.19.1"
thiserror = { workspace = true } thiserror = { workspace = true }
tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] } tokio = { version = "1.37.0", features = ["rt-multi-thread", "macros"] }
tracing = "0.1.40"
tracing-subscriber = "0.3.18" tracing-subscriber = "0.3.18"
uuid = { version = "1.8.0", features = ["v4", "fast-rng"] }

29
cops-web/src/data/book.rs Normal file
View File

@ -0,0 +1,29 @@
use calibre_db::data::{book::Book as DbBook, series::Series as DbSeries};
use serde::Serialize;
#[derive(Debug, Serialize)]
pub struct Book {
pub id: u64,
pub title: String,
pub sort: String,
pub path: String,
pub author: String,
pub series: Option<(String, f64)>,
}
impl Book {
pub fn from_db_book(
db_book: &DbBook,
db_series: Option<(DbSeries, f64)>,
author: &str,
) -> Self {
Self {
id: db_book.id,
title: db_book.title.clone(),
sort: db_book.sort.clone(),
path: db_book.path.clone(),
author: author.to_string(),
series: db_series.map(|x| (x.0.name, x.1)),
}
}
}

View File

@ -0,0 +1,40 @@
use calibre_db::data::error::DataStoreError;
use poem::{error::ResponseError, http::StatusCode, Body, Response};
use tracing::error;
use uuid::Uuid;
#[derive(Debug, thiserror::Error)]
#[error("sqlite error")]
pub struct SqliteError(pub DataStoreError);
impl From<DataStoreError> for SqliteError {
fn from(item: DataStoreError) -> Self {
SqliteError(item)
}
}
impl ResponseError for SqliteError {
fn status(&self) -> StatusCode {
match &self.0 {
DataStoreError::NoResults(_) => StatusCode::NOT_FOUND,
_ => StatusCode::BAD_GATEWAY,
}
}
fn as_response(&self) -> Response {
let id = Uuid::new_v4();
let internal_msg = self.to_string();
let external_msg = match &self.0 {
DataStoreError::NoResults(_) => "item not found",
_ => "internal server error",
};
error!("{id}: {internal_msg}");
let body = Body::from_json(serde_json::json!({
"id": id.to_string(),
"message": external_msg,
}))
.unwrap();
Response::builder().status(self.status()).body(body)
}
}

View File

@ -7,11 +7,21 @@ use poem::{
}; };
use tera::Context; use tera::Context;
use crate::{app_state::AppState, templates::TEMPLATES}; use crate::{
app_state::AppState, data::book::Book, handlers::error::SqliteError, templates::TEMPLATES,
};
#[handler] #[handler]
pub async fn handler(state: Data<&Arc<AppState>>) -> Result<Html<String>, poem::Error> { pub async fn handler(state: Data<&Arc<AppState>>) -> Result<Html<String>, poem::Error> {
let recent_books = state.calibre.recent_books(50).unwrap(); let recent_books = state.calibre.recent_books(50).map_err(SqliteError)?;
let recent_books = recent_books
.iter()
.filter_map(|x| {
let author = state.calibre.book_author(x.id).ok()?;
let series = state.calibre.book_series(x.id).ok()?;
Some(Book::from_db_book(x, series, &author.name))
})
.collect::<Vec<Book>>();
let mut context = Context::new(); let mut context = Context::new();
context.insert("books", &recent_books); context.insert("books", &recent_books);

View File

@ -14,8 +14,12 @@ mod app_state;
mod basic_auth; mod basic_auth;
mod cli; mod cli;
mod config; mod config;
mod data {
pub mod book;
}
mod handlers { mod handlers {
pub mod cover; pub mod cover;
pub mod error;
pub mod recents; pub mod recents;
} }
mod templates; mod templates;

View File

@ -4,6 +4,10 @@
text-overflow: ellipsis; text-overflow: ellipsis;
} }
.book-card hgroup {
margin-bottom: 0;
}
.cover { .cover {
width: 100%; width: 100%;
object-fit: contain; object-fit: contain;

View File

@ -3,10 +3,30 @@
<h1>Recent Books</h1> <h1>Recent Books</h1>
<div class="grid-container"> <div class="grid-container">
{% for book in books %} {% for book in books %}
<article class="book-card grid-item"> <article class="book-card">
<header>{{ book.title }}</header> <header class="grid-item">
<hgroup>
<h5>{{ book.title }}</h5>
<!-- {% if book.series %}<p>{{ book.series.0 }} ({{ book.series.1 }})</p>{% endif %} -->
<p>{{ book.author }}</p>
</hgroup>
</header>
<img class="cover" src="/cover/{{ book.id }}" alt="book cover"> <img class="cover" src="/cover/{{ book.id }}" alt="book cover">
<!-- <footer>{{ book.title }}</footer> --> <footer>
<form>
<fieldset role="group">
<details class="dropdown">
<summary role="button" class="outline">
Download
</summary>
<ul>
<li><a href="#">Epub</a></li>
<li><a href="#">Pdf</a></li>
</ul>
</details>
</fieldset>
</form>
</footer>
</article> </article>
{% endfor %} {% endfor %}
</div> </div>

View File

@ -9,7 +9,6 @@
outputs = outputs =
{ {
self,
nixpkgs, nixpkgs,
naersk, naersk,
fenix, fenix,
@ -72,14 +71,11 @@
pkgs = import nixpkgs { inherit system; }; pkgs = import nixpkgs { inherit system; };
rust = fenix.packages.${system}.stable; rust = fenix.packages.${system}.stable;
in in
with pkgs;
{ {
devShells.default = mkShell { devShells.default = pkgs.mkShell {
buildInputs = [ buildInputs = [
mosquitto
rust.toolchain rust.toolchain
rust-analyzer pkgs.rust-analyzer
sea-orm-cli
]; ];
}; };
} }