Commit fc48e64c authored by Aryan Noshirvani's avatar Aryan Noshirvani

Add real-time WebSocket infrastructure for Pass-the-Aux rooms

There was zero real-time infrastructure anywhere in this backend
before this - LiveRoom only ever supported create/list. Added
WS /social/rooms/{room_id}/ws:

- Chat: broadcast to everyone in the room (including the sender - a
  simpler, more predictable rule than asymmetric exclusion; clients
  can dedupe by user_id if they update optimistically).
- Reactions + a "fire meter": 🔥 reactions accumulate into a count
  that decays over a 30s window (src/services/room_manager.py), so it
  reads as "how hot is it right now," not a lifetime total.
- DJ handoff: request_aux queues a listener, pass_aux (DJ-only, an
  explicit rejection if a non-DJ tries) hands off to the front of the
  queue or a requested user_id. Confirmed via the actual LiveRoom.dj_id
  column, not just the in-memory session.
- now_playing (DJ-only) updates LiveRoom.current_song_id live.
- Presence (user_joined/user_left) and an initial state snapshot on
  connect (current DJ, current song, who's here, recent chat, fire
  count, queue) so a client joining mid-session isn't starting blind.

Room state (connections, chat history, fire events, DJ queue) is
in-memory and ephemeral by design (src/services/room_manager.py) -
only dj_id/current_song_id persist to the DB, since that's the only
part that should still be true if someone checks GET /social/rooms
without being live-connected. An empty room's ephemeral state is
discarded when the last person disconnects.

