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,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