Files
romm/backend/endpoints/permissions.py
Stu Anderson 5f3b983b7f perf(roms): serve the filter dropdown values from their own endpoint (#5786)
* perf(roms)!: serve the filter dropdown values from their own endpoint

GET /api/roms computed the filter dropdown lists (genres, franchises,
companies, platforms and the rest) on every gallery open and every filter
change. For a search they were 0.58 s of the 0.72 s of database time, almost
all of it reading roms_facets, and a gallery needs none of them to show its
cards.

The lists now have their own request, GET /api/roms/filter-values, which the
filter drawer makes when it opens. It takes the same scope parameters as the
gallery (search_term, platform_ids, platforms_logic, collection_id,
virtual_collection_id, smart_collection_id) and returns the same
RomFiltersDict, limited to the roms the caller can see.

On a 100,000 ROM MariaDB library with one API worker, a searched open falls
from 0.85 s to 0.10 s. Opening the drawer pays the cost instead: 0.3 s for a
search, 0.8 s for the whole library, which is no longer cached.

BREAKING CHANGE: GET /api/roms no longer accepts with_filter_values and no
longer returns filter_values. Use GET /api/roms/filter-values. The web client
is updated in this commit.

Backend:
- add GET /api/roms/filter-values
- remove with_filter_values, filter_values and the unscoped filter-values
  cache key from GET /api/roms
- with_filter_values() in the handler no longer caches; the shared cache
  version counter stays because the id list and letter caches use it

Frontend:
- the gallery store no longer asks for the lists on open, refresh or scroll
- fetchFilterValues() asks once per displayed result, and GalleryShell calls
  it when the drawer opens
- the generated response type loses filter_values

Tests:
- remove the filter-values cache tests
- read the lists from the new endpoint in the endpoint tests
- check /api/roms no longer returns them, that the lists are never null, and
  that values of a hidden rom are left out
- cover the on-demand fetch in the store tests

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

* perf(roms) docstring updates

* pr-ready: code-review

- key the filter-values dedupe by scope, not result epoch, so filter,
  sort and group changes stop refetching the lists
- empty another scope's lists while the new ones load, and refetch after
  a library change or context switch
- abort an in-flight filter-values request for a superseded scope
- send platform_ids in the filter-values endpoint tests and cover scope
  narrowing and ignored row filters
- update comments that still called the filter values cached
- test the drawer-open fetch in GalleryShell

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

* pr-ready: simplify

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

* pr-ready: review-polish

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

* pr-ready: prose

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

* pr-ready: prose (code-review follow-up)

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

* pr-ready: simplify (code-review follow-up)

Rename the filterValuesScope state field to filterValuesScopeKey so it no
longer shares a name with the filterValuesScope() helper.

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

* perf(roms): cache the whole-library filter values on the new endpoint

GET /api/roms/filter-values computed the unscoped lists on every drawer
open, a 0.8 s scan on a 100k-rom library. Serve them from the per-user
versioned cache GET /api/roms used, under the same key, so only a scope
(platform, collection or search) computes live.

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

* pr-ready: code-review

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

* pr-ready: prose (code-review follow-up)

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

* pr-ready: simplify

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

* pr-ready: review-polish

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

* pr-ready: prose

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

* feat(gallery): show a loading state while the filter values load

The drawer's attribute dropdowns now show a spinner, and an open dropdown
says Loading, while GET /api/roms/filter-values is in flight. The metadata
provider and status lists are fixed and never show it.

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

* test(roms): cover filter-values cache invalidation and private collections

Hiding a rom after the whole-library lists are cached drops its values on
the next request, and another user's private collection or smart
collection yields no values.

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-28 21:10:02 -05:00

567 lines
19 KiB
Python

import asyncio
from typing import Annotated, Any, Final
from fastapi import Body, HTTPException, Request, status
from decorators.auth import protected_route
from endpoints.responses.permission import (
GrantSchemaIO,
HiddenEntityCreate,
HiddenEntitySchema,
OverrideSchemaIO,
PermissionCatalogSchema,
PermissionGroupCreate,
PermissionGroupSchema,
PermissionGroupUpdate,
PermissionsResponse,
UserPermissionsSchema,
UserPermissionsUpdate,
)
from handler.audit_handler import AuditTarget, record
from handler.auth.constants import Scope
from handler.auth.dependencies import assert_admin, get_permissions
from handler.database import (
db_client_token_handler,
db_permission_handler,
db_platform_handler,
db_rom_handler,
db_user_handler,
)
from handler.socket_handler import close_client_token_sockets, socket_handler
from logger.logger import log
from models.audit_event import AuditAction, AuditTargetType
from models.permission import (
OWNABLE_PERM_ENTITIES,
PermAction,
PermEntity,
PermissionGroup,
)
from utils.router import APIRouter
router = APIRouter(
prefix="/permissions",
tags=["permissions"],
)
ADMIN_ONLY_RESPONSE: Final[dict[int | str, dict[str, Any]]] = {
status.HTTP_403_FORBIDDEN: {"description": "The caller is not an admin."}
}
GROUP_NOT_FOUND_RESPONSE: Final[dict[int | str, dict[str, Any]]] = {
status.HTTP_404_NOT_FOUND: {"description": "No permission group has this ID."}
}
USER_NOT_FOUND_RESPONSE: Final[dict[int | str, dict[str, Any]]] = {
status.HTTP_404_NOT_FOUND: {"description": "No user has this ID."}
}
async def _broadcast_permissions_changed(user_id: int) -> None:
try:
await socket_handler.socket_server.emit(
"permissions:changed", {"user_id": user_id}
)
except Exception as e: # noqa: BLE001
log.warning(f"Failed to broadcast permissions:changed for user {user_id}: {e}")
async def emit_permissions_changed(*user_ids: int) -> None:
"""Notify clients that the users' effective permissions changed.
Broadcast (Redis-backed fan-out); the frontend re-fetches `/permissions/me`
only when the affected user is the current user. Call this from any path that
mutates a user's role, group, overrides, hidden entities or age settings.
"""
# The gallery's cached id index, letter index and filter values are computed
# per user with visibility applied, so they go stale with it.
db_rom_handler.invalidate_filter_values_cache()
if not user_ids:
return
await asyncio.gather(*(_broadcast_permissions_changed(u) for u in user_ids))
try:
token_ids = db_client_token_handler.get_token_ids_by_users(user_ids)
except Exception: # noqa: BLE001
log.warning(f"Failed to look up the tokens of users {user_ids}", exc_info=True)
return
await close_client_token_sockets(token_ids)
@protected_route(router.get, "/me", [Scope.ME_READ])
def get_my_permissions(request: Request) -> PermissionsResponse:
"""Return the caller's effective permissions for the UI to gate on.
The backend remains the source of truth; this is a UX hint. Includes the
granted action keys and the platform/rom ids hidden from the caller.
"""
return PermissionsResponse.from_resolved(get_permissions(request))
# --- Admin: catalog -----------------------------------------------------------
@protected_route(
router.get, "/catalog", [Scope.USERS_READ], responses=ADMIN_ONLY_RESPONSE
)
def get_permission_catalog(request: Request) -> PermissionCatalogSchema:
"""The entity/action vocabulary the admin UI renders its matrix from."""
assert_admin(request)
return PermissionCatalogSchema(
entities=list(PermEntity),
actions=list(PermAction),
ownable_entities=[e for e in PermEntity if e in OWNABLE_PERM_ENTITIES],
)
# --- Admin: permission groups -------------------------------------------------
def _group_schema(group: PermissionGroup) -> PermissionGroupSchema:
return PermissionGroupSchema(
id=group.id,
name=group.name,
description=group.description,
is_default=group.is_default,
system_key=group.system_key,
color=group.color,
grants=[
GrantSchemaIO(entity=g.entity, action=g.action, own_only=g.own_only)
for g in group.grants
],
member_count=len(db_permission_handler.get_group_member_ids(group.id)),
hidden=[
HiddenEntitySchema(entity=h.entity, entity_id=h.entity_id)
for h in db_permission_handler.get_hidden_entities(group_id=group.id)
],
age_limit=group.age_limit,
hide_unrated_roms=group.hide_unrated_roms,
)
def _group_target(group: PermissionGroup) -> AuditTarget:
return AuditTarget(AuditTargetType.PERMISSION_GROUP, group.id, group.name)
def _hidden_target(entity: PermEntity, entity_id: int) -> AuditTarget | None:
if entity == PermEntity.ROMS:
rom = db_rom_handler.get_rom_visibility_label(entity_id)
return (
AuditTarget.of_rom(rom)
if rom
else AuditTarget(AuditTargetType.ROM, entity_id, None)
)
if entity == PermEntity.PLATFORMS:
platform = db_platform_handler.get_platform(entity_id)
return (
AuditTarget.of_platform(platform)
if platform
else AuditTarget(AuditTargetType.PLATFORM, entity_id, None)
)
return None
def _group_name(group_id: int | None) -> str | None:
group = db_permission_handler.get_group(group_id) if group_id is not None else None
return group.name if group else None
def _principal(user_id: int | None, group_id: int | None) -> dict[str, Any]:
"""Who something was hidden from, named for the audit log."""
if user_id is not None:
user = db_user_handler.get_user(user_id)
return {"type": "user", "id": user_id, "name": user.username if user else None}
return {"type": "group", "id": group_id, "name": _group_name(group_id)}
@protected_route(
router.get, "/groups", [Scope.USERS_READ], responses=ADMIN_ONLY_RESPONSE
)
def list_permission_groups(request: Request) -> list[PermissionGroupSchema]:
"""List all permission groups with their grants."""
assert_admin(request)
return [_group_schema(g) for g in db_permission_handler.get_groups()]
@protected_route(
router.post,
"/groups",
[Scope.USERS_WRITE],
status_code=status.HTTP_201_CREATED,
responses={
status.HTTP_400_BAD_REQUEST: {
"description": "A group with this name already exists."
},
**ADMIN_ONLY_RESPONSE,
},
)
async def create_permission_group(
request: Request, body: PermissionGroupCreate
) -> PermissionGroupSchema:
"""Create a permission group."""
assert_admin(request)
if db_permission_handler.get_group_by_name(body.name):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A group with that name already exists",
)
group = db_permission_handler.create_group(
name=body.name,
description=body.description,
is_default=body.is_default,
color=body.color,
grants=[(g.entity, g.action, g.own_only) for g in body.grants],
age_limit=body.age_limit,
hide_unrated_roms=body.hide_unrated_roms,
)
if body.is_default:
await emit_permissions_changed(
*db_permission_handler.get_group_follower_ids(group.id)
)
record(
AuditAction.PERMISSION_GROUP_CREATE,
request,
_group_target(group),
{"grants": len(body.grants), "is_default": body.is_default},
)
return _group_schema(group)
@protected_route(
router.put,
"/groups/{id}",
[Scope.USERS_WRITE],
responses={
status.HTTP_400_BAD_REQUEST: {
"description": (
"Another group has this name, or the request unsets the default"
" group without making another group the default."
)
},
**ADMIN_ONLY_RESPONSE,
**GROUP_NOT_FOUND_RESPONSE,
},
)
async def update_permission_group(
request: Request,
id: int,
body: PermissionGroupUpdate,
) -> PermissionGroupSchema:
"""Update a permission group (name/description/default/grants)."""
assert_admin(request)
group = db_permission_handler.get_group(id)
if group is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
# Renaming onto an existing name would hit the unique constraint as a 500.
if body.name is not None:
clash = db_permission_handler.get_group_by_name(body.name)
if clash is not None and clash.id != id:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="A group with that name already exists",
)
# Don't leave the system without a default group; reassign first.
if body.is_default is False and group.is_default:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Set another group as default first",
)
updated = db_permission_handler.update_group(
id,
name=body.name,
description=body.description,
is_default=body.is_default,
color=body.color,
grants=(
[(g.entity, g.action, g.own_only) for g in body.grants]
if body.grants is not None
else None
),
set_age_settings=body.set_age_settings,
age_limit=body.age_limit,
hide_unrated_roms=body.hide_unrated_roms,
)
if updated is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
await emit_permissions_changed(*db_permission_handler.get_group_follower_ids(id))
# Age settings apply only with the flag, so only the flag reports them.
age_fields = {"set_age_settings", "age_limit", "hide_unrated_roms"}
changed = set(body.model_dump(exclude_none=True)) - age_fields
if body.set_age_settings:
changed |= {"age_limit", "hide_unrated_roms"}
record(
AuditAction.PERMISSION_GROUP_EDIT,
request,
_group_target(updated),
{"changed": sorted(changed)},
)
return _group_schema(updated)
@protected_route(
router.delete,
"/groups/{id}",
[Scope.USERS_WRITE],
responses={
status.HTTP_400_BAD_REQUEST: {"description": "The group is the default group."},
**ADMIN_ONLY_RESPONSE,
**GROUP_NOT_FOUND_RESPONSE,
},
)
async def delete_permission_group(
request: Request,
id: int,
) -> None:
"""Delete a permission group. Members fall back to the default group."""
assert_admin(request)
group = db_permission_handler.get_group(id)
if group is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
if group.is_default:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Cannot delete the default group; set another default first",
)
member_ids = db_permission_handler.get_group_member_ids(id)
db_permission_handler.delete_group(id)
record(
AuditAction.PERMISSION_GROUP_DELETE,
request,
_group_target(group),
{"members": len(member_ids)},
)
await emit_permissions_changed(*member_ids)
# --- Admin: per-user assignment ----------------------------------------------
def _user_permissions(
user_id: int,
*,
group_id: int | None,
age_limit: int | None,
hide_unrated_roms: bool | None,
) -> UserPermissionsSchema:
overrides = db_permission_handler.get_user_overrides(user_id)
hidden = db_permission_handler.get_hidden_entities(user_id=user_id)
return UserPermissionsSchema(
user_id=user_id,
permission_group_id=group_id,
overrides=[
OverrideSchemaIO(
entity=o.entity,
action=o.action,
granted=o.granted,
own_only=o.own_only,
)
for o in overrides
],
hidden=[
HiddenEntitySchema(entity=h.entity, entity_id=h.entity_id) for h in hidden
],
age_limit=age_limit,
hide_unrated_roms=hide_unrated_roms,
)
@protected_route(
router.get,
"/users/{user_id}",
[Scope.USERS_READ],
responses={**ADMIN_ONLY_RESPONSE, **USER_NOT_FOUND_RESPONSE},
)
def get_user_permissions(
request: Request,
user_id: int,
) -> UserPermissionsSchema:
"""A user's group membership, per-user overrides and hidden entities."""
assert_admin(request)
user = db_user_handler.get_user(user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
return _user_permissions(
user_id,
group_id=user.permission_group_id,
age_limit=user.age_limit,
hide_unrated_roms=user.hide_unrated_roms,
)
@protected_route(
router.put,
"/users/{user_id}",
[Scope.USERS_WRITE],
responses={**ADMIN_ONLY_RESPONSE, **USER_NOT_FOUND_RESPONSE},
)
async def update_user_permissions(
request: Request,
user_id: int,
body: UserPermissionsUpdate,
) -> UserPermissionsSchema:
"""Assign a user's group and/or replace their per-user overrides."""
assert_admin(request)
user = db_user_handler.get_user(user_id)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Not found")
group_id = user.permission_group_id
if body.set_group:
group_id = body.permission_group_id
db_permission_handler.set_user_group(user_id, group_id)
if body.overrides is not None:
db_permission_handler.replace_user_overrides(
user_id,
[(o.entity, o.action, o.granted, o.own_only) for o in body.overrides],
)
age_limit, hide_unrated_roms = user.age_limit, user.hide_unrated_roms
if body.set_age_settings:
age_limit, hide_unrated_roms = body.age_limit, body.hide_unrated_roms
db_user_handler.update_user(
user_id,
{"age_limit": age_limit, "hide_unrated_roms": hide_unrated_roms},
)
await emit_permissions_changed(user_id)
record(
AuditAction.USER_PERMISSIONS_EDIT,
request,
AuditTarget.of_user(user),
lambda: {
"group": _group_name(group_id),
"group_changed": body.set_group and group_id != user.permission_group_id,
"overrides": len(body.overrides) if body.overrides is not None else None,
"age_settings_changed": body.set_age_settings,
},
)
return _user_permissions(
user_id,
group_id=group_id,
age_limit=age_limit,
hide_unrated_roms=hide_unrated_roms,
)
# --- Admin: hidden entities ---------------------------------------------------
@protected_route(
router.post,
"/hidden",
[Scope.USERS_WRITE],
responses={
status.HTTP_400_BAD_REQUEST: {
"description": (
"The request does not set exactly one of `user_id` and `group_id`,"
" or the entity is not a platform or a rom."
)
},
**ADMIN_ONLY_RESPONSE,
},
)
async def add_hidden_entity(
request: Request, body: HiddenEntityCreate
) -> HiddenEntitySchema:
"""Hide an entity from a user OR a group (exactly one principal)."""
assert_admin(request)
if (body.user_id is None) == (body.group_id is None):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Exactly one of user_id or group_id must be set",
)
# Only platforms and roms are honored by the resolver (firmware is hidden via
# its platform cascade), so reject other entity types instead of storing a
# row the visibility filter would silently ignore. The id itself is a
# denylist entry, so a not-yet-present id is a harmless no-op, not an error.
if body.entity not in (PermEntity.PLATFORMS, PermEntity.ROMS):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Only platforms and roms can be hidden",
)
db_permission_handler.add_hidden_entity(
body.entity, body.entity_id, user_id=body.user_id, group_id=body.group_id
)
record(
AuditAction.VISIBILITY_HIDE,
request,
lambda: _hidden_target(body.entity, body.entity_id),
lambda: {
"from": _principal(body.user_id, body.group_id),
"entity": body.entity,
"entity_id": body.entity_id,
},
)
await _emit_for_principal(body.user_id, body.group_id)
return HiddenEntitySchema(entity=body.entity, entity_id=body.entity_id)
@protected_route(
router.delete,
"/hidden",
[Scope.USERS_WRITE],
status_code=status.HTTP_204_NO_CONTENT,
responses={
status.HTTP_400_BAD_REQUEST: {
"description": "The request does not set exactly one of `user_id` and `group_id`."
},
**ADMIN_ONLY_RESPONSE,
},
)
async def remove_hidden_entity(
request: Request,
entity: Annotated[PermEntity, Body(embed=True)],
entity_id: Annotated[int, Body(embed=True)],
user_id: Annotated[
int | None,
Body(
embed=True,
description=(
"The user it was hidden from. Set exactly one of `user_id` and"
" `group_id`."
),
),
] = None,
group_id: Annotated[
int | None,
Body(
embed=True,
description=(
"The group it was hidden from. Set exactly one of `user_id` and"
" `group_id`."
),
),
] = None,
) -> None:
"""Un-hide an entity for a user OR a group."""
assert_admin(request)
if (user_id is None) == (group_id is None):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="Exactly one of user_id or group_id must be set",
)
db_permission_handler.remove_hidden_entity(
entity, entity_id, user_id=user_id, group_id=group_id
)
record(
AuditAction.VISIBILITY_UNHIDE,
request,
lambda: _hidden_target(entity, entity_id),
lambda: {
"from": _principal(user_id, group_id),
"entity": entity,
"entity_id": entity_id,
},
)
await _emit_for_principal(user_id, group_id)
async def _emit_for_principal(user_id: int | None, group_id: int | None) -> None:
if user_id is not None:
await emit_permissions_changed(user_id)
elif group_id is not None:
await emit_permissions_changed(
*db_permission_handler.get_group_follower_ids(group_id)
)