Партии: оптимистичная блокировка (version) — устаревшие правки/отмена отклоняются (фикс гонки завершить-vs-отменить)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-17 22:39:20 +03:00
co-authored by Claude Opus 4.8
parent eb34714868
commit 16452f7bbe
8 changed files with 148 additions and 13 deletions
+1
View File
@@ -229,6 +229,7 @@ def update_match(
win_reason=body.win_reason,
win_reason_set=("win_reason" in body.model_fields_set),
participants=participants,
expected_version=body.expected_version,
)
audit_service.record(
session,
+6 -2
View File
@@ -1,7 +1,7 @@
"""Роутер партий: рандом фракции, старт, завершение, детали, правка, удаление."""
from __future__ import annotations
from fastapi import APIRouter, Depends, File, Request, UploadFile
from fastapi import APIRouter, Depends, File, Query, Request, UploadFile
from fastapi.responses import FileResponse
from sqlmodel import Session
@@ -69,6 +69,7 @@ def build_match_read(session: Session, match: Match, *, can_modify: bool = False
overall_comment=match.overall_comment,
created_by=match.created_by,
can_modify=can_modify,
version=match_service.match_version(match),
participants=parts,
attachments=[
attachment_read(a, f"/api/matches/{match.id}")
@@ -143,6 +144,7 @@ def finish_match(
win_reason=body.win_reason,
overall_comment=body.overall_comment,
overall_comment_set=("overall_comment" in body.model_fields_set),
expected_version=body.expected_version,
)
audit_service.record(
session,
@@ -200,6 +202,7 @@ def update_match(
win_reason=body.win_reason,
win_reason_set=("win_reason" in body.model_fields_set),
participants=participants,
expected_version=body.expected_version,
)
audit_service.record(
session,
@@ -278,6 +281,7 @@ def get_attachment(
def delete_match(
match_id: int,
request: Request,
expected_version: str | None = Query(None),
session: Session = Depends(get_session),
user: User = Depends(get_current_user),
) -> s.OkResponse:
@@ -285,7 +289,7 @@ def delete_match(
match_service.assert_can_modify(session, match, user)
match_id_val = match.id
group_id_val = match.group_id
match_service.delete_match(session, match)
match_service.delete_match(session, match, expected_version=expected_version)
audit_service.record(
session,
actor_id=user.id,
+4
View File
@@ -192,6 +192,8 @@ class MatchFinish(BaseModel):
participants: list[MatchFinishParticipant]
win_reason: WinReason
overall_comment: str | None = None
# Оптимистичная блокировка: версия партии, которую видел клиент (см. MatchRead.version).
expected_version: str | None = None
# Полный участник (правка завершённой партии админом).
@@ -208,6 +210,7 @@ class MatchUpdate(BaseModel):
overall_comment: str | None = None
win_reason: WinReason | None = None
participants: list[ParticipantInput] | None = None
expected_version: str | None = None # оптимистичная блокировка
class MatchParticipantRead(BaseModel):
@@ -242,6 +245,7 @@ class MatchRead(BaseModel):
overall_comment: str | None = None
created_by: int
can_modify: bool = False # может ли текущий зритель править/завершать партию
version: str # для оптимистичной блокировки (iso updated_at); клиент шлёт обратно
participants: list[MatchParticipantRead] = []
attachments: list[AttachmentRead] = []
+21 -2
View File
@@ -16,7 +16,7 @@ from app.core.errors import (
NotFoundError,
ValidationError,
)
from app.core.timeutil import app_today
from app.core.timeutil import app_today, iso_utc
from app.models import Faction, GroupMember, Match, MatchParticipant, User
from app.services import group_service
@@ -70,6 +70,20 @@ def get_match(session: Session, match_id: int) -> Match:
return match
def match_version(match: Match) -> str:
"""Версия партии для оптимистичной блокировки (меняется при любом изменении)."""
return iso_utc(match.updated_at)
def assert_version(match: Match, expected: str | None) -> None:
"""Если клиент прислал версию и она устарела — отказываем (кто-то изменил партию)."""
if expected is not None and expected != match_version(match):
raise ConflictError(
"Партия уже изменена на другом устройстве — обновите страницу.",
code="STALE_WRITE",
)
def participants_detail(
session: Session, match_id: int
) -> list[tuple[MatchParticipant, User, Faction]]:
@@ -193,7 +207,9 @@ def finish_match(
win_reason: str,
overall_comment: str | None = None,
overall_comment_set: bool = False,
expected_version: str | None = None,
) -> Match:
assert_version(match, expected_version)
if match.status != "in_progress":
raise ConflictError("Партия уже завершена.")
if win_reason not in WIN_REASONS:
@@ -274,8 +290,10 @@ def update_match(
win_reason: str | None = None,
win_reason_set: bool = False,
participants: list[ParticipantInput] | None = None,
expected_version: str | None = None,
) -> Match:
"""Правка завершённой партии (админ): полный список участников с местами."""
assert_version(match, expected_version)
if played_at is not None:
match.played_at = played_at
if overall_comment_set:
@@ -317,9 +335,10 @@ def update_match(
return match
def delete_match(session: Session, match: Match) -> None:
def delete_match(session: Session, match: Match, expected_version: str | None = None) -> None:
from app.services import attachment_service # избегаем цикла импорта
assert_version(match, expected_version)
match_id = match.id
session.delete(match) # участники и вложения (БД) удалятся каскадом (FK ON DELETE CASCADE)
session.commit()