mirror of
https://github.com/rommapp/romm.git
synced 2026-11-29 18:11:16 +01:00
* fix(platforms): count only the roms the caller can see in rom_count and fs_size_bytes Platform.rom_count and fs_size_bytes are column properties over every rom row on the platform, and the platform endpoints only filter hidden platforms. So the platform header's "In library" count and "On disk" size included roms hidden from the caller (directly, or by an age limit), while the gallery left them out. Server Stats was off the same way: its per-platform metadata coverage divides /api/stats' visibility-filtered match counts by the unfiltered rom_count, so a restricted user saw coverage too low and platform counts and sizes too high. For a restricted caller, the list, detail and update endpoints now subtract the totals of the roms RomVisibilityFilter hides (DBStatsHandler.get_hidden_rom_totals_by_platform, next to the other per-platform aggregates). Direct hides are matched by primary key, so a few hidden roms cost a few lookups rather than a pass over every rom on the platform. Admins and other unrestricted callers keep the model's values and skip the query. On a generated library of 50 platforms and 100k roms (MariaDB), the platform list takes ~44 ms; this adds ~4 ms with 100 roms hidden, ~44 ms with 5,000, and ~60 ms with an age limit (min_age isn't indexed, so that case scans the platforms' roms). Fixes #5312 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(platforms): read the hidden roms' totals in the platform query Addresses Greptile's review of #5313: - Counts can become negative: the hidden totals came from a second query, so a rom added between the two could be subtracted without having been counted. They now come from a grouped subquery outer-joined into the statement that computes the full totals, so both read one snapshot (on PostgreSQL's READ COMMITTED too, which a shared transaction wouldn't give). - Counting rules live in endpoints: the endpoint helper is gone. get_platform and get_platforms take the caller's RomVisibilityFilter (unrestricted by default) and return platforms with the visible totals; DBStatsHandler.get_hidden_rom_totals_by_platform is removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(platforms): code-review fixes for visible platform totals - Re-read rows with populate_existing so a shared session never subtracts twice - Narrow the hidden-totals subquery to the one platform get_platform reads - Re-read after update only for restricted callers, and 404 instead of leaking full totals - Test the update endpoint's restricted totals and the shared-session read Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * refactor(platforms): simplify pass on visible platform totals Gate the row clause in one condition with a why comment, fold the MariaDB narrowing reason into the docstring, and drop restating comments. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix(platforms): count only visible roms in /supported and RetroArch listings - Move the hidden-ROM predicate into RomVisibilityFilter.hidden_on_visible_platforms_clause, with the age rule spelled as ranges an index on min_age can serve - get_platforms reads hidden platforms from the visibility filter instead of a second hidden_platform_ids argument - /api/platforms/supported lists a hidden platform as unmatched and counts only the caller's ROMs on the rest - RetroArch WebDAV skips a platform whose ROMs are all hidden from the caller Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * perf(roms): index platform_id, min_age, fs_size_bytes for age-limited totals On a 73k-ROM copy of a real library (MariaDB 13), GET /api/platforms for an age-limited user went from 208 ms to 55 ms: the hidden-totals aggregate is now an index-only scan instead of a full scan of the wide roms rows. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com> Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
225 lines
6.7 KiB
Python
225 lines
6.7 KiB
Python
from datetime import datetime
|
|
from typing import Annotated
|
|
|
|
from fastapi import Body
|
|
from fastapi import Path as PathVar
|
|
from fastapi import Query, Request, status
|
|
|
|
from decorators.auth import protected_route
|
|
from endpoints.responses.platform import PlatformSchema
|
|
from exceptions.endpoint_exceptions import PlatformNotFoundInDatabaseException
|
|
from exceptions.fs_exceptions import PlatformAlreadyExistsException
|
|
from handler.audit_handler import AuditTarget, changed_fields, record
|
|
from handler.auth.constants import Scope
|
|
from handler.auth.dependencies import (
|
|
assert_can,
|
|
assert_platform_visible,
|
|
get_permissions,
|
|
get_rom_visibility_filter,
|
|
)
|
|
from handler.database import db_platform_handler
|
|
from handler.filesystem import fs_platform_handler
|
|
from handler.scan_handler import scan_platform
|
|
from logger.formatter import BLUE
|
|
from logger.formatter import highlight as hl
|
|
from logger.logger import log
|
|
from models.audit_event import AuditAction
|
|
from models.permission import PermAction, PermEntity
|
|
from models.platform import (
|
|
CUSTOM_NAME_MAX_LENGTH,
|
|
DESCRIPTION_MAX_LENGTH,
|
|
)
|
|
from utils.platforms import get_filesystem_platforms, get_supported_platforms
|
|
from utils.router import APIRouter
|
|
|
|
router = APIRouter(
|
|
prefix="/platforms",
|
|
tags=["platforms"],
|
|
)
|
|
|
|
|
|
@protected_route(
|
|
router.post,
|
|
"",
|
|
[Scope.PLATFORMS_WRITE],
|
|
status_code=status.HTTP_201_CREATED,
|
|
)
|
|
async def add_platform(
|
|
request: Request,
|
|
fs_slug: Annotated[str, Body(description="Platform slug.", embed=True)],
|
|
) -> PlatformSchema:
|
|
"""Create a platform."""
|
|
|
|
try:
|
|
await fs_platform_handler.add_platform(fs_slug=fs_slug)
|
|
except PlatformAlreadyExistsException:
|
|
log.info(f"Detected platform: {hl(fs_slug)}")
|
|
|
|
scanned_platform = await scan_platform(fs_slug, [fs_slug])
|
|
platform = db_platform_handler.add_platform(scanned_platform)
|
|
record(
|
|
AuditAction.PLATFORM_CREATE,
|
|
request,
|
|
AuditTarget.of_platform(platform),
|
|
{"fs_slug": fs_slug},
|
|
)
|
|
return PlatformSchema.model_validate(platform)
|
|
|
|
|
|
@protected_route(router.get, "", [Scope.PLATFORMS_READ])
|
|
def get_platforms(
|
|
request: Request,
|
|
updated_after: Annotated[
|
|
datetime | None,
|
|
Query(
|
|
description="Filter platforms updated after this datetime (ISO 8601 format with timezone information)."
|
|
),
|
|
] = None,
|
|
) -> list[PlatformSchema]:
|
|
"""Retrieve platforms."""
|
|
|
|
return [
|
|
PlatformSchema.model_validate(p)
|
|
for p in db_platform_handler.get_platforms(
|
|
updated_after=updated_after,
|
|
visibility=get_rom_visibility_filter(request),
|
|
)
|
|
]
|
|
|
|
|
|
@protected_route(router.get, "/identifiers", [Scope.PLATFORMS_READ])
|
|
def get_platform_identifiers(
|
|
request: Request,
|
|
) -> list[int]:
|
|
"""Retrieve platform identifiers."""
|
|
|
|
perms = get_permissions(request)
|
|
return db_platform_handler.get_platform_ids(
|
|
hidden_platform_ids=perms.hidden_platform_ids,
|
|
)
|
|
|
|
|
|
@protected_route(router.get, "/supported", [Scope.PLATFORMS_READ])
|
|
def get_supported_platforms_endpoint(request: Request) -> list[PlatformSchema]:
|
|
"""Retrieve the list of supported platforms."""
|
|
|
|
return get_supported_platforms(get_rom_visibility_filter(request))
|
|
|
|
|
|
@protected_route(router.get, "/filesystem", [Scope.PLATFORMS_READ])
|
|
async def get_filesystem_platforms_endpoint(request: Request) -> list[PlatformSchema]:
|
|
"""Retrieve platform folders on disk that have no database row yet."""
|
|
|
|
return await get_filesystem_platforms()
|
|
|
|
|
|
@protected_route(
|
|
router.get,
|
|
"/{id}",
|
|
[Scope.PLATFORMS_READ],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
def get_platform(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
|
|
) -> PlatformSchema:
|
|
"""Retrieve a platform by ID."""
|
|
|
|
platform = db_platform_handler.get_platform(
|
|
id, visibility=get_rom_visibility_filter(request)
|
|
)
|
|
if not platform:
|
|
raise PlatformNotFoundInDatabaseException(id)
|
|
assert_platform_visible(request, platform)
|
|
return PlatformSchema.model_validate(platform)
|
|
|
|
|
|
@protected_route(
|
|
router.put,
|
|
"/{id}",
|
|
[Scope.PLATFORMS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
async def update_platform(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
|
|
custom_name: Annotated[
|
|
str | None,
|
|
Body(
|
|
embed=True,
|
|
max_length=CUSTOM_NAME_MAX_LENGTH,
|
|
description="Custom platform name.",
|
|
),
|
|
] = None,
|
|
description: Annotated[
|
|
str | None,
|
|
Body(
|
|
embed=True,
|
|
max_length=DESCRIPTION_MAX_LENGTH,
|
|
description="Custom platform description.",
|
|
),
|
|
] = None,
|
|
) -> PlatformSchema:
|
|
"""Update a platform."""
|
|
|
|
platform_db = db_platform_handler.get_platform(id)
|
|
if not platform_db:
|
|
raise PlatformNotFoundInDatabaseException(id)
|
|
assert_platform_visible(request, platform_db)
|
|
|
|
submitted = {"custom_name": custom_name, "description": description}
|
|
changed = changed_fields(
|
|
platform_db, {k: v for k, v in submitted.items() if v is not None}, submitted
|
|
)
|
|
if custom_name is not None:
|
|
platform_db.custom_name = custom_name
|
|
if description is not None:
|
|
platform_db.description = description
|
|
platform_db = db_platform_handler.add_platform(platform_db)
|
|
if changed:
|
|
record(
|
|
AuditAction.PLATFORM_EDIT,
|
|
request,
|
|
AuditTarget.of_platform(platform_db),
|
|
{"changed": changed},
|
|
)
|
|
|
|
visibility = get_rom_visibility_filter(request)
|
|
if not visibility.is_unrestricted:
|
|
# Re-read for the caller's totals; the saved row carries everyone's.
|
|
platform_db = db_platform_handler.get_platform(id, visibility=visibility)
|
|
if not platform_db:
|
|
raise PlatformNotFoundInDatabaseException(id)
|
|
return PlatformSchema.model_validate(platform_db)
|
|
|
|
|
|
@protected_route(
|
|
router.delete,
|
|
"/{id}",
|
|
[Scope.PLATFORMS_WRITE],
|
|
responses={status.HTTP_404_NOT_FOUND: {}},
|
|
)
|
|
async def delete_platform(
|
|
request: Request,
|
|
id: Annotated[int, PathVar(description="Platform id.", ge=1)],
|
|
) -> None:
|
|
"""Delete a platform by ID."""
|
|
|
|
perms = get_permissions(request)
|
|
platform = db_platform_handler.get_platform(id)
|
|
if not platform:
|
|
raise PlatformNotFoundInDatabaseException(id)
|
|
assert_platform_visible(request, platform)
|
|
assert_can(perms, PermEntity.PLATFORMS, PermAction.DELETE)
|
|
|
|
log.info(
|
|
f"Deleting {hl(platform.name, color=BLUE)} [{hl(platform.fs_slug)}] from database"
|
|
)
|
|
db_platform_handler.delete_platform(id)
|
|
record(
|
|
AuditAction.PLATFORM_DELETE,
|
|
request,
|
|
AuditTarget.of_platform(platform),
|
|
{"fs_slug": platform.fs_slug},
|
|
)
|