diff --git a/backend/endpoints/roms/__init__.py b/backend/endpoints/roms/__init__.py index 388906a42..91baa3444 100644 --- a/backend/endpoints/roms/__init__.py +++ b/backend/endpoints/roms/__init__.py @@ -41,6 +41,7 @@ from pydantic import ( ) from pydantic import ValidationError as PydanticValidationError from sqlalchemy.exc import IntegrityError +from sqlalchemy.orm import Session from starlette.responses import FileResponse from adapters.services.sigil import SWITCH_PLATFORM_SLUGS @@ -145,7 +146,12 @@ from logger.formatter import BLUE from logger.formatter import highlight as hl from logger.logger import log from models.audit_event import AuditAction, AuditTargetType -from models.collection import Collection, SmartCollection, VirtualCollection +from models.collection import ( + Collection, + SmartCollection, + VirtualCollection, + VirtualCollectionId, +) from models.permission import PermAction, PermEntity from models.rom import ( HAS_FILE_ON_DISK_FILTERS, @@ -186,6 +192,8 @@ from utils.nginx import ( from utils.router import APIRouter, as_query_dependency from utils.screenshots import continue_playing_screenshot from utils.validation import ( + MAX_ROM_IDS_PER_QUERY, + RomIdScope, ValidationError, dedupe_in_order, parse_comma_separated_ids, @@ -791,9 +799,111 @@ def get_roms( bool, Query(description="Whether to include each rom's file entries."), ] = False, + rom_ids: Annotated[ + RomIdScope, + Query( + description=( + "Load exactly these roms, in this order, instead of a page." + f" Repeat the parameter, up to {MAX_ROM_IDS_PER_QUERY} ids. Ids" + " the caller can't see, or that no longer exist, are left out." + " Filters don't narrow the result, the sidecars and the total" + " are skipped, and `offset` and `limit` come back as 0 and the" + " id count." + ), + ), + ] = None, ) -> CustomLimitOffsetPage[SimpleRomSchema]: - """Retrieve roms.""" + """Retrieve a page of roms, or the roms named by `rom_ids`.""" perms = get_permissions(request) + + def _transform(session: Session, items: Sequence[Rom]) -> list[SimpleRomSchema]: + item_ids = [i.id for i in items] + files_by_rom = ( + db_rom_handler.get_files_for_roms(item_ids, session=session) + if with_files + else {} + ) + siblings_by_rom = db_rom_handler.get_siblings_for_roms( + item_ids, + user_id=request.user.id, + session=session, + visibility=perms.rom_visibility, + ) + rom_ids_with_notes = db_rom_handler.get_rom_ids_with_notes( + item_ids, user_id=request.user.id, session=session + ) + if with_files: + for item in items: + apply_file_stats(item, files_by_rom.get(item.id, [])) + + # Continue-playing rail + screenshot_by_rom: dict[int, str | None] = {} + if filters.last_played: + latest_saves = db_save_handler.get_latest_saves_for_roms( + user_id=request.user.id, rom_ids=item_ids, session=session + ) + for item in items: + screenshot_by_rom[item.id] = continue_playing_screenshot( + item, latest_saves.get(item.id) + ) + + return [ + SimpleRomSchema.from_orm_with_request( + db_rom=item, + request=request, + files=files_by_rom.get(item.id, []), + siblings=siblings_by_rom.get(item.id, []), + screenshot_path=screenshot_by_rom.get(item.id), + has_notes=item.id in rom_ids_with_notes, + with_provider_metadata=with_provider_metadata, + ) + for item in items + ] + + def _hydrate(session: Session, page_ids: list[int]) -> list[SimpleRomSchema]: + if not page_ids: + return [] + # The access check on caller-supplied ids; paged ids already passed the + # filters and the sibling grouping, so neither is re-run. + page_rows = session.scalars( + db_rom_handler.get_page_rows_query( + page_ids, + visibility=perms.rom_visibility, + include_file_stats=not with_files, + ) + ).all() + rows_by_id = {rom.id: rom for rom in page_rows} + return _transform(session, [rows_by_id[i] for i in page_ids if i in rows_by_id]) + + empty_filter_values = RomFiltersDict( + genres=[], + franchises=[], + collections=[], + companies=[], + publishers=[], + developers=[], + game_modes=[], + age_ratings=[], + player_counts=[], + regions=[], + languages=[], + tags=[], + platforms=[], + ) + + if rom_ids is not None: + # The caller already holds the ordered list, so nothing spans the set. + with sync_session.begin() as session: + return CustomLimitOffsetPage( + items=_hydrate(session, rom_ids), + total=None, + limit=len(rom_ids), + offset=0, + char_index={}, + rom_id_index=[], + filter_values=empty_filter_values, + ) + parsed_released_days = parse_released_days(released_days) # Normalised once so the query layer and every cache key agree on case. @@ -870,21 +980,7 @@ def get_roms( ) char_index_dict = {char: index for (char, index) in char_index} - filter_values = RomFiltersDict( - genres=[], - franchises=[], - collections=[], - companies=[], - publishers=[], - developers=[], - game_modes=[], - age_ratings=[], - player_counts=[], - regions=[], - languages=[], - tags=[], - platforms=[], - ) + filter_values = empty_filter_values if with_filter_values: # We use the unfiltered query so applied filters don't affect the list filter_query = db_rom_handler.filter_roms( @@ -928,50 +1024,6 @@ def get_roms( # Hydrate the requested page and its additional data with sync_session.begin() as session: - def _transform(items: Sequence[Rom]) -> list[SimpleRomSchema]: - rom_ids = [i.id for i in items] - files_by_rom = ( - db_rom_handler.get_files_for_roms(rom_ids, session=session) - if with_files - else {} - ) - siblings_by_rom = db_rom_handler.get_siblings_for_roms( - rom_ids, - user_id=request.user.id, - session=session, - visibility=perms.rom_visibility, - ) - rom_ids_with_notes = db_rom_handler.get_rom_ids_with_notes( - rom_ids, user_id=request.user.id, session=session - ) - if with_files: - for item in items: - apply_file_stats(item, files_by_rom.get(item.id, [])) - - # Continue-playing rail - screenshot_by_rom: dict[int, str | None] = {} - if filters.last_played: - latest_saves = db_save_handler.get_latest_saves_for_roms( - user_id=request.user.id, rom_ids=rom_ids, session=session - ) - for item in items: - screenshot_by_rom[item.id] = continue_playing_screenshot( - item, latest_saves.get(item.id) - ) - - return [ - SimpleRomSchema.from_orm_with_request( - db_rom=item, - request=request, - files=files_by_rom.get(item.id, []), - siblings=siblings_by_rom.get(item.id, []), - screenshot_path=screenshot_by_rom.get(item.id), - has_notes=item.id in rom_ids_with_notes, - with_provider_metadata=with_provider_metadata, - ) - for item in items - ] - def resolve_total() -> int | None: if with_rom_id_index: # The index already spans the result set, so the count is free. @@ -998,23 +1050,8 @@ def get_roms( ).all() ) - if page_ids: - # The ids already passed the filters and the sibling grouping, so the - # rows load without re-running either. - page_rows = session.scalars( - db_rom_handler.get_page_rows_query( - page_ids, - visibility=perms.rom_visibility, - include_file_stats=not with_files, - ) - ).all() - rows_by_id = {rom.id: rom for rom in page_rows} - page_items = [rows_by_id[i] for i in page_ids if i in rows_by_id] - else: - page_items = [] - return CustomLimitOffsetPage( - items=_transform(page_items), + items=_hydrate(session, page_ids), total=resolve_total(), limit=params.limit, offset=params.offset, @@ -1053,7 +1090,7 @@ def get_random_rom( Query(description="Collection internal id.", ge=1), ] = None, virtual_collection_id: Annotated[ - str | None, + VirtualCollectionId, Query(description="Virtual collection internal id."), ] = None, smart_collection_id: Annotated[ @@ -1148,7 +1185,7 @@ async def download_roms( Query(description="Download every ROM in this collection as a zip file.", ge=1), ] = None, virtual_collection_id: Annotated[ - str | None, + VirtualCollectionId, Query( description="Download every ROM in this virtual collection as a zip file.", ), diff --git a/backend/handler/database/collections_handler.py b/backend/handler/database/collections_handler.py index 2b5a44e4f..b18e83f59 100644 --- a/backend/handler/database/collections_handler.py +++ b/backend/handler/database/collections_handler.py @@ -394,7 +394,10 @@ class DBCollectionsHandler(DBBaseHandler): visibility: RomVisibilityFilter = UNRESTRICTED, session: Session = INJECTED_SESSION, ) -> VirtualCollection | None: - name, type = VirtualCollection.from_id(id) + try: + name, type = VirtualCollection.from_id(id) + except ValueError: + return None collection = session.scalar( select(VirtualCollection).filter_by(name=name, type=type).limit(1) ) diff --git a/backend/handler/database/rom_filters.py b/backend/handler/database/rom_filters.py index e2ea1185a..50ff4a054 100644 --- a/backend/handler/database/rom_filters.py +++ b/backend/handler/database/rom_filters.py @@ -20,6 +20,7 @@ from pydantic import BaseModel, Field, ValidationError from sqlalchemy.orm import QueryableAttribute from logger.logger import log +from models.collection import VirtualCollectionId from models.rom import RomFacets @@ -135,7 +136,7 @@ class RomFilterParams(BaseModel): Field(description="Collection internal id.", ge=1), ] = None virtual_collection_id: Annotated[ - str | None, + VirtualCollectionId, Field(description="Virtual collection internal id."), ] = None smart_collection_id: Annotated[ diff --git a/backend/handler/database/roms_handler.py b/backend/handler/database/roms_handler.py index f19d89acc..d11f1b965 100644 --- a/backend/handler/database/roms_handler.py +++ b/backend/handler/database/roms_handler.py @@ -1982,11 +1982,12 @@ class DBRomsHandler(DBBaseHandler): self, page_ids: Sequence[int], *, - visibility: RomVisibilityFilter = UNRESTRICTED, + visibility: RomVisibilityFilter, include_file_stats: bool = False, ) -> RomSelect: """The rows of one page, loaded by id with none of the filters re-run.""" - # Visibility is re-checked in case a cached id index predates a rule change. + # The only access check on caller-supplied ids, and it also catches a + # cached id index that predates a rule change. return ( select(Rom) .where(Rom.id.in_(page_ids), *visibility.clauses()) diff --git a/backend/models/collection.py b/backend/models/collection.py index 34ab19186..39f8761d0 100644 --- a/backend/models/collection.py +++ b/backend/models/collection.py @@ -2,8 +2,9 @@ from __future__ import annotations import base64 import json -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Annotated, Any +from pydantic import AfterValidator from sqlalchemy import ForeignKey, Index, String, Text, UniqueConstraint from sqlalchemy.orm import Mapped, mapped_column, relationship @@ -165,8 +166,15 @@ class VirtualCollection(BaseModel): @classmethod def from_id(cls, id_: str) -> tuple[str, str]: - data = json.loads(base64.urlsafe_b64decode(id_).decode()) - return data["name"], data["type"] + """Decode an id into its name and type, raising ValueError when malformed.""" + try: + data = json.loads(base64.urlsafe_b64decode(id_).decode()) + name, type_ = data["name"], data["type"] + except (ValueError, TypeError, KeyError) as exc: + raise ValueError(f"Invalid virtual collection id: {id_!r}") from exc + if not isinstance(name, str) or not isinstance(type_, str): + raise ValueError(f"Invalid virtual collection id: {id_!r}") + return name, type_ @property def rom_count(self) -> int: @@ -257,3 +265,15 @@ class SmartCollection(BaseModel): def __repr__(self) -> str: return self.name + + +def _validate_virtual_collection_id(id_: str | None) -> str | None: + if id_ is not None: + VirtualCollection.from_id(id_) + return id_ + + +# A request parameter naming a virtual collection; a malformed id is a 422. +VirtualCollectionId = Annotated[ + str | None, AfterValidator(_validate_virtual_collection_id) +] diff --git a/backend/tests/endpoints/roms/test_rom_window_by_id.py b/backend/tests/endpoints/roms/test_rom_window_by_id.py new file mode 100644 index 000000000..48fde1339 --- /dev/null +++ b/backend/tests/endpoints/roms/test_rom_window_by_id.py @@ -0,0 +1,201 @@ +from typing import Any, cast + +import pytest +from fastapi import status +from fastapi.testclient import TestClient +from tests.auth_helpers import hide, user_headers +from tests.factories import make_platform, make_rom + +from handler.database import db_rom_handler +from models.permission import PermEntity +from models.platform import Platform +from models.user import User +from utils.validation import MAX_ROM_IDS_PER_QUERY + + +def _get( + client: TestClient, headers: dict[str, str], **params: Any +) -> tuple[int, dict[str, Any]]: + response = client.get("/api/roms", headers=headers, params=params) + return response.status_code, cast(dict[str, Any], response.json()) + + +def _ids(page: dict[str, Any]) -> list[int]: + return [item["id"] for item in page["items"]] + + +def test_a_window_by_id_keeps_the_order_given( + client: TestClient, headers: dict[str, str], platform: Platform +): + # Arrange + roms = [make_rom(platform, name) for name in ("alpha", "bravo", "charlie")] + wanted = [roms[2].id, roms[0].id, roms[1].id] + + # Act + code, page = _get(client, headers, rom_ids=wanted) + + # Assert + assert code == status.HTTP_200_OK + assert _ids(page) == wanted + assert page["total"] is None + assert page["rom_id_index"] == [] + assert page["char_index"] == {} + assert (page["offset"], page["limit"]) == (0, len(wanted)) + + +def test_a_repeated_id_is_loaded_once( + client: TestClient, headers: dict[str, str], platform: Platform +): + # Arrange + first, second = make_rom(platform, "india"), make_rom(platform, "juliett") + + # Act + _, page = _get( + client, + headers, + rom_ids=[second.id, first.id, second.id], + ) + + # Assert + assert _ids(page) == [second.id, first.id] + + +def test_a_window_by_id_skips_the_grouped_page_cache( + client: TestClient, + headers: dict[str, str], + platform: Platform, + monkeypatch: pytest.MonkeyPatch, +): + # Arrange + rom = make_rom(platform, "kilo") + calls: list[str] = [] + monkeypatch.setattr( + db_rom_handler, + "get_cached_rom_id_page", + lambda *args: calls.append("page"), + ) + + # Act + _, page = _get( + client, + headers, + rom_ids=[rom.id], + group_by_meta_id="true", + ) + + # Assert + assert _ids(page) == [rom.id] + assert calls == [] + + +def test_a_window_by_id_matches_the_window_by_offset( + client: TestClient, headers: dict[str, str], platform: Platform +): + # Arrange + for name in ("delta", "echo", "foxtrot", "golf", "hotel"): + make_rom(platform, name) + _, first = _get(client, headers, order_by="name", limit=72) + window = first["rom_id_index"][1:4] + + # Act + _, by_offset = _get( + client, + headers, + order_by="name", + offset=1, + limit=3, + with_rom_id_index="false", + with_total="false", + ) + _, by_id = _get(client, headers, order_by="name", rom_ids=window) + + # Assert + assert _ids(by_offset) == window + assert _ids(by_id) == window + + +def test_a_hidden_rom_is_left_out_of_a_window_by_id( + client: TestClient, viewer_user: User, platform: Platform +): + # Arrange + shown = make_rom(platform, "shown") + hidden = make_rom(platform, "hidden") + hide(PermEntity.ROMS, hidden.id, user_id=viewer_user.id) + + # Act + code, page = _get(client, user_headers(viewer_user), rom_ids=[hidden.id, shown.id]) + + # Assert + assert code == status.HTTP_200_OK + assert _ids(page) == [shown.id] + + +def test_a_rom_on_a_hidden_platform_is_left_out_of_a_window_by_id( + client: TestClient, viewer_user: User, platform: Platform +): + # Arrange + shown = make_rom(platform, "shown") + hidden_platform = make_platform("hidden-platform") + hidden = make_rom(hidden_platform, "hidden") + hide(PermEntity.PLATFORMS, hidden_platform.id, user_id=viewer_user.id) + + # Act + _, page = _get(client, user_headers(viewer_user), rom_ids=[hidden.id, shown.id]) + + # Assert + assert _ids(page) == [shown.id] + + +def test_a_deleted_rom_is_left_out_of_a_window_by_id( + client: TestClient, headers: dict[str, str], platform: Platform +): + # Arrange + kept = make_rom(platform, "kept") + gone = make_rom(platform, "gone") + db_rom_handler.delete_rom(gone.id) + + # Act + _, page = _get( + client, + headers, + rom_ids=[gone.id, kept.id], + ) + + # Assert + assert _ids(page) == [kept.id] + + +def test_the_window_holds_up_to_the_cap_whatever_the_limit( + client: TestClient, headers: dict[str, str], platform: Platform +): + # Arrange + rom = make_rom(platform, "only") + wanted = [rom.id, *range(10_000_000, 10_000_000 + MAX_ROM_IDS_PER_QUERY - 1)] + + # Act + code, page = _get(client, headers, rom_ids=wanted, limit=2) + + # Assert + assert code == status.HTTP_200_OK + assert _ids(page) == [rom.id] + + +@pytest.mark.parametrize( + "rom_ids", + [ + list(range(1, MAX_ROM_IDS_PER_QUERY + 2)), + [0], + [-5], + ["abc"], + ], + ids=["over the cap", "zero", "negative", "not a number"], +) +def test_an_invalid_window_is_refused( + client: TestClient, headers: dict[str, str], rom_ids: list[Any] +): + # Act + code, body = _get(client, headers, rom_ids=rom_ids) + + # Assert + assert code == status.HTTP_422_UNPROCESSABLE_CONTENT + assert any("rom_ids" in error["loc"] for error in body["detail"]) diff --git a/backend/tests/endpoints/test_virtual_collection_id.py b/backend/tests/endpoints/test_virtual_collection_id.py new file mode 100644 index 000000000..b9a2dcb91 --- /dev/null +++ b/backend/tests/endpoints/test_virtual_collection_id.py @@ -0,0 +1,31 @@ +import pytest +from fastapi import status +from fastapi.testclient import TestClient + +MALFORMED_ID = "!!!" + + +@pytest.mark.parametrize( + "path", + ["/api/roms", "/api/roms/random", "/api/roms/download"], + ids=["gallery", "random", "bulk download"], +) +def test_a_malformed_virtual_collection_id_is_refused( + client: TestClient, headers: dict[str, str], path: str +): + response = client.get( + path, headers=headers, params={"virtual_collection_id": MALFORMED_ID} + ) + + assert response.status_code == status.HTTP_422_UNPROCESSABLE_CONTENT + assert any( + "virtual_collection_id" in error["loc"] for error in response.json()["detail"] + ) + + +def test_a_malformed_virtual_collection_is_not_found( + client: TestClient, headers: dict[str, str] +): + response = client.get(f"/api/collections/virtual/{MALFORMED_ID}", headers=headers) + + assert response.status_code == status.HTTP_404_NOT_FOUND diff --git a/backend/tests/handler/database/test_roms_page_rows_query.py b/backend/tests/handler/database/test_roms_page_rows_query.py index 775d483ef..ed07d9a98 100644 --- a/backend/tests/handler/database/test_roms_page_rows_query.py +++ b/backend/tests/handler/database/test_roms_page_rows_query.py @@ -6,7 +6,7 @@ from sqlalchemy import Select from tests.conftest import engine # noqa: F401 (loads the test database setup) from tests.sql_dialects import POSTGRESQL_DIALECT, compile_sql -from handler.auth.rom_visibility import RomVisibilityFilter +from handler.auth.rom_visibility import UNRESTRICTED, RomVisibilityFilter from handler.database import db_rom_handler from handler.database.rom_filters import RomFilterParams @@ -32,17 +32,21 @@ def test_the_grouped_query_does_rank_the_library(): def test_loading_a_page_does_not_rank_the_library(): - assert "row_number()" not in _sql(db_rom_handler.get_page_rows_query(PAGE_IDS)) + assert "row_number()" not in _sql( + db_rom_handler.get_page_rows_query(PAGE_IDS, visibility=UNRESTRICTED) + ) def test_loading_a_page_is_limited_to_its_ids(): assert "roms.id in (11, 22, 33)" in _sql( - db_rom_handler.get_page_rows_query(PAGE_IDS) + db_rom_handler.get_page_rows_query(PAGE_IDS, visibility=UNRESTRICTED) ) def test_loading_a_page_does_not_refilter_on_rom_user(): - assert "rom_user" not in _sql(db_rom_handler.get_page_rows_query(PAGE_IDS)) + assert "rom_user" not in _sql( + db_rom_handler.get_page_rows_query(PAGE_IDS, visibility=UNRESTRICTED) + ) def test_loading_a_page_keeps_the_visibility_filter(): @@ -54,5 +58,7 @@ def test_loading_a_page_keeps_the_visibility_filter(): def test_loading_a_page_keeps_the_file_stats_the_serializer_reads(): assert "rom_files" in _sql( - db_rom_handler.get_page_rows_query(PAGE_IDS, include_file_stats=True) + db_rom_handler.get_page_rows_query( + PAGE_IDS, visibility=UNRESTRICTED, include_file_stats=True + ) ) diff --git a/backend/tests/models/test_collection.py b/backend/tests/models/test_collection.py new file mode 100644 index 000000000..6bbcefb32 --- /dev/null +++ b/backend/tests/models/test_collection.py @@ -0,0 +1,39 @@ +import base64 + +import pytest + +from models.collection import VirtualCollection + + +def _encode(raw: str) -> str: + return base64.urlsafe_b64encode(raw.encode()).decode() + + +def test_from_id_decodes_an_encoded_id(): + collection = VirtualCollection(name="Racing", type="genre") + + assert VirtualCollection.from_id(collection.id) == ("Racing", "genre") + + +@pytest.mark.parametrize( + "id_", + [ + "!!!", + _encode("not json"), + _encode("[]"), + _encode('{"name": "Racing"}'), + _encode('{"name": 1, "type": "genre"}'), + "\udcff", + ], + ids=[ + "not base64", + "not json", + "not an object", + "missing type", + "non-string name", + "not ascii", + ], +) +def test_from_id_refuses_a_malformed_id(id_: str): + with pytest.raises(ValueError, match="Invalid virtual collection id"): + VirtualCollection.from_id(id_) diff --git a/frontend/src/services/api/rom.test.ts b/frontend/src/services/api/rom.test.ts index 5b7978ef1..919c497ae 100644 --- a/frontend/src/services/api/rom.test.ts +++ b/frontend/src/services/api/rom.test.ts @@ -214,3 +214,22 @@ describe("getRoms game-length range", () => { expect(params.hltb_main_story_max).toBe(36000); }); }); + +describe("getRoms by id", () => { + beforeEach(() => { + get.mockReset(); + get.mockResolvedValue({ data: {} }); + }); + + it("sends the ids in order", async () => { + await romApi.getRoms({ romIds: [5, 3, 9] }); + + expect(get.mock.calls[0]![1].params.rom_ids).toEqual([5, 3, 9]); + }); + + it("leaves rom_ids out of a paged request", async () => { + await romApi.getRoms({ offset: 72 }); + + expect(get.mock.calls[0]![1].params.rom_ids).toBeUndefined(); + }); +}); diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index bee344ebc..494a45103 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -233,6 +233,9 @@ export interface GetRomsParams { withFilterValues?: boolean; withRomIdIndex?: boolean; withTotal?: boolean; + /** Load exactly these roms, in this order; the backend skips the filtered + * query, the sidecars and the total. */ + romIds?: number[] | null; // Cancel an in-flight request signal?: AbortSignal; } @@ -295,6 +298,7 @@ export function buildGetRomsQuery({ withFilterValues = undefined, withRomIdIndex = undefined, withTotal = undefined, + romIds = null, }: Omit) { return { platform_ids: @@ -436,6 +440,7 @@ export function buildGetRomsQuery({ ? { with_rom_id_index: withRomIdIndex } : {}), ...(withTotal !== undefined ? { with_total: withTotal } : {}), + rom_ids: romIds && romIds.length > 0 ? romIds : undefined, }; } diff --git a/frontend/src/stores/galleryRoms.test.ts b/frontend/src/stores/galleryRoms.test.ts index 7e8fdfc5a..19c5db07e 100644 --- a/frontend/src/stores/galleryRoms.test.ts +++ b/frontend/src/stores/galleryRoms.test.ts @@ -318,6 +318,63 @@ describe("galleryRoms windowed fetch", () => { expect(store.total).toBe(300); }); + it("loads a window by id once the bootstrap holds the whole id index", async () => { + const index = Array.from({ length: 150 }, (_, i) => 1000 + i); + getRoms.mockImplementation( + (params: { limit?: number; romIds?: number[] }) => { + if (params.limit === 1) { + return Promise.resolve({ + data: { + total: 150, + items: [], + char_index: {}, + rom_id_index: index, + }, + }); + } + // The second id of the window went missing since the index was built. + const ids = (params.romIds ?? []).filter((id) => id !== index[73]); + return Promise.resolve( + windowResponse( + null, + ids.map((id) => romFixture({ id })), + ), + ); + }, + ); + const store = storeGalleryRoms(); + + await store.fetchInitialMetadata(); + store.syncVisibleWindows([72]); + await flushPromises(); + + const windowCall = getRoms.mock.calls.find((c) => c[0].romIds); + expect(windowCall?.[0].romIds).toEqual(index.slice(72, 144)); + expect(store.byPosition.get(72)?.id).toBe(index[72]); + expect(store.byPosition.has(73)).toBe(false); + expect(store.byPosition.get(74)?.id).toBe(index[74]); + }); + + it("pages by offset when the id index doesn't cover the result", async () => { + getRoms.mockImplementation((params: { limit?: number }) => + Promise.resolve( + params.limit === 1 + ? { + data: { total: 500, items: [], char_index: {}, rom_id_index: [] }, + } + : windowResponse(null), + ), + ); + const store = storeGalleryRoms(); + + await store.fetchInitialMetadata(); + store.syncVisibleWindows([72]); + await flushPromises(); + + const windowCall = getRoms.mock.calls.find((c) => c[0].offset === 72); + expect(windowCall?.[0].romIds).toBeUndefined(); + }); + it("does not mark a window loaded when the context is invalidated mid-apply", async () => { // Controllable frame yield so we can interleave a context switch between // the batched-apply's frames. diff --git a/frontend/src/stores/galleryRoms.ts b/frontend/src/stores/galleryRoms.ts index c97e2cfdf..7004b4fc9 100644 --- a/frontend/src/stores/galleryRoms.ts +++ b/frontend/src/stores/galleryRoms.ts @@ -184,20 +184,35 @@ function nextFrame(): Promise { async function applyItemsBatched( byPosition: Map, - items: SimpleRom[], - baseOffset: number, + entries: [position: number, rom: SimpleRom][], isStillRelevant: () => boolean, ): Promise { - for (let i = 0; i < items.length; i += APPLY_BATCH_SIZE) { + for (let i = 0; i < entries.length; i += APPLY_BATCH_SIZE) { if (!isStillRelevant()) return; - const end = Math.min(i + APPLY_BATCH_SIZE, items.length); + const end = Math.min(i + APPLY_BATCH_SIZE, entries.length); for (let j = i; j < end; j++) { - byPosition.set(baseOffset + j, items[j]!); + const [position, rom] = entries[j]!; + byPosition.set(position, rom); } - if (end < items.length) await nextFrame(); + if (end < entries.length) await nextFrame(); } } +/** Pair each rom of a window fetched by id with its position in the index. + * The backend drops ids that went missing or hidden since the index was + * built, so the response can't be placed by sequence. */ +export function placeById( + items: SimpleRom[], + ids: number[], + baseOffset: number, +): [number, SimpleRom][] { + const positionOf = new Map(ids.map((id, i) => [id, baseOffset + i])); + return items.flatMap((rom): [number, SimpleRom][] => { + const position = positionOf.get(rom.id); + return position === undefined ? [] : [[position, rom]]; + }); +} + /** Which whole-library sidecars a bootstrap asks the backend to compute. * Each one is a scan over the full result set, so a surface that renders * none of them (the Settings "Missing" tab: no filter drawer, no AlphaStrip, @@ -703,11 +718,20 @@ export default defineStore("v2GalleryRoms", { // another name for a total the bootstrap already gave us, so opt out of // that too and keep the window fetch to just its page of covers. const withAggregations = !this.metadataLoaded; + // With the whole ordered index in hand, a window loads by id and the + // backend skips the filtered, offset-paged query. + const windowIds = + !withAggregations && + this.romIdIndex.length > 0 && + this.romIdIndex.length === this.total + ? this.romIdIndex.slice(offset, offset + WINDOW_SIZE) + : null; try { const response = await romApi.getRoms({ ...params, ...(withAggregations ? {} : SKIP_AGGREGATES), + ...(windowIds ? { romIds: windowIds } : {}), signal: controller.signal, }); // Re-check identity: invalidateWindows / resetGallery / a context @@ -746,8 +770,12 @@ export default defineStore("v2GalleryRoms", { // row (8 items) so input dispatches between paints. await applyItemsBatched( this.byPosition, - data.items, - offset, + windowIds + ? placeById(data.items, windowIds, offset) + : data.items.map((rom, i): [number, SimpleRom] => [ + offset + i, + rom, + ]), () => inFlightControllers.get(ctrlKey) === controller, );