mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 10:33:22 +01:00
fix(activity): survive audience lookup failures and late events
Consume the groups query and order the audience by user id, so the buffered-results check and Postgres both pass. A failed audience lookup now logs and sends nothing instead of failing the heartbeat. On the client, a clear only drops the session for the game it names, and a listing that raced a socket event is fetched again, up to three times. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PU9EuYhLpqR1DGMtmymr79
This commit is contained in:
@@ -124,12 +124,12 @@ class ActivityHandler:
|
||||
"""Store a session and send it to everyone allowed to see its ROM."""
|
||||
previous = await self.get_active(entry["user_id"], entry["device_id"])
|
||||
await self.set_active(entry)
|
||||
rooms = await asyncio.to_thread(_audience, entry["rom_id"])
|
||||
rooms = await _audience_rooms(entry["rom_id"])
|
||||
await self._emit("activity:update", dict(entry), rooms)
|
||||
|
||||
if 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 asyncio.to_thread(_audience, previous["rom_id"]))
|
||||
stale = set(await _audience_rooms(previous["rom_id"]))
|
||||
await self._emit(
|
||||
"activity:clear",
|
||||
ActivityClearSchema(
|
||||
@@ -150,7 +150,7 @@ class ActivityHandler:
|
||||
ActivityClearSchema(
|
||||
user_id=user_id, device_id=device_id, rom_id=rom_id
|
||||
).model_dump(),
|
||||
await asyncio.to_thread(_audience, rom_id),
|
||||
await _audience_rooms(rom_id),
|
||||
)
|
||||
return rom_id
|
||||
|
||||
@@ -296,6 +296,15 @@ 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."""
|
||||
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 []
|
||||
|
||||
|
||||
def _audience(rom_id: int) -> list[str]:
|
||||
"""Sockets join their `user:{id}` room on connect; anonymous sockets join none."""
|
||||
rom = db_rom_handler.get_rom_visibility(rom_id)
|
||||
|
||||
@@ -106,11 +106,7 @@ class DBPermissionsHandler(DBBaseHandler):
|
||||
rom: VisibilityColumns,
|
||||
session: Session = INJECTED_SESSION,
|
||||
) -> list[int]:
|
||||
"""Ids of the enabled users who can see `rom`, in four queries for any number.
|
||||
|
||||
Applies what `resolve_permissions` would for each user, reading only the
|
||||
hides that name this ROM or its platform.
|
||||
"""
|
||||
"""Ids of the enabled users who can see `rom`, in four queries."""
|
||||
users = session.execute(
|
||||
select(
|
||||
User.id,
|
||||
@@ -118,7 +114,9 @@ class DBPermissionsHandler(DBBaseHandler):
|
||||
User.permission_group_id,
|
||||
User.age_limit,
|
||||
User.hide_unrated_roms,
|
||||
).where(User.enabled.is_(True))
|
||||
)
|
||||
.where(User.enabled.is_(True))
|
||||
.order_by(User.id)
|
||||
).all()
|
||||
default_group_id = self.get_default_group_id(session=session)
|
||||
groups = {
|
||||
@@ -129,7 +127,7 @@ class DBPermissionsHandler(DBBaseHandler):
|
||||
PermissionGroup.age_limit,
|
||||
PermissionGroup.hide_unrated_roms,
|
||||
)
|
||||
)
|
||||
).all()
|
||||
}
|
||||
hides = session.execute(
|
||||
select(
|
||||
|
||||
@@ -80,11 +80,11 @@ def _visibility(rom: Rom) -> RomVisibility:
|
||||
|
||||
|
||||
def _resolved(rom: RomVisibility) -> list[int]:
|
||||
return [
|
||||
return sorted(
|
||||
user.id
|
||||
for user in db_user_handler.get_users()
|
||||
if user.enabled and resolve_permissions(user).can_see_rom(rom)
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -390,3 +390,20 @@ class TestAudience:
|
||||
await activity_handler.publish_active(switched)
|
||||
|
||||
assert [c.args[0] for c in emit.await_args_list] == ["activity:update"]
|
||||
|
||||
async def test_a_failed_audience_lookup_does_not_fail_publishing(
|
||||
self, entry: ActivityEntry, admin_user: User
|
||||
):
|
||||
with (
|
||||
patch.object(
|
||||
db_rom_handler, "get_rom_visibility", side_effect=OSError("db down")
|
||||
),
|
||||
_captured_emits() as emit,
|
||||
):
|
||||
await activity_handler.publish_active(entry)
|
||||
assert await activity_handler.publish_clear(admin_user.id, "deck") == (
|
||||
entry["rom_id"]
|
||||
)
|
||||
|
||||
emit.assert_not_awaited()
|
||||
assert await activity_handler.get_active(admin_user.id, "deck") is None
|
||||
|
||||
@@ -80,4 +80,46 @@ describe("activity store socket events", () => {
|
||||
|
||||
expect(get).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("keeps a session when a late clear names its previous game", () => {
|
||||
const store = storeActivity();
|
||||
handlers.get("activity:update")!(entry({ rom_id: 11 }));
|
||||
|
||||
handlers.get("activity:clear")!({
|
||||
user_id: 2,
|
||||
device_id: "deck",
|
||||
rom_id: 10,
|
||||
});
|
||||
|
||||
expect(store.activities.map((a) => a.rom_id)).toEqual([11]);
|
||||
});
|
||||
|
||||
it("re-lists when an event lands while the list is in flight", async () => {
|
||||
const store = storeActivity();
|
||||
get
|
||||
.mockImplementationOnce(async () => {
|
||||
handlers.get("activity:update")!(entry({ rom_id: 11 }));
|
||||
return { data: [] };
|
||||
})
|
||||
.mockResolvedValueOnce({ data: [entry({ rom_id: 11 })] });
|
||||
|
||||
await store.fetchAll();
|
||||
|
||||
expect(get).toHaveBeenCalledTimes(2);
|
||||
expect(store.activities.map((a) => a.rom_id)).toEqual([11]);
|
||||
});
|
||||
|
||||
it("settles for the last list when events keep landing", async () => {
|
||||
const store = storeActivity();
|
||||
get.mockImplementation(async () => {
|
||||
handlers.get("activity:update")!(entry({ rom_id: 11 }));
|
||||
return { data: [entry({ rom_id: 12 })] };
|
||||
});
|
||||
|
||||
await store.fetchAll();
|
||||
|
||||
expect(get).toHaveBeenCalledTimes(3);
|
||||
expect(store.activities.map((a) => a.rom_id)).toEqual([12]);
|
||||
expect(store.initialized).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -13,6 +13,8 @@ export default defineStore("activity", {
|
||||
activities: [] as ActivityEntry[],
|
||||
initialized: false,
|
||||
socketBound: false,
|
||||
// Bumped by each socket event, so a fetch that raced one can tell.
|
||||
version: 0,
|
||||
}),
|
||||
|
||||
getters: {
|
||||
@@ -35,15 +37,22 @@ export default defineStore("activity", {
|
||||
actions: {
|
||||
async fetchAll() {
|
||||
try {
|
||||
const { data } = await activityApi.getAllActivity();
|
||||
this.activities = data;
|
||||
this.initialized = true;
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const version = this.version;
|
||||
const { data } = await activityApi.getAllActivity();
|
||||
// An event that landed mid-request may be missing, so ask again.
|
||||
if (version !== this.version && attempt < 3) continue;
|
||||
this.activities = data;
|
||||
this.initialized = true;
|
||||
return;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Error fetching activity:", error);
|
||||
}
|
||||
},
|
||||
|
||||
handleUpdate(entry: ActivityEntry) {
|
||||
this.version++;
|
||||
const idx = this.activities.findIndex(
|
||||
(a) => a.user_id === entry.user_id && a.device_id === entry.device_id,
|
||||
);
|
||||
@@ -56,8 +65,15 @@ export default defineStore("activity", {
|
||||
},
|
||||
|
||||
handleClear(data: ActivityClearEvent) {
|
||||
this.version++;
|
||||
// A clear for the device's previous game must not drop its current one.
|
||||
this.activities = this.activities.filter(
|
||||
(a) => !(a.user_id === data.user_id && a.device_id === data.device_id),
|
||||
(a) =>
|
||||
!(
|
||||
a.user_id === data.user_id &&
|
||||
a.device_id === data.device_id &&
|
||||
a.rom_id === data.rom_id
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
|
||||
Reference in New Issue
Block a user