mirror of
https://github.com/rommapp/romm.git
synced 2026-11-28 17:48:31 +01:00
* chore(mypy): switch to strict mode with listed exceptions Replace the hand-picked flags with `strict = True`, turning off only the four flags that aren't clean yet (disallow_any_generics, warn_return_any, disallow_untyped_calls, disallow_untyped_decorators). Any other strict flag, including those future mypy releases add to the preset, is on by default. That turns on no_implicit_reexport, strict_equality and extra_checks: - Import each name from the module that defines it. About 240 test sites patched a dependency through the module that imported it (`scan_module.fs_rom_handler`); they now import the same object from its source, so every patch targets what it did before. Tests that replace a module attribute are unchanged. - handler.streaming.memory_cards re-exports store_memory_card_version explicitly, since endpoints call it there and tests patch it there. - mutagen gets implicit_reexport, as it re-exports without __all__. - Test comparisons build typed values (CoverResult, a typed expected dict, enum .value) and the CORS lookup casts for its identity check. - One ss_handler ** spread keeps a coded ignore: extra_checks wants its NotRequired dump_* keys spelled out, and the media dict never has them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * chore(mypy): give every generic its type arguments Drop disallow_any_generics from the strict-mode exceptions and fix the 347 bare generics it reports, 230 of them in app code. - Bare `dict` becomes `dict[str, Any]`: update payloads, raw provider JSON and endpoint bodies map string keys to mixed values, so the Any is real and now written down. The OpenAPI document is unchanged. - Rom query filters take and return RomSelect; _music_facet_joins and _exclude_hidden are generic over the Select they're given, and _build_hash_selects returns id-only selects. - Redis clients are typed by what they return: the decoding caches are Redis[str], the RQ connection and binary cache Redis[bytes]. - The rest get explicit parameters: Row, Pattern, ColumnElement, QueryableAttribute, SpooledTemporaryFile, Task, Future and friends. Precise types reached callers that had been getting Any, which surfaced: - The LaunchBox cache writer is fed binary-cache pipelines. - The flashpoint and IGDB request helpers return raw JSON of varying shape, not always a dict. - The rom search endpoint returned dicts under a list[SearchRomSchema] annotation; it now validates them into that schema. - The audit filter's id subquery selects strings. - In tests the binary cache is the non-decoding fake shared with async_cache, so it is cast to Redis[bytes] rather than changed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * test(upload): assert cleanup against the patched upload directory The 409 test checked config's ROM_UPLOAD_TMP_BASE while the fixture patches the endpoint's copy to tmp_path/uploads, so it passed even if cleanup failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G * chore(mypy): keep the row type through the ROM filter helpers filter_roms and its helpers also receive select(Rom.id) membership queries, so they now take and return the caller's Select type instead of narrowing to RomSelect. merged_ra_metadata mixes scalar and list values. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PLzXae5up2pYXRoBjfjn2G --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
199 lines
6.8 KiB
Python
199 lines
6.8 KiB
Python
from __future__ import annotations
|
|
|
|
from collections.abc import Collection
|
|
from typing import Any
|
|
|
|
from sqlalchemy import distinct, func, select
|
|
from sqlalchemy.orm import InstrumentedAttribute, Session
|
|
from sqlalchemy.sql.selectable import Select
|
|
|
|
from decorators.database import begin_session
|
|
from endpoints.responses.stats import MetadataCoverageItem, RegionBreakdownItem
|
|
from models.assets import Save, Screenshot, State
|
|
from models.rom import METADATA_SOURCE_FACET_COLUMNS, Rom, RomFacets, RomFile
|
|
|
|
from .base_handler import DBBaseHandler
|
|
|
|
|
|
def _exclude_hidden[S: Select[Any]](
|
|
query: S,
|
|
hidden_platform_ids: Collection[int] | None,
|
|
hidden_rom_ids: Collection[int] | None,
|
|
*,
|
|
platform_id_col: InstrumentedAttribute[int] = Rom.platform_id,
|
|
rom_id_col: InstrumentedAttribute[int] = Rom.id,
|
|
) -> S:
|
|
"""Drop rows for platforms/roms hidden from the caller (admins pass None).
|
|
|
|
The platform/rom id columns are overridable so callers reading the narrow
|
|
`roms_facets` mirror can filter on its columns instead of `roms`.
|
|
"""
|
|
if hidden_platform_ids:
|
|
query = query.where(platform_id_col.not_in(hidden_platform_ids))
|
|
if hidden_rom_ids:
|
|
query = query.where(rom_id_col.not_in(hidden_rom_ids))
|
|
return query
|
|
|
|
|
|
class DBStatsHandler(DBBaseHandler):
|
|
@begin_session
|
|
def get_platforms_count(
|
|
self,
|
|
hidden_platform_ids: Collection[int] | None = None,
|
|
hidden_rom_ids: Collection[int] | None = None,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> int:
|
|
"""Get the number of platforms with any roms."""
|
|
query = _exclude_hidden(
|
|
select(func.count(distinct(Rom.platform_id))).select_from(Rom),
|
|
hidden_platform_ids,
|
|
hidden_rom_ids,
|
|
)
|
|
return session.scalar(query) or 0
|
|
|
|
@begin_session
|
|
def get_roms_count(
|
|
self,
|
|
hidden_platform_ids: Collection[int] | None = None,
|
|
hidden_rom_ids: Collection[int] | None = None,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> int:
|
|
query = _exclude_hidden(
|
|
select(func.count()).select_from(Rom),
|
|
hidden_platform_ids,
|
|
hidden_rom_ids,
|
|
)
|
|
return session.scalar(query) or 0
|
|
|
|
@begin_session
|
|
def get_saves_count(
|
|
self,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> int:
|
|
return session.scalar(select(func.count()).select_from(Save)) or 0
|
|
|
|
@begin_session
|
|
def get_states_count(
|
|
self,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> int:
|
|
return session.scalar(select(func.count()).select_from(State)) or 0
|
|
|
|
@begin_session
|
|
def get_screenshots_count(
|
|
self,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> int:
|
|
return session.scalar(select(func.count()).select_from(Screenshot)) or 0
|
|
|
|
@begin_session
|
|
def get_total_filesize(
|
|
self,
|
|
hidden_platform_ids: Collection[int] | None = None,
|
|
hidden_rom_ids: Collection[int] | None = None,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> int:
|
|
"""Get the total filesize of all roms in the database, in bytes."""
|
|
query = select(func.sum(RomFile.file_size_bytes)).select_from(RomFile)
|
|
if hidden_platform_ids or hidden_rom_ids:
|
|
query = _exclude_hidden(
|
|
query.join(Rom), hidden_platform_ids, hidden_rom_ids
|
|
)
|
|
return session.scalar(query) or 0
|
|
|
|
@begin_session
|
|
def get_platform_filesize(
|
|
self,
|
|
platform_id: int,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> int:
|
|
"""Get the total filesize of all roms in the database, in bytes."""
|
|
return (
|
|
session.scalar(
|
|
select(func.sum(RomFile.file_size_bytes))
|
|
.select_from(RomFile)
|
|
.join(Rom)
|
|
.filter(Rom.platform_id == platform_id)
|
|
)
|
|
or 0
|
|
)
|
|
|
|
@begin_session
|
|
def get_metadata_coverage_by_platform(
|
|
self,
|
|
hidden_platform_ids: Collection[int] | None = None,
|
|
hidden_rom_ids: Collection[int] | None = None,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> dict[int, list[MetadataCoverageItem]]:
|
|
"""Get the count of ROMs matched per metadata source, grouped by platform.
|
|
|
|
Aggregates the narrow `roms_facets` mirror instead of `roms`, whose rows
|
|
also carry the raw provider-metadata blobs.
|
|
"""
|
|
rows = session.execute(
|
|
_exclude_hidden(
|
|
select(
|
|
RomFacets.platform_id,
|
|
*(
|
|
func.count(col).label(key)
|
|
for key, col in METADATA_SOURCE_FACET_COLUMNS.items()
|
|
),
|
|
).select_from(RomFacets),
|
|
hidden_platform_ids,
|
|
hidden_rom_ids,
|
|
platform_id_col=RomFacets.platform_id,
|
|
rom_id_col=RomFacets.rom_id,
|
|
).group_by(RomFacets.platform_id)
|
|
).all()
|
|
|
|
result: dict[int, list[MetadataCoverageItem]] = {}
|
|
for row in rows:
|
|
result[row.platform_id] = [
|
|
MetadataCoverageItem(source=key, matched=getattr(row, key))
|
|
for key in METADATA_SOURCE_FACET_COLUMNS
|
|
if getattr(row, key) > 0
|
|
]
|
|
|
|
return result
|
|
|
|
@begin_session
|
|
def get_region_breakdown_by_platform(
|
|
self,
|
|
hidden_platform_ids: Collection[int] | None = None,
|
|
hidden_rom_ids: Collection[int] | None = None,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> dict[int, list[RegionBreakdownItem]]:
|
|
"""Get the count of ROMs per region, grouped by platform.
|
|
|
|
Reads the narrow `roms_facets` mirror rather than scanning `roms`.
|
|
"""
|
|
rows = session.execute(
|
|
_exclude_hidden(
|
|
select(RomFacets.platform_id, RomFacets.regions).where(
|
|
RomFacets.regions.is_not(None)
|
|
),
|
|
hidden_platform_ids,
|
|
hidden_rom_ids,
|
|
platform_id_col=RomFacets.platform_id,
|
|
rom_id_col=RomFacets.rom_id,
|
|
)
|
|
).all()
|
|
|
|
counter: dict[int, dict[str, int]] = {}
|
|
for platform_id, regions_list in rows:
|
|
if regions_list:
|
|
if platform_id not in counter:
|
|
counter[platform_id] = {}
|
|
for region in regions_list:
|
|
counter[platform_id][region] = (
|
|
counter[platform_id].get(region, 0) + 1
|
|
)
|
|
|
|
return {
|
|
pid: [
|
|
{"region": r, "count": c}
|
|
for r, c in sorted(regions.items(), key=lambda x: -x[1])
|
|
]
|
|
for pid, regions in counter.items()
|
|
}
|