Found and fixed a real deployment gap while verifying this against the
actual running server rather than just the test suite: uvicorn had no
WebSocket protocol implementation installed at all (no `websockets` or
`wsproto` in requirements.txt) - Starlette's TestClient simulates
WebSockets in-process and doesn't need one, so all 8 new tests passed
happily while the real deployed server would have silently rejected
every WebSocket connection. Added websockets>=13.0 to requirements.txt
and confirmed a real end-to-end session (two live `websockets` client
connections, not TestClient) against the actual running dev instance:
chat, reactions, fire count, aux request/handoff, all working and
persisting to the DB correctly.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 375a447d
Pipeline #1003 passed with stage
in 17 minutes and 26 seconds
...@@ -10,6 +10,9 @@ google-generativeai==0.8.3 ...@@ -10,6 +10,9 @@ google-generativeai==0.8.3
pedalboard==0.9.8 pedalboard==0.9.8
fastapi>=0.110.0 fastapi>=0.110.0
uvicorn>=0.28.0 uvicorn>=0.28.0
websockets>=13.0 # uvicorn's WebSocket protocol implementation - without this, uvicorn
# silently has no WebSocket support at all (no error, connections just
# fail); needed for the Pass-the-Aux room websocket routes
sqlalchemy>=2.0.0 sqlalchemy>=2.0.0
httpx>=0.27.0 httpx>=0.27.0
python-multipart>=0.0.9 python-multipart>=0.0.9
......
from fastapi import APIRouter, Depends, HTTPException, status import time
from fastapi import APIRouter, Depends, HTTPException, WebSocket, WebSocketDisconnect, status
from pydantic import BaseModel from pydantic import BaseModel
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from src.core.database import get_db, User, Post, GeoDrop, LiveRoom from src.core.database import get_db, SessionLocal, User, Post, GeoDrop, LiveRoom
from src.services.room_manager import room_manager
from datetime import datetime, timezone from datetime import datetime, timezone
import math import math
...@@ -92,3 +95,126 @@ def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db)): ...@@ -92,3 +95,126 @@ def create_live_room(room: LiveRoomCreate, db: Session = Depends(get_db)):
def get_active_rooms(db: Session = Depends(get_db)): def get_active_rooms(db: Session = Depends(get_db)):
rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all() rooms = db.query(LiveRoom).filter(LiveRoom.is_active == True).all()
return rooms return rooms
# --- Pass-the-Aux: live room WebSocket ---
# Chat, reactions/fire-meter, presence, and DJ handoff are all in-memory ephemeral state
# (src/services/room_manager.py) - only dj_id and current_song_id persist to the LiveRoom
# row, since those are the only parts that make sense to still be true if someone checks
# the room later via GET /social/rooms rather than being connected live.
def _get_room_or_none(room_id: int):
db = SessionLocal()
try:
return db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
finally:
db.close()
def _set_room_dj(room_id: int, dj_id: int):
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if room:
room.dj_id = dj_id
db.commit()
finally:
db.close()
def _set_room_current_song(room_id: int, song_id):
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
if room:
room.current_song_id = song_id
db.commit()
finally:
db.close()
@router.websocket("/rooms/{room_id}/ws")
async def room_websocket(websocket: WebSocket, room_id: int, user_id: int):
room_row = _get_room_or_none(room_id)
if not room_row:
await websocket.close(code=4404)
return
if not room_row.is_active:
await websocket.close(code=4403)
return
await room_manager.connect(room_id, user_id, websocket)
state = room_manager.get_room(room_id)
await websocket.send_json({
"type": "snapshot",
"dj_id": room_row.dj_id,
"current_song_id": room_row.current_song_id,
"presence": room_manager.presence(room_id),
"chat_history": list(state.chat_history),
"fire_count": state.fire_count(),
"dj_queue": state.dj_queue,
})
await room_manager.broadcast(room_id, {"type": "user_joined", "user_id": user_id}, exclude_user_id=user_id)
try:
while True:
data = await websocket.receive_json()
msg_type = data.get("type")
if msg_type == "chat":
text = str(data.get("text", ""))[:500]
if not text.strip():
continue
chat_msg = {"type": "chat", "user_id": user_id, "text": text}
state.chat_history.append(chat_msg)
await room_manager.broadcast(room_id, chat_msg)
elif msg_type == "reaction":
emoji = str(data.get("emoji", "🔥"))[:8]
if emoji == "🔥":
state.fire_events.append(time.time())
await room_manager.broadcast(room_id, {
"type": "reaction", "user_id": user_id, "emoji": emoji, "fire_count": state.fire_count(),
})
elif msg_type == "request_aux":
if user_id != room_row.dj_id and user_id not in state.dj_queue:
state.dj_queue.append(user_id)
await room_manager.broadcast(room_id, {"type": "queue_updated", "dj_queue": state.dj_queue})
elif msg_type == "pass_aux":
if user_id != room_row.dj_id:
await websocket.send_json({"type": "error", "detail": "Only the current DJ can pass the aux."})
continue
next_dj = None
if state.dj_queue:
next_dj = state.dj_queue.pop(0)
else:
requested = data.get("to_user_id")
if requested in state.connections:
next_dj = requested
if next_dj is not None:
room_row.dj_id = next_dj
_set_room_dj(room_id, next_dj)
await room_manager.broadcast(room_id, {"type": "dj_changed", "dj_id": next_dj, "dj_queue": state.dj_queue})
else:
await websocket.send_json({"type": "error", "detail": "No one is waiting to take the aux."})
elif msg_type == "now_playing":
if user_id != room_row.dj_id:
await websocket.send_json({"type": "error", "detail": "Only the current DJ can change what's playing."})
continue
song_id = data.get("song_id")
room_row.current_song_id = song_id
_set_room_current_song(room_id, song_id)
await room_manager.broadcast(room_id, {"type": "now_playing_changed", "song_id": song_id, "dj_id": user_id})
else:
await websocket.send_json({"type": "error", "detail": f"Unknown message type: {msg_type!r}"})
except WebSocketDisconnect:
pass
finally:
room_manager.disconnect(room_id, user_id)
await room_manager.broadcast(room_id, {"type": "user_left", "user_id": user_id})
import time
from collections import deque
from fastapi import WebSocket
MAX_CHAT_HISTORY = 50
FIRE_DECAY_SECONDS = 30 # a "fire meter" reading is how many 🔥 reactions landed in the
# last N seconds, not a lifetime total - it should visibly cool
# off when the room isn't currently popping.
class RoomState:
"""All in-memory, per-room, ephemeral live-session state. None of this is meant to
survive a process restart - it's the equivalent of "who's in the room right now,"
not a historical record. LiveRoom.dj_id/current_song_id in the DB are the durable
parts, updated alongside this."""
def __init__(self):
self.connections: dict[int, WebSocket] = {} # user_id -> websocket
self.chat_history: deque = deque(maxlen=MAX_CHAT_HISTORY)
self.dj_queue: list = [] # user_ids waiting to be handed the aux
self.fire_events: deque = deque() # timestamps of recent fire reactions
def fire_count(self) -> int:
cutoff = time.time() - FIRE_DECAY_SECONDS
while self.fire_events and self.fire_events[0] < cutoff:
self.fire_events.popleft()
return len(self.fire_events)
class RoomConnectionManager:
def __init__(self):
self.rooms: dict[int, RoomState] = {}
def get_room(self, room_id: int) -> RoomState:
if room_id not in self.rooms:
self.rooms[room_id] = RoomState()
return self.rooms[room_id]
async def connect(self, room_id: int, user_id: int, websocket: WebSocket):
await websocket.accept()
self.get_room(room_id).connections[user_id] = websocket
def disconnect(self, room_id: int, user_id: int):
room = self.rooms.get(room_id)
if not room:
return
room.connections.pop(user_id, None)
if user_id in room.dj_queue:
room.dj_queue.remove(user_id)
# An empty room's ephemeral state (chat history, fire meter, queue) is discarded -
# the next person to join starts a fresh session, matching how a live room should
# behave once everyone's left.
if not room.connections:
self.rooms.pop(room_id, None)
async def broadcast(self, room_id: int, message: dict, exclude_user_id: int = None):
room = self.rooms.get(room_id)
if not room:
return
dead = []
for uid, ws in list(room.connections.items()):
if uid == exclude_user_id:
continue
try:
await ws.send_json(message)
except Exception:
dead.append(uid)
for uid in dead:
room.connections.pop(uid, None)
def presence(self, room_id: int) -> list:
room = self.rooms.get(room_id)
return list(room.connections.keys()) if room else []
room_manager = RoomConnectionManager()
from src.core.database import LiveRoom, SessionLocal
def _make_room(dj_id=1, name="Test Room"):
db = SessionLocal()
try:
room = LiveRoom(dj_id=dj_id, name=name, is_active=True)
db.add(room)
db.commit()
db.refresh(room)
return room.id
finally:
db.close()
def test_websocket_closes_for_unknown_room(client):
from starlette.websockets import WebSocketDisconnect
import pytest
with pytest.raises(WebSocketDisconnect):
with client.websocket_connect("/social/rooms/999999/ws?user_id=1"):
pass
def test_websocket_snapshot_on_connect(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws:
snapshot = ws.receive_json()
assert snapshot["type"] == "snapshot"
assert snapshot["dj_id"] == 1
assert snapshot["presence"] == [1]
assert snapshot["chat_history"] == []
assert snapshot["fire_count"] == 0
assert snapshot["dj_queue"] == []
def test_websocket_broadcasts_chat_between_clients(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws1:
ws1.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws2:
ws2.receive_json() # snapshot
joined = ws1.receive_json()
assert joined == {"type": "user_joined", "user_id": 2}
ws2.send_json({"type": "chat", "text": "hey everyone"})
chat_on_ws1 = ws1.receive_json()
assert chat_on_ws1 == {"type": "chat", "user_id": 2, "text": "hey everyone"}
# Broadcasts (chat/reactions) intentionally include the sender too - simpler,
# more predictable than an asymmetric "everyone except me" rule, and clients
# can always ignore/dedupe their own user_id if they update optimistically.
# This bit a manual live-server test script during development (it assumed
# sender exclusion and read messages out of order) - locking it in explicitly.
chat_echoed_to_sender = ws2.receive_json()
assert chat_echoed_to_sender == {"type": "chat", "user_id": 2, "text": "hey everyone"}
def test_websocket_reaction_increments_fire_count(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws:
ws.receive_json() # snapshot
ws.send_json({"type": "reaction", "emoji": "🔥"})
reaction = ws.receive_json()
assert reaction["type"] == "reaction"
assert reaction["emoji"] == "🔥"
assert reaction["fire_count"] == 1
def test_websocket_dj_handoff_flow(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as listener_ws:
listener_ws.receive_json() # snapshot
dj_ws.receive_json() # user_joined for user 2
listener_ws.send_json({"type": "request_aux"})
queue_update_on_listener = listener_ws.receive_json()
queue_update_on_dj = dj_ws.receive_json()
assert queue_update_on_listener == {"type": "queue_updated", "dj_queue": [2]}
assert queue_update_on_dj == {"type": "queue_updated", "dj_queue": [2]}
dj_ws.send_json({"type": "pass_aux"})
dj_changed_on_dj = dj_ws.receive_json()
dj_changed_on_listener = listener_ws.receive_json()
assert dj_changed_on_dj == {"type": "dj_changed", "dj_id": 2, "dj_queue": []}
assert dj_changed_on_listener == {"type": "dj_changed", "dj_id": 2, "dj_queue": []}
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.dj_id == 2
finally:
db.close()
def test_websocket_only_dj_can_pass_aux(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws:
ws.receive_json() # snapshot
ws.send_json({"type": "pass_aux"})
error = ws.receive_json()
assert error == {"type": "error", "detail": "Only the current DJ can pass the aux."}
def test_websocket_only_dj_can_set_now_playing(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as dj_ws:
dj_ws.receive_json() # snapshot
dj_ws.send_json({"type": "now_playing", "song_id": 42})
update = dj_ws.receive_json()
assert update == {"type": "now_playing_changed", "song_id": 42, "dj_id": 1}
db = SessionLocal()
try:
room = db.query(LiveRoom).filter(LiveRoom.id == room_id).first()
assert room.current_song_id == 42
finally:
db.close()
def test_websocket_user_left_broadcast_on_disconnect(client):
room_id = _make_room(dj_id=1)
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=1") as ws1:
ws1.receive_json() # snapshot
with client.websocket_connect(f"/social/rooms/{room_id}/ws?user_id=2") as ws2:
ws2.receive_json() # snapshot
ws1.receive_json() # user_joined
left = ws1.receive_json()
assert left == {"type": "user_left", "user_id": 2}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment