Files
tsumugu/backend/app/main.py
T
LarsandClaude Sonnet 5.5 d39c7d7999 Liefere Zähler, Rauminhalt und Teilen im Stapel für die neue Ablage.
Akten und Vorgänge melden Unterakten, Vorgänge und die Räume, mit denen sie geteilt sind, jeweils nur aus Lesbarem. Neue Endpunkte zeigen die Räume als Kacheln, den Inhalt eines Raums und teilen mehrere Einträge auf einmal oder gar nicht. Beim Anlegen lässt sich ein Eintrag gleich in einen Raum legen.

Die lokale Suite läuft mit 148 Tests grün.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-22 11:38:02 +02:00

136 lines
4.6 KiB
Python

"""Application factory. Importing this module does not open a database connection."""
from __future__ import annotations
import logging
from contextlib import asynccontextmanager
from fastapi import FastAPI, Request
from fastapi.exceptions import RequestValidationError
from fastapi.responses import JSONResponse
from app.api.accounts import router as accounts_router
from app.api.correspondence import router as correspondence_router
from app.api.export import router as export_router
from app.api.library import router as library_router
from app.api.rooms import router as rooms_router
from app.api.roomshare import router as roomshare_router
from app.api.team import router as team_router
from app.api.routes import router
from app.api.sources import router as sources_router
from app.core.errors import Problem, problem_response
from app.core.settings import get_settings
from app.db.pool import open_pool
logger = logging.getLogger("tsumugu")
def _database_ok(app: FastAPI) -> bool:
pool = getattr(app.state, "pool", None)
if pool is None:
return False
try:
with pool.connection() as conn:
conn.execute("SELECT 1")
conn.rollback()
return True
except Exception:
logger.warning("database check failed")
return False
def create_app() -> FastAPI:
settings = get_settings()
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(name)s %(message)s")
@asynccontextmanager
async def lifespan(app: FastAPI):
app.state.pool = open_pool(settings)
try:
yield
finally:
app.state.pool.close()
app = FastAPI(title="Tsumugu", docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
app.state.settings = settings
@app.middleware("http")
async def origin_guard(request: Request, call_next):
if request.method not in {"GET", "HEAD", "OPTIONS"} and request.url.path.startswith("/api/"):
origin = request.headers.get("origin")
if origin not in settings.origin_set:
problem = Problem(403, "Keine Berechtigung", "Der Ursprung der Anfrage ist nicht erlaubt.", "forbidden")
return problem_response(problem, request)
response = await call_next(request)
logger.info("%s %s -> %s", request.method, request.url.path, response.status_code)
return response
@app.exception_handler(Problem)
async def handle_problem(request: Request, exc: Problem):
return problem_response(exc, request)
@app.exception_handler(RequestValidationError)
async def handle_validation(request: Request, exc: RequestValidationError):
return JSONResponse(
status_code=422,
content={
"type": "about:blank",
"title": "Eingabe ungültig",
"status": 422,
"detail": "Die Eingabe ist unvollständig oder ungültig.",
"instance": request.url.path,
"code": "unprocessable",
},
media_type="application/problem+json",
)
@app.exception_handler(Exception)
async def handle_unexpected(request: Request, exc: Exception):
logger.exception("unhandled error")
return JSONResponse(
status_code=500,
content={
"type": "about:blank",
"title": "Unerwarteter Fehler",
"status": 500,
"detail": "Die Aktion konnte nicht abgeschlossen werden.",
"instance": request.url.path,
"code": "internal",
},
media_type="application/problem+json",
)
@app.get("/api/health")
def api_health():
ok = _database_ok(app)
return JSONResponse(
status_code=200 if ok else 503,
content={"status": "ok" if ok else "degraded", "app": "tsumugu"},
)
@app.get("/health/live")
def health_live():
return {"status": "ok", "app": "tsumugu"}
@app.get("/health/ready")
def health_ready():
ok = _database_ok(app)
return JSONResponse(
status_code=200 if ok else 503,
content={"status": "ok" if ok else "degraded", "app": "tsumugu"},
)
app.include_router(router)
app.include_router(accounts_router)
app.include_router(library_router)
app.include_router(rooms_router)
app.include_router(roomshare_router)
app.include_router(team_router)
app.include_router(sources_router)
app.include_router(export_router)
app.include_router(correspondence_router)
return app
app = create_app()