Files
romm/backend/endpoints/device/install.py
Georges-Antoine Assi 4159710e79 docs(api): document the error responses routes raise (#5693)
* docs(api): document error responses for roms routes

Describe every 4xx and 5xx the rom routes and their helpers raise in each
decorator's responses=, so the OpenAPI schema lists them. A hidden rom,
platform or file is described like a missing one.

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

* docs(api): document error responses for saves routes

Describe every 4xx/5xx the saves, states, screenshots, snapshots,
play-sessions and sync routes raise in their responses=, and rewrite the
states identifiers docstring that carried Args/Returns blocks.

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

* docs(api): document error responses for devices routes

Describe the 4xx/5xx statuses that the device, device auth, install,
client token, notification, notification channel, sync channel and
heartbeat routes raise, and fill the empty install route entries.
Rewrite the setup and heartbeat docstrings that published Args and
Returns blocks.

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

* docs(api): document error responses for streaming routes

Describe the 4xx and 5xx statuses the streaming, memory card and netplay routes raise in their responses= declarations, and replace the Args: blocks in route docstrings that FastAPI published verbatim.

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

* docs(api): document error responses for admin routes

Describe the 4xx and 5xx statuses the config, permissions, user, auth,
tasks, logs, activity and export routes raise, and rewrite their
Args/Returns docstrings as plain operation descriptions.

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

* docs(api): document error responses for library routes

Describe the 400/403/404/409/500 statuses the collection, feed, firmware,
platform, music, playlist and search routes raise, and replace route
docstrings that carried Args/Returns blocks with plain sentences.

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

* docs(api): describe private collections and playlists as missing

Matches #5686, where another user's private collection or playlist
answers 404 and a play session on a hidden rom answers like a missing
one. The read routes drop their 403, and the write 403 now covers only
a public resource another user owns.

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

* docs(api): address Greptile review on route error docs

Fold the nine multi-paragraph route docstrings into one line, and keep
the device-scope 403 descriptions in utils/auth.py next to
resolve_device, which raises them, instead of in both saves.py and
states.py.

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

* docs(api): plain-prose pass on route error descriptions

Spell out clipped error descriptions, replace internal slang (picked,
taken, live, moved past), name the parameter an ID comes from, and split
the long save conversion 400s into sentences.

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

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 09:11:20 -05:00

401 lines
14 KiB
Python

"""Install requests: the web UI queues and cancels them, the device claims and reports them."""
import asyncio
from collections.abc import Iterator
from contextlib import contextmanager
from typing import Annotated, Final
from fastapi import HTTPException
from fastapi import Path as PathVar
from fastapi import Request, Response, status
from pydantic import Field, field_validator
from config import DEVICE_INSTALL_ENABLED
from decorators.auth import protected_route
from endpoints.responses.base import BaseModel
from endpoints.responses.device.install import (
InstallReason,
InstallRequestSchema,
InstallStatus,
)
from endpoints.sockets.devices import (
emit_install_cancelled,
emit_install_queued,
emit_install_updated,
mark_claimed,
online_device_ids,
)
from exceptions.endpoint_exceptions import (
DeviceInstallDisabledException,
)
from handler.auth.constants import Scope
from handler.auth.dependencies import (
get_rom_visibility_filter,
visible_rom_or_404,
)
from handler.database import db_device_handler, db_rom_handler
from handler.device_install import (
InstallRequestNotFoundError,
InstallTransitionError,
device_install_handler,
)
from handler.device_install.policy import (
InstallNotAllowedError,
accepts_remote_install,
is_installable_platform,
select_install_files,
)
from handler.notification_handler import notify
from logger.logger import log
from models.device import Device
from models.notification import NotificationKind, NotificationLevel
from utils.auth import require_device, token_reaches_device
from utils.router import APIRouter
router = APIRouter()
DEVICE_REPORTS: Final = frozenset(
{InstallStatus.DONE, InstallStatus.ALREADY_INSTALLED, InstallStatus.FAILED}
)
class InstallRequestCreatePayload(BaseModel):
rom_id: int = Field(ge=1)
class InstallRequestUpdatePayload(BaseModel):
status: InstallStatus
reason: InstallReason | None = None
@field_validator("status")
@classmethod
def _reportable(cls, value: InstallStatus) -> InstallStatus:
if value not in DEVICE_REPORTS:
raise ValueError(
f"A device reports one of {', '.join(sorted(DEVICE_REPORTS))}"
)
return value
async def _require_request(request: Request, device_id: str, request_id: str) -> None:
install = await device_install_handler.get(request_id)
if (
install is None
or install.device_id != device_id
or install.user_id != request.user.id
):
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Install request {request_id} not found",
)
@contextmanager
def _install_errors() -> Iterator[None]:
"""A gone request as a 404, a request in the wrong status as a 409."""
try:
yield
except InstallRequestNotFoundError as exc:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Install request {exc.args[0]} not found",
) from exc
except InstallTransitionError as exc:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail=str(exc)
) from exc
def _hidden_rom_ids(request: Request, installs: list[InstallRequestSchema]) -> set[int]:
return db_rom_handler.get_hidden_rom_ids_among(
[install.rom_id for install in installs], get_rom_visibility_filter(request)
)
async def _notify_outcome(
request: Request, install: InstallRequestSchema, device: Device
) -> None:
rom = db_rom_handler.get_rom_visibility_label(install.rom_id)
# The reporting device acts as `install.user_id`, so the visibility is theirs.
hidden = rom is not None and not get_rom_visibility_filter(request).allows(rom)
failed = install.status == InstallStatus.FAILED
await notify(
install.user_id,
(
NotificationKind.DEVICE_INSTALL_FAILED
if failed
else NotificationKind.DEVICE_INSTALL_COMPLETED
),
NotificationLevel.ERROR if failed else NotificationLevel.SUCCESS,
{
"rom_id": None if hidden else install.rom_id,
"rom_name": (rom.name or rom.fs_name) if rom and not hidden else None,
"device_name": device.name or device.hostname,
"status": install.status,
"reason": install.reason,
},
)
@protected_route(
router.get,
"/online",
[Scope.DEVICES_READ],
responses={
status.HTTP_404_NOT_FOUND: {
"description": "Installing on a device is disabled on this server."
}
},
)
async def get_online_devices(request: Request) -> list[str]:
"""Ids of the caller's devices holding an open device socket or that claimed lately."""
if not DEVICE_INSTALL_ENABLED:
raise DeviceInstallDisabledException()
device_ids = [
device.id
for device in db_device_handler.get_devices(user_id=request.user.id)
if token_reaches_device(request, device.id)
]
return await online_device_ids(device_ids)
@protected_route(
router.post,
"/{device_id}/installs",
[Scope.DEVICES_WRITE, Scope.ROMS_READ],
status_code=status.HTTP_201_CREATED,
responses={
status.HTTP_200_OK: {"model": InstallRequestSchema},
status.HTTP_400_BAD_REQUEST: {
"description": (
"The device does not accept remote installs, roms of this platform"
" cannot be installed on a device, or the rom has no installable"
" files."
)
},
status.HTTP_404_NOT_FOUND: {
"description": (
"Installing on a device is disabled on this server, the caller has no device with"
" this ID that it can see, or no rom the caller can see has the ID"
" in `rom_id`."
)
},
status.HTTP_409_CONFLICT: {
"description": (
"The request was not queued because concurrent changes to the device's install requests kept colliding."
)
},
},
)
async def create_install_request(
request: Request,
response: Response,
device_id: Annotated[str, PathVar(description="Target device id.")],
payload: InstallRequestCreatePayload,
) -> InstallRequestSchema:
"""Queue a rom for install on a device, returning a live request for the same pair with 200."""
if not DEVICE_INSTALL_ENABLED:
raise DeviceInstallDisabledException()
device = require_device(request, device_id)
if not accepts_remote_install(device.capabilities):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Device {device_id} does not accept remote installs",
)
rom = visible_rom_or_404(
request, db_rom_handler.get_rom_install_target(payload.rom_id), payload.rom_id
)
if not is_installable_platform(rom.platform_slug):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=f"Roms for {rom.platform_slug} cannot be installed on a device",
)
# A rescan flags only the rom when its path is gone, never its file rows.
files = [] if rom.missing_from_fs else db_rom_handler.rom_files_for_rom_id(rom.id)
try:
file_ids = select_install_files(files)
except InstallNotAllowedError as exc:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)
) from exc
with _install_errors():
install, created = await device_install_handler.create(
user_id=request.user.id,
device_id=device_id,
rom_id=rom.id,
file_ids=file_ids,
)
if not created:
response.status_code = status.HTTP_200_OK
return install
# A delete that ran between the device check and the write missed this request.
if (
db_device_handler.get_device(device_id=device_id, user_id=request.user.id)
is None
):
await device_install_handler.discard_for_device(device_id)
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Device with ID {device_id} not found",
)
log.info(f"Queued rom {rom.id} for install on device {device_id}")
await asyncio.gather(emit_install_queued(install), emit_install_updated(install))
return install
@protected_route(
router.get,
"/{device_id}/installs",
[Scope.DEVICES_READ],
responses={
status.HTTP_404_NOT_FOUND: {
"description": (
"Installing on a device is disabled on this server, or the caller has no device with"
" this ID that it can see."
)
},
},
)
async def list_install_requests(
request: Request,
device_id: Annotated[str, PathVar(description="Target device id.")],
) -> list[InstallRequestSchema]:
"""The device's pending and taken requests, oldest first."""
if not DEVICE_INSTALL_ENABLED:
raise DeviceInstallDisabledException()
require_device(request, device_id)
installs = await device_install_handler.list_for_device(device_id)
hidden = _hidden_rom_ids(request, installs)
return [install for install in installs if install.rom_id not in hidden]
@protected_route(
router.post,
"/{device_id}/installs/claim",
[Scope.DEVICES_WRITE, Scope.ROMS_READ],
responses={
status.HTTP_403_FORBIDDEN: {
"description": "The request does not use a client token bound to this device."
},
status.HTTP_404_NOT_FOUND: {
"description": (
"Installing on a device is disabled on this server, or the caller has no device with"
" this ID that it can see."
)
},
status.HTTP_409_CONFLICT: {
"description": (
"Nothing was claimed because concurrent changes to the device's install requests kept colliding."
)
},
},
)
async def claim_install_requests(
request: Request,
device_id: Annotated[str, PathVar(description="Target device id.")],
) -> list[InstallRequestSchema]:
"""Take every pending request and return all the device holds taken, oldest first."""
if not DEVICE_INSTALL_ENABLED:
raise DeviceInstallDisabledException()
require_device(request, device_id, device_only=True)
# A request is only queued for a visible ROM, so one hidden later stays pending.
hidden: set[int] = set()
if not get_rom_visibility_filter(request).is_unrestricted:
hidden = _hidden_rom_ids(
request, await device_install_handler.list_for_device(device_id)
)
with _install_errors():
claim = await device_install_handler.claim(device_id, skip_rom_ids=hidden)
await mark_claimed(device_id)
await asyncio.gather(*(emit_install_updated(i) for i in claim.newly_taken))
return claim.taken
@protected_route(
router.put,
"/{device_id}/installs/{request_id}",
[Scope.DEVICES_WRITE],
responses={
status.HTTP_403_FORBIDDEN: {
"description": "The request does not use a client token bound to this device."
},
status.HTTP_404_NOT_FOUND: {
"description": (
"Installing on a device is disabled on this server, the caller has no device with"
" this ID that it can see, or the device has no unfinished install"
" request with this ID."
)
},
status.HTTP_409_CONFLICT: {
"description": (
"The device has not claimed the request, or concurrent changes to"
" the request kept colliding."
)
},
},
)
async def update_install_request(
request: Request,
device_id: Annotated[str, PathVar(description="Target device id.")],
request_id: Annotated[str, PathVar(description="Install request id.")],
payload: InstallRequestUpdatePayload,
) -> InstallRequestSchema:
"""The device reports the outcome of a request it has claimed, which ends the request."""
if not DEVICE_INSTALL_ENABLED:
raise DeviceInstallDisabledException()
device = require_device(request, device_id, device_only=True)
await _require_request(request, device_id, request_id)
with _install_errors():
ended = await device_install_handler.report(
request_id, payload.status, payload.reason
)
await emit_install_updated(ended)
await _notify_outcome(request, ended, device)
return ended
@protected_route(
router.delete,
"/{device_id}/installs/{request_id}",
[Scope.DEVICES_WRITE],
responses={
status.HTTP_404_NOT_FOUND: {
"description": (
"Installing on a device is disabled on this server, the caller has no"
" device with this ID that it can see, or the device has no unfinished"
" install request with this ID."
)
},
status.HTTP_409_CONFLICT: {
"description": "The request cannot be cancelled in its current state."
},
},
)
async def cancel_install_request(
request: Request,
device_id: Annotated[str, PathVar(description="Target device id.")],
request_id: Annotated[str, PathVar(description="Install request id.")],
) -> InstallRequestSchema:
"""Cancel a request that is still pending or taken."""
if not DEVICE_INSTALL_ENABLED:
raise DeviceInstallDisabledException()
require_device(request, device_id)
await _require_request(request, device_id, request_id)
with _install_errors():
ended = await device_install_handler.cancel(request_id)
await asyncio.gather(emit_install_cancelled(ended), emit_install_updated(ended))
return ended