chore: initial project scaffold

Set up Mangalord with a Rust/axum backend, SvelteKit frontend, Postgres,
and Docker Compose deployment. Establishes the architecture and TDD
patterns the project will extend:

- Hexagonal-ish backend layering (domain / repo / storage / api) with
  a pluggable Storage trait (LocalStorage today, S3 as a future impl).
- Initial migration: users, mangas, chapters, bookmarks.
- Vertical slice for mangas (list, search, create, get) with
  #[sqlx::test] integration coverage and storage unit tests.
- SvelteKit frontend using Svelte 5 runes, typed API client, Vitest
  unit tests and Playwright e2e with route mocking.
- CLAUDE.md documenting layering, TDD/git/SemVer workflow rules, and
  extension points (tags, fulltext search, OCR, S3, auth).
- Project-scoped .claude/settings.json with permission allowlist for
  the toolchain (git, cargo, npm/vite, docker, psql, gh, doc fetches).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
MechaCat02
2026-05-16 21:05:16 +02:00
commit 6c1d04aaf4
48 changed files with 1657 additions and 0 deletions

39
backend/src/api/files.rs Normal file
View File

@@ -0,0 +1,39 @@
//! Serves blobs from the `Storage` trait. Same endpoint serves manga
//! covers and chapter pages; the key embedded in the URL is whatever
//! the writer stored.
use axum::extract::{Path, State};
use axum::http::header;
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use axum::Router;
use crate::app::AppState;
use crate::error::AppResult;
use crate::storage::StorageError;
pub fn routes() -> Router<AppState> {
Router::new().route("/files/*key", get(serve))
}
async fn serve(State(state): State<AppState>, Path(key): Path<String>) -> AppResult<Response> {
let bytes = match state.storage.get(&key).await {
Ok(b) => b,
Err(StorageError::NotFound) => return Err(crate::error::AppError::NotFound),
Err(e) => return Err(e.into()),
};
let ct = content_type_for(&key);
Ok(([(header::CONTENT_TYPE, ct)], bytes).into_response())
}
fn content_type_for(key: &str) -> &'static str {
let ext = key.rsplit('.').next().unwrap_or("").to_ascii_lowercase();
match ext.as_str() {
"jpg" | "jpeg" => "image/jpeg",
"png" => "image/png",
"webp" => "image/webp",
"gif" => "image/gif",
"avif" => "image/avif",
_ => "application/octet-stream",
}
}

12
backend/src/api/health.rs Normal file
View File

@@ -0,0 +1,12 @@
use axum::{routing::get, Json, Router};
use serde_json::{json, Value};
use crate::app::AppState;
pub fn routes() -> Router<AppState> {
Router::new().route("/health", get(health))
}
async fn health() -> Json<Value> {
Json(json!({ "status": "ok" }))
}

59
backend/src/api/mangas.rs Normal file
View File

@@ -0,0 +1,59 @@
use axum::extract::{Path, Query, State};
use axum::routing::get;
use axum::{Json, Router};
use serde::Deserialize;
use uuid::Uuid;
use crate::app::AppState;
use crate::domain::manga::{Manga, NewManga};
use crate::error::{AppError, AppResult};
use crate::repo;
pub fn routes() -> Router<AppState> {
Router::new()
.route("/mangas", get(list).post(create))
.route("/mangas/:id", get(get_one))
}
#[derive(Debug, Deserialize)]
pub struct ListParams {
#[serde(default)]
pub search: Option<String>,
#[serde(default = "default_limit")]
pub limit: i64,
#[serde(default)]
pub offset: i64,
}
fn default_limit() -> i64 {
50
}
async fn list(
State(state): State<AppState>,
Query(params): Query<ListParams>,
) -> AppResult<Json<Vec<Manga>>> {
let q = repo::manga::ListQuery {
search: params.search.filter(|s| !s.trim().is_empty()),
limit: params.limit.clamp(1, 200),
offset: params.offset.max(0),
};
Ok(Json(repo::manga::list(&state.db, &q).await?))
}
async fn get_one(
State(state): State<AppState>,
Path(id): Path<Uuid>,
) -> AppResult<Json<Manga>> {
Ok(Json(repo::manga::get(&state.db, id).await?))
}
async fn create(
State(state): State<AppState>,
Json(input): Json<NewManga>,
) -> AppResult<Json<Manga>> {
if input.title.trim().is_empty() {
return Err(AppError::InvalidInput("title is required".into()));
}
Ok(Json(repo::manga::create(&state.db, input).await?))
}

