Files
romm/backend/utils/platforms.py
Ryan Farthing c6b5f0ae11 fix(platforms): count only the roms the caller can see in rom_count and fs_size_bytes (#5313)
* 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>
2026-10-29 10:48:04 -04:00

139 lines
4.9 KiB
Python

from datetime import datetime, timezone
from config.config_manager import config_manager as cm
from endpoints.responses.platform import PlatformSchema
from handler.auth.rom_visibility import UNRESTRICTED, RomVisibilityFilter
from handler.database import db_platform_handler
from handler.filesystem import fs_platform_handler
from handler.metadata import (
meta_flashpoint_handler,
meta_hasheous_handler,
meta_hltb_handler,
meta_igdb_handler,
meta_launchbox_handler,
meta_moby_handler,
meta_ra_handler,
meta_ss_handler,
meta_tgdb_handler,
)
from handler.metadata.platform_names import resolve_platform_name
from models.platform import Platform
from utils.platform_aliases import resolve_platform_slug
from utils.platform_slugs import UniversalPlatformSlug as UPS
def _build_unmatched_platform(slug: str, fs_slug: str, now: datetime) -> PlatformSchema:
"""Build a PlatformSchema for a platform that has no database row yet."""
igdb_platform = meta_igdb_handler.get_platform(slug)
moby_platform = meta_moby_handler.get_platform(slug)
ss_platform = meta_ss_handler.get_platform(slug)
ra_platform = meta_ra_handler.get_platform(slug)
launchbox_platform = meta_launchbox_handler.get_platform(slug)
hasheous_platform = meta_hasheous_handler.get_platform(slug)
tgdb_platform = meta_tgdb_handler.get_platform(slug)
flashpoint_platform = meta_flashpoint_handler.get_platform(slug)
hltb_platform = meta_hltb_handler.get_platform(slug)
platform_attrs = {
"id": -1,
"name": slug.replace("-", " ").title(),
"fs_slug": fs_slug,
"slug": slug,
"roms": [],
"rom_count": 0,
"created_at": now,
"updated_at": now,
"fs_size_bytes": 0,
"missing_from_fs": False,
}
platform_attrs.update(
{
**hltb_platform,
**flashpoint_platform,
**hasheous_platform,
**tgdb_platform,
**launchbox_platform,
**ra_platform,
**moby_platform,
**ss_platform,
**igdb_platform,
"igdb_id": igdb_platform.get("igdb_id")
or hasheous_platform.get("igdb_id")
or None,
"ra_id": ra_platform.get("ra_id") or hasheous_platform.get("ra_id") or None,
"tgdb_id": moby_platform.get("tgdb_id")
or hasheous_platform.get("tgdb_id")
or tgdb_platform.get("tgdb_id")
or None,
"name": resolve_platform_name(slug),
"url_logo": igdb_platform.get("url_logo")
or tgdb_platform.get("url_logo")
or "",
}
)
return PlatformSchema.model_validate(Platform(**platform_attrs))
def get_supported_platforms(
visibility: RomVisibilityFilter = UNRESTRICTED,
) -> list[PlatformSchema]:
"""Get all supported platforms with metadata from various sources.
Args:
visibility: The caller's ROM visibility. A platform it hides is listed as
if it had no database row, and the rest count only the ROMs it shows.
Returns:
List of platform dictionaries with metadata from IGDB, MobyGames,
ScreenScraper, RetroAchievements, Launchbox, Hasheous, TGDB,
Flashpoint, and HowLongToBeat.
"""
db_platforms = db_platform_handler.get_platforms(visibility=visibility)
# Multiple folders can resolve to the same slug (a folder alias or a
# platform variant bound to a parent platform). When that happens, prefer
# the canonical platform (the one whose fs_slug matches its slug) so a
# variant folder doesn't shadow the parent and rename it in the picker.
db_platforms_map: dict[str, Platform] = {}
for p in db_platforms:
existing = db_platforms_map.get(p.slug)
if existing is None or p.fs_slug == p.slug:
db_platforms_map[p.slug] = p
now = datetime.now(timezone.utc)
supported_platforms = []
for upslug in UPS:
slug = upslug.value
db_platform = db_platforms_map.get(slug, None)
if db_platform:
supported_platforms.append(PlatformSchema.model_validate(db_platform))
continue
supported_platforms.append(_build_unmatched_platform(slug, slug, now))
return supported_platforms
async def get_filesystem_platforms() -> list[PlatformSchema]:
"""Get platform folders that exist on disk but have no database row yet."""
cnfg = cm.get_config()
fs_slugs = await fs_platform_handler.get_platforms()
existing_fs_slugs = {p.fs_slug for p in db_platform_handler.get_platforms()}
now = datetime.now(timezone.utc)
filesystem_platforms = []
# Build a platform for each folder on disk
for fs_slug in fs_slugs:
if fs_slug in existing_fs_slugs:
continue
slug = resolve_platform_slug(fs_slug, cnfg)
filesystem_platforms.append(_build_unmatched_platform(slug, fs_slug, now))
return filesystem_platforms