fix(activity): refresh clients when an audience is unknown

When the server can't tell who may see a session, it no longer stays
silent: every socket gets a payload-less activity:refresh, and signed-in
clients re-list the activity they're allowed to see. A slower, older
activity request can no longer overwrite a newer one, and the store
tests use the typed user fixture.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PU9EuYhLpqR1DGMtmymr79
This commit is contained in:
Sam Dornan
2026-10-04 18:05:08 +00:00
committed by Claude
parent 5fdf004134
commit ef79916add
4 changed files with 96 additions and 13 deletions

View File

@@ -127,9 +127,10 @@ class ActivityHandler:
rooms = await _audience_rooms(entry["rom_id"])
await self._emit("activity:update", dict(entry), rooms)
if previous and previous["rom_id"] != entry["rom_id"]:
# Without this game's audience the refresh just sent covers everyone.
if rooms is not None and previous and previous["rom_id"] != entry["rom_id"]:
# Whoever saw the last game but can't see this one would keep its card.
stale = set(await _audience_rooms(previous["rom_id"]))
stale = await _audience_rooms(previous["rom_id"])
await self._emit(
"activity:clear",
ActivityClearSchema(
@@ -137,7 +138,7 @@ class ActivityHandler:
device_id=entry["device_id"],
rom_id=previous["rom_id"],
).model_dump(),
sorted(stale - set(rooms)),
None if stale is None else sorted(set(stale) - set(rooms)),
)
async def publish_clear(self, user_id: int, device_id: str) -> int | None:
@@ -155,13 +156,17 @@ class ActivityHandler:
return rom_id
async def _emit(
self, event: str, payload: dict[str, Any], rooms: list[str]
self, event: str, payload: dict[str, Any], rooms: list[str] | None
) -> None:
# The REST app shares this process with the Socket.IO server, so emit
# through the already-initialised, Redis-backed server (it fans out
# across workers) rather than opening a manager per call. An empty
# `to` would reach every socket, so no audience sends nothing.
if not rooms:
if rooms is None:
# An unknown audience can't be sent the session; every client
# re-lists what it may see instead.
event, payload = "activity:refresh", {}
elif not rooms:
return
try:
await socket_handler.socket_server.emit(event, payload, to=rooms)
@@ -296,13 +301,13 @@ class ActivityHandler:
pass
async def _audience_rooms(rom_id: int) -> list[str]:
"""The ROM's audience, or none if it can't be read, so publishing still succeeds."""
async def _audience_rooms(rom_id: int) -> list[str] | None:
"""The ROM's audience, or None if it can't be read, so publishing still succeeds."""
try:
return await asyncio.to_thread(_audience, rom_id)
except Exception: # noqa: BLE001 - activity is best-effort, like its broadcast
log.warning(f"Failed to resolve who can see ROM {rom_id}", exc_info=True)
return []
return None
def _audience(rom_id: int) -> list[str]:

View File