14
backend/src/api/mod.rs Normal file
View File

@@ -0,0 +1,14 @@
pub mod files;
pub mod health;
pub mod mangas;
use axum::Router;
use crate::app::AppState;
pub fn routes() -> Router<AppState> {
Router::new()
.merge(health::routes())
.merge(mangas::routes())
.merge(files::routes())
}

36
backend/src/app.rs Normal file
View File

@@ -0,0 +1,36 @@
use std::sync::Arc;
use axum::Router;
use sqlx::postgres::PgPoolOptions;
use sqlx::PgPool;
use tower_http::trace::TraceLayer;
use crate::config::Config;
use crate::storage::{LocalStorage, Storage};
#[derive(Clone)]
pub struct AppState {
pub db: PgPool,
pub storage: Arc<dyn Storage>,
}
pub async fn build(config: Config) -> anyhow::Result<Router> {
let db = PgPoolOptions::new()
.max_connections(10)
.connect(&config.database_url)
.await?;
sqlx::migrate!("./migrations").run(&db).await?;
let storage: Arc<dyn Storage> = Arc::new(LocalStorage::new(config.storage_dir.clone()));
Ok(router(AppState { db, storage }))
}
/// Build a router from a pre-assembled state. Used by integration tests
/// so they can swap in a test DB pool and a `tempfile`-backed storage.
pub fn router(state: AppState) -> Router {
Router::new()
.nest("/api", crate::api::routes())
.with_state(state)
.layer(TraceLayer::new_for_http())
}

22
backend/src/config.rs Normal file
View File

@@ -0,0 +1,22 @@
use std::path::PathBuf;
#[derive(Clone, Debug)]
pub struct Config {
pub database_url: String,
pub bind_address: String,
pub storage_dir: PathBuf,
}
impl Config {
pub fn from_env() -> anyhow::Result<Self> {
Ok(Self {
database_url: std::env::var("DATABASE_URL")
.map_err(|_| anyhow::anyhow!("DATABASE_URL must be set"))?,
bind_address: std::env::var("BIND_ADDRESS")
.unwrap_or_else(|_| "0.0.0.0:8080".to_string()),
storage_dir: std::env::var("STORAGE_DIR")
.unwrap_or_else(|_| "./data/storage".to_string())
.into(),
})
}
}

View File

@@ -0,0 +1,14 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct Bookmark {
pub id: Uuid,
pub user_id: Uuid,
pub manga_id: Uuid,
pub chapter_id: Option<Uuid>,
pub page: Option<i32>,
pub created_at: DateTime<Utc>,
}

View File

