mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 01:58:41 +01:00
refactor(streaming): share the claim query params, mark-and-start the exit save pull in one call, and drop no-op casts (simplify)
- Declare the container and claimed_at query params once, with named length limits. - Add lifecycle.start_exit_save_pull for the two callers that mark and start back to back. - Build every claim query on the frontend through one claimParams helper. - Drop PlayerState casts that narrowed nothing in the launch socket handlers. - Reuse _load_session in the _drain test helper. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -171,11 +171,21 @@ class LoadStateRequest(BaseModel):
|
||||
slot: Annotated[int, Field(ge=1, le=MAX_SLOT)] = 1
|
||||
|
||||
|
||||
CONTAINER_KEY_MAX_LENGTH = 300
|
||||
CLAIMED_AT_MAX_LENGTH = 64
|
||||
|
||||
# A claim is named by its container and the stamp it was taken at.
|
||||
ContainerQuery = Annotated[
|
||||
str | None, Query(alias="container", max_length=CONTAINER_KEY_MAX_LENGTH)
|
||||
]
|
||||
ClaimedAtQuery = Annotated[str | None, Query(max_length=CLAIMED_AT_MAX_LENGTH)]
|
||||
|
||||
|
||||
class DesktopStreamingSessionRequest(BaseModel):
|
||||
# The container to open, named by the key GET /streaming/containers
|
||||
# reports. Named rather than pooled: an admin configuring a container
|
||||
# needs that one, not whichever is free.
|
||||
container: Annotated[str, Field(min_length=1, max_length=300)]
|
||||
container: Annotated[str, Field(min_length=1, max_length=CONTAINER_KEY_MAX_LENGTH)]
|
||||
|
||||
|
||||
def platform_capabilities(platform: str) -> PlatformCapabilities:
|
||||
@@ -884,8 +894,8 @@ async def save_and_exit_session(
|
||||
request: Request,
|
||||
platform: str,
|
||||
req: Annotated[SaveAndExitRequest, Body()],
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
container_key: ContainerQuery = None,
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
) -> SaveAndExitResponse:
|
||||
"""Save game state then release the session.
|
||||
|
||||
@@ -927,8 +937,7 @@ async def save_and_exit_session(
|
||||
await lifecycle.record_play_session(session)
|
||||
await lifecycle.clear_session_activity(session_key, session)
|
||||
# Before the key goes, so a claim that wins it next waits for the pull.
|
||||
pull_mark = await lifecycle.mark_exit_saves_pending(container, session)
|
||||
lifecycle.collect_exit_saves(container, session, pull_mark, settled=settled)
|
||||
await lifecycle.start_exit_save_pull(container, session, settled=settled)
|
||||
|
||||
# Sync the exit save to the library. With wait=false the broker save may
|
||||
# still be running; the pull blocks on the broker until it finishes.
|
||||
@@ -1007,8 +1016,8 @@ async def save_and_exit_session(
|
||||
async def heartbeat_session(
|
||||
request: Request,
|
||||
platform: str,
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
container_key: ContainerQuery = None,
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
) -> SessionStatusSchema:
|
||||
"""Refresh the liveness stamp the frontend beats every ~30s, without which the
|
||||
claim is abandoned after _STREAMING_SESSION_STALE_SECONDS for the next to take.
|
||||
@@ -1029,7 +1038,7 @@ async def heartbeat_session(
|
||||
named = container_key is not None
|
||||
candidates = (
|
||||
[access.named_container(platform, container_key)]
|
||||
if container_key is not None
|
||||
if named
|
||||
else containers_for_platform(platform)
|
||||
)
|
||||
found = await access.find_session_for_user(
|
||||
@@ -1072,7 +1081,7 @@ async def heartbeat_session(
|
||||
async def session_status(
|
||||
request: Request,
|
||||
platform: str,
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
) -> SessionStatusSchema:
|
||||
"""Does the caller still hold this platform's session?
|
||||
|
||||
@@ -1168,8 +1177,8 @@ async def set_volume(
|
||||
request: Request,
|
||||
platform: str,
|
||||
req: Annotated[VolumeRequest, Body()],
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
container_key: ContainerQuery = None,
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
) -> VolumeResponse:
|
||||
"""Set emulator audio volume (0-100)."""
|
||||
container, session_key, _ = await access.require_claim(
|
||||
@@ -1189,8 +1198,8 @@ async def set_mute(
|
||||
request: Request,
|
||||
platform: str,
|
||||
req: Annotated[MuteRequest, Body()],
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
container_key: ContainerQuery = None,
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
) -> MuteResponse:
|
||||
"""Toggle or explicitly set mute state. Omit body to toggle."""
|
||||
container, session_key, _ = await access.require_claim(
|
||||
@@ -1212,8 +1221,8 @@ async def save_state(
|
||||
request: Request,
|
||||
platform: str,
|
||||
req: Annotated[SaveStateRequest, Body()],
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
container_key: ContainerQuery = None,
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
) -> SaveStateResponse:
|
||||
"""Save game state to a slot without stopping the emulator.
|
||||
|
||||
@@ -1255,8 +1264,8 @@ async def load_state(
|
||||
request: Request,
|
||||
platform: str,
|
||||
req: Annotated[LoadStateRequest, Body()],
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
container_key: ContainerQuery = None,
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
) -> LoadStateResponse:
|
||||
"""Load game state from a manual slot or the platform's autosave slot."""
|
||||
container, session_key, _ = await access.require_claim(
|
||||
@@ -1277,8 +1286,8 @@ async def swap_disc(
|
||||
request: Request,
|
||||
platform: str,
|
||||
req: Annotated[SwapDiscRequest, Body()],
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
container_key: ContainerQuery = None,
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
) -> SwapDiscResponse:
|
||||
"""Change the mounted disc without restarting the emulator."""
|
||||
container, session_key, session = await access.require_claim(
|
||||
@@ -1325,8 +1334,8 @@ async def release_session(
|
||||
platform: str,
|
||||
background_tasks: BackgroundTasks,
|
||||
reason: str | None = Query(default=None, max_length=200),
|
||||
container_key: str | None = Query(default=None, alias="container", max_length=300),
|
||||
claimed_at: str | None = Query(default=None, max_length=64),
|
||||
container_key: ContainerQuery = None,
|
||||
claimed_at: ClaimedAtQuery = None,
|
||||
save: bool = Query(default=True),
|
||||
) -> ReleaseSessionResponse:
|
||||
"""Release a session and tell the broker to stop the emulator.
|
||||
@@ -1625,11 +1634,8 @@ async def force_release_all(
|
||||
await lifecycle.collect_exit_state(
|
||||
container, session, stopped.state_slot
|
||||
)
|
||||
pull_mark = await lifecycle.mark_exit_saves_pending(
|
||||
container, session
|
||||
)
|
||||
lifecycle.collect_exit_saves(
|
||||
container, session, pull_mark, settled=stopped.settled
|
||||
await lifecycle.start_exit_save_pull(
|
||||
container, session, settled=stopped.settled
|
||||
)
|
||||
|
||||
# Note who ended it before the key goes, so the player's next poll
|
||||
|
||||
@@ -179,6 +179,14 @@ def collect_exit_saves(
|
||||
)
|
||||
|
||||
|
||||
async def start_exit_save_pull(
|
||||
container: ResolvedContainer, session: dict[str, Any], *, settled: bool
|
||||
) -> None:
|
||||
"""Mark the exit pull pending, then start it, for a stop that is already done."""
|
||||
mark = await mark_exit_saves_pending(container, session)
|
||||
collect_exit_saves(container, session, mark, settled=settled)
|
||||
|
||||
|
||||
async def collect_exit_state(
|
||||
container: ResolvedContainer, session: dict[str, Any], state_slot: int | None
|
||||
) -> None:
|
||||
|
||||
@@ -1320,7 +1320,7 @@ def _session_raw(container: dict):
|
||||
|
||||
|
||||
def _drain(container: dict) -> None:
|
||||
session = json.loads(_session_raw(container))
|
||||
session = _load_session(session_store.session_redis_key(_key_of(container)))
|
||||
token = asyncio.run(session_store.claim_drain_marker(_key_of(container), session))
|
||||
assert token is not None
|
||||
|
||||
|
||||
@@ -93,6 +93,17 @@ export interface ContainerBusyDetail {
|
||||
claimed_at: string | null;
|
||||
}
|
||||
|
||||
/** The query naming a claim by its container and the stamp it was taken at. */
|
||||
function claimParams(
|
||||
container?: string | null,
|
||||
claimedAt?: string | null,
|
||||
): { container?: string; claimed_at?: string } {
|
||||
return {
|
||||
...(container != null ? { container } : {}),
|
||||
...(claimedAt != null ? { claimed_at: claimedAt } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
// ── Requests ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async function fetchConfig() {
|
||||
@@ -131,15 +142,12 @@ async function releaseSession(
|
||||
) {
|
||||
return api.delete(`/streaming/sessions/${platform}`, {
|
||||
params: {
|
||||
// The claim this release is for, so a tab whose claim was taken over
|
||||
// cannot end the one that replaced it. Admin releases send none.
|
||||
...(claimedAt != null ? { claimed_at: claimedAt } : {}),
|
||||
// The holder names its container and stamp so a taken-over tab cannot end
|
||||
// the claim that replaced it. An admin names its pick and no stamp.
|
||||
...claimParams(container, claimedAt),
|
||||
// Sent whenever the caller supplied one, empty string included: the
|
||||
// backend treats the param's presence as "this is an admin force-release".
|
||||
...(reason !== undefined ? { reason } : {}),
|
||||
// Names which container to release, since a pool serves one platform
|
||||
// from several: the holder names the one it claimed, an admin its pick.
|
||||
...(container != null ? { container } : {}),
|
||||
// Only the player who deliberately stopped without saving sends this.
|
||||
// Everything else leaves it off so the backend still autosaves.
|
||||
...(save === false ? { save: false } : {}),
|
||||
@@ -171,7 +179,7 @@ async function saveAndExit(
|
||||
return api.post(
|
||||
`/streaming/sessions/${platform}/save-and-exit`,
|
||||
{ slot, wait },
|
||||
{ params: { container, claimed_at: claimedAt } },
|
||||
{ params: claimParams(container, claimedAt) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -183,7 +191,7 @@ async function heartbeatSession(
|
||||
return api.post<SessionStatus>(
|
||||
`/streaming/sessions/${platform}/heartbeat`,
|
||||
undefined,
|
||||
{ params: { container, claimed_at: claimedAt } },
|
||||
{ params: claimParams(container, claimedAt) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -202,7 +210,7 @@ async function setVolume(
|
||||
return api.post(
|
||||
`/streaming/sessions/${platform}/volume`,
|
||||
{ level: Math.round(level) },
|
||||
{ params: { container, claimed_at: claimedAt } },
|
||||
{ params: claimParams(container, claimedAt) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -215,7 +223,7 @@ async function setMute(
|
||||
return api.post(
|
||||
`/streaming/sessions/${platform}/mute`,
|
||||
mute !== undefined ? { mute } : {},
|
||||
{ params: { container, claimed_at: claimedAt } },
|
||||
{ params: claimParams(container, claimedAt) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -228,7 +236,7 @@ async function saveState(
|
||||
return api.post(
|
||||
`/streaming/sessions/${platform}/save-state`,
|
||||
{ slot },
|
||||
{ params: { container, claimed_at: claimedAt } },
|
||||
{ params: claimParams(container, claimedAt) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -241,7 +249,7 @@ async function loadState(
|
||||
return api.post(
|
||||
`/streaming/sessions/${platform}/load-state`,
|
||||
{ slot },
|
||||
{ params: { container, claimed_at: claimedAt } },
|
||||
{ params: claimParams(container, claimedAt) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -254,7 +262,7 @@ async function swapDisc(
|
||||
return api.post(
|
||||
`/streaming/sessions/${platform}/swap-disc`,
|
||||
{ file_id: fileId },
|
||||
{ params: { container, claimed_at: claimedAt } },
|
||||
{ params: claimParams(container, claimedAt) },
|
||||
);
|
||||
}
|
||||
|
||||
@@ -285,10 +293,11 @@ function claimQuery(
|
||||
container?: string | null,
|
||||
claimedAt?: string | null,
|
||||
): string {
|
||||
const params = new URLSearchParams();
|
||||
if (container) params.set("container", container);
|
||||
if (claimedAt) params.set("claimed_at", claimedAt);
|
||||
const search = params.toString();
|
||||
const search = new URLSearchParams(
|
||||
Object.entries(claimParams(container, claimedAt)).filter(
|
||||
([, value]) => value,
|
||||
),
|
||||
).toString();
|
||||
return search ? `?${search}` : "";
|
||||
}
|
||||
|
||||
|
||||
@@ -696,14 +696,14 @@ useSocketEvent<LaunchPhase>("streaming:launch-phase", (payload) => {
|
||||
useSocketEvent<LaunchReady>("streaming:launch-ready", async (payload) => {
|
||||
if (!isOurClaim(payload)) return;
|
||||
launchPhase.value = null;
|
||||
if ((playerState.value as PlayerState) === "exited") {
|
||||
if (playerState.value === "exited") {
|
||||
await handBackClaim(payload.platform);
|
||||
return;
|
||||
}
|
||||
if (payload.resume === false) snackbar.warning(t("play.resume-failed"));
|
||||
// A status poll can land between the launch stamp and this push and enter
|
||||
// first; entering again would force fullscreen back on.
|
||||
if ((playerState.value as PlayerState) === "playing") return;
|
||||
if (playerState.value === "playing") return;
|
||||
await enterStream(payload.host);
|
||||
});
|
||||
|
||||
@@ -712,7 +712,7 @@ useSocketEvent<LaunchFailed>("streaming:launch-failed", (payload) => {
|
||||
// The backend already released the claim, so there is nothing to hand back.
|
||||
forgetClaim();
|
||||
launchPhase.value = null;
|
||||
if ((playerState.value as PlayerState) === "exited") return;
|
||||
if (playerState.value === "exited") return;
|
||||
errorType.value = "server";
|
||||
errorMessage.value = t("play.stream-error-generic");
|
||||
errorHint.value = payload.detail;
|
||||
|
||||
Reference in New Issue
Block a user