@@ -12,7 +12,7 @@ from handler.database.base_handler import sync_session
from handler.redis_handler import async_cache, sync_cache
from handler.socket_handler import socket_handler
from models.permission import HiddenEntity, PermEntity
from models.rom import Rom
from models.rom import Rom, RomVisibility
from models.user import User
@@ -391,7 +391,7 @@ class TestAudience:
assert [c.args[0] for c in emit.await_args_list] == ["activity:update"]
async def test_a_failed_audience_lookup_does_not_fail_publishing(
async def test_a_failed_audience_lookup_asks_everyone_to_refresh(
self, entry: ActivityEntry, admin_user: User
):
with (
@@ -405,5 +405,41 @@ class TestAudience:
entry["rom_id"]
)
emit.assert_not_awaited()
# Nothing about the session itself goes out to an unknown audience.
assert [(c.args, c.kwargs) for c in emit.await_args_list] == [
(("activity:refresh", {}), {"to": None}),
(("activity:refresh", {}), {"to": None}),
]
assert await activity_handler.get_active(admin_user.id, "deck") is None
async def test_a_failed_lookup_of_the_last_game_asks_everyone_to_refresh(
self,
entry: ActivityEntry,
admin_user: User,
second_rom: Rom,
):
await activity_handler.publish_active(entry)
switched = await activity_handler.build_entry(
user_id=admin_user.id,
device_id="deck",
rom_id=second_rom.id,
preserve_started_at=False,
)
assert switched is not None
visibility = db_rom_handler.get_rom_visibility
def fail_for_the_last_game(rom_id: int) -> RomVisibility | None:
if rom_id == entry["rom_id"]:
raise OSError("db down")
return visibility(rom_id)
with (
patch.object(db_rom_handler, "get_rom_visibility", fail_for_the_last_game),
_captured_emits() as emit,
):
await activity_handler.publish_active(switched)
assert [(c.args[0], c.kwargs["to"]) for c in emit.await_args_list] == [
("activity:update", [f"user:{admin_user.id}"]),
("activity:refresh", None),
]

View File

@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
import type { ActivityEntry } from "@/services/api/activity";
import storeActivity from "@/stores/activity";
import storeAuth from "@/stores/auth";
import type { User } from "@/stores/users";
import { userFixture } from "@/utils/user.fixtures";
const { get, handlers } = vi.hoisted(() => ({
get: vi.fn(),
@@ -45,7 +45,7 @@ describe("activity store socket events", () => {
setActivePinia(createPinia());
handlers.clear();
get.mockReset();
storeAuth().setCurrentUser({ id: 1 } as User);
storeAuth().setCurrentUser(userFixture({ id: 1 }));
storeActivity().initSocket();
});
@@ -122,4 +122,38 @@ describe("activity store socket events", () => {
expect(store.activities.map((a) => a.rom_id)).toEqual([12]);
expect(store.initialized).toBe(true);
});
it("keeps the newest list when an older request answers last", async () => {
const store = storeActivity();
let answerFirst = (_: { data: ActivityEntry[] }) => {};
get
.mockImplementationOnce(
() => new Promise((resolve) => (answerFirst = resolve)),
)
.mockResolvedValueOnce({ data: [] });
const first = store.fetchAll();
await store.fetchAll();
answerFirst({ data: [entry()] });
await first;
expect(store.activities).toEqual([]);
});
it("re-lists sessions when the server asks everyone to refresh", async () => {
const store = storeActivity();
handlers.get("activity:update")!(entry());
get.mockResolvedValue({ data: [] });
handlers.get("activity:refresh")!({});
await vi.waitFor(() => expect(store.activities).toEqual([]));
});
it("ignores a refresh when signed out", () => {
storeAuth().setCurrentUser(null);
handlers.get("activity:refresh")!({});
expect(get).not.toHaveBeenCalled();
});
});

View File

@@ -15,6 +15,8 @@ export default defineStore("activity", {
socketBound: false,
// Bumped by each socket event, so a fetch that raced one can tell.
version: 0,
// Bumped by each fetch, so a slower, older response can't overwrite a newer one.
latestFetch: 0,
}),
getters: {
@@ -36,10 +38,12 @@ export default defineStore("activity", {
actions: {
async fetchAll() {
const fetchId = ++this.latestFetch;
try {
for (let attempt = 1; ; attempt++) {
const version = this.version;
const { data } = await activityApi.getAllActivity();
if (fetchId !== this.latestFetch) return;
// An event that landed mid-request may be missing, so ask again.
if (version !== this.version && attempt < 3) continue;
this.activities = data;
@@ -91,6 +95,10 @@ export default defineStore("activity", {
socket.on("permissions:changed", (data: { user_id: number }) => {
if (data.user_id === storeAuth().user?.id) this.fetchAll();
});
// Sent to every socket when the server couldn't tell who may see a session.
socket.on("activity:refresh", () => {
if (storeAuth().user) this.fetchAll();
});
this.socketBound = true;
},