fix(streaming): join the session the caller asked for

An unnamed join stopped at the first pool member holding a live session, so a
desktop, another platform's game, the caller's own session or a ROM they cannot
see masked the session they were offered and the join answered 404 or handed
back somebody else's room.

The walk now skips a member that fails the same filter the joinable listing
applies and keeps looking, and the Join button carries the container of the row
it came from into the stream URL so the join names its session outright.
This commit is contained in:
Zach Clendenen committed 2026-09-17 15:59:57 -05:00
1 parent f512bead7f
commit 5233649ebd
10 files changed
+179 -15

No files matched your search

+14 -3
View File
@@ -93,6 +93,7 @@ from handler.streaming.session_store import (
release_own_session,
session_disc_id,
session_is_stale,
session_platform_matches,
session_redis_key,
set_session_disc,
stamp_launched,
@@ -1096,9 +1097,19 @@ async def join_session(
session = await get_live_session(candidate.key)
if session is None:
continue
if session.get("multiplayer"):
found = (candidate, session)
break
# Same filter the joinable listing applies, so the button and the
# join agree on what is joinable. A member that fails it is not the
# answer and must not mask a later one that is.
if not session.get("multiplayer"):
continue
if not session_platform_matches(session, platform):
continue
if session.get("user_id") == request.user.id:
continue
if not access.session_rom_is_visible(request, session):
continue
found = (candidate, session)
break
if found is None:
raise HTTPException(
+3 -3
View File
@@ -54,7 +54,7 @@ def rom_is_visible(request: Request, rom: Rom | None) -> bool:
return get_permissions(request).can_see_rom(rom.id, rom.platform_id)
def _session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool:
def session_rom_is_visible(request: Request, session: dict[str, Any]) -> bool:
"""Can the caller see the ROM a session is running?"""
rom_id = session.get("rom_id")
if rom_id is None:
@@ -66,14 +66,14 @@ def assert_session_rom_visible(
request: Request, session: dict[str, Any], *, not_found_detail: str
) -> None:
"""Raise 404 when the session's ROM is hidden from the caller."""
if not _session_rom_is_visible(request, session):
if not session_rom_is_visible(request, session):
raise HTTPException(status_code=404, detail=not_found_detail)
def visible_rom_name(request: Request, session: dict[str, Any]) -> str | None:
"""The name of the ROM a session is running, blanked when the caller cannot
see that ROM. "Busy" is safe to report to anyone; what is running is not."""
if not session or not _session_rom_is_visible(request, session):
if not session or not session_rom_is_visible(request, session):
return None
name = session.get("rom_name")
return str(name) if name else None
+81
View File
@@ -6679,6 +6679,87 @@ def test_joining_a_rom_on_a_hidden_platform_is_404_masked(
join_broker.assert_not_called()
def _ws_pool_member(rom: Rom, index: int, **overrides) -> dict:
"""One member of a pool of webstation containers, the broker a joiner
needs. Distinct hosts, so the room URL says which member answered."""
return _webstation(
**{
"host": f"http://192.168.1.1{index}:3000",
"broker_host": f"http://192.168.1.1{index}:8000",
"platforms": {rom.platform_slug: "pcsx2"},
**overrides,
}
)
def _joined_room(url: str = "/webstation/?token=abc"):
return patch("handler.streaming.webstation.join", return_value={"url": url})
def test_joining_walks_past_a_session_whose_rom_is_hidden(
client,
access_token,
editor_access_token,
viewer_access_token,
viewer_user: User,
rom: Rom,
second_rom: Rom,
):
"""A hidden ROM earlier in the pool is not the caller's answer, so it must
not mask the joinable session behind it."""
_hide(PermEntity.ROMS, rom.id, viewer_user.id)
with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)):
_claim_multiplayer(client, access_token, rom.id)
_claim_multiplayer(client, editor_access_token, second_rom.id)
with _joined_room():
r = _join(client, viewer_access_token, rom.platform_slug)
assert r.status_code == 200
assert r.json()["rom_id"] == second_rom.id
def test_joining_walks_past_the_callers_own_session(
client, access_token, viewer_access_token, rom: Rom, second_rom: Rom
):
"""Joining is for somebody else's game: the caller's own session is the one
they already hold, and the listing leaves it out for the same reason."""
with _streaming(_ws_pool_member(rom, 0), _ws_pool_member(rom, 1)):
_claim_multiplayer(client, viewer_access_token, rom.id)
_claim_multiplayer(client, access_token, second_rom.id)
with _joined_room():
r = _join(client, viewer_access_token, rom.platform_slug)
assert r.status_code == 200
assert r.json()["rom_id"] == second_rom.id
def test_joining_walks_past_a_session_on_another_platform(
client,
access_token,
editor_access_token,
viewer_access_token,
rom: Rom,
second_rom: Rom,
):
"""A container serves several platforms and holds one session, so a member
busy with another platform is not this platform's session to join."""
member = _ws_pool_member(
rom, 0, platforms={rom.platform_slug: "pcsx2", "ngc": "dolphin"}
)
with _streaming(member, _ws_pool_member(rom, 1)):
_claim_multiplayer(client, access_token, rom.id)
key = session_store.session_redis_key(_key_of(member))
session = json.loads(asyncio.run(async_cache.get(key)))
session["platform"] = "ngc"
asyncio.run(async_cache.set(key, json.dumps(session)))
_claim_multiplayer(client, editor_access_token, second_rom.id)
with _joined_room():
r = _join(client, viewer_access_token, rom.platform_slug)
assert r.status_code == 200
assert r.json()["rom_id"] == second_rom.id
def test_joining_a_solo_session_finds_nothing_to_join(
client, access_token, viewer_access_token, rom: Rom
):
@@ -57,6 +57,7 @@ async function join(): Promise<void> {
romId,
romName: title.value,
hostUsername: props.session.host_username ?? null,
container: props.session.container,
});
}
</script>
@@ -15,7 +15,7 @@ const canPlayPico8 = { value: false };
const canPlayRuffle = { value: false };
const streamContainer = { value: null as object | null };
const joinableSession = {
value: null as { host_username: string | null } | null,
value: null as { host_username: string | null; container?: string } | null,
};
// Granted action keys — `null` means "everything" (the default).
const grantedActions: { value: Set<ActionKey> | null } = { value: null };
@@ -142,7 +142,10 @@ beforeEach(() => {
describe("useGameActions.joinStream", () => {
beforeEach(() => {
streamContainer.value = { host: "http://stream" };
joinableSession.value = { host_username: "ada" };
joinableSession.value = {
host_username: "ada",
container: "http://box:8000",
};
});
it("does not navigate until the user confirms", async () => {
@@ -161,7 +164,11 @@ describe("useGameActions.joinStream", () => {
await actions.joinStream();
expect(push).toHaveBeenCalledWith("/rom/1/stream?join=1");
// The joinable row names the container, and a pool needs it: the stream
// view would otherwise walk the pool and could land on another session.
expect(push).toHaveBeenCalledWith(
"/rom/1/stream?join=1&container=http%3A%2F%2Fbox%3A8000",
);
});
it("names the host in the confirmation", async () => {
@@ -376,6 +376,7 @@ export function useGameActions(
romId: rom.id,
romName: rom.name ?? rom.fs_name_no_ext ?? "",
hostUsername: joinHostLabel.value || null,
container: joinableSession.value?.container ?? null,
},
);
}
@@ -14,7 +14,12 @@ vi.mock("@/v2/composables/useConfirm", () => ({
useConfirm: () => confirmFn,
}));
const target = { romId: 1, romName: "Chrono Trigger", hostUsername: "ada" };
const target = {
romId: 1,
romName: "Chrono Trigger",
hostUsername: "ada",
container: null,
};
describe("useJoinStreamConfirm", () => {
beforeEach(() => {
@@ -40,6 +45,17 @@ describe("useJoinStreamConfirm", () => {
expect(push).toHaveBeenCalledWith("/rom/1/stream?join=1");
});
it("carries the container into the join URL", async () => {
confirmFn.mockResolvedValue(true);
const { joinStream } = useJoinStreamConfirm();
await joinStream({ ...target, container: "http://box:8000" });
expect(push).toHaveBeenCalledWith(
"/rom/1/stream?join=1&container=http%3A%2F%2Fbox%3A8000",
);
});
it("names the host in the confirmation", async () => {
confirmFn.mockResolvedValue(false);
const { joinStream } = useJoinStreamConfirm();
@@ -11,6 +11,9 @@ export interface JoinStreamTarget {
romId: number;
romName: string;
hostUsername: string | null;
// A pool holds a session per container, so the one being joined has to be
// named rather than left to the backend to pick.
container: string | null;
}
interface JoinStreamDeps {
@@ -35,7 +38,9 @@ export async function confirmJoinStream(
confirmText: t("rom.join-session"),
});
if (!ok) return;
void router.push(`/rom/${target.romId}/stream?join=1`);
const query = new URLSearchParams({ join: "1" });
if (target.container) query.set("container", target.container);
void router.push(`/rom/${target.romId}/stream?${query}`);
}
export function useJoinStreamConfirm() {
+37 -3
View File
@@ -1,5 +1,5 @@
import { flushPromises, mount, type VueWrapper } from "@vue/test-utils";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { defineComponent } from "vue";
import type { SaveSchema } from "@/__generated__";
import type { DetailedRom } from "@/stores/roms";
@@ -14,11 +14,13 @@ const mocks = vi.hoisted(() => ({
getRom: vi.fn(),
fetchSessionStatus: vi.fn(),
heartbeatSession: vi.fn(),
joinSession: vi.fn(),
releaseSession: vi.fn(),
releaseSessionKeepalive: vi.fn(),
container: null as Record<string, unknown> | null,
presenceTick: null as (() => Promise<void>) | null,
socketHandlers: {} as Record<string, (payload: unknown) => unknown>,
query: {} as Record<string, string>,
}));
vi.mock("vue-i18n", () => ({
@@ -27,7 +29,7 @@ vi.mock("vue-i18n", () => ({
vi.mock("vue-router", () => ({
onBeforeRouteLeave: vi.fn(),
useRoute: () => ({ params: { rom: "3" }, query: {} }),
useRoute: () => ({ params: { rom: "3" }, query: mocks.query }),
useRouter: () => ({ push: vi.fn(), replace: vi.fn() }),
}));
@@ -69,7 +71,7 @@ vi.mock("@/stores/streaming", () => ({
fetchSessionStatus: mocks.fetchSessionStatus,
forgetJoinableSession: vi.fn(),
heartbeatSession: mocks.heartbeatSession,
joinSession: vi.fn(),
joinSession: mocks.joinSession,
releaseSession: mocks.releaseSession,
releaseSessionKeepalive: mocks.releaseSessionKeepalive,
saveAndExit: vi.fn(),
@@ -566,3 +568,35 @@ describe("Stream launch recovery", () => {
wrapper.unmount();
});
});
describe("Stream join", () => {
beforeEach(() => {
vi.clearAllMocks();
mocks.joinSession.mockResolvedValue({ host: "http://box:3000/room/x" });
mocks.query = { join: "1", container: "http://box:8000" };
});
afterEach(() => {
mocks.query = {};
});
it("joins the session on the container the game page named", async () => {
// A pool has several sessions on one platform, so without the container
// the join lands on whichever the backend walks to first.
const wrapper = await launch({ picker: false });
await flushPromises();
expect(mocks.joinSession).toHaveBeenCalledWith("gba", "http://box:8000");
expect(vmOf(wrapper).playerState).toBe("playing");
wrapper.unmount();
});
it("joins without one when the page had no container to name", async () => {
mocks.query = { join: "1" };
const wrapper = await launch({ picker: false });
await flushPromises();
expect(mocks.joinSession).toHaveBeenCalledWith("gba", undefined);
wrapper.unmount();
});
});
+9 -1
View File
@@ -137,6 +137,11 @@ useStageActive(gameRunning);
// host's session out from under them.
const isJoining = route.query.join === "1";
// Named by the row that offered the join: a pool holds a session per container,
// and an unnamed join takes whichever one the backend walks to first.
const joinContainer =
typeof route.query.container === "string" ? route.query.container : undefined;
// True only while this tab's own claim is held. The teardown paths key off
// this rather than the player state, because a joiner reaches "playing" too.
const holdsClaim = ref(false);
@@ -817,7 +822,10 @@ async function onPlay(cardImport?: MemoryCardImport): Promise<void> {
try {
if (isJoining) {
const joined = await streamingStore.joinSession(rom.value.platform_slug);
const joined = await streamingStore.joinSession(
rom.value.platform_slug,
joinContainer,
);
await flourish;
if ((playerState.value as PlayerState) === "exited") return;
containerHost.value = joined.host;