mirror of
https://github.com/rommapp/romm.git
synced 2026-12-02 10:08:40 +01:00
fix(streaming): let a tab that missed launch-ready find its way in
The room URL only ever existed in the launch-ready push, so a socket that dropped while the game was coming up left the tab loading forever over a session that was running, with no way out but a release. The session now records the room the launch answered with, the status poll reports it along with the container it was found on, and a loading tab enters the stream on that answer.
This commit is contained in:
@@ -60,6 +60,12 @@ class SessionStatusSchema(BaseModel):
|
||||
extraction_phase: str | None = None
|
||||
"""Set while a webstation broker unpacks a pkg or archive, which is the
|
||||
part of a launch long enough that the player needs to see something."""
|
||||
host: str | None = None
|
||||
"""The room URL of a session already up, for a tab that missed the
|
||||
launch-ready push. None until the launch returns."""
|
||||
container: str | None = None
|
||||
"""The container the session was found on, so a recovering tab names the
|
||||
claim it holds on every release and heartbeat."""
|
||||
termination: SessionTerminationSchema | None = None
|
||||
|
||||
|
||||
|
||||
@@ -219,7 +219,14 @@ async def _session_status(
|
||||
)
|
||||
if found is not None:
|
||||
container, _, session = found
|
||||
status: dict[str, Any] = {"status": "active", "platform": platform}
|
||||
status: dict[str, Any] = {
|
||||
"status": "active",
|
||||
"platform": platform,
|
||||
# The room the launch answered with, so a tab that missed the
|
||||
# launch-ready push can enter the stream off a poll.
|
||||
"host": session.get("host"),
|
||||
"container": container.key,
|
||||
}
|
||||
# An activate that has not returned yet leaves no launched_at behind.
|
||||
# Gating the broker round trip on it keeps this route pure Redis for
|
||||
# the rest of the session, which is the part that gets polled forever.
|
||||
@@ -1457,7 +1464,7 @@ async def claim_desktop_session(
|
||||
room_url = str(launch_result.get("url", "")) if launch_result else ""
|
||||
host = room_url_on(container.host, room_url)
|
||||
|
||||
await stamp_launched(session_key, session)
|
||||
await stamp_launched(session_key, session, host=host)
|
||||
log.info("desktop session claimed, container=%s", session_key)
|
||||
return DesktopSessionSchema(
|
||||
container=session_key,
|
||||
|
||||
@@ -111,7 +111,8 @@ async def run_launch(
|
||||
claim_hold.cancel()
|
||||
|
||||
log.info("session claimed, platform=%s rom=%s", platform, rom_name)
|
||||
await stamp_launched(session_key, session)
|
||||
host = container.protocol.stream_url(container.host, launch_result)
|
||||
await stamp_launched(session_key, session, host=host)
|
||||
await lifecycle.publish_session_activity(session_key, session)
|
||||
|
||||
# The webstation broker's deferred load waits for its emulator to report
|
||||
@@ -126,7 +127,7 @@ async def run_launch(
|
||||
LaunchReadyPayload(
|
||||
platform=platform,
|
||||
container=session_key,
|
||||
host=container.protocol.stream_url(container.host, launch_result),
|
||||
host=host,
|
||||
resume=resume_pushed if resume_state is not None else None,
|
||||
).model_dump(),
|
||||
)
|
||||
|
||||
@@ -425,10 +425,15 @@ async def hold_session_claim(session_key: str, claim: dict[str, Any]) -> None:
|
||||
return
|
||||
|
||||
|
||||
async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None:
|
||||
async def stamp_launched(
|
||||
session_key: str, claim: dict[str, Any], host: str | None = None
|
||||
) -> None:
|
||||
"""Record that the activate returned, so the status poll stops asking the
|
||||
broker for an extraction phase.
|
||||
|
||||
The room URL is recorded with it: the launch reply is the only place it
|
||||
exists, and the status poll is how a tab that missed the push gets in.
|
||||
|
||||
Guarded on the claim it was made for, like `set_session_disc`: an activate
|
||||
outlives the claim when a release lands while it runs, and an unguarded
|
||||
write would stamp a stranger's session or bring a short drain marker back
|
||||
@@ -440,7 +445,10 @@ async def stamp_launched(session_key: str, claim: dict[str, Any]) -> None:
|
||||
try:
|
||||
await mutate_session(
|
||||
session_key,
|
||||
{"launched_at": datetime.now(timezone.utc).isoformat()},
|
||||
{
|
||||
"launched_at": datetime.now(timezone.utc).isoformat(),
|
||||
**({"host": host} if host else {}),
|
||||
},
|
||||
require=lambda current: same_claim(current, claim),
|
||||
)
|
||||
except StreamingSessionContended:
|
||||
|
||||
@@ -2652,7 +2652,8 @@ def test_heartbeat_for_unknown_platform_returns_404(client, access_token, rom: R
|
||||
|
||||
|
||||
def test_status_reports_active_for_owner(client, access_token, rom: Rom):
|
||||
with _streaming(_container_for(rom)):
|
||||
container = _container_for(rom)
|
||||
with _streaming(container):
|
||||
_claim_ok(client, access_token, rom.id)
|
||||
r = client.get(
|
||||
f"/api/streaming/sessions/{rom.platform_slug}/status",
|
||||
@@ -2664,9 +2665,37 @@ def test_status_reports_active_for_owner(client, access_token, rom: Rom):
|
||||
"platform": rom.platform_slug,
|
||||
"extraction_phase": None,
|
||||
"termination": None,
|
||||
"host": container["host"],
|
||||
"container": _key_of(container),
|
||||
}
|
||||
|
||||
|
||||
def test_status_carries_the_room_the_launch_answered_with(client, access_token):
|
||||
"""launch-ready is pushed once: a tab that was reloading when the game came
|
||||
up has only the poll to find its way back into the stream."""
|
||||
rom = _rom_on("ps2")
|
||||
container = _webstation()
|
||||
with _streaming(container):
|
||||
assert _claim_webstation_ok(client, access_token, rom.id).status_code == 202
|
||||
r = client.get(
|
||||
"/api/streaming/sessions/ps2/status", headers=_auth(access_token)
|
||||
)
|
||||
assert r.status_code == 200
|
||||
assert r.json()["host"].endswith("/room/x")
|
||||
assert r.json()["container"] == _key_of(container)
|
||||
|
||||
|
||||
def test_a_desktop_records_the_room_it_opened(client, access_token):
|
||||
"""Same recovery for the desktop: the room the activate answered with is
|
||||
only ever returned once, so the session has to keep it."""
|
||||
container = _webstation()
|
||||
with _streaming(container):
|
||||
response, _ = _desktop(client, access_token, _key_of(container))
|
||||
assert response.status_code == 200
|
||||
session = json.loads(_session_raw(container))
|
||||
assert session["host"] == response.json()["host"]
|
||||
|
||||
|
||||
def test_status_does_not_refresh_the_session(client, access_token, rom: Rom):
|
||||
"""Status is read-only: polling it must not extend a claim, otherwise a
|
||||
background tab could keep a container hostage without playing."""
|
||||
@@ -2958,12 +2987,8 @@ def test_status_stops_asking_the_broker_once_the_launch_returned(client, access_
|
||||
r = client.get(
|
||||
"/api/streaming/sessions/ps2/status", headers=_auth(access_token)
|
||||
)
|
||||
assert r.json() == {
|
||||
"status": "active",
|
||||
"platform": "ps2",
|
||||
"extraction_phase": None,
|
||||
"termination": None,
|
||||
}
|
||||
assert r.json()["status"] == "active"
|
||||
assert r.json()["extraction_phase"] is None
|
||||
broker.assert_not_called()
|
||||
|
||||
|
||||
@@ -2980,12 +3005,8 @@ def test_status_on_a_legacy_container_never_asks_for_a_phase(
|
||||
f"/api/streaming/sessions/{rom.platform_slug}/status",
|
||||
headers=_auth(access_token),
|
||||
)
|
||||
assert r.json() == {
|
||||
"status": "active",
|
||||
"platform": rom.platform_slug,
|
||||
"extraction_phase": None,
|
||||
"termination": None,
|
||||
}
|
||||
assert r.json()["status"] == "active"
|
||||
assert r.json()["extraction_phase"] is None
|
||||
broker.assert_not_called()
|
||||
|
||||
|
||||
|
||||
@@ -7,6 +7,8 @@ export type SessionStatusSchema = {
|
||||
status: 'active' | 'ended';
|
||||
platform: string;
|
||||
extraction_phase?: (string | null);
|
||||
host?: (string | null);
|
||||
container?: (string | null);
|
||||
termination?: (SessionTerminationSchema | null);
|
||||
};
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ const mocks = vi.hoisted(() => ({
|
||||
claimSession: vi.fn(),
|
||||
fetchConfig: vi.fn(),
|
||||
getRom: vi.fn(),
|
||||
fetchSessionStatus: vi.fn(),
|
||||
heartbeatSession: vi.fn(),
|
||||
releaseSession: vi.fn(),
|
||||
releaseSessionKeepalive: vi.fn(),
|
||||
@@ -65,7 +66,7 @@ vi.mock("@/stores/streaming", () => ({
|
||||
containerForPlatform: () => mocks.container,
|
||||
platformCapabilities: () => ({}),
|
||||
fetchConfig: mocks.fetchConfig,
|
||||
fetchSessionStatus: vi.fn(),
|
||||
fetchSessionStatus: mocks.fetchSessionStatus,
|
||||
forgetJoinableSession: vi.fn(),
|
||||
heartbeatSession: mocks.heartbeatSession,
|
||||
joinSession: vi.fn(),
|
||||
@@ -368,6 +369,7 @@ type StreamVm = {
|
||||
playerState: string;
|
||||
endedDialogOpen: boolean;
|
||||
holdsClaim: boolean;
|
||||
containerHost: string;
|
||||
};
|
||||
|
||||
function vmOf(wrapper: VueWrapper): StreamVm {
|
||||
@@ -518,3 +520,49 @@ describe("Stream claim hygiene", () => {
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
describe("Stream launch recovery", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mocks.claimSession.mockResolvedValue(CLAIM);
|
||||
});
|
||||
|
||||
it("enters the stream when the poll finds the game already up", async () => {
|
||||
// launch-ready is pushed once, so a socket that dropped during the launch
|
||||
// left the tab loading over a game that was running.
|
||||
const wrapper = await launch({ picker: false });
|
||||
await vmOf(wrapper).onPlay();
|
||||
mocks.heartbeatSession.mockResolvedValue({
|
||||
status: "active",
|
||||
platform: "gba",
|
||||
host: "http://webstation-dev:8080/room/x",
|
||||
container: CLAIM.container,
|
||||
});
|
||||
|
||||
await mocks.presenceTick?.();
|
||||
await flushPromises();
|
||||
|
||||
expect(vmOf(wrapper).playerState).toBe("playing");
|
||||
expect(vmOf(wrapper).containerHost).toBe(
|
||||
"http://webstation-dev:8080/room/x",
|
||||
);
|
||||
wrapper.unmount();
|
||||
});
|
||||
|
||||
it("keeps waiting while the launch has no room yet", async () => {
|
||||
const wrapper = await launch({ picker: false });
|
||||
await vmOf(wrapper).onPlay();
|
||||
mocks.heartbeatSession.mockResolvedValue({
|
||||
status: "active",
|
||||
platform: "gba",
|
||||
host: null,
|
||||
container: CLAIM.container,
|
||||
});
|
||||
|
||||
await mocks.presenceTick?.();
|
||||
await flushPromises();
|
||||
|
||||
expect(vmOf(wrapper).playerState).toBe("loading");
|
||||
wrapper.unmount();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -518,7 +518,7 @@ async function handleSessionStatus(
|
||||
): Promise<void> {
|
||||
// Null means the poll failed, not that the session is gone. A transient
|
||||
// network error must never tear down a live game.
|
||||
if (!status || status.status !== "ended") return;
|
||||
if (!status) return;
|
||||
// Already leaving under our own power (stop, save-and-exit, unload).
|
||||
if (!sessionActive.value) return;
|
||||
// The socket push arrives per-user, not per-platform (one room for every
|
||||
@@ -526,6 +526,11 @@ async function handleSessionStatus(
|
||||
// must not tear down the one actually on screen.
|
||||
if (rom.value && status.platform !== rom.value.platform_slug) return;
|
||||
|
||||
if (status.status === "active") {
|
||||
await enterRunningSession(status);
|
||||
return;
|
||||
}
|
||||
|
||||
// Leave fullscreen before anything else. RDialog teleports to <body>,
|
||||
// outside the stage, so the notice would otherwise be painted under a
|
||||
// fullscreened stage; and tearing the stage down first would unmount the
|
||||
@@ -549,6 +554,22 @@ async function handleSessionStatus(
|
||||
endedDialogOpen.value = true;
|
||||
}
|
||||
|
||||
// launch-ready is pushed once, so a socket that dropped while the game came up
|
||||
// leaves the tab loading over a session that is running. The poll answers with
|
||||
// the room the launch recorded, which is the way back in.
|
||||
async function enterRunningSession(status: SessionStatus): Promise<void> {
|
||||
if (playerState.value !== "loading" || !status.host) return;
|
||||
// The 202 named it, except for a tab that came back without one.
|
||||
claimedContainer.value ??= status.container ?? null;
|
||||
launchPhase.value = null;
|
||||
containerHost.value = status.host;
|
||||
playerState.value = "playing";
|
||||
if (fullscreenOnPlay.value) {
|
||||
await nextTick();
|
||||
await stage.value?.enterFullscreen();
|
||||
}
|
||||
}
|
||||
|
||||
function dismissEndedDialog(): void {
|
||||
endedDialogOpen.value = false;
|
||||
backToRom();
|
||||
|
||||
Reference in New Issue
Block a user