@@ -0,0 +1,20 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct Chapter {
pub id: Uuid,
pub manga_id: Uuid,
pub number: i32,
pub title: Option<String>,
pub page_count: i32,
pub created_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct NewChapter {
pub number: i32,
pub title: Option<String>,
}

View File

@@ -0,0 +1,22 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct Manga {
pub id: Uuid,
pub title: String,
pub author: Option<String>,
pub description: Option<String>,
pub cover_image_path: Option<String>,
pub created_at: DateTime<Utc>,
pub updated_at: DateTime<Utc>,
}
#[derive(Debug, Clone, Deserialize)]
pub struct NewManga {
pub title: String,
pub author: Option<String>,
pub description: Option<String>,
}

View File

@@ -0,0 +1,9 @@
pub mod bookmark;
pub mod chapter;
pub mod manga;
pub mod user;
pub use bookmark::Bookmark;
pub use chapter::Chapter;
pub use manga::Manga;
pub use user::User;

View File

@@ -0,0 +1,11 @@
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use sqlx::FromRow;
use uuid::Uuid;
#[derive(Debug, Clone, Serialize, Deserialize, FromRow)]
pub struct User {
pub id: Uuid,
pub username: String,
pub created_at: DateTime<Utc>,
}

45
backend/src/error.rs Normal file
View File

@@ -0,0 +1,45 @@
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde_json::json;
use crate::storage::StorageError;
#[derive(thiserror::Error, Debug)]
pub enum AppError {
#[error("not found")]
NotFound,
#[error("invalid input: {0}")]
InvalidInput(String),
#[error(transparent)]
Database(#[from] sqlx::Error),
#[error(transparent)]
Storage(#[from] StorageError),
#[error(transparent)]
Other(#[from] anyhow::Error),
}
pub type AppResult<T> = Result<T, AppError>;
impl IntoResponse for AppError {
fn into_response(self) -> Response {
let (status, message) = match &self {
AppError::NotFound => (StatusCode::NOT_FOUND, self.to_string()),
AppError::InvalidInput(_) => (StatusCode::BAD_REQUEST, self.to_string()),
AppError::Database(sqlx::Error::RowNotFound) => {
(StatusCode::NOT_FOUND, "not found".to_string())
}
AppError::Storage(StorageError::NotFound) => {
(StatusCode::NOT_FOUND, "not found".to_string())
}
AppError::Storage(StorageError::BadKey) => {
(StatusCode::BAD_REQUEST, "invalid file key".to_string())
}
AppError::Database(_) | AppError::Storage(_) | AppError::Other(_) => {
tracing::error!(error = ?self, "internal error");
(StatusCode::INTERNAL_SERVER_ERROR, "internal error".to_string())
}
};
(status, Json(json!({ "error": message }))).into_response()
}
}

7
backend/src/lib.rs Normal file
View File

@@ -0,0 +1,7 @@
pub mod api;
pub mod app;
pub mod config;
pub mod domain;
pub mod error;
pub mod repo;
pub mod storage;

21
backend/src/main.rs Normal file
View File

@@ -0,0 +1,21 @@
use std::net::SocketAddr;
use tracing_subscriber::EnvFilter;
#[tokio::main]
async fn main() -> anyhow::Result<()> {
dotenvy::dotenv().ok();
tracing_subscriber::fmt()
.with_env_filter(
EnvFilter::try_from_default_env().unwrap_or_else(|_| "info,mangalord=debug".into()),
)
.init();
let config = mangalord::config::Config::from_env()?;
let addr: SocketAddr = config.bind_address.parse()?;
let app = mangalord::app::build(config).await?;
tracing::info!(%addr, "mangalord listening");
let listener = tokio::net::TcpListener::bind(addr).await?;
axum::serve(listener, app).await?;
Ok(())
}

76
backend/src/repo/manga.rs Normal file
View File

@@ -0,0 +1,76 @@
//! Manga persistence.
//!
//! Plain async functions over `&PgPool` rather than a repository struct —
//! each function is easy to test in isolation with `#[sqlx::test]`, and
//! handlers depend only on `sqlx::PgPool`, not on a trait object. Swap to
//! a trait + impl if a second backend ever becomes necessary.
use sqlx::PgPool;
use uuid::Uuid;
use crate::domain::manga::{Manga, NewManga};
use crate::error::{AppError, AppResult};
#[derive(Debug, Clone)]
pub struct ListQuery {
pub search: Option<String>,
pub limit: i64,
pub offset: i64,
}
impl Default for ListQuery {
fn default() -> Self {
Self { search: None, limit: 50, offset: 0 }
}
}
pub async fn list(pool: &PgPool, query: &ListQuery) -> AppResult<Vec<Manga>> {
let pattern = query.search.as_deref().map(|s| format!("%{}%", s));
let rows = sqlx::query_as::<_, Manga>(
r#"
SELECT id, title, author, description, cover_image_path, created_at, updated_at
FROM mangas
WHERE $1::text IS NULL
OR title ILIKE $1
OR COALESCE(author, '') ILIKE $1
ORDER BY created_at DESC
LIMIT $2 OFFSET $3
"#,
)
.bind(pattern)
.bind(query.limit)
.bind(query.offset)
.fetch_all(pool)
.await?;
Ok(rows)
}
pub async fn get(pool: &PgPool, id: Uuid) -> AppResult<Manga> {
sqlx::query_as::<_, Manga>(
r#"
SELECT id, title, author, description, cover_image_path, created_at, updated_at
FROM mangas
WHERE id = $1
"#,
)
.bind(id)
.fetch_optional(pool)
.await?
.ok_or(AppError::NotFound)
}
pub async fn create(pool: &PgPool, input: NewManga) -> AppResult<Manga> {
let row = sqlx::query_as::<_, Manga>(
r#"
INSERT INTO mangas (title, author, description)
VALUES ($1, $2, $3)
RETURNING id, title, author, description, cover_image_path, created_at, updated_at
"#,
)
.bind(&input.title)
.bind(&input.author)
.bind(&input.description)
.fetch_one(pool)
.await?;
Ok(row)
}

1
backend/src/repo/mod.rs Normal file
View File

@@ -0,0 +1 @@
pub mod manga;

View File

@@ -0,0 +1,97 @@
use std::path::{Path, PathBuf};
use async_trait::async_trait;
use tokio::fs;
use super::{Storage, StorageError};
pub struct LocalStorage {
root: PathBuf,
}
impl LocalStorage {
pub fn new(root: impl Into<PathBuf>) -> Self {
Self { root: root.into() }
}
fn resolve(&self, key: &str) -> Result<PathBuf, StorageError> {
let key = key.trim_start_matches('/');
if key.is_empty() {
return Err(StorageError::BadKey);
}
if key.split('/').any(|seg| seg.is_empty() || seg == "." || seg == "..") {
return Err(StorageError::BadKey);
}
Ok(self.root.join(key))
}
}
#[async_trait]
impl Storage for LocalStorage {
async fn put(&self, key: &str, bytes: &[u8]) -> Result<(), StorageError> {
let path = self.resolve(key)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent).await?;
}
fs::write(path, bytes).await?;
Ok(())
}
async fn get(&self, key: &str) -> Result<Vec<u8>, StorageError> {
let path = self.resolve(key)?;
match fs::read(&path).await {
Ok(b) => Ok(b),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(StorageError::NotFound),
Err(e) => Err(e.into()),
}
}
async fn delete(&self, key: &str) -> Result<(), StorageError> {
let path = self.resolve(key)?;
match fs::remove_file(&path).await {
Ok(()) => Ok(()),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(StorageError::NotFound),
Err(e) => Err(e.into()),
}
}
async fn exists(&self, key: &str) -> Result<bool, StorageError> {
let path: &Path = &self.resolve(key)?;
Ok(fs::try_exists(path).await?)
}
}
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[tokio::test]
async fn put_get_delete_roundtrip() {
let dir = tempdir().unwrap();
let s = LocalStorage::new(dir.path());
s.put("mangas/abc/cover.jpg", b"hello").await.unwrap();
assert!(s.exists("mangas/abc/cover.jpg").await.unwrap());
assert_eq!(s.get("mangas/abc/cover.jpg").await.unwrap(), b"hello");
s.delete("mangas/abc/cover.jpg").await.unwrap();
assert!(!s.exists("mangas/abc/cover.jpg").await.unwrap());
}
#[tokio::test]
async fn rejects_path_traversal() {
let dir = tempdir().unwrap();
let s = LocalStorage::new(dir.path());
assert!(matches!(s.put("../escape", b"x").await, Err(StorageError::BadKey)));
assert!(matches!(s.get("a/../../b").await, Err(StorageError::BadKey)));
assert!(matches!(s.exists("").await, Err(StorageError::BadKey)));
}
#[tokio::test]
async fn missing_key_is_not_found() {
let dir = tempdir().unwrap();
let s = LocalStorage::new(dir.path());
assert!(matches!(s.get("nope").await, Err(StorageError::NotFound)));
assert!(matches!(s.delete("nope").await, Err(StorageError::NotFound)));
}
}

View File

@@ -0,0 +1,31 @@
//! Pluggable blob storage.
//!
//! Handlers depend on the `Storage` trait, never on a concrete backend.
//! Add new backends (S3, GCS, …) as new impls in this module and wire
//! them up in `app::build` based on config.
mod local;
use std::io;
use async_trait::async_trait;
pub use local::LocalStorage;
#[derive(thiserror::Error, Debug)]
pub enum StorageError {
#[error(transparent)]
Io(#[from] io::Error),
#[error("not found")]
NotFound,
#[error("invalid storage key")]
BadKey,
}
#[async_trait]
pub trait Storage: Send + Sync {
async fn put(&self, key: &str, bytes: &[u8]) -> Result<(), StorageError>;
async fn get(&self, key: &str) -> Result<Vec<u8>, StorageError>;
async fn delete(&self, key: &str) -> Result<(), StorageError>;
async fn exists(&self, key: &str) -> Result<bool, StorageError>;
}