Files
romm/backend/endpoints/responses/notification.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

125 lines
4.3 KiB
Python

import json
from typing import Any, Literal
from pydantic import ConfigDict, Field, field_validator
from models.notification import (
MAX_NOTIFICATIONS_PER_USER,
NOTIFICATION_BODY_MAX_LENGTH,
NOTIFICATION_DATA_MAX_LENGTH,
NOTIFICATION_ICON_MAX_LENGTH,
NOTIFICATION_KIND_MAX_LENGTH,
NOTIFICATION_LINK_MAX_LENGTH,
NOTIFICATION_TITLE_MAX_LENGTH,
NotificationKind,
NotificationLevel,
)
from .base import BaseModel, UTCDatetime
class NotificationActorSchema(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
username: str
avatar_path: str
updated_at: UTCDatetime
class NotificationSchema(BaseModel):
model_config = ConfigDict(from_attributes=True)
id: int
# A row written under a kind a later version dropped must still list.
kind: NotificationKind | str
level: NotificationLevel
title: str | None
body: str | None
link: str | None
icon: str | None
data: dict[str, Any]
actor: NotificationActorSchema | None
read_at: UTCDatetime | None
created_at: UTCDatetime
class NotificationCreatePayload(BaseModel):
"""A notification sent through the API, shown with its own title and body."""
title: str = Field(min_length=1, max_length=NOTIFICATION_TITLE_MAX_LENGTH)
body: str | None = Field(default=None, max_length=NOTIFICATION_BODY_MAX_LENGTH)
level: NotificationLevel = NotificationLevel.INFO
kind: str = Field(
default=NotificationKind.CUSTOM,
max_length=NOTIFICATION_KIND_MAX_LENGTH,
pattern=r"^[a-z0-9][a-z0-9_.:-]*$",
)
"""A label a client uses to tell its own notifications apart, such as `my_app.sync_done`."""
link: str | None = Field(default=None, max_length=NOTIFICATION_LINK_MAX_LENGTH)
"""A path inside RomM, such as `/rom/12`."""
icon: str | None = Field(
default=None,
max_length=NOTIFICATION_ICON_MAX_LENGTH,
pattern=r"^mdi-[a-z0-9-]+$",
)
"""A Material Design Icons name, such as `mdi-sync`."""
data: dict[str, Any] = Field(default_factory=dict)
recipients: list[int] | Literal["admins", "all"] | None = None
"""Who to notify: a list of user IDs, `admins` or `all`. Null notifies only the caller. Only an admin can notify other users."""
@field_validator("kind")
@classmethod
def _kind_not_reserved(cls, value: str) -> str:
# Stops a client passing itself off as one of RomM's own events.
if value != NotificationKind.CUSTOM and value in NotificationKind:
raise ValueError(f"'{value}' is reserved for RomM's own notifications")
return value
@field_validator("title", "body", "link")
@classmethod
def _no_nul(cls, value: str | None) -> str | None:
# PostgreSQL refuses NUL in text columns.
if value is not None and "\x00" in value:
raise ValueError("must not contain NUL characters")
return value
@field_validator("recipients")
@classmethod
def _names_someone(
cls, value: list[int] | Literal["admins", "all"] | None
) -> list[int] | Literal["admins", "all"] | None:
if value == []:
raise ValueError("must name at least one user")
return value
@field_validator("data")
@classmethod
def _data_fits(cls, value: dict[str, Any]) -> dict[str, Any]:
# `allow_nan=False` rejects NaN and Infinity, which no database stores as JSON.
if len(json.dumps(value, allow_nan=False)) > NOTIFICATION_DATA_MAX_LENGTH:
raise ValueError(
f"data must serialize to at most {NOTIFICATION_DATA_MAX_LENGTH} characters"
)
return value
@field_validator("link")
@classmethod
def _link_stays_in_app(cls, value: str | None) -> str | None:
if value is None:
return None
if (
not value.startswith("/")
or value.startswith("//")
or "\\" in value
or any(char.isspace() for char in value)
):
raise ValueError("link must be a path inside RomM, such as /rom/12")
return value
class NotificationIdsPayload(BaseModel):
"""Targets some of the caller's notifications, or all of them when `ids` is null."""
ids: list[int] | None = Field(default=None, max_length=MAX_NOTIFICATIONS_PER_USER)