Files
romm/backend/endpoints/responses/streaming.py
Stu Anderson e06e0e4010 chore(docs): better openapi descriptions (#5660)
* docs(api): describe the core endpoints and add a docs test

Give the parameters, operations and response fields of the core routers a
description in the OpenAPI document: roms, platforms, collections, users,
saves, states, screenshots, channels, snapshots, streaming, devices, client
tokens, play sessions, search, auth, music, memory cards, firmware, sync,
config, feeds, notifications and permissions.

Response models read attribute docstrings (`use_attribute_docstrings` on the
shared response `BaseModel`), so a string after a field is its description.
The update-rom form reads its descriptions from `RomUpdateForm`, so they
have one home. The paging parameters gain examples, such as 72 per page.

`tests/endpoints/test_openapi_docs.py` reads `app.openapi()` and fails when a
parameter or operation of a listed router has no description, or when a
schema with some described fields leaves others bare. Add a router to
`DOCUMENTED_ROUTERS` once its parameters and operations are described.

Descriptions only: no parameter, constraint or default changes. The frontend
types need regenerating (`npm run generate`).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs(api): describe the remaining routers and the roms list parameters

Cover the last routers (tasks, activity, heartbeat, audit events, stats, logs
and netplay) and add the routers to the docs test's allow-list, so every
router is now held to a description on each parameter and operation.

Describe the schemas that test found partly documented: the task status
responses and `TaskInfo` (as `Annotated[..., Field(...)]`, since a TypedDict
takes no attribute docstrings) and the audit page's `max_id`.

Rewrite the `GET /api/roms` parameters that did not say what they do:
`with_char_index`, `with_filter_values`, `with_rom_id_index`, `with_total`,
`with_provider_metadata`, `order_by`, `with_files`, `group_by_meta_id` and
`search_term`, each with an example or the values it accepts.

Replace a franchise name in an existing docstring example with a neutral one.

Descriptions only: no parameter, constraint or default changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* chore(api): regenerate the frontend types

Run `npm run generate` against the backend so the generated models carry the
descriptions added to the OpenAPI document. Only comments change: no type,
field or signature differs.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs(api): fix alternative_names and shorten docstrings per review

Address the review feedback:

- Describe `alternative_names` as the hand-set titles when there are any,
  otherwise the titles from IGDB, MobyGames and ScreenScraper, as
  `resolve_alternative_names` returns them. It said every matched provider.
- Check HEAD routes in the docs test. Both existing HEAD routes already pass.
- Keep docstrings to one paragraph, as the repository asks. The test module
  docstring is one sentence and its two rules are short comments. Nineteen
  operation docstrings added in this change drop their second paragraph.

Descriptions and a test only: no parameter, constraint or default changes.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* chore(api): regenerate the frontend types

Pick up the corrected `alternative_names` description. Only comments change.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

* docs(api): correct descriptions that disagree with the code (pr-ready: code-review)

Fix 12 OpenAPI descriptions that contradicted handler behavior (empty
provider metadata, virtual collection types, streaming container lookup,
save device sync, user collections, search terms, file order, firmware
file name, audit max_id, play session offset, save target layouts).
Share the music filter descriptions through Annotated aliases and drop
comments that restated the new docstrings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(api): share parameter aliases and check every router (pr-ready: simplify)

Move the rom id and sort direction aliases to utils/router.py and reuse
them, add per-router id path aliases in place of repeated inline params,
let LimitOffsetPage inherit the shared BaseModel config, and drop Args
blocks that restated parameter descriptions. The docs test now covers
every /api path instead of an allowlist. The OpenAPI spec is unchanged
apart from description strings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* refactor(api): form model for rom updates, shared schema config and rom id alias

- Take RomUpdateForm as a FastAPI form model instead of 33 Form params
  and a duplicate field dict; only sent keys still count as provided.
- Document TypedDict responses with attribute docstrings through
  @with_config(API_SCHEMA_CONFIG) instead of per-field Annotated wrappers.
- Move request payload models onto the shared BaseModel and use
  attribute docstrings for their descriptions.
- Replace the 32 inline rom id path params with RomIdPath, which now
  carries ge=1 (adds minimum: 1 to the activity and streaming rom ids).

The update rom request body now references a RomUpdateForm schema; the
multipart fields are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): keep only the descriptions that explain something

