Files
romm/backend/models/collection.py
Stu Anderson 0941b3033e feat(roms): load roms by an array of ids (#5663)
* feat(roms): load roms by an array of ids

GET /api/roms accepts up to 256 rom_ids and returns those roms in the
order given. Ids the caller can't see, or that don't exist, are left out.

Closes #5659

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

* fix(roms): code-review pass on rom_ids window

Reuse RomIdScope (dedupe, shared 500 cap), skip sidecar and grouped page
cache reads for a window by id, report offset 0 and the id count as limit,
and rename the shadowed rom_ids local in _transform.

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

* refactor(roms): simplify pass on rom_ids window

Return early for rom_ids before building the filtered query, the sidecars
or any cache key, through a shared _hydrate helper, so the paged path is
back to its prior shape. Tests use the headers fixture.

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

* test(roms): review-polish pass, cover a hidden platform in the rom_ids window

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

* fix(collections): refuse malformed virtual collection ids, require page-row visibility

A malformed virtual_collection_id raised an uncaught decode error (500) on
the gallery, random and bulk download routes. It is now a 422 at the query
boundary, and GET /collections/virtual/{id} answers 404.

get_page_rows_query takes visibility as a required argument, since it is
the access check on caller-supplied rom ids.

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

* feat(gallery): load scroll windows by rom id

Once the bootstrap holds the whole ordered id index, a window fetch sends
that slice as rom_ids, so the backend skips the filtered, offset-paged
query. Items are placed by id, since ids that went missing or hidden are
dropped from the response.

On a 100k-rom MariaDB library, a filtered grouped window went from
0.8-2.0 s to ~50 ms, and a deep ungrouped window from 106 to 50 ms.

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-20 11:12:57 -05:00

280 lines
8.6 KiB
Python

from __future__ import annotations
import base64
import json
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
from config import FRONTEND_RESOURCES_PATH
from models.base import BaseModel
from utils.database import CustomJSON
if TYPE_CHECKING:
from models.rom import Rom
from models.user import User
COLLECTION_NAME_MAX_LENGTH = 400
class Collection(BaseModel):
__tablename__ = "collections"
__table_args__ = (Index("ix_collections_updated_at", "updated_at"),)
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(length=COLLECTION_NAME_MAX_LENGTH))
description: Mapped[str | None] = mapped_column(Text)
is_public: Mapped[bool] = mapped_column(default=False)
is_favorite: Mapped[bool] = mapped_column(default=False)
path_cover_l: Mapped[str | None] = mapped_column(Text, default="")
path_cover_s: Mapped[str | None] = mapped_column(Text, default="")
url_cover: Mapped[str | None] = mapped_column(
Text, default="", doc="URL of cover pulled from metadata providers"
)
roms: Mapped[list["Rom"]] = relationship(
"Rom",
secondary="collections_roms",
collection_class=set,
back_populates="collections",
lazy="raise",
)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
user: Mapped["User"] = relationship(lazy="joined", back_populates="collections")
@property
def owner_username(self) -> str:
return self.user.username
@property
def rom_ids(self) -> list[int]:
return [r.id for r in self.roms]
@property
def rom_count(self) -> int:
return len(self.roms)
@property
def fs_resources_path(self) -> str:
return f"collections/{str(self.id)}"
@property
def path_cover_small(self) -> str | None:
return (
f"{FRONTEND_RESOURCES_PATH}/{self.path_cover_s}?ts={self.updated_at}"
if self.path_cover_s
else None
)
@property
def path_cover_large(self) -> str | None:
return (
f"{FRONTEND_RESOURCES_PATH}/{self.path_cover_l}?ts={self.updated_at}"
if self.path_cover_l
else None
)
@property
def path_covers_small(self) -> list[str]:
return [
f"{FRONTEND_RESOURCES_PATH}/{r.path_cover_s}?ts={self.updated_at}"
for r in self.roms
if r.path_cover_s
]
@property
def path_covers_large(self) -> list[str]:
return [
f"{FRONTEND_RESOURCES_PATH}/{r.path_cover_l}?ts={self.updated_at}"
for r in self.roms
if r.path_cover_l
]
def __repr__(self) -> str:
return self.name
class CollectionRom(BaseModel):
__tablename__ = "collections_roms"
collection_id: Mapped[int] = mapped_column(
ForeignKey("collections.id", ondelete="CASCADE"), primary_key=True
)
rom_id: Mapped[int] = mapped_column(
ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True
)
__table_args__ = (
UniqueConstraint("collection_id", "rom_id", name="unique_collection_rom"),
)
class VirtualCollectionRom(BaseModel):
"""Membership of a rom in a virtual collection, one row per (rom, tag).
Maintained entirely by database triggers on ``roms``, which unnest the
``generated_*`` metadata columns. Reading it is a plain indexed lookup, so
neither the collection list nor a single collection has to re-derive
anything from raw provider metadata.
"""
__tablename__ = "virtual_collection_roms"
__table_args__ = (Index("idx_virtual_collection_roms_rom_id", "rom_id"),)
type: Mapped[str] = mapped_column(String(length=50), primary_key=True)
name: Mapped[str] = mapped_column(String(length=400), primary_key=True)
rom_id: Mapped[int] = mapped_column(
ForeignKey("roms.id", ondelete="CASCADE"), primary_key=True
)
# Denormalized so the collection list never has to touch the roms table.
path_cover_s: Mapped[str | None] = mapped_column(Text, default="")
path_cover_l: Mapped[str | None] = mapped_column(Text, default="")
class VirtualCollection(BaseModel):
__tablename__ = "virtual_collections"
# path_covers_* below are plain attributes, not columns of the view.
__allow_unmapped__ = True
name: Mapped[str] = mapped_column(String(length=400), primary_key=True)
type: Mapped[str] = mapped_column(String(length=50), primary_key=True)
description: Mapped[str | None] = mapped_column(Text)
rom_ids: Mapped[set[int]] = mapped_column(
CustomJSON(), default=[], doc="Rom IDs that belong to this collection"
)
# Resolved by the collections handler, capped at MAX_VIRTUAL_COLLECTION_COVERS.
# Aggregating every member's cover in the view costs megabytes per request on
# a large library, and the UI only ever renders a handful.
path_covers_s: list[str] = []
path_covers_l: list[str] = []
@property
def id(self) -> str:
# Create a reversible encoded ID
data = json.dumps({"name": self.name, "type": self.type})
return base64.urlsafe_b64encode(data.encode()).decode()
@classmethod
def from_id(cls, id_: str) -> tuple[str, str]:
"""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:
return len(self.rom_ids)
@property
def path_cover_small(self) -> str | None:
return None
@property
def path_cover_large(self) -> str | None:
return None
@property
def path_covers_small(self) -> list[str]:
return [
f"{FRONTEND_RESOURCES_PATH}/{cover}?ts={self.updated_at}"
for cover in self.path_covers_s
if cover
]
@property
def path_covers_large(self) -> list[str]:
return [
f"{FRONTEND_RESOURCES_PATH}/{cover}?ts={self.updated_at}"
for cover in self.path_covers_l
if cover
]
__table_args__ = (
UniqueConstraint(
"name",
"type",
name="unique_virtual_collection_name_type",
),
)
SMART_COLLECTION_MAX_COVERS = 5
class SmartCollection(BaseModel):
__tablename__ = "smart_collections"
__table_args__ = (Index("ix_smart_collections_updated_at", "updated_at"),)
id: Mapped[int] = mapped_column(primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(length=COLLECTION_NAME_MAX_LENGTH))
description: Mapped[str | None] = mapped_column(Text)
is_public: Mapped[bool] = mapped_column(default=False)
rom_ids: Mapped[list[int]] = mapped_column(
CustomJSON(), default=[], doc="Rom IDs that belong to this smart collection"
)
path_covers_small: Mapped[list[str]] = mapped_column(CustomJSON(), default=[])
path_covers_large: Mapped[list[str]] = mapped_column(CustomJSON(), default=[])
filter_criteria: Mapped[dict[str, Any]] = mapped_column(
CustomJSON(),
default=dict,
doc="JSON object containing all filter criteria for the smart collection",
)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"))
user: Mapped["User"] = relationship(
lazy="joined", back_populates="smart_collections"
)
@property
def owner_username(self) -> str:
return self.user.username
@property
def rom_count(self) -> int:
return len(self.rom_ids)
@property
def path_cover_small(self) -> str | None:
return None
@property
def path_cover_large(self) -> str | None:
return None
@property
def filter_summary(self) -> str:
return json.dumps(self.filter_criteria)
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)
]