Spaces:
Paused
Paused
feat: broadcast bot chat over WS, structured interaction logs, real auto-start
Browse files- single Simulation thread (no per-room thread leak) drives bot chatter + matchmaking
- bot DURRRR now broadcast to live clients, not just written to SQLite
- eventlog: CLICK/USER_CHAT/BOT_CHAT/WS_* lines with UA+IP, recent HTTP filter
- AutoAssigner naive default + try_auto_start creates Game/GamePlayer rows
- late-join bot pushes rooms over the threshold
- HTTP chat + polling endpoints so chat works without the socket
- app.py +57 -14
- games/registry.py +41 -7
- requirements.txt +1 -0
- routes/lobby.py +249 -30
- routes/telemetry.py +24 -2
- routes/websocket.py +27 -16
- services/eventlog.py +91 -0
- services/matchmaking.py +157 -42
- services/rooms.py +72 -0
- services/test_players.py +26 -48
app.py
CHANGED
|
@@ -1,13 +1,17 @@
|
|
| 1 |
import os
|
|
|
|
| 2 |
import logging
|
| 3 |
-
from flask import Flask
|
| 4 |
from config import Config
|
| 5 |
from extensions import db, sock
|
| 6 |
from models import *
|
| 7 |
from routes import lobby, telemetry, websocket
|
| 8 |
from games import registry, assigner
|
| 9 |
from games.loader import GameLoader
|
| 10 |
-
from services.matchmaking import
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# Configure heavy logging - output to stdout so HF captures it
|
| 13 |
logging.basicConfig(
|
|
@@ -17,6 +21,10 @@ logging.basicConfig(
|
|
| 17 |
)
|
| 18 |
logger = logging.getLogger(__name__)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
app = Flask(__name__, instance_path=Config.INSTANCE_PATH)
|
| 21 |
app.config.from_object(Config)
|
| 22 |
os.makedirs(app.instance_path, exist_ok=True)
|
|
@@ -29,6 +37,51 @@ sock.init_app(app)
|
|
| 29 |
app.register_blueprint(lobby.bp)
|
| 30 |
app.register_blueprint(telemetry.bp)
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
# Load games
|
| 33 |
loader = GameLoader(registry)
|
| 34 |
loader.discover()
|
|
@@ -43,20 +96,10 @@ with app.app_context():
|
|
| 43 |
# Start test mode if enabled
|
| 44 |
if Config.TEST_MODE:
|
| 45 |
logger.warning("TEST_MODE ENABLED - auto-assign and DURRRR bots active")
|
| 46 |
-
|
| 47 |
-
logger.info("
|
| 48 |
# Test mode setup happens per-request in lobby.index
|
| 49 |
|
| 50 |
-
@app.route("/inference")
|
| 51 |
-
def inference():
|
| 52 |
-
"""Keep inference test accessible for fun."""
|
| 53 |
-
logger.info("INFERENCE_TEST_ACCESSED")
|
| 54 |
-
try:
|
| 55 |
-
import smoke
|
| 56 |
-
return "Inference test module available. Run via smoke.py for full test."
|
| 57 |
-
except Exception as e:
|
| 58 |
-
return f"Inference test: {e}"
|
| 59 |
-
|
| 60 |
@app.route("/health")
|
| 61 |
def health():
|
| 62 |
return {"status": "ok", "games": len(registry.list_games()), "test_mode": Config.TEST_MODE}
|
|
|
|
| 1 |
import os
|
| 2 |
+
import time
|
| 3 |
import logging
|
| 4 |
+
from flask import Flask, request, g
|
| 5 |
from config import Config
|
| 6 |
from extensions import db, sock
|
| 7 |
from models import *
|
| 8 |
from routes import lobby, telemetry, websocket
|
| 9 |
from games import registry, assigner
|
| 10 |
from games.loader import GameLoader
|
| 11 |
+
from services.matchmaking import SIMULATION
|
| 12 |
+
from services.eventlog import log_event
|
| 13 |
+
from services.brand import random_mark
|
| 14 |
+
from services.avatar import AvatarService
|
| 15 |
|
| 16 |
# Configure heavy logging - output to stdout so HF captures it
|
| 17 |
logging.basicConfig(
|
|
|
|
| 21 |
)
|
| 22 |
logger = logging.getLogger(__name__)
|
| 23 |
|
| 24 |
+
# Silence Werkzeug's per-request HTTP access lines. We emit our own richer,
|
| 25 |
+
# filtered request log below (non-GET, errors, and API traffic only).
|
| 26 |
+
logging.getLogger("werkzeug").setLevel(logging.ERROR)
|
| 27 |
+
|
| 28 |
app = Flask(__name__, instance_path=Config.INSTANCE_PATH)
|
| 29 |
app.config.from_object(Config)
|
| 30 |
os.makedirs(app.instance_path, exist_ok=True)
|
|
|
|
| 37 |
app.register_blueprint(lobby.bp)
|
| 38 |
app.register_blueprint(telemetry.bp)
|
| 39 |
|
| 40 |
+
|
| 41 |
+
@app.context_processor
|
| 42 |
+
def inject_brand():
|
| 43 |
+
from flask import session as _session
|
| 44 |
+
uid = _session.get("user_id")
|
| 45 |
+
user = User.query.get(uid) if uid else None
|
| 46 |
+
avatar = (
|
| 47 |
+
AvatarService.build_url(user.avatar_style, user.avatar_seed, user.avatar_bg)
|
| 48 |
+
if user else None
|
| 49 |
+
)
|
| 50 |
+
return {
|
| 51 |
+
"mark_svg": random_mark(),
|
| 52 |
+
"current_user": user,
|
| 53 |
+
"current_avatar": avatar,
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@app.before_request
|
| 58 |
+
def _start_timer():
|
| 59 |
+
g._t0 = time.perf_counter()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@app.after_request
|
| 63 |
+
def _log_request(response):
|
| 64 |
+
"""Compact request log: skip successful GETs, keep writes/errors/API."""
|
| 65 |
+
path = request.path
|
| 66 |
+
interesting = (
|
| 67 |
+
request.method not in ("GET", "HEAD", "OPTIONS")
|
| 68 |
+
or response.status_code >= 400
|
| 69 |
+
or path.startswith("/api/")
|
| 70 |
+
)
|
| 71 |
+
if interesting and not path.startswith("/static/"):
|
| 72 |
+
ms = (time.perf_counter() - getattr(g, "_t0", time.perf_counter())) * 1000
|
| 73 |
+
log_event(
|
| 74 |
+
"http",
|
| 75 |
+
page=path,
|
| 76 |
+
payload={
|
| 77 |
+
"method": request.method,
|
| 78 |
+
"status": response.status_code,
|
| 79 |
+
"ms": round(ms, 1),
|
| 80 |
+
},
|
| 81 |
+
req=request,
|
| 82 |
+
)
|
| 83 |
+
return response
|
| 84 |
+
|
| 85 |
# Load games
|
| 86 |
loader = GameLoader(registry)
|
| 87 |
loader.discover()
|
|
|
|
| 96 |
# Start test mode if enabled
|
| 97 |
if Config.TEST_MODE:
|
| 98 |
logger.warning("TEST_MODE ENABLED - auto-assign and DURRRR bots active")
|
| 99 |
+
SIMULATION.start(app, room_interval=30, bots_per_room=4, chat_interval=5)
|
| 100 |
+
logger.info("SIMULATION_STARTED interval=30s bots_per_room=4 chat=5s")
|
| 101 |
# Test mode setup happens per-request in lobby.index
|
| 102 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
@app.route("/health")
|
| 104 |
def health():
|
| 105 |
return {"status": "ok", "games": len(registry.list_games()), "test_mode": Config.TEST_MODE}
|
games/registry.py
CHANGED
|
@@ -29,23 +29,57 @@ class GameRegistry:
|
|
| 29 |
})
|
| 30 |
return result
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def has(self, game_type: str) -> bool:
|
| 33 |
return game_type in self._games
|
| 34 |
|
| 35 |
|
| 36 |
class AutoAssigner:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
"""
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
|
|
|
| 41 |
def can_auto_create(self, player_count: int, room_config: Dict[str, Any]) -> bool:
|
| 42 |
-
min_players = room_config.get("min_players",
|
| 43 |
return player_count >= min_players
|
| 44 |
|
| 45 |
def select_game(self, room_id: int, players: List[Dict[str, Any]], room_config: Dict[str, Any]) -> Optional[str]:
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
def assign(self, room_id: int, players: List[Dict[str, Any]], room_config: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 51 |
if not self.can_auto_create(len(players), room_config):
|
|
|
|
| 29 |
})
|
| 30 |
return result
|
| 31 |
|
| 32 |
+
def eligible_games(self, player_count: int) -> List[Dict[str, Any]]:
|
| 33 |
+
"""Games whose player bounds fit ``player_count``."""
|
| 34 |
+
out = []
|
| 35 |
+
for g in self.list_games():
|
| 36 |
+
if g["min_players"] <= player_count <= g["max_players"]:
|
| 37 |
+
out.append(g)
|
| 38 |
+
return out
|
| 39 |
+
|
| 40 |
def has(self, game_type: str) -> bool:
|
| 41 |
return game_type in self._games
|
| 42 |
|
| 43 |
|
| 44 |
class AutoAssigner:
|
| 45 |
+
"""Extension point for auto-assigning a game to a room.
|
| 46 |
+
|
| 47 |
+
This is intentionally small. It ships a *naive* default that simply picks
|
| 48 |
+
the first registered game whose player bounds fit the room. To implement
|
| 49 |
+
smarter matchmaking (skill, history, queues, weighting, etc.) subclass this
|
| 50 |
+
and override :meth:`select_game`, then swap the module-level ``assigner`` in
|
| 51 |
+
``games/__init__.py``.
|
| 52 |
+
|
| 53 |
+
Contract:
|
| 54 |
+
- ``can_auto_create`` decides whether the room is ready.
|
| 55 |
+
- ``select_game`` returns a ``game_type`` string, or ``None`` to leave the
|
| 56 |
+
room in the lobby.
|
| 57 |
+
- ``assign`` returns a plain dict describing the assignment, or ``None``.
|
| 58 |
"""
|
| 59 |
+
|
| 60 |
+
#: How many players a room needs before it can auto-start.
|
| 61 |
+
default_min_players = 5
|
| 62 |
+
|
| 63 |
def can_auto_create(self, player_count: int, room_config: Dict[str, Any]) -> bool:
|
| 64 |
+
min_players = room_config.get("min_players", self.default_min_players)
|
| 65 |
return player_count >= min_players
|
| 66 |
|
| 67 |
def select_game(self, room_id: int, players: List[Dict[str, Any]], room_config: Dict[str, Any]) -> Optional[str]:
|
| 68 |
+
"""Naive default: first game whose bounds fit the current player count.
|
| 69 |
+
|
| 70 |
+
Override this method for custom assignment logic.
|
| 71 |
+
"""
|
| 72 |
+
from games import registry as _registry
|
| 73 |
+
eligible = _registry.eligible_games(len(players))
|
| 74 |
+
if not eligible:
|
| 75 |
+
return None
|
| 76 |
+
# A room may pin a specific game via config; honour it if eligible.
|
| 77 |
+
pinned = room_config.get("game_type")
|
| 78 |
+
if pinned:
|
| 79 |
+
for g in eligible:
|
| 80 |
+
if g["game_type"] == pinned:
|
| 81 |
+
return pinned
|
| 82 |
+
return eligible[0]["game_type"]
|
| 83 |
|
| 84 |
def assign(self, room_id: int, players: List[Dict[str, Any]], room_config: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
| 85 |
if not self.can_auto_create(len(players), room_config):
|
requirements.txt
CHANGED
|
@@ -9,3 +9,4 @@ pyyaml==6.0.1
|
|
| 9 |
requests==2.31.0
|
| 10 |
dicebear==3.9.5
|
| 11 |
python-dotenv==1.0.0
|
|
|
|
|
|
| 9 |
requests==2.31.0
|
| 10 |
dicebear==3.9.5
|
| 11 |
python-dotenv==1.0.0
|
| 12 |
+
huggingface_hub==1.16.1
|
routes/lobby.py
CHANGED
|
@@ -1,11 +1,19 @@
|
|
|
|
|
| 1 |
import logging
|
| 2 |
import uuid
|
| 3 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
from extensions import db
|
| 5 |
-
from models import Room, User, RoomMembership, ChatMessage
|
| 6 |
from services.rooms import RoomService
|
| 7 |
from services.avatar import AvatarService
|
| 8 |
from services.telemetry import Telemetry
|
|
|
|
|
|
|
| 9 |
from services.test_players import TestMode
|
| 10 |
from config import Config
|
| 11 |
|
|
@@ -18,7 +26,10 @@ bp = Blueprint("lobby", __name__)
|
|
| 18 |
def ensure_user():
|
| 19 |
if "user_id" not in session:
|
| 20 |
uid = str(uuid.uuid4())[:8]
|
| 21 |
-
user = User(
|
|
|
|
|
|
|
|
|
|
| 22 |
db.session.add(user)
|
| 23 |
db.session.commit()
|
| 24 |
session["user_id"] = user.id
|
|
@@ -27,35 +38,96 @@ def ensure_user():
|
|
| 27 |
Telemetry.log("user_create", user_id=user.id)
|
| 28 |
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
@bp.route("/")
|
| 31 |
def index():
|
| 32 |
user_id = session.get("user_id")
|
|
|
|
| 33 |
Telemetry.log("page_view", user_id=user_id, page="/")
|
| 34 |
-
logger.info("PAGE_VIEW user=%s path=/", user_id)
|
| 35 |
|
| 36 |
-
# Test mode: auto-setup a room and redirect
|
| 37 |
if TestMode.is_enabled():
|
| 38 |
-
from flask import current_app
|
| 39 |
room = TestMode.auto_setup_room(current_app._get_current_object(), user_id)
|
| 40 |
logger.info("TEST_MODE_AUTOJOIN user=%s room=%s", user_id, room.id)
|
| 41 |
return redirect(url_for("lobby.room", room_id=room.id))
|
| 42 |
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
|
| 51 |
@bp.route("/create", methods=["POST"])
|
| 52 |
def create():
|
| 53 |
user_id = session.get("user_id")
|
| 54 |
-
name = request.form.get("name", "")
|
| 55 |
is_public = request.form.get("is_public") == "on"
|
| 56 |
max_players = int(request.form.get("max_players", Config.MAX_PLAYERS_DEFAULT))
|
| 57 |
min_players = int(request.form.get("min_players", Config.AUTO_CREATE_MIN_PLAYERS))
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
Telemetry.log("room_create", user_id=user_id, room_id=room.id)
|
| 60 |
logger.info("ROOM_CREATE user=%s room=%s", user_id, room.id)
|
| 61 |
return redirect(url_for("lobby.room", room_id=room.id))
|
|
@@ -75,31 +147,80 @@ def join(room_id):
|
|
| 75 |
def room(room_id):
|
| 76 |
room = Room.query.get_or_404(room_id)
|
| 77 |
user_id = session.get("user_id")
|
| 78 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
members = []
|
| 80 |
for m in memberships:
|
| 81 |
u = User.query.get(m.user_id)
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
chat_list = []
|
| 88 |
for c in chats:
|
| 89 |
u = User.query.get(c.user_id) if c.user_id else None
|
| 90 |
-
chat_list.append({
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
|
| 97 |
@bp.route("/avatar/update", methods=["POST"])
|
| 98 |
def avatar_update():
|
| 99 |
user_id = session.get("user_id")
|
| 100 |
user = User.query.get(user_id)
|
|
|
|
|
|
|
| 101 |
style = request.form.get("style")
|
| 102 |
-
seed = request.form.get("seed") or user.avatar_seed
|
| 103 |
bg = request.form.get("bg") or user.avatar_bg
|
| 104 |
if style in AvatarService.get_styles():
|
| 105 |
user.avatar_style = style
|
|
@@ -107,14 +228,112 @@ def avatar_update():
|
|
| 107 |
if bg in AvatarService.get_backgrounds():
|
| 108 |
user.avatar_bg = bg
|
| 109 |
db.session.commit()
|
| 110 |
-
Telemetry.log(
|
|
|
|
|
|
|
|
|
|
| 111 |
logger.info("AVATAR_UPDATE user=%s style=%s bg=%s", user_id, user.avatar_style, user.avatar_bg)
|
| 112 |
-
return redirect(request.referrer or url_for("lobby.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 113 |
|
| 114 |
|
| 115 |
@bp.route("/inference")
|
| 116 |
def inference():
|
| 117 |
-
"""Keep inference test accessible for fun."""
|
| 118 |
logger.info("INFERENCE_TEST_ACCESSED")
|
| 119 |
Telemetry.log("inference_test_view", user_id=session.get("user_id"))
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
import logging
|
| 3 |
import uuid
|
| 4 |
+
|
| 5 |
+
from flask import (
|
| 6 |
+
Blueprint, render_template, request, session, redirect, url_for,
|
| 7 |
+
jsonify, current_app,
|
| 8 |
+
)
|
| 9 |
+
|
| 10 |
from extensions import db
|
| 11 |
+
from models import Room, User, RoomMembership, ChatMessage, Game
|
| 12 |
from services.rooms import RoomService
|
| 13 |
from services.avatar import AvatarService
|
| 14 |
from services.telemetry import Telemetry
|
| 15 |
+
from services.eventlog import log_user_chat
|
| 16 |
+
from services.connections import MANAGER
|
| 17 |
from services.test_players import TestMode
|
| 18 |
from config import Config
|
| 19 |
|
|
|
|
| 26 |
def ensure_user():
|
| 27 |
if "user_id" not in session:
|
| 28 |
uid = str(uuid.uuid4())[:8]
|
| 29 |
+
user = User(
|
| 30 |
+
nickname=f"Player{uid}", avatar_style="lorelei",
|
| 31 |
+
avatar_seed=uid, avatar_bg="transparent",
|
| 32 |
+
)
|
| 33 |
db.session.add(user)
|
| 34 |
db.session.commit()
|
| 35 |
session["user_id"] = user.id
|
|
|
|
| 38 |
Telemetry.log("user_create", user_id=user.id)
|
| 39 |
|
| 40 |
|
| 41 |
+
def _me():
|
| 42 |
+
uid = session.get("user_id")
|
| 43 |
+
return User.query.get(uid) if uid else None
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _avatar(user):
|
| 47 |
+
if not user:
|
| 48 |
+
return ""
|
| 49 |
+
return AvatarService.build_url(user.avatar_style, user.avatar_seed, user.avatar_bg)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _lobby_context(user):
|
| 53 |
+
rooms = (
|
| 54 |
+
Room.query.filter_by(is_public=True)
|
| 55 |
+
.order_by(Room.created_at.desc())
|
| 56 |
+
.limit(50)
|
| 57 |
+
.all()
|
| 58 |
+
)
|
| 59 |
+
cards = []
|
| 60 |
+
for room in rooms:
|
| 61 |
+
memberships = (
|
| 62 |
+
RoomMembership.query.filter_by(room_id=room.id)
|
| 63 |
+
.filter(RoomMembership.left_at.is_(None))
|
| 64 |
+
.all()
|
| 65 |
+
)
|
| 66 |
+
avatars = []
|
| 67 |
+
for m in memberships[:4]:
|
| 68 |
+
u = User.query.get(m.user_id)
|
| 69 |
+
if u:
|
| 70 |
+
avatars.append(_avatar(u))
|
| 71 |
+
cards.append({
|
| 72 |
+
"id": room.id,
|
| 73 |
+
"name": room.name,
|
| 74 |
+
"status": room.status,
|
| 75 |
+
"min_players": room.min_players,
|
| 76 |
+
"max_players": room.max_players,
|
| 77 |
+
"player_count": len(memberships),
|
| 78 |
+
"avatars": avatars,
|
| 79 |
+
})
|
| 80 |
+
styles = AvatarService.get_styles()
|
| 81 |
+
seed = user.avatar_seed if user else "seed"
|
| 82 |
+
previews = [
|
| 83 |
+
{"style": s, "url": AvatarService.build_url(s, seed, "transparent")}
|
| 84 |
+
for s in styles
|
| 85 |
+
]
|
| 86 |
+
return {
|
| 87 |
+
"user": user,
|
| 88 |
+
"avatar_url": _avatar(user),
|
| 89 |
+
"styles": styles,
|
| 90 |
+
"style_previews": previews,
|
| 91 |
+
"backgrounds": AvatarService.get_backgrounds(),
|
| 92 |
+
"room_cards": cards,
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
@bp.route("/")
|
| 97 |
def index():
|
| 98 |
user_id = session.get("user_id")
|
| 99 |
+
user = _me()
|
| 100 |
Telemetry.log("page_view", user_id=user_id, page="/")
|
|
|
|
| 101 |
|
|
|
|
| 102 |
if TestMode.is_enabled():
|
|
|
|
| 103 |
room = TestMode.auto_setup_room(current_app._get_current_object(), user_id)
|
| 104 |
logger.info("TEST_MODE_AUTOJOIN user=%s room=%s", user_id, room.id)
|
| 105 |
return redirect(url_for("lobby.room", room_id=room.id))
|
| 106 |
|
| 107 |
+
return render_template("index.html", **_lobby_context(user))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
@bp.route("/lobby")
|
| 111 |
+
def lobby_browser():
|
| 112 |
+
"""Always show the room browser, even in test mode."""
|
| 113 |
+
user = _me()
|
| 114 |
+
Telemetry.log("page_view", user_id=session.get("user_id"), page="/lobby")
|
| 115 |
+
return render_template("index.html", **_lobby_context(user))
|
| 116 |
|
| 117 |
|
| 118 |
@bp.route("/create", methods=["POST"])
|
| 119 |
def create():
|
| 120 |
user_id = session.get("user_id")
|
| 121 |
+
name = request.form.get("name", "").strip()
|
| 122 |
is_public = request.form.get("is_public") == "on"
|
| 123 |
max_players = int(request.form.get("max_players", Config.MAX_PLAYERS_DEFAULT))
|
| 124 |
min_players = int(request.form.get("min_players", Config.AUTO_CREATE_MIN_PLAYERS))
|
| 125 |
+
max_players = min(15, max(5, max_players))
|
| 126 |
+
min_players = min(max_players, max(5, min_players))
|
| 127 |
+
room = RoomService.create_room(
|
| 128 |
+
user_id, name=name, is_public=is_public,
|
| 129 |
+
max_players=max_players, min_players=min_players,
|
| 130 |
+
)
|
| 131 |
Telemetry.log("room_create", user_id=user_id, room_id=room.id)
|
| 132 |
logger.info("ROOM_CREATE user=%s room=%s", user_id, room.id)
|
| 133 |
return redirect(url_for("lobby.room", room_id=room.id))
|
|
|
|
| 147 |
def room(room_id):
|
| 148 |
room = Room.query.get_or_404(room_id)
|
| 149 |
user_id = session.get("user_id")
|
| 150 |
+
me = _me()
|
| 151 |
+
|
| 152 |
+
memberships = (
|
| 153 |
+
RoomMembership.query.filter_by(room_id=room.id)
|
| 154 |
+
.filter(RoomMembership.left_at.is_(None))
|
| 155 |
+
.all()
|
| 156 |
+
)
|
| 157 |
members = []
|
| 158 |
for m in memberships:
|
| 159 |
u = User.query.get(m.user_id)
|
| 160 |
+
if not u:
|
| 161 |
+
continue
|
| 162 |
+
members.append({
|
| 163 |
+
"user": u,
|
| 164 |
+
"membership": m,
|
| 165 |
+
"avatar": _avatar(u),
|
| 166 |
+
"is_you": u.id == user_id,
|
| 167 |
+
})
|
| 168 |
+
members.sort(key=lambda m: (not m["membership"].is_host, m["user"].nickname))
|
| 169 |
+
|
| 170 |
+
chats = (
|
| 171 |
+
ChatMessage.query.filter_by(room_id=room.id)
|
| 172 |
+
.order_by(ChatMessage.created_at.asc())
|
| 173 |
+
.limit(150)
|
| 174 |
+
.all()
|
| 175 |
+
)
|
| 176 |
chat_list = []
|
| 177 |
for c in chats:
|
| 178 |
u = User.query.get(c.user_id) if c.user_id else None
|
| 179 |
+
chat_list.append({
|
| 180 |
+
"id": c.id,
|
| 181 |
+
"user": u.nickname if u else "System",
|
| 182 |
+
"content": c.content,
|
| 183 |
+
"is_system": c.is_system,
|
| 184 |
+
"avatar": _avatar(u) if u else None,
|
| 185 |
+
"is_you": bool(u and u.id == user_id),
|
| 186 |
+
"at": c.created_at.strftime("%H:%M") if c.created_at else "",
|
| 187 |
+
})
|
| 188 |
+
|
| 189 |
+
game = (
|
| 190 |
+
Game.query.filter_by(room_id=room.id, ended_at=None)
|
| 191 |
+
.order_by(Game.started_at.desc())
|
| 192 |
+
.first()
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
is_member = any(m["is_you"] for m in members)
|
| 196 |
+
is_host = any(m["is_you"] and m["membership"].is_host for m in members)
|
| 197 |
+
|
| 198 |
+
Telemetry.log("page_view", user_id=user_id, room_id=room.id, page=f"/room/{room_id}")
|
| 199 |
+
logger.info("ROOM_VIEW user=%s room=%s members=%s", user_id, room_id, len(members))
|
| 200 |
+
|
| 201 |
+
return render_template(
|
| 202 |
+
"room.html",
|
| 203 |
+
room=room,
|
| 204 |
+
me=me,
|
| 205 |
+
avatar_url=_avatar(me),
|
| 206 |
+
members=members,
|
| 207 |
+
chats=chat_list,
|
| 208 |
+
game=game,
|
| 209 |
+
player_count=len(members),
|
| 210 |
+
needed=max(0, room.min_players - len(members)),
|
| 211 |
+
is_member=is_member,
|
| 212 |
+
is_host=is_host,
|
| 213 |
+
)
|
| 214 |
|
| 215 |
|
| 216 |
@bp.route("/avatar/update", methods=["POST"])
|
| 217 |
def avatar_update():
|
| 218 |
user_id = session.get("user_id")
|
| 219 |
user = User.query.get(user_id)
|
| 220 |
+
if not user:
|
| 221 |
+
return redirect(url_for("lobby.lobby_browser"))
|
| 222 |
style = request.form.get("style")
|
| 223 |
+
seed = (request.form.get("seed") or "").strip() or user.avatar_seed
|
| 224 |
bg = request.form.get("bg") or user.avatar_bg
|
| 225 |
if style in AvatarService.get_styles():
|
| 226 |
user.avatar_style = style
|
|
|
|
| 228 |
if bg in AvatarService.get_backgrounds():
|
| 229 |
user.avatar_bg = bg
|
| 230 |
db.session.commit()
|
| 231 |
+
Telemetry.log(
|
| 232 |
+
"avatar_update", user_id=user_id,
|
| 233 |
+
payload={"style": user.avatar_style, "bg": user.avatar_bg},
|
| 234 |
+
)
|
| 235 |
logger.info("AVATAR_UPDATE user=%s style=%s bg=%s", user_id, user.avatar_style, user.avatar_bg)
|
| 236 |
+
return redirect(request.referrer or url_for("lobby.lobby_browser"))
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
@bp.route("/api/room/<int:room_id>/chat", methods=["POST"])
|
| 240 |
+
def api_chat(room_id):
|
| 241 |
+
"""Send a chat message over HTTP (WS fallback and primary path)."""
|
| 242 |
+
room = Room.query.get_or_404(room_id)
|
| 243 |
+
user_id = session.get("user_id")
|
| 244 |
+
user = User.query.get(user_id)
|
| 245 |
+
if not user:
|
| 246 |
+
return jsonify({"ok": False, "error": "no user"}), 403
|
| 247 |
+
data = request.get_json(silent=True) or {}
|
| 248 |
+
content = (data.get("msg") or "").strip()[:500]
|
| 249 |
+
if not content:
|
| 250 |
+
return jsonify({"ok": False, "error": "empty"}), 400
|
| 251 |
+
|
| 252 |
+
msg = ChatMessage(room_id=room.id, user_id=user.id, content=content)
|
| 253 |
+
db.session.add(msg)
|
| 254 |
+
db.session.commit()
|
| 255 |
+
|
| 256 |
+
label = f"{user.id}({user.nickname})"
|
| 257 |
+
Telemetry.log("chat_message", user_id=user.id, room_id=room.id, payload={"len": len(content)})
|
| 258 |
+
log_user_chat(room.id, label, content, req=request)
|
| 259 |
+
|
| 260 |
+
payload = json.dumps({"type": "chat", "id": msg.id, "user": user.nickname, "msg": content})
|
| 261 |
+
MANAGER.broadcast(room.id, payload)
|
| 262 |
+
return jsonify({
|
| 263 |
+
"ok": True,
|
| 264 |
+
"id": msg.id,
|
| 265 |
+
"user": user.nickname,
|
| 266 |
+
"msg": content,
|
| 267 |
+
"at": msg.created_at.strftime("%H:%M") if msg.created_at else "",
|
| 268 |
+
})
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
@bp.route("/api/room/<int:room_id>/messages")
|
| 272 |
+
def api_messages(room_id):
|
| 273 |
+
after = request.args.get("after", type=int) or 0
|
| 274 |
+
rows = (
|
| 275 |
+
ChatMessage.query.filter_by(room_id=room_id)
|
| 276 |
+
.filter(ChatMessage.id > after)
|
| 277 |
+
.order_by(ChatMessage.id.asc())
|
| 278 |
+
.limit(50)
|
| 279 |
+
.all()
|
| 280 |
+
)
|
| 281 |
+
out = []
|
| 282 |
+
user_id = session.get("user_id")
|
| 283 |
+
for c in rows:
|
| 284 |
+
u = User.query.get(c.user_id) if c.user_id else None
|
| 285 |
+
out.append({
|
| 286 |
+
"id": c.id,
|
| 287 |
+
"user": u.nickname if u else "System",
|
| 288 |
+
"msg": c.content,
|
| 289 |
+
"is_system": c.is_system,
|
| 290 |
+
"is_you": bool(u and u.id == user_id),
|
| 291 |
+
"at": c.created_at.strftime("%H:%M") if c.created_at else "",
|
| 292 |
+
"avatar": _avatar(u) if u else None,
|
| 293 |
+
})
|
| 294 |
+
return jsonify({"messages": out})
|
| 295 |
|
| 296 |
|
| 297 |
@bp.route("/inference")
|
| 298 |
def inference():
|
|
|
|
| 299 |
logger.info("INFERENCE_TEST_ACCESSED")
|
| 300 |
Telemetry.log("inference_test_view", user_id=session.get("user_id"))
|
| 301 |
+
status = None
|
| 302 |
+
latest = None
|
| 303 |
+
error = None
|
| 304 |
+
try:
|
| 305 |
+
import smoke # kept from the original Space, for fun
|
| 306 |
+
status = smoke.get_token_status()
|
| 307 |
+
latest = smoke.load_latest_run()
|
| 308 |
+
except Exception as exc:
|
| 309 |
+
error = str(exc)
|
| 310 |
+
return render_template(
|
| 311 |
+
"inference.html", status=status, latest=latest, error=error, result=None,
|
| 312 |
+
)
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
@bp.route("/inference/run", methods=["POST"])
|
| 316 |
+
def inference_run():
|
| 317 |
+
limit = request.form.get("limit", type=int) or 3
|
| 318 |
+
limit = max(1, min(10, limit))
|
| 319 |
+
status = latest = result = error = None
|
| 320 |
+
try:
|
| 321 |
+
import smoke
|
| 322 |
+
smoke.configure()
|
| 323 |
+
status = smoke.get_token_status()
|
| 324 |
+
snapshot = smoke.fetch_trending_models(limit=limit, save=False)
|
| 325 |
+
found = snapshot.get("models", [])
|
| 326 |
+
if not found:
|
| 327 |
+
raise RuntimeError("No models with a live provider were found.")
|
| 328 |
+
result = smoke.run_smoke(found)
|
| 329 |
+
latest = smoke.load_latest_run()
|
| 330 |
+
except Exception as exc:
|
| 331 |
+
error = str(exc)
|
| 332 |
+
try:
|
| 333 |
+
import smoke
|
| 334 |
+
latest = smoke.load_latest_run()
|
| 335 |
+
except Exception:
|
| 336 |
+
pass
|
| 337 |
+
return render_template(
|
| 338 |
+
"inference.html", status=status, latest=latest, error=error, result=result,
|
| 339 |
+
)
|
routes/telemetry.py
CHANGED
|
@@ -1,6 +1,9 @@
|
|
|
|
|
| 1 |
from flask import Blueprint, request, session, jsonify
|
|
|
|
| 2 |
from services.telemetry import Telemetry
|
| 3 |
-
import
|
|
|
|
| 4 |
|
| 5 |
logger = logging.getLogger(__name__)
|
| 6 |
|
|
@@ -12,8 +15,14 @@ def collect():
|
|
| 12 |
data = request.get_json(silent=True) or {}
|
| 13 |
user_id = session.get("user_id")
|
| 14 |
room_id = data.get("room_id")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
Telemetry.log(
|
| 16 |
-
event_type=
|
| 17 |
user_id=user_id,
|
| 18 |
room_id=room_id,
|
| 19 |
page=data.get("page", ""),
|
|
@@ -21,4 +30,17 @@ def collect():
|
|
| 21 |
coords=data.get("coords"),
|
| 22 |
payload=data.get("payload"),
|
| 23 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
return jsonify({"ok": True})
|
|
|
|
| 1 |
+
import logging
|
| 2 |
from flask import Blueprint, request, session, jsonify
|
| 3 |
+
|
| 4 |
from services.telemetry import Telemetry
|
| 5 |
+
from services.eventlog import log_event
|
| 6 |
+
from models import User
|
| 7 |
|
| 8 |
logger = logging.getLogger(__name__)
|
| 9 |
|
|
|
|
| 15 |
data = request.get_json(silent=True) or {}
|
| 16 |
user_id = session.get("user_id")
|
| 17 |
room_id = data.get("room_id")
|
| 18 |
+
event_type = data.get("event_type", "event")
|
| 19 |
+
|
| 20 |
+
user = User.query.get(user_id) if user_id else None
|
| 21 |
+
user_label = f"{user_id}({user.nickname})" if user else user_id
|
| 22 |
+
|
| 23 |
+
# Persist to SQLite (existing behaviour).
|
| 24 |
Telemetry.log(
|
| 25 |
+
event_type=event_type,
|
| 26 |
user_id=user_id,
|
| 27 |
room_id=room_id,
|
| 28 |
page=data.get("page", ""),
|
|
|
|
| 30 |
coords=data.get("coords"),
|
| 31 |
payload=data.get("payload"),
|
| 32 |
)
|
| 33 |
+
|
| 34 |
+
# Emit a readable line to container stdout with UA/IP/etc.
|
| 35 |
+
log_event(
|
| 36 |
+
event_type,
|
| 37 |
+
user=user_label,
|
| 38 |
+
session_id=session.get("sid", ""),
|
| 39 |
+
room_id=room_id,
|
| 40 |
+
page=data.get("page", ""),
|
| 41 |
+
element=data.get("element", ""),
|
| 42 |
+
coords=data.get("coords"),
|
| 43 |
+
payload=data.get("payload"),
|
| 44 |
+
req=request,
|
| 45 |
+
)
|
| 46 |
return jsonify({"ok": True})
|
routes/websocket.py
CHANGED
|
@@ -1,10 +1,13 @@
|
|
| 1 |
import json
|
| 2 |
import logging
|
| 3 |
-
|
|
|
|
|
|
|
| 4 |
from extensions import sock, db
|
| 5 |
from models import Room, User, ChatMessage
|
| 6 |
from services.telemetry import Telemetry
|
| 7 |
from services.connections import MANAGER
|
|
|
|
| 8 |
|
| 9 |
logger = logging.getLogger(__name__)
|
| 10 |
|
|
@@ -17,11 +20,11 @@ def room_ws(ws, room_id):
|
|
| 17 |
ws.close()
|
| 18 |
return
|
| 19 |
user = User.query.get(user_id)
|
|
|
|
| 20 |
MANAGER.register(ws, user_id, room_id, user.nickname)
|
| 21 |
Telemetry.log('ws_connect', user_id=user_id, room_id=room.id)
|
| 22 |
-
|
| 23 |
|
| 24 |
-
# Send welcome
|
| 25 |
try:
|
| 26 |
ws.send(json.dumps({'type': 'system', 'msg': f'{user.nickname} joined'}))
|
| 27 |
except Exception:
|
|
@@ -33,27 +36,35 @@ def room_ws(ws, room_id):
|
|
| 33 |
if not data:
|
| 34 |
break
|
| 35 |
msg = json.loads(data)
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
db.session.add(
|
|
|
|
|
|
|
| 40 |
db.session.commit()
|
| 41 |
-
Telemetry.log(
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
Telemetry.log('typing', user_id=user_id, room_id=room.id)
|
|
|
|
| 48 |
except Exception as e:
|
| 49 |
logger.warning("WS_ERROR user=%s room=%s: %s", user_id, room_id, e)
|
| 50 |
break
|
| 51 |
|
| 52 |
MANAGER.unregister(ws)
|
| 53 |
Telemetry.log('ws_disconnect', user_id=user_id, room_id=room.id)
|
| 54 |
-
|
| 55 |
-
# Notify others
|
| 56 |
try:
|
| 57 |
-
MANAGER.broadcast(
|
|
|
|
|
|
|
| 58 |
except Exception:
|
| 59 |
pass
|
|
|
|
| 1 |
import json
|
| 2 |
import logging
|
| 3 |
+
|
| 4 |
+
from flask import session, request
|
| 5 |
+
|
| 6 |
from extensions import sock, db
|
| 7 |
from models import Room, User, ChatMessage
|
| 8 |
from services.telemetry import Telemetry
|
| 9 |
from services.connections import MANAGER
|
| 10 |
+
from services.eventlog import log_connection, log_user_chat, log_event
|
| 11 |
|
| 12 |
logger = logging.getLogger(__name__)
|
| 13 |
|
|
|
|
| 20 |
ws.close()
|
| 21 |
return
|
| 22 |
user = User.query.get(user_id)
|
| 23 |
+
label = f"{user_id}({user.nickname})"
|
| 24 |
MANAGER.register(ws, user_id, room_id, user.nickname)
|
| 25 |
Telemetry.log('ws_connect', user_id=user_id, room_id=room.id)
|
| 26 |
+
log_connection('connect', room_id=room_id, user=label, req=request)
|
| 27 |
|
|
|
|
| 28 |
try:
|
| 29 |
ws.send(json.dumps({'type': 'system', 'msg': f'{user.nickname} joined'}))
|
| 30 |
except Exception:
|
|
|
|
| 36 |
if not data:
|
| 37 |
break
|
| 38 |
msg = json.loads(data)
|
| 39 |
+
kind = msg.get('type')
|
| 40 |
+
if kind == 'chat':
|
| 41 |
+
content = (msg.get('msg') or '')[:500]
|
| 42 |
+
db.session.add(
|
| 43 |
+
ChatMessage(room_id=room.id, user_id=user_id, content=content)
|
| 44 |
+
)
|
| 45 |
db.session.commit()
|
| 46 |
+
Telemetry.log(
|
| 47 |
+
'chat_message', user_id=user_id, room_id=room.id,
|
| 48 |
+
payload={'len': len(content)},
|
| 49 |
+
)
|
| 50 |
+
log_user_chat(room_id, label, content, req=request)
|
| 51 |
+
MANAGER.broadcast(
|
| 52 |
+
room_id,
|
| 53 |
+
json.dumps({'type': 'chat', 'user': user.nickname, 'msg': content}),
|
| 54 |
+
)
|
| 55 |
+
elif kind == 'typing':
|
| 56 |
Telemetry.log('typing', user_id=user_id, room_id=room.id)
|
| 57 |
+
log_event('typing', user=label, room_id=room_id, req=request)
|
| 58 |
except Exception as e:
|
| 59 |
logger.warning("WS_ERROR user=%s room=%s: %s", user_id, room_id, e)
|
| 60 |
break
|
| 61 |
|
| 62 |
MANAGER.unregister(ws)
|
| 63 |
Telemetry.log('ws_disconnect', user_id=user_id, room_id=room.id)
|
| 64 |
+
log_connection('disconnect', room_id=room_id, user=label, req=request)
|
|
|
|
| 65 |
try:
|
| 66 |
+
MANAGER.broadcast(
|
| 67 |
+
room_id, json.dumps({'type': 'system', 'msg': f'{user.nickname} left'})
|
| 68 |
+
)
|
| 69 |
except Exception:
|
| 70 |
pass
|
services/eventlog.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Readable, structured event logging for the Space stdout logs.
|
| 2 |
+
|
| 3 |
+
The goal is that the Hugging Face container log tells a story: every click,
|
| 4 |
+
scroll, keystroke, chat message, bot line, and connection, with the visitor's
|
| 5 |
+
user agent, IP, session, room, and page in one line. No raw HTTP access noise.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import json
|
| 11 |
+
import logging
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger("event")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _kv(**fields) -> str:
|
| 17 |
+
parts = []
|
| 18 |
+
for key, value in fields.items():
|
| 19 |
+
if value is None or value == "":
|
| 20 |
+
continue
|
| 21 |
+
if isinstance(value, (dict, list, tuple)):
|
| 22 |
+
value = json.dumps(value, separators=(",", ":"), ensure_ascii=False)
|
| 23 |
+
else:
|
| 24 |
+
value = str(value)
|
| 25 |
+
if " " in value or '"' in value:
|
| 26 |
+
value = json.dumps(value, ensure_ascii=False)
|
| 27 |
+
parts.append(f"{key}={value}")
|
| 28 |
+
return " ".join(parts)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def client_context(req) -> dict:
|
| 32 |
+
"""Pull the useful bits of a Flask request for logging."""
|
| 33 |
+
if req is None:
|
| 34 |
+
return {}
|
| 35 |
+
forwarded = req.headers.get("X-Forwarded-For", "")
|
| 36 |
+
ip = forwarded.split(",")[0].strip() if forwarded else req.remote_addr
|
| 37 |
+
return {
|
| 38 |
+
"ip": ip,
|
| 39 |
+
"ua": req.headers.get("User-Agent", "")[:200],
|
| 40 |
+
"ref": req.headers.get("Referer", ""),
|
| 41 |
+
"path": req.path,
|
| 42 |
+
}
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def log_event(event: str, *, user=None, session_id=None, room_id=None, page=None,
|
| 46 |
+
element=None, coords=None, payload=None, req=None, **extra) -> None:
|
| 47 |
+
"""Emit one structured line to the container log."""
|
| 48 |
+
ctx = client_context(req)
|
| 49 |
+
fields = {
|
| 50 |
+
"user": user,
|
| 51 |
+
"sid": (session_id or "")[:8] if session_id else None,
|
| 52 |
+
"room": room_id,
|
| 53 |
+
"page": page or ctx.get("path"),
|
| 54 |
+
"element": element,
|
| 55 |
+
"at": coords,
|
| 56 |
+
"ip": ctx.get("ip"),
|
| 57 |
+
"ua": ctx.get("ua"),
|
| 58 |
+
"ref": ctx.get("ref"),
|
| 59 |
+
"data": payload,
|
| 60 |
+
}
|
| 61 |
+
fields.update(extra)
|
| 62 |
+
logger.info("[%s] %s", event.upper(), _kv(**fields))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def log_bot_chat(room_id: int, bot: str, msg: str) -> None:
|
| 66 |
+
logger.info("[BOT_CHAT] %s", _kv(room=room_id, bot=bot, msg=msg))
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def log_user_chat(room_id: int, user, msg: str, *, req=None) -> None:
|
| 70 |
+
ctx = client_context(req)
|
| 71 |
+
logger.info(
|
| 72 |
+
"[USER_CHAT] %s",
|
| 73 |
+
_kv(room=room_id, user=user, msg=msg, ip=ctx.get("ip"), ua=ctx.get("ua")),
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def log_bot_spawn(room_id: int, bots) -> None:
|
| 78 |
+
logger.info("[BOT_SPAWN] %s", _kv(room=room_id, bots=list(bots)))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def log_join(room_id: int, who) -> None:
|
| 82 |
+
logger.info("[JOIN] %s", _kv(room=room_id, user=who))
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def log_connection(action: str, *, room_id=None, user=None, req=None) -> None:
|
| 86 |
+
ctx = client_context(req)
|
| 87 |
+
logger.info(
|
| 88 |
+
"[WS_%s] %s",
|
| 89 |
+
action.upper(),
|
| 90 |
+
_kv(room=room_id, user=user, ip=ctx.get("ip"), ua=ctx.get("ua")),
|
| 91 |
+
)
|
services/matchmaking.py
CHANGED
|
@@ -1,53 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import threading
|
| 2 |
import time
|
| 3 |
-
|
| 4 |
from extensions import db
|
| 5 |
-
from models import User,
|
| 6 |
-
from services.rooms import RoomService
|
| 7 |
from services.test_players import TestMode
|
| 8 |
-
from
|
|
|
|
| 9 |
|
| 10 |
logger = logging.getLogger(__name__)
|
| 11 |
|
| 12 |
|
| 13 |
-
class
|
| 14 |
-
|
| 15 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
if
|
| 21 |
return
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Single background simulation loop.
|
| 2 |
+
|
| 3 |
+
One daemon thread drives the whole test world so we never leak a thread per
|
| 4 |
+
room:
|
| 5 |
+
|
| 6 |
+
* every ``chat_interval`` seconds each registered room's bots say DURRRR,
|
| 7 |
+
which is written to SQLite, broadcast over WebSocket, and logged;
|
| 8 |
+
* every ``room_interval`` seconds a fresh room is opened with N bots and
|
| 9 |
+
auto-started through the game registry.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import json
|
| 15 |
+
import logging
|
| 16 |
import threading
|
| 17 |
import time
|
| 18 |
+
|
| 19 |
from extensions import db
|
| 20 |
+
from models import User, ChatMessage
|
| 21 |
+
from services.rooms import RoomService, try_auto_start
|
| 22 |
from services.test_players import TestMode
|
| 23 |
+
from services.connections import MANAGER
|
| 24 |
+
from services.eventlog import log_bot_chat, log_bot_spawn, log_join
|
| 25 |
|
| 26 |
logger = logging.getLogger(__name__)
|
| 27 |
|
| 28 |
|
| 29 |
+
class Simulation:
|
| 30 |
+
def __init__(self):
|
| 31 |
+
self.app = None
|
| 32 |
+
self.rooms = {} # room_id -> {"bots": [user_id], "last": float}
|
| 33 |
+
self.pending_joins = [] # [(due_ts, room_id)]
|
| 34 |
+
self.chat_interval = 5
|
| 35 |
+
self.room_interval = 30
|
| 36 |
+
self.bots_per_room = 4
|
| 37 |
+
self._thread = None
|
| 38 |
+
self._stop = threading.Event()
|
| 39 |
+
|
| 40 |
+
def start(self, app, *, room_interval=30, bots_per_room=4, chat_interval=5):
|
| 41 |
+
if self._thread and self._thread.is_alive():
|
| 42 |
+
return
|
| 43 |
+
self.app = app
|
| 44 |
+
self.room_interval = room_interval
|
| 45 |
+
self.bots_per_room = bots_per_room
|
| 46 |
+
self.chat_interval = chat_interval
|
| 47 |
+
self._stop.clear()
|
| 48 |
+
self._thread = threading.Thread(
|
| 49 |
+
target=self._loop, daemon=True, name="simulation-loop"
|
| 50 |
+
)
|
| 51 |
+
self._thread.start()
|
| 52 |
+
logger.info(
|
| 53 |
+
"SIMULATION_STARTED chat_every=%ss room_every=%ss bots_per_room=%s",
|
| 54 |
+
chat_interval, room_interval, bots_per_room,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
def stop(self):
|
| 58 |
+
self._stop.set()
|
| 59 |
+
|
| 60 |
+
def register_room(self, room_id: int, bot_ids):
|
| 61 |
+
self.rooms[room_id] = {"bots": list(bot_ids), "last": time.time()}
|
| 62 |
+
|
| 63 |
+
def schedule_join(self, room_id: int, delay: float = 4.0):
|
| 64 |
+
"""Have one more bot walk in a few seconds after the visitor."""
|
| 65 |
+
self.pending_joins.append((time.time() + delay, room_id))
|
| 66 |
|
| 67 |
+
def _process_pending_joins(self):
|
| 68 |
+
now = time.time()
|
| 69 |
+
due = [p for p in self.pending_joins if p[0] <= now]
|
| 70 |
+
if not due:
|
| 71 |
return
|
| 72 |
+
self.pending_joins = [p for p in self.pending_joins if p[0] > now]
|
| 73 |
+
with self.app.app_context():
|
| 74 |
+
for _, room_id in due:
|
| 75 |
+
from models import Room, RoomMembership, User
|
| 76 |
+
room = Room.query.get(room_id)
|
| 77 |
+
if not room:
|
| 78 |
+
continue
|
| 79 |
+
# A fresh one-off bot (not one already in the room).
|
| 80 |
+
n = len(self.rooms.get(room_id, {}).get("bots", []))
|
| 81 |
+
bot = User(
|
| 82 |
+
nickname=f"LateBot{n}",
|
| 83 |
+
avatar_style="bottts",
|
| 84 |
+
avatar_seed=f"LATE{room_id}-{n}",
|
| 85 |
+
avatar_bg="ffdfbf",
|
| 86 |
+
)
|
| 87 |
+
db.session.add(bot)
|
| 88 |
+
db.session.commit()
|
| 89 |
+
RoomService.join_room(room_id, bot.id)
|
| 90 |
+
info = self.rooms.setdefault(room_id, {"bots": [], "last": time.time()})
|
| 91 |
+
if bot.id not in info["bots"]:
|
| 92 |
+
info["bots"].append(bot.id)
|
| 93 |
+
log_join(room_id, bot.nickname)
|
| 94 |
+
game = try_auto_start(room_id)
|
| 95 |
+
logger.warning(
|
| 96 |
+
"LATE_JOIN room=%s bot=%s game=%s",
|
| 97 |
+
room_id, bot.nickname, getattr(game, "id", None),
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
def _loop(self):
|
| 101 |
+
last_room = 0.0
|
| 102 |
+
while not self._stop.is_set():
|
| 103 |
+
time.sleep(1)
|
| 104 |
+
now = time.time()
|
| 105 |
+
try:
|
| 106 |
+
self._chatter(now)
|
| 107 |
+
except Exception as exc: # pragma: no cover
|
| 108 |
+
logger.exception("SIM_CHATTER_ERROR: %s", exc)
|
| 109 |
+
|
| 110 |
+
try:
|
| 111 |
+
self._process_pending_joins()
|
| 112 |
+
except Exception as exc: # pragma: no cover
|
| 113 |
+
logger.exception("SIM_LATE_JOIN_ERROR: %s", exc)
|
| 114 |
+
|
| 115 |
+
if now - last_room >= self.room_interval:
|
| 116 |
+
last_room = now
|
| 117 |
try:
|
| 118 |
+
self._spawn_room()
|
| 119 |
+
except Exception as exc: # pragma: no cover
|
| 120 |
+
logger.exception("SIM_SPAWN_ERROR: %s", exc)
|
| 121 |
+
|
| 122 |
+
def _chatter(self, now):
|
| 123 |
+
due = [
|
| 124 |
+
rid for rid, info in list(self.rooms.items())
|
| 125 |
+
if now - info["last"] >= self.chat_interval
|
| 126 |
+
]
|
| 127 |
+
if not due:
|
| 128 |
+
return
|
| 129 |
+
with self.app.app_context():
|
| 130 |
+
for rid in due:
|
| 131 |
+
info = self.rooms.get(rid)
|
| 132 |
+
if not info:
|
| 133 |
+
continue
|
| 134 |
+
info["last"] = now
|
| 135 |
+
for bot_id in info["bots"]:
|
| 136 |
+
user = User.query.get(bot_id)
|
| 137 |
+
if not user:
|
| 138 |
+
continue
|
| 139 |
+
db.session.add(
|
| 140 |
+
ChatMessage(room_id=rid, user_id=bot_id, content="DURRRR")
|
| 141 |
+
)
|
| 142 |
+
db.session.commit()
|
| 143 |
+
payload = json.dumps(
|
| 144 |
+
{"type": "chat", "user": user.nickname, "msg": "DURRRR"}
|
| 145 |
+
)
|
| 146 |
+
MANAGER.broadcast(rid, payload)
|
| 147 |
+
log_bot_chat(rid, user.nickname, "DURRRR")
|
| 148 |
+
|
| 149 |
+
def _spawn_room(self):
|
| 150 |
+
with self.app.app_context():
|
| 151 |
+
bots = TestMode.create_test_players(self.bots_per_room)
|
| 152 |
+
room = RoomService.create_room(
|
| 153 |
+
bots[0].id, name=f"Match Room {int(time.time())}"
|
| 154 |
+
)
|
| 155 |
+
for b in bots[1:]:
|
| 156 |
+
RoomService.join_room(room.id, b.id)
|
| 157 |
+
self.register_room(room.id, [b.id for b in bots])
|
| 158 |
+
log_bot_spawn(room.id, [b.nickname for b in bots])
|
| 159 |
+
# A 5th bot arrives shortly after, which trips auto-start.
|
| 160 |
+
self.schedule_join(room.id, delay=8.0)
|
| 161 |
+
game = try_auto_start(room.id)
|
| 162 |
+
logger.warning(
|
| 163 |
+
"MATCHMAKING_ASSIGNED room=%s bots=%s game=%s",
|
| 164 |
+
room.id, len(bots), getattr(game, "id", None),
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
SIMULATION = Simulation()
|
services/rooms.py
CHANGED
|
@@ -49,3 +49,75 @@ class RoomService:
|
|
| 49 |
m.left_at = db.func.now() if False else __import__('datetime').datetime.utcnow()
|
| 50 |
db.session.commit()
|
| 51 |
logger.info("ROOM_LEAVE room_id=%s user=%s", room_id, user_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
m.left_at = db.func.now() if False else __import__('datetime').datetime.utcnow()
|
| 50 |
db.session.commit()
|
| 51 |
logger.info("ROOM_LEAVE room_id=%s user=%s", room_id, user_id)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def try_auto_start(room_id):
|
| 55 |
+
"""Create a game for a room once it has enough players.
|
| 56 |
+
|
| 57 |
+
Returns the created ``Game`` or ``None``. This is the single place where
|
| 58 |
+
the auto-assigner hook is invoked; the actual game choice lives in
|
| 59 |
+
``games.registry.AutoAssigner.select_game`` so it can be swapped out.
|
| 60 |
+
"""
|
| 61 |
+
from models import Room, RoomMembership, Game, GamePlayer
|
| 62 |
+
from games import assigner, registry
|
| 63 |
+
|
| 64 |
+
room = Room.query.get(room_id)
|
| 65 |
+
if not room or room.status != "lobby":
|
| 66 |
+
return None
|
| 67 |
+
|
| 68 |
+
members = (
|
| 69 |
+
RoomMembership.query
|
| 70 |
+
.filter_by(room_id=room_id)
|
| 71 |
+
.filter(RoomMembership.left_at.is_(None))
|
| 72 |
+
.all()
|
| 73 |
+
)
|
| 74 |
+
players = [{"user_id": m.user_id} for m in members]
|
| 75 |
+
room_config = {
|
| 76 |
+
"min_players": room.min_players,
|
| 77 |
+
"max_players": room.max_players,
|
| 78 |
+
"game_type": room.game_type or None,
|
| 79 |
+
}
|
| 80 |
+
|
| 81 |
+
# ---- extension point -------------------------------------------------
|
| 82 |
+
assignment = assigner.assign(room_id, players, room_config)
|
| 83 |
+
# ----------------------------------------------------------------------
|
| 84 |
+
if not assignment:
|
| 85 |
+
return None
|
| 86 |
+
|
| 87 |
+
game_type = assignment["game_type"]
|
| 88 |
+
game_cls = registry.get(game_type)
|
| 89 |
+
if game_cls is None:
|
| 90 |
+
logger.warning("AUTO_START_SKIP room=%s unknown game_type=%s", room_id, game_type)
|
| 91 |
+
return None
|
| 92 |
+
|
| 93 |
+
game = Game(room_id=room_id, game_type=game_type, phase="setup", state_json="{}")
|
| 94 |
+
db.session.add(game)
|
| 95 |
+
db.session.flush() # assign game.id
|
| 96 |
+
|
| 97 |
+
for p in players:
|
| 98 |
+
db.session.add(GamePlayer(game_id=game.id, user_id=p["user_id"]))
|
| 99 |
+
|
| 100 |
+
# Let the game seed its own state. Guarded so a broken plugin can't take
|
| 101 |
+
# down the join request.
|
| 102 |
+
try:
|
| 103 |
+
impl = game_cls(game_id=game.id, room_id=room_id, config=room_config)
|
| 104 |
+
state = impl.initialize(players)
|
| 105 |
+
import json as _json
|
| 106 |
+
game.state_json = _json.dumps(state or {})
|
| 107 |
+
except Exception as exc: # pragma: no cover - plugin safety
|
| 108 |
+
logger.exception("GAME_INIT_FAILED room=%s type=%s: %s", room_id, game_type, exc)
|
| 109 |
+
|
| 110 |
+
room.status = "playing"
|
| 111 |
+
room.game_type = game_type
|
| 112 |
+
db.session.commit()
|
| 113 |
+
|
| 114 |
+
logger.warning(
|
| 115 |
+
"AUTO_START room=%s game_id=%s type=%s players=%s",
|
| 116 |
+
room_id, game.id, game_type, len(players),
|
| 117 |
+
)
|
| 118 |
+
Telemetry.log(
|
| 119 |
+
"game_auto_start",
|
| 120 |
+
room_id=room_id,
|
| 121 |
+
payload={"game_id": game.id, "game_type": game_type, "players": len(players)},
|
| 122 |
+
)
|
| 123 |
+
return game
|
services/test_players.py
CHANGED
|
@@ -1,8 +1,7 @@
|
|
| 1 |
-
import threading
|
| 2 |
-
import time
|
| 3 |
import logging
|
|
|
|
| 4 |
from extensions import db
|
| 5 |
-
from models import User, Room, RoomMembership
|
| 6 |
from services.rooms import RoomService
|
| 7 |
from config import Config
|
| 8 |
|
|
@@ -10,7 +9,7 @@ logger = logging.getLogger(__name__)
|
|
| 10 |
|
| 11 |
|
| 12 |
class TestMode:
|
| 13 |
-
|
| 14 |
|
| 15 |
@staticmethod
|
| 16 |
def is_enabled():
|
|
@@ -36,54 +35,33 @@ class TestMode:
|
|
| 36 |
return test_users
|
| 37 |
|
| 38 |
@staticmethod
|
| 39 |
-
def
|
| 40 |
-
"""
|
| 41 |
-
if room_id in TestMode._threads:
|
| 42 |
-
return
|
| 43 |
-
test_users = TestMode.create_test_players()
|
| 44 |
-
stop_event = threading.Event()
|
| 45 |
-
|
| 46 |
-
def _loop():
|
| 47 |
-
logger.info("TESTBOT_CHAT_LOOP_START room=%s interval=%s", room_id, Config.TEST_BOT_CHAT_INTERVAL)
|
| 48 |
-
while not stop_event.is_set():
|
| 49 |
-
time.sleep(Config.TEST_BOT_CHAT_INTERVAL)
|
| 50 |
-
if stop_event.is_set():
|
| 51 |
-
break
|
| 52 |
-
try:
|
| 53 |
-
with app.app_context():
|
| 54 |
-
for user in test_users:
|
| 55 |
-
msg = ChatMessage(room_id=room_id, user_id=user.id, content="DURRRR")
|
| 56 |
-
db.session.add(msg)
|
| 57 |
-
db.session.commit()
|
| 58 |
-
logger.info("TESTBOT_CHAT room=%s bots=%s", room_id, len(test_users))
|
| 59 |
-
except Exception as e:
|
| 60 |
-
logger.exception("TESTBOT_CHAT_ERROR: %s", e)
|
| 61 |
-
try:
|
| 62 |
-
db.session.rollback()
|
| 63 |
-
except Exception:
|
| 64 |
-
pass
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
|
| 71 |
-
@staticmethod
|
| 72 |
-
def auto_setup_room(app, user_id):
|
| 73 |
-
"""Create a room with test bots and join the user. Returns room."""
|
| 74 |
room_id = None
|
|
|
|
| 75 |
with app.app_context():
|
| 76 |
-
|
| 77 |
-
room = RoomService.create_room(
|
| 78 |
-
for u in test_users[1:]:
|
| 79 |
-
RoomService.join_room(room.id, u.id)
|
| 80 |
-
RoomService.join_room(room.id, user_id)
|
| 81 |
room_id = room.id
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
with app.app_context():
|
| 89 |
return Room.query.get(room_id)
|
|
|
|
|
|
|
|
|
|
| 1 |
import logging
|
| 2 |
+
|
| 3 |
from extensions import db
|
| 4 |
+
from models import User, Room, RoomMembership
|
| 5 |
from services.rooms import RoomService
|
| 6 |
from config import Config
|
| 7 |
|
|
|
|
| 9 |
|
| 10 |
|
| 11 |
class TestMode:
|
| 12 |
+
"""Creates the simulated players used by test mode."""
|
| 13 |
|
| 14 |
@staticmethod
|
| 15 |
def is_enabled():
|
|
|
|
| 35 |
return test_users
|
| 36 |
|
| 37 |
@staticmethod
|
| 38 |
+
def auto_setup_room(app, user_id):
|
| 39 |
+
"""Create the visitor's room with test bots and register it for chatter.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
|
| 41 |
+
Returns the room (detached, re-fetched inside a context).
|
| 42 |
+
"""
|
| 43 |
+
from services.matchmaking import SIMULATION
|
| 44 |
+
from services.rooms import try_auto_start
|
| 45 |
|
|
|
|
|
|
|
|
|
|
| 46 |
room_id = None
|
| 47 |
+
bot_ids = []
|
| 48 |
with app.app_context():
|
| 49 |
+
bots = TestMode.create_test_players()
|
| 50 |
+
room = RoomService.create_room(bots[0].id, name="Auto-Test Room")
|
|
|
|
|
|
|
|
|
|
| 51 |
room_id = room.id
|
| 52 |
+
for u in bots[1:]:
|
| 53 |
+
RoomService.join_room(room_id, u.id)
|
| 54 |
+
RoomService.join_room(room_id, user_id)
|
| 55 |
+
bot_ids = [u.id for u in bots]
|
| 56 |
+
logger.warning(
|
| 57 |
+
"AUTO_ASSIGN room=%s bots=%s user=%s", room_id, len(bots), user_id
|
| 58 |
+
)
|
| 59 |
+
# try to auto-create a game now that players are present
|
| 60 |
+
try_auto_start(room_id)
|
| 61 |
+
|
| 62 |
+
SIMULATION.register_room(room_id, bot_ids)
|
| 63 |
+
# One more bot walks in a few seconds later, pushing the room to the
|
| 64 |
+
# auto-start threshold and creating a game.
|
| 65 |
+
SIMULATION.schedule_join(room_id, delay=4.0)
|
| 66 |
with app.app_context():
|
| 67 |
return Room.query.get(room_id)
|