feat: fastapi-backend mit healthcheck und alembic-basis
- GET /api/health prüft die Datenbankverbindung - SQLite im WAL-Modus unter /data/app.db - Auslieferung des gebauten Frontends mit SPA-Fallback - leere Basis-Migration, Tests mit pytest Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
ff666175d0
commit
8e6ef05304
15 files changed
+414
No files matched your search
@@ -0,0 +1,39 @@
|
|||||||
|
[alembic]
|
||||||
|
script_location = %(here)s/alembic
|
||||||
|
file_template = %%(year)d%%(month).2d%%(day).2d_%%(rev)s_%%(slug)s
|
||||||
|
prepend_sys_path = .
|
||||||
|
# sqlalchemy.url is taken from app settings in alembic/env.py
|
||||||
|
|
||||||
|
[loggers]
|
||||||
|
keys = root,sqlalchemy,alembic
|
||||||
|
|
||||||
|
[handlers]
|
||||||
|
keys = console
|
||||||
|
|
||||||
|
[formatters]
|
||||||
|
keys = generic
|
||||||
|
|
||||||
|
[logger_root]
|
||||||
|
level = WARNING
|
||||||
|
handlers = console
|
||||||
|
qualname =
|
||||||
|
|
||||||
|
[logger_sqlalchemy]
|
||||||
|
level = WARNING
|
||||||
|
handlers =
|
||||||
|
qualname = sqlalchemy.engine
|
||||||
|
|
||||||
|
[logger_alembic]
|
||||||
|
level = INFO
|
||||||
|
handlers =
|
||||||
|
qualname = alembic
|
||||||
|
|
||||||
|
[handler_console]
|
||||||
|
class = logging.StreamHandler
|
||||||
|
args = (sys.stderr,)
|
||||||
|
level = NOTSET
|
||||||
|
formatter = generic
|
||||||
|
|
||||||
|
[formatter_generic]
|
||||||
|
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||||
|
datefmt = %H:%M:%S
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
from app.db import get_engine
|
||||||
|
from app.models import Base
|
||||||
|
|
||||||
|
config = context.config
|
||||||
|
|
||||||
|
if config.config_file_name is not None:
|
||||||
|
fileConfig(config.config_file_name)
|
||||||
|
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_offline() -> None:
|
||||||
|
context.configure(
|
||||||
|
url=str(get_engine().url),
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
render_as_batch=True,
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
def run_migrations_online() -> None:
|
||||||
|
with get_engine().connect() as connection:
|
||||||
|
# render_as_batch: SQLite needs table rebuilds for most ALTER operations
|
||||||
|
context.configure(
|
||||||
|
connection=connection, target_metadata=target_metadata, render_as_batch=True
|
||||||
|
)
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
revision: str = ${repr(up_revision)}
|
||||||
|
down_revision: str | None = ${repr(down_revision)}
|
||||||
|
branch_labels: str | Sequence[str] | None = ${repr(branch_labels)}
|
||||||
|
depends_on: str | Sequence[str] | None = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
"""initial (empty baseline)
|
||||||
|
|
||||||
|
Revision ID: 0001
|
||||||
|
Revises:
|
||||||
|
Create Date: 2026-10-25
|
||||||
|
|
||||||
|
"""
|
||||||
|
|
||||||
|
from collections.abc import Sequence
|
||||||
|
|
||||||
|
revision: str = "0001"
|
||||||
|
down_revision: str | None = None
|
||||||
|
branch_labels: str | Sequence[str] | None = None
|
||||||
|
depends_on: str | Sequence[str] | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
from importlib.metadata import PackageNotFoundError, version
|
||||||
|
|
||||||
|
try:
|
||||||
|
__version__ = version("lan-clipboard")
|
||||||
|
except PackageNotFoundError: # running from source without install
|
||||||
|
__version__ = "0.0.0"
|
||||||
Whitespace-only changes.
@@ -0,0 +1,37 @@
|
|||||||
|
import logging
|
||||||
|
from typing import Annotated, Literal
|
||||||
|
|
||||||
|
from fastapi import APIRouter, Depends, Response, status
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy import text
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from app import __version__
|
||||||
|
from app.db import get_db
|
||||||
|
|
||||||
|
logger = logging.getLogger(__name__)
|
||||||
|
|
||||||
|
router = APIRouter()
|
||||||
|
|
||||||
|
|
||||||
|
class HealthResponse(BaseModel):
|
||||||
|
status: Literal["ok", "error"]
|
||||||
|
version: str
|
||||||
|
db: Literal["ok", "error"]
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/health", response_model=HealthResponse)
|
||||||
|
def health(response: Response, db: Annotated[Session, Depends(get_db)]) -> HealthResponse:
|
||||||
|
try:
|
||||||
|
db.execute(text("SELECT 1"))
|
||||||
|
db_status = "ok"
|
||||||
|
except Exception:
|
||||||
|
logger.exception("Database health check failed")
|
||||||
|
db_status = "error"
|
||||||
|
response.status_code = status.HTTP_503_SERVICE_UNAVAILABLE
|
||||||
|
|
||||||
|
return HealthResponse(
|
||||||
|
status="ok" if db_status == "ok" else "error",
|
||||||
|
version=__version__,
|
||||||
|
db=db_status,
|
||||||
|
)
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
from functools import lru_cache
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||||
|
|
||||||
|
data_dir: Path = Path("/data")
|
||||||
|
static_dir: Path = Path("/app/static")
|
||||||
|
log_level: str = "info"
|
||||||
|
|
||||||
|
@property
|
||||||
|
def database_url(self) -> str:
|
||||||
|
return f"sqlite:///{self.data_dir / 'app.db'}"
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
return Settings()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
from collections.abc import Iterator
|
||||||
|
from functools import lru_cache
|
||||||
|
|
||||||
|
from sqlalchemy import Engine, create_engine, event
|
||||||
|
from sqlalchemy.orm import Session, sessionmaker
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
|
||||||
|
def _set_sqlite_pragmas(dbapi_connection, _connection_record) -> None:
|
||||||
|
cursor = dbapi_connection.cursor()
|
||||||
|
cursor.execute("PRAGMA journal_mode=WAL")
|
||||||
|
cursor.execute("PRAGMA foreign_keys=ON")
|
||||||
|
cursor.execute("PRAGMA busy_timeout=5000")
|
||||||
|
cursor.close()
|
||||||
|
|
||||||
|
|
||||||
|
def create_db_engine(url: str) -> Engine:
|
||||||
|
engine = create_engine(url, connect_args={"check_same_thread": False})
|
||||||
|
event.listen(engine, "connect", _set_sqlite_pragmas)
|
||||||
|
return engine
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_engine() -> Engine:
|
||||||
|
settings = get_settings()
|
||||||
|
settings.data_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
return create_db_engine(settings.database_url)
|
||||||
|
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def _session_factory() -> sessionmaker[Session]:
|
||||||
|
return sessionmaker(bind=get_engine(), expire_on_commit=False)
|
||||||
|
|
||||||
|
|
||||||
|
def get_db() -> Iterator[Session]:
|
||||||
|
with _session_factory()() as session:
|
||||||
|
yield session
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from fastapi import FastAPI, HTTPException
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
|
||||||
|
from app import __version__
|
||||||
|
from app.api import health
|
||||||
|
from app.config import get_settings
|
||||||
|
|
||||||
|
|
||||||
|
def _register_frontend(app: FastAPI, static_dir: Path) -> None:
|
||||||
|
"""Serve the built Vue SPA; unknown non-API paths fall back to index.html."""
|
||||||
|
root = static_dir.resolve()
|
||||||
|
index_file = root / "index.html"
|
||||||
|
|
||||||
|
@app.get("/{path:path}", include_in_schema=False)
|
||||||
|
def spa(path: str) -> FileResponse:
|
||||||
|
if path == "api" or path.startswith("api/") or not index_file.is_file():
|
||||||
|
raise HTTPException(status_code=404)
|
||||||
|
candidate = (root / path).resolve()
|
||||||
|
if path and candidate.is_relative_to(root) and candidate.is_file():
|
||||||
|
return FileResponse(candidate)
|
||||||
|
return FileResponse(index_file, headers={"Cache-Control": "no-cache"})
|
||||||
|
|
||||||
|
|
||||||
|
def create_app() -> FastAPI:
|
||||||
|
settings = get_settings()
|
||||||
|
app = FastAPI(
|
||||||
|
title="LAN-Clipboard",
|
||||||
|
version=__version__,
|
||||||
|
docs_url="/api/docs",
|
||||||
|
openapi_url="/api/openapi.json",
|
||||||
|
redoc_url=None,
|
||||||
|
)
|
||||||
|
app.include_router(health.router, prefix="/api")
|
||||||
|
_register_frontend(app, settings.static_dir)
|
||||||
|
return app
|
||||||
|
|
||||||
|
|
||||||
|
app = create_app()
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
from sqlalchemy.orm import DeclarativeBase
|
||||||
|
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
[project]
|
||||||
|
name = "lan-clipboard"
|
||||||
|
version = "0.1.0"
|
||||||
|
description = "Self-hosted web clipboard for the private network"
|
||||||
|
requires-python = ">=3.13"
|
||||||
|
dependencies = [
|
||||||
|
"fastapi>=0.115",
|
||||||
|
"uvicorn[standard]>=0.32",
|
||||||
|
"sqlalchemy>=2.0.36",
|
||||||
|
"alembic>=1.14",
|
||||||
|
"pydantic>=2.10",
|
||||||
|
"pydantic-settings>=2.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[project.optional-dependencies]
|
||||||
|
dev = [
|
||||||
|
"pytest>=8.3",
|
||||||
|
"httpx>=0.28",
|
||||||
|
"ruff>=0.8",
|
||||||
|
]
|
||||||
|
|
||||||
|
[build-system]
|
||||||
|
requires = ["setuptools>=75"]
|
||||||
|
build-backend = "setuptools.build_meta"
|
||||||
|
|
||||||
|
[tool.setuptools.packages.find]
|
||||||
|
include = ["app*"]
|
||||||
|
|
||||||
|
[tool.ruff]
|
||||||
|
line-length = 100
|
||||||
|
target-version = "py313"
|
||||||
|
|
||||||
|
[tool.ruff.lint]
|
||||||
|
select = ["E", "F", "W", "I", "B", "UP", "SIM", "S", "ASYNC"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.isort]
|
||||||
|
known-first-party = ["app"]
|
||||||
|
known-third-party = ["alembic"]
|
||||||
|
|
||||||
|
[tool.ruff.lint.per-file-ignores]
|
||||||
|
"tests/**" = ["S101"]
|
||||||
|
|
||||||
|
[tool.pytest.ini_options]
|
||||||
|
testpaths = ["tests"]
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
from collections.abc import Iterator
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from fastapi.testclient import TestClient
|
||||||
|
|
||||||
|
from app.config import get_settings
|
||||||
|
from app.db import _session_factory, get_engine
|
||||||
|
|
||||||
|
|
||||||
|
def _clear_caches() -> None:
|
||||||
|
get_settings.cache_clear()
|
||||||
|
get_engine.cache_clear()
|
||||||
|
_session_factory.cache_clear()
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def static_dir(tmp_path):
|
||||||
|
"""Directory for the built frontend; empty by default (no SPA routes)."""
|
||||||
|
path = tmp_path / "static"
|
||||||
|
path.mkdir()
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def client(tmp_path, static_dir, monkeypatch) -> Iterator[TestClient]:
|
||||||
|
monkeypatch.setenv("DATA_DIR", str(tmp_path / "data"))
|
||||||
|
monkeypatch.setenv("STATIC_DIR", str(static_dir))
|
||||||
|
_clear_caches()
|
||||||
|
|
||||||
|
from app.main import create_app
|
||||||
|
|
||||||
|
with TestClient(create_app()) as test_client:
|
||||||
|
yield test_client
|
||||||
|
|
||||||
|
get_engine().dispose()
|
||||||
|
_clear_caches()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import pytest
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture
|
||||||
|
def spa_client(tmp_path, static_dir, client):
|
||||||
|
(static_dir / "assets").mkdir()
|
||||||
|
(static_dir / "index.html").write_text("<html>spa</html>")
|
||||||
|
(static_dir / "assets" / "app.js").write_text("console.log('x')")
|
||||||
|
(tmp_path / "secret.txt").write_text("secret")
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def test_serves_index_at_root(spa_client):
|
||||||
|
response = spa_client.get("/")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert "spa" in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_serves_static_asset(spa_client):
|
||||||
|
response = spa_client.get("/assets/app.js")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert "console.log" in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_client_route_falls_back_to_index(spa_client):
|
||||||
|
response = spa_client.get("/clips/123")
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert "spa" in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_path_traversal_is_blocked(spa_client):
|
||||||
|
response = spa_client.get("/..%2Fsecret.txt")
|
||||||
|
assert "secret" not in response.text
|
||||||
|
|
||||||
|
|
||||||
|
def test_api_paths_are_not_swallowed_by_spa(spa_client):
|
||||||
|
assert spa_client.get("/api/unknown").status_code == 404
|
||||||
|
assert spa_client.get("/api/health").json()["status"] == "ok"
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
from sqlalchemy import text
|
||||||
|
|
||||||
|
from app import __version__
|
||||||
|
from app.db import get_engine
|
||||||
|
|
||||||
|
|
||||||
|
def test_health_ok(client):
|
||||||
|
response = client.get("/api/health")
|
||||||
|
|
||||||
|
assert response.status_code == 200
|
||||||
|
assert response.json() == {"status": "ok", "version": __version__, "db": "ok"}
|
||||||
|
|
||||||
|
|
||||||
|
def test_sqlite_uses_wal(client):
|
||||||
|
client.get("/api/health")
|
||||||
|
|
||||||
|
with get_engine().connect() as conn:
|
||||||
|
assert conn.execute(text("PRAGMA journal_mode")).scalar() == "wal"
|
||||||
|
assert conn.execute(text("PRAGMA foreign_keys")).scalar() == 1
|
||||||
|
|
||||||
|
|
||||||
|
def test_unknown_api_path_returns_404(client):
|
||||||
|
assert client.get("/api/does-not-exist").status_code == 404
|
||||||
Reference in new issue
Block a user