Drop the field and parameter descriptions that restate the name, the
type, or what the schema already shows (enum and literal values,
defaults, bounds, nullability), along with the wrappers and aliases
that only carried them. Reword four that did not say what the field
is. The docs test now checks operations only, since requiring a
description on every parameter and field is what produced the filler.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): plainer wording for three sync and rom descriptions

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): rewrite clipped descriptions as full sentences

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document error statuses in responses instead of docstrings

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): document pairing code exchange errors

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* docs(api): move error statuses from route docstrings into responses

Covers the routes whose docstrings stated an error in prose or in a
Raises: block, new in this PR or older.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-20 14:11:13 -05:00

325 lines
8.7 KiB
Python

"""Response shapes for the streaming routes.
Declared rather than returned as bare dicts, so they reach the OpenAPI schema
and generate into the frontend's types.
"""
from typing import Literal
from .base import BaseModel
class SlotCapabilitiesSchema(BaseModel):
"""What save-state controls a platform's emulator actually exposes."""
max_slots: int
has_autosave: bool
autosave_slot: int
has_memory_card: bool
supports_disc_swap: bool
has_manual_disc_swap: bool
class StreamingContainerSchema(BaseModel):
"""One platform the fleet can stream, as the play screen needs it."""
platform: str
"""The slug of the platform the container serves."""
host: str
label: str
"""The display name of the container."""
capabilities: SlotCapabilitiesSchema
emulator: str
supports_memory_cards: bool
supports_save_picker: bool
supports_live_states: bool
import_kinds: list[Literal["save", "state"]]
"""The kinds of files from other emulators, saves or states, that the broker can import. Empty when the broker declares none or does not answer."""
class StreamStatePicksSchema(BaseModel):
"""Which of a ROM's states the stream's resume picker offers, by id."""
# Resume as they are; the newest is preselected.
native: list[int]
# Native ones plus the foreign ones the broker imports.
pickable: list[int]
class StreamingConfigSchema(BaseModel):
enabled: bool
containers: list[StreamingContainerSchema]
# Display name per emulator id, so a save or state tagged with one can be labelled
# without a second copy of the map on the frontend.
emulator_labels: dict[str, str]
class SessionTerminationSchema(BaseModel):
"""Why a session the caller held is gone, left behind for their next poll.
Only an admin force-release records one; a session the player released or
that simply expired leaves no notice.
"""
ended_by: str | None = None
reason: str | None = None
ended_at: str | None = None
platform: str | None = None
rom_id: int | None = None
rom_name: str | None = None
container: str | None = None
claimed_at: str | None = None
desktop: bool = False
class SessionStatusSchema(BaseModel):
status: Literal["active", "ended"]
platform: str
# 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.
extraction_phase: str | None = None
# The room URL of a launched session, for a tab that missed launch-ready, reported by
# the status poll only and left None by a heartbeat.
host: str | None = None
# The launch's core warning, for that same tab.
core: str | None = None
core_tier: str | None = None
termination: SessionTerminationSchema | None = None
class LaunchingSessionSchema(BaseModel):
"""The 202 a claim answers with: the container is reserved and the game is
on its way up. The room URL follows over the socket, since only the
broker's launch reply carries it."""
platform: str
container: str
label: str
rom_name: str
claimed_at: str
class LaunchReadyPayload(BaseModel):
"""`streaming:launch-ready`, pushed once the game is up."""
platform: str
container: str
# The claim's stamp, since a re-claim of the same container shares its key.
claimed_at: str
host: str
# None when no resume was asked for; False means the state could not be pushed and the
# session started fresh.
resume: bool | None = None
# The libretro core the platform asked for, None when it names none.
core: str | None = None
# How far the broker vouches for that core: "default", "vetted",
# "untested" or "blocked". None when no core was asked for.
core_tier: str | None = None
class ImportRefusalSchema(BaseModel):
"""One `.import/` member the broker's activate declined to place."""
reason: str
member: str | None = None
expected: str | None = None
detail: str | None = None
suggest_emulator: str | None = None
docs: str | None = None
class LaunchFailedPayload(BaseModel):
"""`streaming:launch-failed`. The claim is already released."""
platform: str
container: str
claimed_at: str
detail: str
refusals: list[ImportRefusalSchema] | None = None
refusals_truncated: int = 0
class LaunchPhasePayload(BaseModel):
"""`streaming:launch-phase`, while a broker unpacks a large title."""
platform: str
container: str
claimed_at: str
phase: str | None = None
class ContainerBusyDetail(BaseModel):
"""The 409 body when a claim finds its container held."""
message: str
# A previous session is still shutting down, rather than anyone holding it.
draining: bool
# The game holding it, None when the caller may not see which.
rom_name: str | None
claimed_at: str | None
SOCKET_PAYLOADS: tuple[type[BaseModel], ...] = (
LaunchReadyPayload,
LaunchFailedPayload,
LaunchPhasePayload,
)
class DesktopSessionSchema(BaseModel):
container: str
platform: str
host: str
label: str
claimed_at: str
class JoinedSessionSchema(BaseModel):
platform: str
host: str
label: str
rom_id: int | None = None
rom_name: str | None = None
class SaveAndExitResponse(BaseModel):
status: Literal["ok", "not_found"]
saved: bool
platform: str
released: bool
class ReleaseSessionResponse(BaseModel):
status: Literal["released", "not_found"]
platform: str
class ForceReleaseResponse(BaseModel):
status: Literal["released"]
platforms: list[str]
class VolumeResponse(BaseModel):
status: Literal["ok"]
level: int
platform: str
class MuteResponse(BaseModel):
status: Literal["ok"]
mute: bool | None = None
platform: str
class SaveStateResponse(BaseModel):
status: Literal["saving"]
slot: int
platform: str
class LoadStateResponse(BaseModel):
status: Literal["ok"]
loaded: bool
slot: int
platform: str
class SwapDiscResponse(BaseModel):
status: Literal["ok"]
file_id: int
platform: str
class JoinableSessionSchema(BaseModel):
"""A session its host opened to other players, plus enough of the ROM to
draw a cover tile without a second request per session."""
container: str
label: str | None = None
platform: str | None = None
rom_id: int | None = None
rom_name: str | None = None
host_username: str | None = None
claimed_at: str | None = None
platform_id: int | None = None
platform_display_name: str | None = None
path_cover_small: str | None = None
path_cover_large: str | None = None
url_cover: str | None = None
class JoinableSessionsResponse(BaseModel):
sessions: list[JoinableSessionSchema]
class AdminSessionSchema(BaseModel):
container: str
label: str | None = None
platform: str | None = None
rom_id: int | None = None
rom_name: str | None = None
desktop: bool
claimed_at: str | None = None
user_id: int | None = None
username: str | None = None
class AdminSessionsResponse(BaseModel):
sessions: list[AdminSessionSchema]
class ContainerSessionSchema(BaseModel):
"""Whatever a container is running, as the fleet view shows it."""
platform: str | None = None
rom_id: int | None = None
rom_name: str | None = None
desktop: bool
claimed_at: str | None = None
user_id: int | None = None
username: str | None = None
class AdminContainerSchema(BaseModel):
container: str
# What URLs call this container: its own label when unique, else the key.
name: str = ""
label: str | None = None
host: str
platforms: list[str]
supports_desktop: bool
# False for a container with no usable broker address: it can never be claimed, and
# saying so beats listing it as idle.
configured: bool
# The previous session's exit work is still running, so the container is held by
# nobody and about to come free.
draining: bool = False
session: ContainerSessionSchema | None = None
class AdminContainersResponse(BaseModel):
enabled: bool
containers: list[AdminContainerSchema]
class MemoryCardSummarySchema(BaseModel):
"""What is on the card a container is holding, enough for the player to
recognise it before deciding whether to keep it."""
file_count: int
total_bytes: int
game_codes: list[str]
class MemoryCardImportRequired(BaseModel):
"""The 428 body: a container still holds a card nobody has decided about.
The claim is not held open behind the prompt; the answer comes back on a
fresh claim as `card_import`.
"""
code: Literal["memory_card_import_required"]
outcome: Literal["found", "unreadable"]
summary: MemoryCardSummarySchema | None = None
reason: str | None = None