feat: clips-api mit konflikterkennung
- GET/POST /api/clips, GET/PATCH/DELETE /api/clips/{id}
- angeheftete zuerst, dann zuletzt geändert; Seitenweise mit limit/offset
- PATCH mit version liefert 409 samt aktuellem Stand bei paralleler Änderung
- Inhalt bis CLIP_MAX_CHARS (Standard 200000), Sprache aus fester Liste
- fremde Clips sind nicht von fehlenden unterscheidbar (404), Tests dafür
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
f1bfa27ba3
commit
4caab7e657
6 files changed
+478
-1
No files matched your search
@@ -0,0 +1,69 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
from app.api.deps import CurrentUser, DbSession
|
||||
from app.models import Clip
|
||||
from app.schemas.clips import ClipCreate, ClipList, ClipOut, ClipUpdate
|
||||
from app.services import clips as clip_service
|
||||
|
||||
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||
|
||||
# Fields that may be null on purpose (clearing them); all others are ignored when null
|
||||
_NULLABLE_FIELDS = {"title", "language"}
|
||||
|
||||
|
||||
def _get_own_clip(db: DbSession, user: CurrentUser, clip_id: int) -> Clip:
|
||||
# Foreign and missing clips look the same, so ids of other users are not revealed
|
||||
clip = clip_service.get_clip(db, user.id, clip_id)
|
||||
if clip is None:
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
return clip
|
||||
|
||||
|
||||
@router.get("", response_model=ClipList)
|
||||
def list_clips(
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
limit: Annotated[int, Query(ge=1, le=100)] = 50,
|
||||
offset: Annotated[int, Query(ge=0)] = 0,
|
||||
) -> ClipList:
|
||||
items, total = clip_service.list_clips(db, user.id, limit, offset)
|
||||
return ClipList(items=[ClipOut.model_validate(c) for c in items], total=total)
|
||||
|
||||
|
||||
@router.post("", response_model=ClipOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession):
|
||||
return clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
|
||||
|
||||
@router.get("/{clip_id}", response_model=ClipOut)
|
||||
def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
return _get_own_clip(db, user, clip_id)
|
||||
|
||||
|
||||
@router.patch("/{clip_id}", response_model=ClipOut)
|
||||
def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession):
|
||||
clip = _get_own_clip(db, user, clip_id)
|
||||
changes = {
|
||||
field: getattr(body, field)
|
||||
for field in body.model_fields_set - {"version"}
|
||||
if getattr(body, field) is not None or field in _NULLABLE_FIELDS
|
||||
}
|
||||
try:
|
||||
return clip_service.update_clip(db, user.id, clip, changes, body.version)
|
||||
except clip_service.ClipConflict as exc:
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
content={
|
||||
"detail": "Der Clip wurde inzwischen auf einem anderen Gerät geändert.",
|
||||
"current": ClipOut.model_validate(exc.current).model_dump(mode="json"),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_clip(clip_id: int, user: CurrentUser, db: DbSession) -> None:
|
||||
if not clip_service.delete_clip(db, user.id, clip_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
@@ -26,6 +26,8 @@ class Settings(BaseSettings):
|
||||
# Only meaningful once the real client IP is known (FORWARDED_ALLOW_IPS set to the proxy)
|
||||
login_ip_lockout: bool = False
|
||||
|
||||
clip_max_chars: int = 200_000
|
||||
|
||||
initial_admin_username: str | None = None
|
||||
initial_admin_password: str | None = None
|
||||
|
||||
|
||||
+2
-1
@@ -9,7 +9,7 @@ from fastapi.concurrency import run_in_threadpool
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
|
||||
from app import __version__
|
||||
from app.api import admin, auth, health
|
||||
from app.api import admin, auth, clips, health
|
||||
from app.config import get_settings
|
||||
from app.db import _session_factory
|
||||
from app.middleware import (
|
||||
@@ -110,6 +110,7 @@ def create_app() -> FastAPI:
|
||||
app.include_router(health.router, prefix="/api")
|
||||
app.include_router(auth.router, prefix="/api")
|
||||
app.include_router(admin.router, prefix="/api")
|
||||
app.include_router(clips.router, prefix="/api")
|
||||
|
||||
@app.exception_handler(UserError)
|
||||
def user_error_handler(_request: Request, exc: UserError) -> JSONResponse:
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
from datetime import datetime
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field
|
||||
|
||||
from app.models import ClipKind
|
||||
|
||||
# Hard upper bound for request parsing; the configurable limit is enforced in the service
|
||||
_CONTENT_MAX = 1_000_000
|
||||
|
||||
|
||||
class ClipCreate(BaseModel):
|
||||
kind: ClipKind = ClipKind.TEXT
|
||||
title: str | None = Field(default=None, max_length=1000)
|
||||
content: str = Field(max_length=_CONTENT_MAX)
|
||||
language: str | None = Field(default=None, max_length=32)
|
||||
pinned: bool = False
|
||||
|
||||
|
||||
class ClipUpdate(BaseModel):
|
||||
"""Partial update; only fields present in the request are changed."""
|
||||
|
||||
kind: ClipKind | None = None
|
||||
title: str | None = Field(default=None, max_length=1000)
|
||||
content: str | None = Field(default=None, max_length=_CONTENT_MAX)
|
||||
language: str | None = Field(default=None, max_length=32)
|
||||
pinned: bool | None = None
|
||||
version: int | None = Field(default=None, description="Expected version for conflict check")
|
||||
|
||||
|
||||
class ClipOut(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
id: int
|
||||
kind: ClipKind
|
||||
title: str | None
|
||||
content: str
|
||||
language: str | None
|
||||
pinned: bool
|
||||
version: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
class ClipList(BaseModel):
|
||||
items: list[ClipOut]
|
||||
total: int
|
||||
@@ -0,0 +1,125 @@
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import delete, func, select, update
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import get_settings
|
||||
from app.languages import LANGUAGES
|
||||
from app.models import Clip, ClipKind, utcnow
|
||||
from app.services.users import UserError
|
||||
|
||||
# Changing only these fields does not count as an edit (no new updated_at)
|
||||
_META_FIELDS = frozenset({"pinned"})
|
||||
|
||||
|
||||
class ClipConflict(Exception):
|
||||
"""The clip was changed elsewhere since the client loaded it."""
|
||||
|
||||
def __init__(self, current: Clip) -> None:
|
||||
super().__init__("clip version conflict")
|
||||
self.current = current
|
||||
|
||||
|
||||
def _normalize(kind: ClipKind, title: str | None, content: str, language: str | None):
|
||||
max_chars = get_settings().clip_max_chars
|
||||
if not content.strip():
|
||||
raise UserError("Der Inhalt darf nicht leer sein.")
|
||||
if len(content) > max_chars:
|
||||
raise UserError(
|
||||
f"Der Inhalt ist zu lang (höchstens {max_chars:,} Zeichen).".replace(",", ".")
|
||||
)
|
||||
title = (title or "").strip() or None
|
||||
if title is not None and len(title) > 200:
|
||||
raise UserError("Der Titel ist zu lang (höchstens 200 Zeichen).")
|
||||
if kind == ClipKind.TEXT:
|
||||
language = None
|
||||
else:
|
||||
language = language or "plaintext"
|
||||
if language not in LANGUAGES:
|
||||
raise UserError("Unbekannte Sprache.")
|
||||
return title, language
|
||||
|
||||
|
||||
def list_clips(db: Session, user_id: int, limit: int, offset: int) -> tuple[list[Clip], int]:
|
||||
items = db.scalars(
|
||||
select(Clip)
|
||||
.where(Clip.user_id == user_id)
|
||||
.order_by(Clip.pinned.desc(), Clip.updated_at.desc(), Clip.id.desc())
|
||||
.limit(limit)
|
||||
.offset(offset)
|
||||
)
|
||||
total = db.scalar(select(func.count()).select_from(Clip).where(Clip.user_id == user_id))
|
||||
return list(items), total or 0
|
||||
|
||||
|
||||
def get_clip(db: Session, user_id: int, clip_id: int) -> Clip | None:
|
||||
return db.scalar(select(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||
|
||||
|
||||
def create_clip(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
*,
|
||||
content: str,
|
||||
kind: ClipKind = ClipKind.TEXT,
|
||||
title: str | None = None,
|
||||
language: str | None = None,
|
||||
pinned: bool = False,
|
||||
) -> Clip:
|
||||
title, language = _normalize(kind, title, content, language)
|
||||
clip = Clip(
|
||||
user_id=user_id,
|
||||
kind=kind,
|
||||
title=title,
|
||||
content=content,
|
||||
language=language,
|
||||
pinned=pinned,
|
||||
)
|
||||
db.add(clip)
|
||||
db.commit()
|
||||
return clip
|
||||
|
||||
|
||||
def update_clip(
|
||||
db: Session,
|
||||
user_id: int,
|
||||
clip: Clip,
|
||||
changes: dict[str, Any],
|
||||
expected_version: int | None = None,
|
||||
) -> Clip:
|
||||
"""Apply a partial update. With expected_version, a concurrent change raises ClipConflict."""
|
||||
kind = changes.get("kind", clip.kind)
|
||||
title = changes.get("title", clip.title)
|
||||
content = changes.get("content", clip.content)
|
||||
language = changes.get("language", clip.language)
|
||||
title, language = _normalize(kind, title, content, language)
|
||||
|
||||
values: dict[str, Any] = {
|
||||
"kind": kind,
|
||||
"title": title,
|
||||
"content": content,
|
||||
"language": language,
|
||||
"pinned": changes.get("pinned", clip.pinned),
|
||||
"version": Clip.version + 1,
|
||||
}
|
||||
if set(changes) - _META_FIELDS:
|
||||
values["updated_at"] = utcnow()
|
||||
|
||||
# Conditional UPDATE keeps the version check atomic across concurrent requests
|
||||
stmt = update(Clip).where(Clip.id == clip.id, Clip.user_id == user_id)
|
||||
if expected_version is not None:
|
||||
stmt = stmt.where(Clip.version == expected_version)
|
||||
result = db.execute(stmt.values(**values).execution_options(synchronize_session=False))
|
||||
if result.rowcount == 0:
|
||||
db.rollback()
|
||||
db.refresh(clip)
|
||||
raise ClipConflict(clip)
|
||||
db.commit()
|
||||
db.refresh(clip)
|
||||
return clip
|
||||
|
||||
|
||||
def delete_clip(db: Session, user_id: int, clip_id: int) -> bool:
|
||||
result = db.execute(delete(Clip).where(Clip.id == clip_id, Clip.user_id == user_id))
|
||||
db.commit()
|
||||
return result.rowcount > 0
|
||||
Reference in new issue
Block a user