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:
3
backend/.gitignore
vendored
Normal file
3
backend/.gitignore
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
/target
|
||||
/.sqlx
|
||||
.env
|
||||
34
backend/Cargo.toml
Normal file
34
backend/Cargo.toml
Normal file
@@ -0,0 +1,34 @@
|
||||
[package]
|
||||
name = "mangalord"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
path = "src/lib.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "mangalord"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
axum = { version = "0.7", features = ["macros"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
sqlx = { version = "0.8", features = ["runtime-tokio", "postgres", "uuid", "chrono", "macros", "migrate"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
uuid = { version = "1", features = ["v4", "serde"] }
|
||||
chrono = { version = "0.4", features = ["serde"] }
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
tower-http = { version = "0.6", features = ["trace", "cors"] }
|
||||
thiserror = "1"
|
||||
anyhow = "1"
|
||||
async-trait = "0.1"
|
||||
dotenvy = "0.15"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3"
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
http-body-util = "0.1"
|
||||
mime = "0.3"
|
||||
27
backend/Dockerfile
Normal file
27
backend/Dockerfile
Normal file
@@ -0,0 +1,27 @@
|
||||
# Multi-stage build for the Rust backend.
|
||||
FROM rust:1-slim AS builder
|
||||
WORKDIR /app
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends pkg-config libssl-dev ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Cache deps separately from sources.
|
||||
COPY Cargo.toml ./
|
||||
RUN mkdir src && echo "fn main() {}" > src/main.rs && echo "" > src/lib.rs \
|
||||
&& cargo build --release \
|
||||
&& rm -rf src
|
||||
|
||||
COPY src ./src
|
||||
COPY migrations ./migrations
|
||||
RUN touch src/main.rs src/lib.rs && cargo build --release
|
||||
|
||||
FROM debian:bookworm-slim
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
WORKDIR /app
|
||||
COPY --from=builder /app/target/release/mangalord /usr/local/bin/mangalord
|
||||
COPY --from=builder /app/migrations /app/migrations
|
||||
ENV STORAGE_DIR=/var/lib/mangalord/storage
|
||||
EXPOSE 8080
|
||||
CMD ["mangalord"]
|
||||
49
backend/migrations/0001_init.sql
Normal file
49
backend/migrations/0001_init.sql
Normal file
@@ -0,0 +1,49 @@
|
||||
-- Initial schema for Mangalord.
|
||||
-- Designed for future extensions: tags, lists, fulltext/fuzzy search,
|
||||
-- OCR-derived metadata. New concepts get new tables joined here; do
|
||||
-- not jam them onto existing rows.
|
||||
|
||||
CREATE EXTENSION IF NOT EXISTS "pgcrypto";
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE mangas (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title text NOT NULL,
|
||||
author text,
|
||||
description text,
|
||||
cover_image_path text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX mangas_created_at_idx ON mangas (created_at DESC);
|
||||
CREATE INDEX mangas_title_lower_idx ON mangas (lower(title));
|
||||
|
||||
CREATE TABLE chapters (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
manga_id uuid NOT NULL REFERENCES mangas(id) ON DELETE CASCADE,
|
||||
number integer NOT NULL,
|
||||
title text,
|
||||
page_count integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (manga_id, number)
|
||||
);
|
||||
|
||||
CREATE INDEX chapters_manga_idx ON chapters (manga_id, number);
|
||||
|
||||
CREATE TABLE bookmarks (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
manga_id uuid NOT NULL REFERENCES mangas(id) ON DELETE CASCADE,
|
||||
chapter_id uuid REFERENCES chapters(id) ON DELETE SET NULL,
|
||||
page integer,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (user_id, manga_id, chapter_id)
|
||||
);
|
||||
|
||||
CREATE INDEX bookmarks_user_idx ON bookmarks (user_id, created_at DESC);
|
||||
39
backend/src/api/files.rs
Normal file
39
backend/src/api/files.rs
Normal 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
12
backend/src/api/health.rs
Normal 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
59
backend/src/api/mangas.rs
Normal 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
14
backend/src/api/mod.rs
Normal 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
36
backend/src/app.rs
Normal 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
22
backend/src/config.rs
Normal 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(),
|
||||
})
|
||||
}
|
||||
}
|
||||
14
backend/src/domain/bookmark.rs
Normal file
14
backend/src/domain/bookmark.rs
Normal 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>,
|
||||
}
|
||||
20
backend/src/domain/chapter.rs
Normal file
20
backend/src/domain/chapter.rs
Normal 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>,
|
||||
}
|
||||
22
backend/src/domain/manga.rs
Normal file
22
backend/src/domain/manga.rs
Normal 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>,
|
||||
}
|
||||
9
backend/src/domain/mod.rs
Normal file
9
backend/src/domain/mod.rs
Normal 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;
|
||||
11
backend/src/domain/user.rs
Normal file
11
backend/src/domain/user.rs
Normal 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
45
backend/src/error.rs
Normal 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
7
backend/src/lib.rs
Normal 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
21
backend/src/main.rs
Normal 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
76
backend/src/repo/manga.rs
Normal 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
1
backend/src/repo/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod manga;
|
||||
97
backend/src/storage/local.rs
Normal file
97
backend/src/storage/local.rs
Normal 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)));
|
||||
}
|
||||
}
|
||||
31
backend/src/storage/mod.rs
Normal file
31
backend/src/storage/mod.rs
Normal 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>;
|
||||
}
|
||||
77
backend/tests/api_mangas.rs
Normal file
77
backend/tests/api_mangas.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use serde_json::json;
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn list_is_empty_initially(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h.app.oneshot(common::get("/api/mangas")).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
assert_eq!(common::body_json(resp).await, json!([]));
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_then_list_roundtrip(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
|
||||
let created = h.app.clone().oneshot(common::post_json(
|
||||
"/api/mangas",
|
||||
json!({ "title": "Berserk", "author": "Kentaro Miura", "description": null }),
|
||||
)).await.unwrap();
|
||||
assert_eq!(created.status(), StatusCode::OK);
|
||||
let body = common::body_json(created).await;
|
||||
assert_eq!(body["title"], "Berserk");
|
||||
assert_eq!(body["author"], "Kentaro Miura");
|
||||
assert!(body["id"].as_str().is_some());
|
||||
|
||||
let listed = h.app.oneshot(common::get("/api/mangas")).await.unwrap();
|
||||
let listed_body = common::body_json(listed).await;
|
||||
assert_eq!(listed_body.as_array().unwrap().len(), 1);
|
||||
assert_eq!(listed_body[0]["title"], "Berserk");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn search_filters_by_title_and_author(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
|
||||
for (title, author) in [
|
||||
("One Piece", "Eiichiro Oda"),
|
||||
("Berserk", "Kentaro Miura"),
|
||||
("Vinland Saga", "Makoto Yukimura"),
|
||||
] {
|
||||
let _ = h.app.clone().oneshot(common::post_json(
|
||||
"/api/mangas",
|
||||
json!({ "title": title, "author": author }),
|
||||
)).await.unwrap();
|
||||
}
|
||||
|
||||
let resp = h.app.clone().oneshot(common::get("/api/mangas?search=miura")).await.unwrap();
|
||||
let body = common::body_json(resp).await;
|
||||
let titles: Vec<&str> = body.as_array().unwrap().iter().map(|m| m["title"].as_str().unwrap()).collect();
|
||||
assert_eq!(titles, vec!["Berserk"]);
|
||||
|
||||
let resp = h.app.oneshot(common::get("/api/mangas?search=saga")).await.unwrap();
|
||||
let body = common::body_json(resp).await;
|
||||
let titles: Vec<&str> = body.as_array().unwrap().iter().map(|m| m["title"].as_str().unwrap()).collect();
|
||||
assert_eq!(titles, vec!["Vinland Saga"]);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_rejects_empty_title(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h.app.oneshot(common::post_json(
|
||||
"/api/mangas",
|
||||
json!({ "title": " ", "author": null }),
|
||||
)).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn get_unknown_id_is_404(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h.app.oneshot(common::get("/api/mangas/00000000-0000-0000-0000-000000000000")).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
44
backend/tests/common/mod.rs
Normal file
44
backend/tests/common/mod.rs
Normal file
@@ -0,0 +1,44 @@
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::Request;
|
||||
use axum::Router;
|
||||
use http_body_util::BodyExt;
|
||||
use sqlx::PgPool;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use mangalord::app::{router, AppState};
|
||||
use mangalord::storage::LocalStorage;
|
||||
|
||||
pub struct Harness {
|
||||
pub app: Router,
|
||||
// Kept alive for the lifetime of the test so the temp dir is not dropped.
|
||||
pub _storage_dir: TempDir,
|
||||
}
|
||||
|
||||
pub fn harness(pool: PgPool) -> Harness {
|
||||
let storage_dir = tempfile::tempdir().expect("tempdir");
|
||||
let state = AppState {
|
||||
db: pool,
|
||||
storage: Arc::new(LocalStorage::new(storage_dir.path())),
|
||||
};
|
||||
Harness { app: router(state), _storage_dir: storage_dir }
|
||||
}
|
||||
|
||||
pub async fn body_json(response: axum::response::Response) -> serde_json::Value {
|
||||
let bytes = response.into_body().collect().await.unwrap().to_bytes();
|
||||
serde_json::from_slice(&bytes).expect("body is JSON")
|
||||
}
|
||||
|
||||
pub fn get(uri: &str) -> Request<Body> {
|
||||
Request::builder().uri(uri).body(Body::empty()).unwrap()
|
||||
}
|
||||
|
||||
pub fn post_json(uri: &str, body: serde_json::Value) -> Request<Body> {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri(uri)
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(body.to_string()))
|
||||
.unwrap()
|
||||
}
|
||||
14
backend/tests/health.rs
Normal file
14
backend/tests/health.rs
Normal file
@@ -0,0 +1,14 @@
|
||||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use sqlx::PgPool;
|
||||
use tower::ServiceExt;
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn health_returns_ok(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let resp = h.app.oneshot(common::get("/api/health")).await.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["status"], "ok");
|
||||
}
|
||||
Reference in New Issue
Block a user