"""Room-scoped loading, serialization, and persistence for game actions.""" from __future__ import annotations import json import logging import threading from datetime import datetime from flask import has_request_context, request from extensions import db from games import registry from models import Game, GamePlayer, Room, RoomMembership, User from services.avatar import AvatarService from services.connections import MANAGER from services.eventlog import log_event from services.telemetry import Telemetry logger = logging.getLogger(__name__) _GAME_ACTION_LOCK = threading.RLock() def _load(room_id: int): room = db.session.get(Room, room_id) if not room: raise LookupError("Room not found") game = Game.query.filter_by(room_id=room.id).order_by(Game.started_at.desc()).first() if not game: raise LookupError("This table does not have a game yet") game_class = registry.get(game.game_type) if not game_class: raise LookupError("The configured game is not installed") instance = game_class(game_id=game.id, room_id=room.id) try: instance.load_state(json.loads(game.state_json or "{}")) except (TypeError, ValueError): logger.exception("GAME_STATE_INVALID game=%s room=%s", game.id, room.id) raise LookupError("The game state could not be loaded") from None return room, game, instance def _require_member(room_id: int, user_id: int) -> RoomMembership: member = RoomMembership.query.filter_by(room_id=room_id, user_id=user_id).filter( RoomMembership.left_at.is_(None) ).first() if not member: raise PermissionError("Join this table before accessing its game") return member def public_state(room_id: int, user_id: int) -> dict: _require_member(room_id, user_id) room, game, instance = _load(room_id) state = instance.get_public_state(user_id) for player in state.get("players", []): user = db.session.get(User, int(player["user_id"])) if user: player["nickname"] = user.nickname player["avatar"] = AvatarService.build_url( user.avatar_style, user.avatar_seed, user.avatar_bg ) player["is_you"] = user.id == user_id player["is_simulated"] = bool(user.is_test_bot) state["game_id"] = game.id state["room_id"] = room.id return state def perform_action(room_id: int, user_id: int, action: str, payload: dict) -> dict: # Vote completion mutates several fields in one serialized JSON document; # keep two room actions from overwriting one another in this worker. with _GAME_ACTION_LOCK: return _perform_action_locked(room_id, user_id, action, payload) def _perform_action_locked(room_id: int, user_id: int, action: str, payload: dict) -> dict: _require_member(room_id, user_id) room, game, instance = _load(room_id) result = instance.handle_action(user_id, action, payload) state = instance.get_state() game.state_json = json.dumps(state, ensure_ascii=False) game.phase = state.get("phase", game.phase) completion = instance.check_end_conditions() if completion: game.winner = completion.get("winner", "") game.ended_at = datetime.utcnow() room.status = "finished" for player in GamePlayer.query.filter_by(game_id=game.id).all(): player.alive = player.user_id in [int(value) for value in state.get("alive", [])] db.session.commit() event_data = { "game_id": game.id, "action": action, "action_payload": payload, "phase": game.phase, "round": state.get("round"), "result": result, } if has_request_context(): Telemetry.log("game_action", user_id=user_id, room_id=room.id, payload=event_data) log_event("game_action", user=user_id, room_id=room.id, payload=event_data, req=request) else: from models import TelemetryEvent db.session.add(TelemetryEvent( user_id=user_id, room_id=room.id, event_type="game_action", page=f"/room/{room.id}/game", payload_json=json.dumps(event_data, ensure_ascii=False), )) db.session.commit() log_event("game_action", user=user_id, room_id=room.id, page=f"/room/{room.id}/game", payload=event_data) MANAGER.broadcast(room.id, json.dumps({"type": "game.updated", "game_id": game.id})) return { "result": result, "state": public_state(room.id, user_id), }