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>
165 lines
6.1 KiB
Python
165 lines
6.1 KiB
Python
from collections.abc import Collection, Sequence
|
|
from dataclasses import dataclass, field
|
|
from datetime import datetime
|
|
|
|
from sqlalchemy import ColumnElement, Select, String, cast, delete, func, or_, select
|
|
from sqlalchemy.orm import Session, joinedload
|
|
from sqlalchemy.orm.interfaces import LoaderOption
|
|
|
|
from decorators.database import begin_session
|
|
from models.audit_event import AuditCategory, AuditEvent, actions_in
|
|
from models.device import Device
|
|
from models.rom import Rom
|
|
from models.user import User
|
|
from utils.database import LIKE_ESCAPE_CHAR, escape_like
|
|
|
|
from .base_handler import DBBaseHandler, affected_rows
|
|
|
|
|
|
def _with_actor() -> LoaderOption:
|
|
# Name and avatar only, the rest of a user row is large JSON.
|
|
return joinedload(AuditEvent.actor).load_only(
|
|
User.id, User.username, User.avatar_path, User.updated_at
|
|
)
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class AuditEventFilters:
|
|
actor_ids: Collection[int] | None = None
|
|
actions: Collection[str] | None = None
|
|
# Narrows `actions`, or stands for them when none are given.
|
|
categories: Collection[AuditCategory] | None = None
|
|
target_type: str | None = None
|
|
target_id: str | None = None
|
|
since: datetime | None = None
|
|
until: datetime | None = None
|
|
# Pins a paged read to the rows that existed when its first page was fetched.
|
|
max_id: int | None = None
|
|
search: str | None = None
|
|
hidden_rom_ids: Collection[int] = field(default_factory=frozenset)
|
|
hidden_platform_ids: Collection[int] = field(default_factory=frozenset)
|
|
|
|
|
|
def _not_targeting(
|
|
target_type: str, ids: Collection[int] | Select[tuple[str]]
|
|
) -> ColumnElement[bool]:
|
|
"""Events other than those on the given targets of one type."""
|
|
excluded = ids if isinstance(ids, Select) else [str(i) for i in ids]
|
|
return or_(
|
|
AuditEvent.target_type.is_(None),
|
|
AuditEvent.target_type != target_type,
|
|
AuditEvent.target_id.is_(None),
|
|
AuditEvent.target_id.not_in(excluded),
|
|
)
|
|
|
|
|
|
class DBAuditEventsHandler(DBBaseHandler):
|
|
@begin_session
|
|
def add_events(
|
|
self,
|
|
events: Sequence[AuditEvent],
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> None:
|
|
session.add_all(events)
|
|
|
|
@begin_session
|
|
def get_events(
|
|
self,
|
|
filters: AuditEventFilters,
|
|
limit: int,
|
|
offset: int,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> tuple[list[tuple[AuditEvent, str | None]], int, int | None]:
|
|
"""A page of events, newest first, each with its device's name, the total,
|
|
and the highest id among the matches for later pages to be pinned to."""
|
|
clauses: list[ColumnElement[bool]] = []
|
|
if filters.actor_ids is not None:
|
|
clauses.append(AuditEvent.actor_id.in_(filters.actor_ids))
|
|
actions = set(filters.actions) if filters.actions is not None else None
|
|
if filters.categories:
|
|
in_categories: set[str] = {
|
|
a for c in filters.categories for a in actions_in(c)
|
|
}
|
|
actions = in_categories if actions is None else actions & in_categories
|
|
if actions is not None:
|
|
clauses.append(AuditEvent.action.in_(actions))
|
|
if filters.target_type is not None:
|
|
clauses.append(AuditEvent.target_type == filters.target_type)
|
|
if filters.target_id is not None:
|
|
clauses.append(AuditEvent.target_id == filters.target_id)
|
|
if filters.since is not None:
|
|
clauses.append(AuditEvent.occurred_at >= filters.since)
|
|
if filters.until is not None:
|
|
clauses.append(AuditEvent.occurred_at < filters.until)
|
|
if filters.max_id is not None:
|
|
clauses.append(AuditEvent.id <= filters.max_id)
|
|
if filters.search:
|
|
like = f"%{escape_like(filters.search.lower())}%"
|
|
clauses.append(
|
|
or_(
|
|
*(
|
|
func.lower(column).like(like, escape=LIKE_ESCAPE_CHAR)
|
|
for column in (
|
|
AuditEvent.actor_name,
|
|
AuditEvent.target_name,
|
|
AuditEvent.ip_address,
|
|
)
|
|
)
|
|
)
|
|
)
|
|
if filters.hidden_rom_ids:
|
|
clauses.append(_not_targeting("rom", filters.hidden_rom_ids))
|
|
if filters.hidden_platform_ids:
|
|
clauses.append(_not_targeting("platform", filters.hidden_platform_ids))
|
|
# A platform's hide covers its roms too.
|
|
clauses.append(
|
|
_not_targeting(
|
|
"rom",
|
|
select(cast(Rom.id, String)).where(
|
|
Rom.platform_id.in_(filters.hidden_platform_ids)
|
|
),
|
|
)
|
|
)
|
|
|
|
total, highest_id = session.execute(
|
|
select(func.count(), func.max(AuditEvent.id)).where(*clauses)
|
|
).one()
|
|
rows = session.execute(
|
|
select(AuditEvent, Device.name)
|
|
.options(_with_actor())
|
|
.outerjoin(Device, Device.id == AuditEvent.device_id)
|
|
.where(*clauses)
|
|
.order_by(AuditEvent.occurred_at.desc(), AuditEvent.id.desc())
|
|
.limit(limit)
|
|
.offset(offset)
|
|
).all()
|
|
return (
|
|
[(event, device_name) for event, device_name in rows],
|
|
total or 0,
|
|
highest_id,
|
|
)
|
|
|
|
@begin_session
|
|
def delete_batch_before(
|
|
self,
|
|
cutoff: datetime,
|
|
batch_size: int,
|
|
session: Session = None, # type: ignore[assignment]
|
|
) -> int:
|
|
"""Delete up to `batch_size` of the oldest events from before `cutoff`."""
|
|
# Ids first: MySQL refuses a LIMIT inside an IN subquery.
|
|
ids = session.scalars(
|
|
select(AuditEvent.id)
|
|
.where(AuditEvent.occurred_at < cutoff)
|
|
.order_by(AuditEvent.occurred_at)
|
|
.limit(batch_size)
|
|
).all()
|
|
if not ids:
|
|
return 0
|
|
result = session.execute(
|
|
delete(AuditEvent)
|
|
.where(AuditEvent.id.in_(ids))
|
|
.execution_options(synchronize_session=False)
|
|
)
|
|
return affected_rows(result)
|