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>
This commit is contained in:
authored and GitHub committed 2026-10-29 10:48:04 -04:00
1 parent 4229c45e0b
commit c6b5f0ae11
14 files changed
+407 -29

No files matched your search

@@ -0,0 +1,31 @@
"""Index `roms` by platform and `min_age` for age-limited platform totals
Revision ID: 0156_roms_platform_min_age_index
Revises: 0155_retired_arcade_slugs
Create Date: 2026-10-29 00:00:00.000000
"""
from alembic import op
# revision identifiers, used by Alembic.
revision = "0156_roms_platform_min_age_index"
down_revision = "0155_retired_arcade_slugs"
branch_labels = None
depends_on = None
INDEX_NAME = "idx_roms_platform_min_age"
def upgrade() -> None:
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.create_index(
INDEX_NAME,
["platform_id", "min_age", "fs_size_bytes"],
if_not_exists=True,
)
def downgrade() -> None:
with op.batch_alter_table("roms", schema=None) as batch_op:
batch_op.drop_index(INDEX_NAME, if_exists=True)
+1 -3
View File
@@ -116,9 +116,7 @@ def platforms_webrcade_feed(request: Request) -> WebrcadeFeedSchema:
"""
visibility = get_rom_visibility_filter(request)
platforms = db_platform_handler.get_platforms(
hidden_platform_ids=visibility.hidden_platform_ids
)
platforms = db_platform_handler.get_platforms(visibility=visibility)
categories = []
for p in platforms:
+12 -4
View File
@@ -15,6 +15,7 @@ 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
@@ -77,12 +78,11 @@ def get_platforms(
) -> list[PlatformSchema]:
"""Retrieve platforms."""
perms = get_permissions(request)
return [
PlatformSchema.model_validate(p)
for p in db_platform_handler.get_platforms(
updated_after=updated_after,
hidden_platform_ids=perms.hidden_platform_ids,
visibility=get_rom_visibility_filter(request),
)
]
@@ -103,7 +103,7 @@ def get_platform_identifiers(
def get_supported_platforms_endpoint(request: Request) -> list[PlatformSchema]:
"""Retrieve the list of supported platforms."""
return get_supported_platforms()
return get_supported_platforms(get_rom_visibility_filter(request))
@protected_route(router.get, "/filesystem", [Scope.PLATFORMS_READ])
@@ -125,7 +125,9 @@ def get_platform(
) -> PlatformSchema:
"""Retrieve a platform by ID."""
platform = db_platform_handler.get_platform(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)
@@ -182,6 +184,12 @@ async def update_platform(
{"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)
+2 -7
View File
@@ -16,7 +16,6 @@ from handler.auth.constants import Scope
from handler.auth.dependencies import get_permissions
from handler.auth.permissions import ResolvedPermissions
from handler.database import (
db_platform_handler,
db_screenshot_handler,
db_state_handler,
)
@@ -314,12 +313,8 @@ def _rom_file_propfind_entry(slug: str, file: browser.RomFile) -> browser.Propfi
def _platform_listing(
slug: str, depth: int, permissions: ResolvedPermissions
) -> list[browser.PropfindEntry] | None:
platform = db_platform_handler.get_platform_by_fs_slug(slug)
if (
not platform
or platform.rom_count == 0
or not permissions.can_see_platform(platform.id)
):
platform = browser.find_platform(slug, permissions)
if not platform:
return None
self_entry = _collection_entry(f"roms/{slug}", platform.name)
+20
View File
@@ -72,6 +72,16 @@ class RomVisibilityFilter:
clauses = self._row_clauses(Rom.platform_id, Rom.min_age)
return not_(and_(*clauses)) if clauses else None
def hidden_on_visible_platforms_clause(self) -> ColumnElement[bool] | None:
"""WHERE clause matching the `roms` rows hidden directly or by the age rule,
or None when neither applies; hidden platforms are left to the caller."""
clauses: list[ColumnElement[bool]] = []
if self.hidden_rom_ids:
clauses.append(Rom.id.in_(self.hidden_rom_ids))
if self.has_age_rule:
clauses.append(self._age_hidden_clause(Rom.min_age))
return or_(*clauses) if clauses else None
def _row_clauses(
self,
platform_id_col: InstrumentedAttribute[int],
@@ -95,6 +105,16 @@ class RomVisibilityFilter:
return and_(min_age_col.is_not(None), min_age_col <= self.age_limit)
return or_(min_age_col.is_(None), min_age_col <= self.age_limit)
def _age_hidden_clause(
self, min_age_col: InstrumentedAttribute[int | None]
) -> ColumnElement[bool]:
"""The negation of `_age_clause`, spelled as ranges an index on `min_age` serves."""
if self.age_limit is None:
return min_age_col.is_(None)
if self.hide_unrated_roms:
return or_(min_age_col.is_(None), min_age_col > self.age_limit)
return min_age_col > self.age_limit
@cached_property
def allows(self) -> Callable[[VisibilityColumns], bool]:
"""Whether a loaded ROM is visible, picked once so a per-ROM loop pays one call."""
+64 -8
View File
@@ -5,8 +5,10 @@ from typing import Any, cast
from sqlalchemy import Select, delete, func, or_, select, update
from sqlalchemy.orm import Session, selectinload
from sqlalchemy.orm.attributes import set_committed_value
from decorators.database import INJECTED_SESSION, begin_session
from handler.auth.rom_visibility import UNRESTRICTED, RomVisibilityFilter
from models.platform import Platform
from models.rom import Rom
@@ -27,6 +29,56 @@ def with_firmware[**P, R](func: Callable[P, R]) -> Callable[P, R]:
return wrapper
def _with_visible_totals(
session: Session,
query: Select[Platform],
visibility: RomVisibilityFilter,
platform_id: int | None = None,
) -> list[Platform]:
"""Load `query`'s platforms, their totals counting only the ROMs `visibility` shows.
Args:
platform_id: The one platform `query` selects. MariaDB doesn't push the outer
WHERE into the grouped derived table, so it narrows the hidden totals itself.
"""
# The totals are adjusted in place, so a shared session must not reuse an adjusted row.
query = query.execution_options(populate_existing=True)
# Callers drop hidden platforms, so only the ROMs hidden on the rest count.
hidden = visibility.hidden_on_visible_platforms_clause()
if hidden is None:
return list(session.scalars(query).unique().all())
hidden_roms = select(
Rom.platform_id,
func.count(Rom.id).label("rom_count"),
func.coalesce(func.sum(Rom.fs_size_bytes), 0).label("fs_size_bytes"),
).where(hidden)
if platform_id is not None:
hidden_roms = hidden_roms.where(Rom.platform_id == platform_id)
totals = hidden_roms.group_by(Rom.platform_id).subquery()
# One statement, so the hidden totals never exceed the full totals it computes.
rows = (
session.execute(
query.add_columns(totals.c.rom_count, totals.c.fs_size_bytes).outerjoin(
totals, totals.c.platform_id == Platform.id
)
)
.unique()
.all()
)
platforms = []
for platform, hidden_count, hidden_size in rows:
if hidden_count:
set_committed_value(
platform, "rom_count", platform.rom_count - hidden_count
)
set_committed_value(
platform, "fs_size_bytes", platform.fs_size_bytes - int(hidden_size)
)
platforms.append(platform)
return platforms
class DBPlatformsHandler(DBBaseHandler):
@begin_session
@with_firmware
@@ -61,29 +113,33 @@ class DBPlatformsHandler(DBBaseHandler):
def get_platform(
self,
id: int,
visibility: RomVisibilityFilter = UNRESTRICTED,
query: Select[Platform] = INJECTED_PLATFORM_QUERY,
session: Session = INJECTED_SESSION,
) -> Platform | None:
return session.scalar(query.filter_by(id=id).limit(1))
platforms = _with_visible_totals(
session, query.filter_by(id=id).limit(1), visibility, platform_id=id
)
return platforms[0] if platforms else None
@begin_session
@with_firmware
def get_platforms(
self,
updated_after: datetime | None = None,
hidden_platform_ids: Collection[int] | None = None,
visibility: RomVisibilityFilter = UNRESTRICTED,
query: Select[Platform] = INJECTED_PLATFORM_QUERY,
session: Session = INJECTED_SESSION,
) -> Sequence[Platform]:
"""The platforms `visibility` shows, their totals counting only its ROMs."""
if updated_after:
query = query.filter(Platform.updated_at > updated_after)
if visibility.hidden_platform_ids:
query = query.filter(Platform.id.not_in(visibility.hidden_platform_ids))
# Admin-driven visibility (opt-out): exclude platforms hidden from the
# caller. Empty/None (e.g. admins) skips filtering.
if hidden_platform_ids:
query = query.filter(Platform.id.not_in(hidden_platform_ids))
return session.scalars(query.order_by(Platform.name.asc())).unique().all()
return _with_visible_totals(
session, query.order_by(Platform.name.asc()), visibility
)
@begin_session
def get_platform_ids(
+12 -3
View File
@@ -90,12 +90,21 @@ def _display_name(rom: Rom) -> str:
def list_platforms(permissions: ResolvedPermissions) -> list[Platform]:
platforms = db_platform_handler.get_platforms(
hidden_platform_ids=list(permissions.hidden_platform_ids)
)
platforms = db_platform_handler.get_platforms(visibility=permissions.rom_visibility)
return [p for p in platforms if p.rom_count > 0]
def find_platform(fs_slug: str, permissions: ResolvedPermissions) -> Platform | None:
"""The platform behind `fs_slug`, if the caller can see it and any of its ROMs."""
platform = db_platform_handler.get_platform_by_fs_slug(fs_slug)
if not platform or not permissions.can_see_platform(platform.id):
return None
platform = db_platform_handler.get_platform(
platform.id, visibility=permissions.rom_visibility
)
return platform if platform and platform.rom_count > 0 else None
def list_rom_files(
platform: Platform, permissions: ResolvedPermissions
) -> list[RomFile]:
+2
View File
@@ -837,6 +837,8 @@ class Rom(BaseModel):
"id",
),
Index("idx_roms_platform_fs_size", "platform_id", "fs_size_bytes"),
# Covers a platform's age-hidden totals; InnoDB appends `id` for direct hides.
Index("idx_roms_platform_min_age", "platform_id", "min_age", "fs_size_bytes"),
# The remaining gallery sorts, each paired with the `id` tiebreak the
# gallery orders by; the key alone would not match its ORDER BY.
Index("idx_roms_platform_id_sorted", "platform_id", "id"),
@@ -184,6 +184,18 @@ class TestEnforcement:
detail = client.get(f"/api/roms/{mature.id}", headers=_auth(viewer_user))
assert detail.status_code == status.HTTP_404_NOT_FOUND
def test_a_limited_user_does_not_count_roms_above_it_on_the_platform(
self, client, headers, viewer_user: User, platform: Platform
):
make_esrb_rated_rom(platform, "Mature", "M")
make_esrb_rated_rom(platform, "Everyone", "E")
gid = _make_kids_group(client, headers, age_limit=12)["id"]
_join(client, headers, viewer_user, gid)
body = client.get(f"/api/platforms/{platform.id}", headers=_auth(viewer_user))
assert body.json()["rom_count"] == 1
def test_a_limit_change_reaches_the_cached_gallery(
self, client, headers, viewer_user: User, platform: Platform
):
@@ -10,7 +10,7 @@ from datetime import timedelta
import pytest
from fastapi import status
from tests.factories import make_rom
from tests.factories import make_platform, make_rom
from config import OAUTH_ACCESS_TOKEN_EXPIRE_SECONDS
from endpoints import roms as rom_endpoints
@@ -147,6 +147,97 @@ def test_hidden_rom_is_dropped_from_a_smart_collection_and_its_count(
assert body["rom_count"] == 1
def test_hidden_rom_is_left_out_of_its_platforms_counts(
client, viewer_user, admin_user, platform
):
make_rom(platform, "shown", fs_size_bytes=100)
hidden = make_rom(platform, "hidden", fs_size_bytes=50)
_hide(PermEntity.ROMS, hidden.id, viewer_user.id)
detail = client.get(
f"/api/platforms/{platform.id}", headers=_auth(viewer_user)
).json()
listed = next(
p
for p in client.get("/api/platforms", headers=_auth(viewer_user)).json()
if p["id"] == platform.id
)
admin = client.get(
f"/api/platforms/{platform.id}", headers=_auth(admin_user)
).json()
for body in (detail, listed):
assert (body["rom_count"], body["fs_size_bytes"]) == (1, 100)
assert (admin["rom_count"], admin["fs_size_bytes"]) == (2, 150)
def test_platform_update_answers_with_the_editors_counts(client, editor_user, platform):
make_rom(platform, "shown", fs_size_bytes=100)
hidden = make_rom(platform, "hidden", fs_size_bytes=50)
_hide(PermEntity.ROMS, hidden.id, editor_user.id)
response = client.put(
f"/api/platforms/{platform.id}",
headers=_auth(editor_user),
json={"custom_name": "Renamed"},
)
assert response.status_code == status.HTTP_200_OK
body = response.json()
assert (body["rom_count"], body["fs_size_bytes"]) == (1, 100)
def test_supported_platforms_count_only_visible_roms(client, viewer_user):
shown = make_platform("n64")
make_rom(shown, "shown", fs_size_bytes=100)
_hide(
PermEntity.ROMS, make_rom(shown, "hidden", fs_size_bytes=50).id, viewer_user.id
)
hidden_platform = make_platform("snes")
make_rom(hidden_platform, "on a hidden platform")
_hide(PermEntity.PLATFORMS, hidden_platform.id, viewer_user.id)
supported = {
p["slug"]: p
for p in client.get(
"/api/platforms/supported", headers=_auth(viewer_user)
).json()
}
assert (supported["n64"]["rom_count"], supported["n64"]["fs_size_bytes"]) == (
1,
100,
)
assert (supported["snes"]["id"], supported["snes"]["rom_count"]) == (-1, 0)
def test_retroarch_skips_a_platform_whose_roms_are_all_hidden(
client, editor_user, rom, platform
):
_hide(PermEntity.ROMS, rom.id, editor_user.id)
auth = ("test_editor", "test_editor_password")
listing = client.request("PROPFIND", "/api/sync/retroarch/roms/", auth=auth)
folder = client.request(
"PROPFIND", f"/api/sync/retroarch/roms/{platform.fs_slug}/", auth=auth
)
assert listing.status_code == 207
assert f"/roms/{platform.fs_slug}/" not in listing.text
assert folder.status_code == status.HTTP_404_NOT_FOUND
def test_platform_with_only_hidden_roms_counts_none(client, viewer_user, platform):
hidden = make_rom(platform, "hidden", fs_size_bytes=50)
_hide(PermEntity.ROMS, hidden.id, viewer_user.id)
body = client.get(
f"/api/platforms/{platform.id}", headers=_auth(viewer_user)
).json()
assert (body["rom_count"], body["fs_size_bytes"]) == (0, 0)
def _rom_with_cover(platform, name, **overrides):
rom = make_rom(platform, name, **overrides)
return db_rom_handler.update_rom(
@@ -69,6 +69,36 @@ def test_direct_hides_alone_need_no_row_clause():
assert UNRESTRICTED.row_hidden_clause() is None
def test_hidden_on_visible_platforms_clause_skips_hidden_platforms():
visibility = RomVisibilityFilter(
hidden_platform_ids=frozenset({5}), hidden_rom_ids=frozenset({99})
)
hidden = visibility.hidden_on_visible_platforms_clause()
assert hidden is not None
assert compile_sql(hidden, MARIADB_DIALECT) == ("roms.id IN (__[POSTCOMPILE_id_1])")
assert (
RomVisibilityFilter(
hidden_platform_ids=frozenset({5})
).hidden_on_visible_platforms_clause()
is None
)
def test_the_hidden_age_clause_is_a_range_per_setting():
def sql(visibility: RomVisibilityFilter) -> str:
hidden = visibility.hidden_on_visible_platforms_clause()
assert hidden is not None
return compile_sql(hidden, MARIADB_DIALECT)
assert sql(RomVisibilityFilter(age_limit=12)) == "roms.min_age > :min_age_1"
assert sql(RomVisibilityFilter(age_limit=12, hide_unrated_roms=True)) == (
"roms.min_age IS NULL OR roms.min_age > :min_age_1"
)
assert sql(RomVisibilityFilter(hide_unrated_roms=True)) == "roms.min_age IS NULL"
def test_admin_permissions_are_unrestricted():
assert _perms(is_admin=True).rom_visibility is UNRESTRICTED
@@ -1,6 +1,9 @@
from tests.factories import make_platform
import pytest
from tests.factories import make_platform, make_rom
from handler.auth.rom_visibility import UNRESTRICTED, RomVisibilityFilter
from handler.database import db_platform_handler
from handler.database.base_handler import sync_session
from models.platform import Platform
@@ -55,3 +58,116 @@ def test_rescan_preserves_user_authored_fields(platform):
assert merged.custom_name == "Sega - Genesis/ Mega Drive (Unofficial)"
assert merged.description == "Aftermarket only"
def _pegi(rating: str) -> dict[str, list[dict[str, str]]]:
return {"age_ratings": [{"category": "PEGI", "rating": rating}]}
PEGI_18 = _pegi("18")
def _totals(platform):
return platform.rom_count, platform.fs_size_bytes
def test_totals_count_only_the_roms_the_visibility_shows():
platform_a = make_platform("platform_a")
platform_b = make_platform("platform_b")
make_rom(platform_a, "a1", fs_size_bytes=10)
hidden = make_rom(platform_a, "a2", fs_size_bytes=5)
make_rom(platform_b, "b1", fs_size_bytes=7)
visibility = RomVisibilityFilter(hidden_rom_ids=frozenset({hidden.id}))
listed = {
p.id: _totals(p)
for p in db_platform_handler.get_platforms(visibility=visibility)
}
detail = db_platform_handler.get_platform(platform_a.id, visibility=visibility)
assert listed[platform_a.id] == (1, 10)
assert listed[platform_b.id] == (1, 7)
assert detail is not None and _totals(detail) == (1, 10)
def test_totals_leave_out_roms_above_the_age_limit():
platform = make_platform("platform_a")
make_rom(platform, "a1", fs_size_bytes=10)
make_rom(platform, "a2", fs_size_bytes=5, igdb_metadata=PEGI_18)
found = db_platform_handler.get_platform(
platform.id, visibility=RomVisibilityFilter(age_limit=16)
)
assert found is not None and _totals(found) == (1, 10)
def test_a_rom_hidden_both_ways_is_left_out_once():
platform = make_platform("platform_a")
make_rom(platform, "a1", fs_size_bytes=10)
hidden = make_rom(platform, "a2", fs_size_bytes=5, igdb_metadata=PEGI_18)
found = db_platform_handler.get_platform(
platform.id,
visibility=RomVisibilityFilter(
hidden_rom_ids=frozenset({hidden.id}), age_limit=16
),
)
assert found is not None and _totals(found) == (1, 10)
def test_a_shared_session_rereads_the_totals():
platform = make_platform("platform_a")
make_rom(platform, "a1", fs_size_bytes=10)
hidden = make_rom(platform, "a2", fs_size_bytes=5)
visibility = RomVisibilityFilter(hidden_rom_ids=frozenset({hidden.id}))
reads = []
with sync_session.begin() as session:
# Each read returns the session's one instance, so take its totals at once.
for read_visibility in (visibility, visibility, UNRESTRICTED):
found = db_platform_handler.get_platform(
platform.id, visibility=read_visibility, session=session
)
assert found is not None
reads.append(_totals(found))
assert reads == [(1, 10), (1, 10), (2, 15)]
def test_totals_are_whole_without_a_visibility():
platform = make_platform("platform_a")
make_rom(platform, "a1", fs_size_bytes=10)
make_rom(platform, "a2", fs_size_bytes=5)
found = db_platform_handler.get_platform(platform.id)
assert found is not None and _totals(found) == (2, 15)
@pytest.mark.parametrize(
"visibility",
[
RomVisibilityFilter(age_limit=12),
RomVisibilityFilter(hide_unrated_roms=True),
RomVisibilityFilter(age_limit=12, hide_unrated_roms=True),
RomVisibilityFilter(age_limit=12, hidden_rom_ids=frozenset({-1})),
],
ids=["limit", "unrated", "limit-and-unrated", "limit-and-hides"],
)
def test_totals_agree_with_the_visibility_rule(visibility: RomVisibilityFilter):
platform = make_platform("platform_a")
roms = [
make_rom(platform, "unrated", fs_size_bytes=1),
make_rom(platform, "pegi3", fs_size_bytes=2, igdb_metadata=_pegi("3")),
make_rom(platform, "pegi12", fs_size_bytes=4, igdb_metadata=_pegi("12")),
make_rom(platform, "pegi18", fs_size_bytes=8, igdb_metadata=_pegi("18")),
]
shown = [rom for rom in roms if visibility.allows(rom)]
found = db_platform_handler.get_platform(platform.id, visibility=visibility)
assert 0 < len(shown) < len(roms)
assert found is not None
assert _totals(found) == (len(shown), sum(rom.fs_size_bytes for rom in shown))
+3
View File
@@ -539,6 +539,7 @@ def test_the_rom_file_title_ids_revision_reverses_and_replays():
def test_the_age_limits_revision_reverses_replays_and_fills(platform: Platform):
"""0148 rates existing ROMs and keeps mirroring the rating into roms_facets."""
migration = _load_migration("0148_rom_age_limits.py")
min_age_index = _load_migration("0156_roms_platform_min_age_index.py")
rated = make_rom(
platform,
"Rated",
@@ -559,6 +560,7 @@ def test_the_age_limits_revision_reverses_replays_and_fills(platform: Platform):
with sync_engine.begin() as connection:
before = {table: _schema_of(connection, table) for table in tables}
with Operations.context(MigrationContext.configure(connection)):
min_age_index.downgrade()
migration.downgrade()
assert not has_column(connection, "roms", "min_age")
assert not has_column(connection, "users", "age_limit")
@@ -566,6 +568,7 @@ def test_the_age_limits_revision_reverses_replays_and_fills(platform: Platform):
migration.upgrade()
migration.upgrade()
min_age_index.upgrade()
assert ages(connection, "roms", "id") == {rated.id: 16, unrated.id: None}
assert ages(connection, "roms_facets", "rom_id") == {
+9 -2
View File
@@ -2,6 +2,7 @@ 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 (
@@ -75,15 +76,21 @@ def _build_unmatched_platform(slug: str, fs_slug: str, now: datetime) -> Platfor
return PlatformSchema.model_validate(Platform(**platform_attrs))
def get_supported_platforms() -> list[PlatformSchema]:
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()
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