Spaces:
Paused
Paused
Download services/lobby.py from igardner/StockAnalysis: direct link, hf CLI and curl.
- Browser
- Download file 23 kB
-
https://huggingface.co/spaces/igardner/StockAnalysis/resolve/main/services/lobby.py
- Command line
-
hf download hf://spaces/igardner/StockAnalysis/services/lobby.py
-
curl -L -o lobby.py https://huggingface.co/spaces/igardner/StockAnalysis/resolve/main/services/lobby.py
23 kB
| """Persistent shared lobby state, matchmaking, minigame, chat, and runtime.""" | |
| from __future__ import annotations | |
| import json | |
| import logging | |
| import re | |
| import threading | |
| import time | |
| import uuid | |
| from datetime import datetime, timedelta | |
| from sqlalchemy.exc import IntegrityError | |
| from config import Config | |
| from extensions import db | |
| from models import ( | |
| ChatGenerationJob, | |
| ChatMessage, | |
| LobbyMessage, | |
| LobbyRound, | |
| LobbyVote, | |
| MatchmakingEntry, | |
| Room, | |
| RoomMembership, | |
| TelemetryEvent, | |
| User, | |
| ) | |
| from services.avatar import AvatarService | |
| from services.connections import LOBBY_MANAGER | |
| from services.eventlog import log_event, redact_sensitive | |
| from services.lobby_chat import LobbyChatGenerator | |
| from services.rooms import try_auto_start | |
| logger = logging.getLogger(__name__) | |
| ROUNDS = ( | |
| ("Which detail would you notice first at a strange dinner party?", ["An empty chair", "A locked door", "A stopped clock"]), | |
| ("The parlor lights flicker. What do you investigate?", ["The hallway", "The music box", "The guest book"]), | |
| ("Pick a clue to bring to the next table.", ["A torn note", "A silver key", "A muddy footprint"]), | |
| ("A mysterious guest offers one hint. Which do you ask for?", ["Who arrived late?", "What changed?", "Where is the exit?"]), | |
| ) | |
| LOBBY_PROMPTS = ( | |
| {"id": "tell-01", "prompt": "What small thing makes you immediately suspicious of someone?"}, | |
| {"id": "tell-02", "prompt": "What harmless rule do you break when no one is looking?"}, | |
| {"id": "tell-03", "prompt": "What would you pretend not to notice at this table?"}, | |
| {"id": "tell-04", "prompt": "What is a truth you only tell when the room feels safe?"}, | |
| ) | |
| _match_lock = threading.Lock() | |
| _round_lock = threading.Lock() | |
| ROUND_REVEAL_SECONDS = 10 | |
| _WORD_PATTERN = re.compile(r"\b[\w'-]+\b", flags=re.UNICODE) | |
| def _word_count(content): | |
| return len(_WORD_PATTERN.findall(content)) | |
| def _prompt_for_user(user_id): | |
| return LOBBY_PROMPTS[(int(user_id) - 1) % len(LOBBY_PROMPTS)] | |
| def _prompt_for_entry(entry): | |
| prompt_id = entry.participation_prompt_id or _prompt_for_user(entry.user_id)["id"] | |
| return next((prompt for prompt in LOBBY_PROMPTS if prompt["id"] == prompt_id), LOBBY_PROMPTS[0]) | |
| def _queue_counts(): | |
| return { | |
| "queue_count": MatchmakingEntry.query.filter_by(status="queued").count(), | |
| "ready_count": MatchmakingEntry.query.filter_by(status="queued").filter( | |
| MatchmakingEntry.participated_at.is_not(None) | |
| ).count(), | |
| } | |
| def _record(event_type, *, user_id=None, page="/lobby", payload=None, room_id=None, redact=True): | |
| """Persist a compact event and emit a corresponding stdout event.""" | |
| payload = payload or {} | |
| stored_payload = dict(payload) | |
| log_payload = redact_sensitive(payload) | |
| event_id = uuid.uuid4().hex[:16] | |
| stored_payload.setdefault("event_id", event_id) | |
| log_payload.setdefault("event_id", event_id) | |
| if redact: | |
| stored_payload = log_payload | |
| try: | |
| db.session.add(TelemetryEvent( | |
| user_id=user_id, | |
| room_id=room_id, | |
| event_type=event_type[:32], | |
| page=page[:64], | |
| payload_json=json.dumps(stored_payload, ensure_ascii=False)[:4000], | |
| )) | |
| db.session.commit() | |
| except Exception: | |
| db.session.rollback() | |
| logger.exception("LOBBY_EVENT_PERSIST_FAILED event=%s", event_type) | |
| log_event(event_type, user=user_id, room_id=room_id, page=page, payload=log_payload, event_id=event_id) | |
| def _publish(event_type, data): | |
| try: | |
| LOBBY_MANAGER.broadcast(None, json.dumps({"type": event_type, "data": data}, ensure_ascii=False)) | |
| except Exception: | |
| logger.exception("LOBBY_BROADCAST_FAILED event=%s", event_type) | |
| def _serialize_message(message): | |
| user = db.session.get(User, message.user_id) if message.user_id else None | |
| return { | |
| "id": message.id, | |
| "user": user.nickname if user else ("Parlor" if message.source != "user" else "Guest"), | |
| "avatar": AvatarService.build_url(user.avatar_style, user.avatar_seed, user.avatar_bg) if user else None, | |
| "msg": message.content, | |
| "source": message.source, | |
| "is_simulated": bool(user and user.is_test_bot), | |
| "at": message.created_at.strftime("%H:%M") if message.created_at else "", | |
| } | |
| def create_lobby_message(content, *, user_id=None, source="user"): | |
| if not isinstance(content, str): | |
| raise ValueError("Message must be text") | |
| content = content.strip()[:500] | |
| if not content: | |
| raise ValueError("Message cannot be empty") | |
| message = LobbyMessage(user_id=user_id, content=content, source=source[:24]) | |
| db.session.add(message) | |
| db.session.flush() | |
| participation = None | |
| queue_entry = None | |
| word_count = _word_count(content) | |
| qualified = word_count >= Config.MATCHMAKING_MIN_WORDS | |
| if user_id and source in ("user", "simulation"): | |
| queue_entry = MatchmakingEntry.query.filter_by(user_id=user_id, status="queued").first() | |
| if queue_entry and not queue_entry.participated_at and qualified: | |
| if not queue_entry.participation_prompt_id: | |
| queue_entry.participation_prompt_id = _prompt_for_user(user_id)["id"] | |
| queue_entry.participated_at = datetime.utcnow() | |
| participation = { | |
| "prompt_id": queue_entry.participation_prompt_id, | |
| "message_id": message.id, | |
| "length": len(content), | |
| "word_count": word_count, | |
| } | |
| db.session.commit() | |
| payload = _serialize_message(message) | |
| _record( | |
| "lobby_chat", | |
| user_id=user_id, | |
| payload={"message_id": message.id, "source": source, "length": len(content), "content": content}, | |
| redact=False, | |
| ) | |
| payload["matchmaking"] = { | |
| "qualified": bool( | |
| qualified and queue_entry and user_id and source in ("user", "simulation") | |
| ), | |
| "participated": bool(queue_entry and queue_entry.participated_at), | |
| "word_count": word_count, | |
| "minimum_words": Config.MATCHMAKING_MIN_WORDS, | |
| } | |
| _publish("chat.message", payload) | |
| if participation: | |
| _record("lobby_participation", user_id=user_id, payload=participation) | |
| _publish("queue.updated", _queue_counts()) | |
| _match_queued_users() | |
| return payload | |
| def submit_participation_answer(user_id, prompt_id, answer): | |
| entry = MatchmakingEntry.query.filter_by(user_id=user_id, status="queued").first() | |
| if not entry: | |
| raise ValueError("Your table search is not active") | |
| if entry.participated_at: | |
| raise ValueError("You have already answered the parlor question") | |
| prompt = _prompt_for_entry(entry) | |
| if prompt_id != prompt["id"]: | |
| raise ValueError("That parlor question has changed; refresh and answer the current one") | |
| if not isinstance(answer, str) or _word_count(answer.strip()) < Config.MATCHMAKING_MIN_WORDS: | |
| raise ValueError(f"Please answer with at least {Config.MATCHMAKING_MIN_WORDS} words") | |
| return create_lobby_message(answer, user_id=user_id, source="user") | |
| def lobby_messages(after=0, limit=50): | |
| rows = (LobbyMessage.query.filter(LobbyMessage.id > max(0, after)) | |
| .order_by(LobbyMessage.id.asc()).limit(min(max(limit, 1), 100)).all()) | |
| return [_serialize_message(message) for message in rows] | |
| def _round_payload(round_, user_id=None): | |
| options = json.loads(round_.options_json or "[]") | |
| counts = {choice: 0 for choice in options} | |
| for vote in LobbyVote.query.filter_by(round_id=round_.id).all(): | |
| if vote.choice in counts: | |
| counts[vote.choice] += 1 | |
| own_vote = LobbyVote.query.filter_by(round_id=round_.id, user_id=user_id).first() if user_id else None | |
| return { | |
| "id": round_.id, | |
| "prompt": round_.prompt, | |
| "options": options, | |
| "status": round_.status, | |
| "ends_at": round_.ends_at.isoformat() + "Z", | |
| "votes": counts if round_.status == "reveal" else {choice: (count > 0) for choice, count in counts.items()}, | |
| "vote_count": sum(counts.values()), | |
| "my_vote": own_vote.choice if own_vote else None, | |
| } | |
| def rotate_round(now=None): | |
| with _round_lock: | |
| return _rotate_round_locked(now or datetime.utcnow()) | |
| def _rotate_round_locked(now): | |
| current = LobbyRound.query.filter(LobbyRound.status.in_(("open", "reveal"))).order_by(LobbyRound.id.desc()).first() | |
| if current and current.ends_at > now: | |
| return current | |
| if current and current.status == "open": | |
| current.status = "reveal" | |
| current.ends_at = now + timedelta(seconds=ROUND_REVEAL_SECONDS) | |
| current.ended_at = now | |
| db.session.commit() | |
| payload = _round_payload(current) | |
| _record("minigame_round_reveal", payload={"round_id": current.id, "votes": payload["votes"]}) | |
| _publish("minigame.round_ended", payload) | |
| return current | |
| if current: | |
| current.status = "closed" | |
| db.session.commit() | |
| prompt, options = ROUNDS[(LobbyRound.query.count()) % len(ROUNDS)] | |
| round_ = LobbyRound( | |
| prompt=prompt, | |
| options_json=json.dumps(options), | |
| status="open", | |
| starts_at=now, | |
| ends_at=now + timedelta(seconds=max(15, Config.LOBBY_ROUND_SECONDS)), | |
| ) | |
| db.session.add(round_) | |
| db.session.commit() | |
| payload = _round_payload(round_) | |
| _record("minigame_round_started", payload={"round_id": round_.id, "prompt": prompt}) | |
| _publish("minigame.round_started", payload) | |
| return round_ | |
| def get_lobby_state(user_id=None): | |
| round_ = rotate_round() | |
| entry = MatchmakingEntry.query.filter_by(user_id=user_id).first() if user_id else None | |
| if entry and entry.status == "queued": | |
| entry.last_seen_at = datetime.utcnow() | |
| db.session.commit() | |
| counts = _queue_counts() | |
| active_count = counts["queue_count"] | |
| queue_position = None | |
| if entry and entry.status == "queued": | |
| ahead = MatchmakingEntry.query.filter( | |
| MatchmakingEntry.status == "queued", | |
| (MatchmakingEntry.joined_at < entry.joined_at) | |
| | ((MatchmakingEntry.joined_at == entry.joined_at) & (MatchmakingEntry.id <= entry.id)), | |
| ).count() | |
| queue_position = ahead | |
| match = None | |
| if entry and entry.status == "matched" and entry.room_id and not entry.consumed_at: | |
| match = {"room_id": entry.room_id, "url": f"/room/{entry.room_id}"} | |
| participation_prompt = None | |
| if entry and entry.status == "queued": | |
| selected_prompt = _prompt_for_entry(entry) | |
| participation_prompt = { | |
| "id": selected_prompt["id"], | |
| "prompt": selected_prompt["prompt"], | |
| "complete": bool(entry.participated_at), | |
| } | |
| user = db.session.get(User, user_id) if user_id else None | |
| latest_message = LobbyMessage.query.order_by(LobbyMessage.id.desc()).with_entities(LobbyMessage.id).first() | |
| recent_messages = lobby_messages(after=max(0, latest_message[0] - 20)) if latest_message else [] | |
| return { | |
| "queue_count": active_count, | |
| "ready_count": counts["ready_count"], | |
| "queued": bool(entry and entry.status == "queued"), | |
| "queue_status": entry.status if entry else "idle", | |
| "participated": bool(entry and entry.participated_at), | |
| "participation_prompt": participation_prompt, | |
| "onboarding_complete": bool(user and user.onboarding_completed_at), | |
| "test_mode": Config.TEST_MODE, | |
| "match": match, | |
| "queue_position": queue_position, | |
| "min_players": min(15, max(2, Config.MATCHMAKING_MIN_PLAYERS)), | |
| "round": _round_payload(round_, user_id), | |
| "messages": recent_messages, | |
| } | |
| def current_minigame_round(user_id=None): | |
| round_ = rotate_round() | |
| return _round_payload(round_, user_id) | |
| def ensure_auto_queue(user_id): | |
| """Place onboarded real guests in matchmaking without a join button.""" | |
| user = db.session.get(User, user_id) if user_id else None | |
| if not user or user.is_test_bot or not user.onboarding_completed_at: | |
| return None | |
| entry = MatchmakingEntry.query.filter_by(user_id=user_id).first() | |
| if entry and entry.status in ("queued", "paused"): | |
| return entry | |
| if entry and entry.status == "matched" and not entry.consumed_at: | |
| return entry | |
| return join_queue(user_id) | |
| def _match_queued_users(): | |
| """Form one room from a complete group, serialized within this process.""" | |
| with _match_lock: | |
| expired_before = datetime.utcnow() - timedelta(minutes=5) | |
| expired = MatchmakingEntry.query.filter( | |
| MatchmakingEntry.status == "queued", | |
| MatchmakingEntry.last_seen_at < expired_before, | |
| ).all() | |
| if expired: | |
| expired_ids = [entry.user_id for entry in expired] | |
| for entry in expired: | |
| db.session.delete(entry) | |
| db.session.commit() | |
| _record("matchmaking_expire", payload={"count": len(expired_ids), "user_ids": expired_ids}) | |
| minimum = min(15, max(2, Config.MATCHMAKING_MIN_PLAYERS)) | |
| queued = (MatchmakingEntry.query.filter_by(status="queued") | |
| .filter(MatchmakingEntry.participated_at.is_not(None)) | |
| .order_by(MatchmakingEntry.joined_at.asc()).limit(15).all()) | |
| if len(queued) < minimum: | |
| return None | |
| batch = queued[:min(15, len(queued))] | |
| user_ids = [entry.user_id for entry in batch] | |
| host_id = user_ids[0] | |
| room = Room( | |
| name="The Midnight Parlor", | |
| is_public=True, | |
| min_players=minimum, | |
| max_players=max(minimum, len(user_ids)), | |
| game_type=Config.DEFAULT_GAME_TYPE, | |
| host_user_id=host_id, | |
| settings_json=json.dumps(Config.GAME_SETTINGS, ensure_ascii=False), | |
| ) | |
| db.session.add(room) | |
| db.session.flush() | |
| room.name = f"The Midnight Parlor · {room.id:03d}" | |
| for index, user_id in enumerate(user_ids): | |
| db.session.add(RoomMembership(room_id=room.id, user_id=user_id, is_host=(index == 0))) | |
| db.session.add(ChatMessage( | |
| room_id=room.id, | |
| user_id=None, | |
| content="The table is gathered. Take a seat and introduce yourself while the game prototype gets ready.", | |
| is_system=True, | |
| )) | |
| for entry in batch: | |
| entry.status = "matched" | |
| entry.room_id = room.id | |
| entry.matched_at = datetime.utcnow() | |
| entry.consumed_at = None | |
| db.session.commit() | |
| try_auto_start(room.id) | |
| logger.info("MATCH_CREATED room=%s players=%s users=%s", room.id, len(user_ids), user_ids) | |
| _record("match_created", room_id=room.id, payload={"room_id": room.id, "players": len(user_ids), "user_ids": user_ids}) | |
| for user_id in user_ids: | |
| _publish("match.created", {"user_id": user_id, "room_id": room.id, "url": f"/room/{room.id}"}) | |
| return room | |
| def join_queue(user_id): | |
| entry = MatchmakingEntry.query.filter_by(user_id=user_id).first() | |
| if entry and entry.status == "matched" and not entry.consumed_at: | |
| return entry | |
| if entry and entry.status == "queued": | |
| entry.last_seen_at = datetime.utcnow() | |
| if not entry.participation_prompt_id: | |
| entry.participation_prompt_id = _prompt_for_user(user_id)["id"] | |
| db.session.commit() | |
| _match_queued_users() | |
| return MatchmakingEntry.query.filter_by(user_id=user_id).first() | |
| elif entry: | |
| entry.status = "queued" | |
| entry.room_id = None | |
| entry.joined_at = datetime.utcnow() | |
| entry.last_seen_at = datetime.utcnow() | |
| entry.matched_at = None | |
| entry.consumed_at = None | |
| entry.participated_at = None | |
| entry.participation_prompt_id = _prompt_for_user(user_id)["id"] | |
| else: | |
| entry = MatchmakingEntry( | |
| user_id=user_id, | |
| participation_prompt_id=_prompt_for_user(user_id)["id"], | |
| ) | |
| db.session.add(entry) | |
| try: | |
| db.session.commit() | |
| except IntegrityError: | |
| db.session.rollback() | |
| entry = MatchmakingEntry.query.filter_by(user_id=user_id).first() | |
| _record("matchmaking_join", user_id=user_id, payload={"queue_count": MatchmakingEntry.query.filter_by(status="queued").count()}) | |
| _publish("queue.updated", _queue_counts()) | |
| _match_queued_users() | |
| return MatchmakingEntry.query.filter_by(user_id=user_id).first() | |
| def leave_queue(user_id): | |
| entry = MatchmakingEntry.query.filter_by(user_id=user_id).first() | |
| if entry and entry.status == "queued": | |
| entry.status = "paused" | |
| entry.participated_at = None | |
| db.session.commit() | |
| count = MatchmakingEntry.query.filter_by(status="queued").count() | |
| _record("matchmaking_leave", user_id=user_id, payload={"queue_count": count}) | |
| _publish("queue.updated", _queue_counts()) | |
| return count | |
| def cast_vote(round_id, user_id, choice): | |
| round_ = rotate_round() | |
| if round_.id != round_id or round_.status != "open": | |
| raise ValueError("That round is closed") | |
| options = json.loads(round_.options_json or "[]") | |
| if choice not in options: | |
| raise ValueError("Choose one of the listed options") | |
| vote = LobbyVote.query.filter_by(round_id=round_id, user_id=user_id).first() | |
| if vote: | |
| vote.choice = choice | |
| vote.created_at = datetime.utcnow() | |
| else: | |
| vote = LobbyVote(round_id=round_id, user_id=user_id, choice=choice) | |
| db.session.add(vote) | |
| db.session.commit() | |
| payload = _round_payload(round_, user_id) | |
| _record("minigame_vote", user_id=user_id, payload={"round_id": round_id, "choice": choice}) | |
| _publish("minigame.vote_count", {key: value for key, value in payload.items() if key != "my_vote"}) | |
| return payload | |
| def create_generation_job(context_key="lobby", idempotency_key=None): | |
| if idempotency_key: | |
| existing = ChatGenerationJob.query.filter_by(idempotency_key=idempotency_key[:128]).first() | |
| if existing: | |
| return existing | |
| pending = ChatGenerationJob.query.filter(ChatGenerationJob.status.in_(("queued", "running"))).count() | |
| if pending >= 3: | |
| raise ValueError("Too many chat-generation jobs are already pending") | |
| recent = ChatGenerationJob.query.filter( | |
| ChatGenerationJob.created_at >= datetime.utcnow() - timedelta(seconds=10) | |
| ).count() | |
| if recent >= 1: | |
| raise ValueError("Chat generation is temporarily rate limited") | |
| job = ChatGenerationJob( | |
| id=str(uuid.uuid4()), | |
| context_key=(context_key or "lobby")[:80], | |
| idempotency_key=(idempotency_key or "")[:128] or None, | |
| ) | |
| db.session.add(job) | |
| try: | |
| db.session.commit() | |
| except IntegrityError: | |
| db.session.rollback() | |
| existing = ChatGenerationJob.query.filter_by(idempotency_key=(idempotency_key or "")[:128]).first() | |
| if existing: | |
| return existing | |
| raise | |
| _record("chat_generation_queued", payload={"job_id": job.id, "context_key": job.context_key}) | |
| return job | |
| def process_generation_job(): | |
| job = ChatGenerationJob.query.filter_by(status="queued").order_by(ChatGenerationJob.created_at.asc()).first() | |
| if not job: | |
| return | |
| job.status = "running" | |
| job.updated_at = datetime.utcnow() | |
| db.session.commit() | |
| try: | |
| content = LobbyChatGenerator.generate(job.context_key) | |
| payload = create_lobby_message(content, source="generated") | |
| job.result_message_id = payload["id"] | |
| job.status = "complete" | |
| job.error = None | |
| logger.info("CHAT_GENERATION_COMPLETE job=%s message=%s", job.id, payload["id"]) | |
| except Exception as exc: | |
| db.session.rollback() | |
| job = db.session.get(ChatGenerationJob, job.id) | |
| job.status = "failed" | |
| job.error = type(exc).__name__ | |
| logger.exception("CHAT_GENERATION_FAILED job=%s", job.id) | |
| job.updated_at = datetime.utcnow() | |
| db.session.commit() | |
| _record("chat_generation_" + job.status, payload={"job_id": job.id, "message_id": job.result_message_id, "error": job.error}) | |
| class LobbyRuntime: | |
| def __init__(self): | |
| self.app = None | |
| self._thread = None | |
| self._lock = threading.Lock() | |
| self._generation_thread = None | |
| self._generation_lock = threading.Lock() | |
| self._stop = threading.Event() | |
| self.simulation = None | |
| def start(self, app): | |
| with self._lock: | |
| if self._thread and self._thread.is_alive(): | |
| return | |
| self.app = app | |
| with app.app_context(): | |
| if Config.TEST_MODE: | |
| from services.test_simulation import SIMULATION | |
| SIMULATION.initialize() | |
| self.simulation = SIMULATION | |
| interrupted = ChatGenerationJob.query.filter_by(status="running").all() | |
| if interrupted: | |
| for job in interrupted: | |
| job.status = "queued" | |
| job.updated_at = datetime.utcnow() | |
| db.session.commit() | |
| logger.warning("CHAT_GENERATION_RECOVERED jobs=%s", len(interrupted)) | |
| _record("chat_generation_recovered", payload={"job_ids": [job.id for job in interrupted]}) | |
| self._stop.clear() | |
| self._thread = threading.Thread(target=self._run, daemon=True, name="lobby-runtime") | |
| self._thread.start() | |
| logger.info("LOBBY_RUNTIME_STARTED interval=5s") | |
| def stop(self): | |
| self._stop.set() | |
| def _run(self): | |
| while not self._stop.wait(5): | |
| try: | |
| with self.app.app_context(): | |
| rotate_round() | |
| if self.simulation: | |
| self.simulation.tick() | |
| _match_queued_users() | |
| self._dispatch_generation_job() | |
| except Exception: | |
| db.session.rollback() | |
| logger.exception("LOBBY_RUNTIME_TICK_FAILED") | |
| def _dispatch_generation_job(self): | |
| with self._generation_lock: | |
| if self._generation_thread and self._generation_thread.is_alive(): | |
| return | |
| if not ChatGenerationJob.query.filter_by(status="queued").first(): | |
| return | |
| self._generation_thread = threading.Thread( | |
| target=self._run_generation_job, | |
| daemon=True, | |
| name="lobby-chat-generation", | |
| ) | |
| self._generation_thread.start() | |
| def _run_generation_job(self): | |
| try: | |
| with self.app.app_context(): | |
| process_generation_job() | |
| except Exception: | |
| db.session.rollback() | |
| logger.exception("CHAT_GENERATION_WORKER_FAILED") | |
| finally: | |
| with self._generation_lock: | |
| self._generation_thread = None | |
| RUNTIME = LobbyRuntime() | |