feat: live-sync per websocket im backend
- /api/ws authentifiziert über das Session-Cookie, Origin-Pflicht gegen CSWSH - Hub im Prozess verteilt clip.created/updated/deleted an alle Geräte des Benutzers - Ereignisse erst nach erfolgreichem Commit (BackgroundTasks), keine bei Konflikt - Logout, Session-Widerruf, Passwortänderung und Admin-Aktionen schließen betroffene Verbindungen (4401); Session wird alle 5 Minuten neu geprüft - Heartbeat alle 30 s, höchstens 20 Verbindungen pro Benutzer - CSP erlaubt wss:// zur eigenen Domain, eingehende WS-Nachrichten max. 64 KiB Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
a444f28681
commit
0d89399090
12 files changed
+483
-38
No files matched your search
@@ -1,12 +1,13 @@
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query, status
|
||||
from fastapi import APIRouter, BackgroundTasks, 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
|
||||
from app.ws.hub import hub
|
||||
|
||||
router = APIRouter(prefix="/clips", tags=["clips"])
|
||||
|
||||
@@ -14,6 +15,15 @@ router = APIRouter(prefix="/clips", tags=["clips"])
|
||||
_NULLABLE_FIELDS = {"title", "language"}
|
||||
|
||||
|
||||
def _notify(background: BackgroundTasks, user_id: int, event: str, data: dict) -> None:
|
||||
"""Tell all devices of the user about a change, after the response is sent."""
|
||||
background.add_task(hub.broadcast, user_id, {"type": event, "data": data})
|
||||
|
||||
|
||||
def _clip_data(clip: Clip) -> dict:
|
||||
return ClipOut.model_validate(clip).model_dump(mode="json")
|
||||
|
||||
|
||||
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)
|
||||
@@ -34,8 +44,10 @@ def list_clips(
|
||||
|
||||
|
||||
@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())
|
||||
def create_clip(body: ClipCreate, user: CurrentUser, db: DbSession, background: BackgroundTasks):
|
||||
clip = clip_service.create_clip(db, user.id, **body.model_dump())
|
||||
_notify(background, user.id, "clip.created", _clip_data(clip))
|
||||
return clip
|
||||
|
||||
|
||||
@router.get("/{clip_id}", response_model=ClipOut)
|
||||
@@ -44,7 +56,13 @@ def get_clip(clip_id: int, user: CurrentUser, db: DbSession):
|
||||
|
||||
|
||||
@router.patch("/{clip_id}", response_model=ClipOut)
|
||||
def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession):
|
||||
def update_clip(
|
||||
clip_id: int,
|
||||
body: ClipUpdate,
|
||||
user: CurrentUser,
|
||||
db: DbSession,
|
||||
background: BackgroundTasks,
|
||||
):
|
||||
clip = _get_own_clip(db, user, clip_id)
|
||||
changes = {
|
||||
field: getattr(body, field)
|
||||
@@ -52,18 +70,23 @@ def update_clip(clip_id: int, body: ClipUpdate, user: CurrentUser, db: DbSession
|
||||
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)
|
||||
clip = 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"),
|
||||
"current": _clip_data(exc.current),
|
||||
},
|
||||
)
|
||||
_notify(background, user.id, "clip.updated", _clip_data(clip))
|
||||
return clip
|
||||
|
||||
|
||||
@router.delete("/{clip_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_clip(clip_id: int, user: CurrentUser, db: DbSession) -> None:
|
||||
def delete_clip(
|
||||
clip_id: int, user: CurrentUser, db: DbSession, background: BackgroundTasks
|
||||
) -> None:
|
||||
if not clip_service.delete_clip(db, user.id, clip_id):
|
||||
raise HTTPException(status.HTTP_404_NOT_FOUND, "Clip nicht gefunden.")
|
||||
_notify(background, user.id, "clip.deleted", {"id": clip_id})
|
||||
Reference in new issue
Block a user