Files
tavolo/src/scopa/stats.py
T
woggioni e9ddb82e9a Initial scopone scientifico backend
Multiplayer scopone scientifico backend on the kaya framework:

- OIDC login (kaya-oidc), session-backed WebSocket auth
- Pure rules engine (forced captures, scopa, primiera scoring) with
  full-match simulation tests
- Live game state in Redis (JSON + TTL, join codes, per-game locks,
  pub/sub state push); in-memory fallback for tests
- WebSocket /ws/games/{id} for real-time play; REST lobby endpoints
  (create/join/snapshot) with hidden-hand views
- Finished matches persisted to Postgres (Tortoise + aerich) for match
  history and leaderboard endpoints
- Docker Compose stack: postgres, redis, mock-oauth2-server, db-migrate, app
- 45 tests passing; mypy clean
2026-09-16 13:20:05 +08:00

58 lines
1.8 KiB
Python

"""Copy finished match results from Redis into Postgres.
Called once when a game reaches the finished phase (guarded by the
``stats_saved`` flag on the state). The write is transactional so a match
never appears with only some of its players.
"""
from __future__ import annotations
import uuid
from datetime import datetime, timezone
from typing import Optional
from tortoise.transactions import in_transaction
from .game.state import PHASE_FINISHED, TEAM_NAMES, GameState
def _parse_timestamp(value: Optional[str]) -> datetime:
if value:
try:
return datetime.fromisoformat(value)
except ValueError:
pass
return datetime.now(timezone.utc)
async def save_match_result(state: GameState) -> None:
"""Persist ``state`` to Postgres if it is finished and not yet saved."""
if state.stats_saved or state.phase != PHASE_FINISHED or state.winner is None:
return
from .models import Match, MatchPlayer
started_at = _parse_timestamp(state.created_at)
finished_at = _parse_timestamp(state.finished_at)
async with in_transaction():
match = await Match.create(
id=uuid.uuid4(),
team_a_score=state.scores[0],
team_b_score=state.scores[1],
winner_team=TEAM_NAMES[state.winner],
target_score=state.target_score,
hands_played=state.hand_number,
started_at=started_at,
finished_at=finished_at,
)
for player in state.players:
await MatchPlayer.create(
id=uuid.uuid4(),
match=match,
user_sub=player.sub,
display_name=player.name,
seat=player.seat,
team=TEAM_NAMES[player.team],
won=player.team == state.winner,
)
state.stats_saved = True