mirror of
https://github.com/rommapp/romm.git
synced 2026-12-05 05:07:31 +01:00
Merge branch 'master' into posthog-code/roms-optional-id-index
This commit is contained in:
@@ -7,14 +7,14 @@ cli:
|
||||
plugins:
|
||||
sources:
|
||||
- id: trunk
|
||||
ref: v1.7.5
|
||||
ref: v1.10.2
|
||||
uri: https://github.com/trunk-io/plugins
|
||||
# Many linters and tools depend on runtimes - configure them here. (https://docs.trunk.io/runtimes)
|
||||
runtimes:
|
||||
enabled:
|
||||
- go@1.21.0
|
||||
- node@22.16.0
|
||||
- python@3.13.3
|
||||
- python@3.14.4
|
||||
# This is the section where you manage your linters. (https://docs.trunk.io/check/configuration)
|
||||
lint:
|
||||
disabled:
|
||||
@@ -22,27 +22,29 @@ lint:
|
||||
- oxipng
|
||||
- pyright
|
||||
enabled:
|
||||
- grype@0.110.0
|
||||
- pinact@4.0.0
|
||||
- dotenv-linter@4.0.0
|
||||
- hadolint@2.14.0
|
||||
- markdownlint@0.48.0
|
||||
- eslint@10.0.3
|
||||
- markdownlint@0.49.1
|
||||
- eslint@10.7.0
|
||||
- actionlint@1.7.11
|
||||
- bandit@1.9.4
|
||||
- black@26.3.0
|
||||
- checkov@3.2.508
|
||||
- black@26.5.1
|
||||
- checkov@3.3.8
|
||||
- git-diff-check
|
||||
- isort@8.0.1
|
||||
- mypy@1.19.1
|
||||
- mypy@2.3.0
|
||||
- osv-scanner@2.3.3
|
||||
- prettier@3.8.1:
|
||||
- prettier@3.9.5:
|
||||
packages:
|
||||
- "@trivago/prettier-plugin-sort-imports@6.0.2"
|
||||
- "@vue/compiler-sfc@3.5.29"
|
||||
- ruff@0.15.5
|
||||
- "@vue/compiler-sfc@3.5.40"
|
||||
- ruff@0.15.22
|
||||
- shellcheck@0.11.0
|
||||
- shfmt@3.6.0
|
||||
- taplo@0.10.0
|
||||
- trivy@0.69.3
|
||||
- trivy@0.70.0
|
||||
- trufflehog@3.93.7
|
||||
- yamllint@1.38.0
|
||||
ignore:
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import asyncio
|
||||
import http
|
||||
import json
|
||||
import re
|
||||
from typing import Final, cast
|
||||
|
||||
import aiohttp
|
||||
@@ -22,6 +23,26 @@ from utils.rate_limiter import ConcurrencyLimiter
|
||||
|
||||
LOGIN_ERROR_CHECK: Final = "Erreur de login"
|
||||
|
||||
# ScreenScraper occasionally returns malformed JSON with unescaped backslashes in
|
||||
# text fields (e.g. game synopses), which the strict parser rejects with
|
||||
# "Invalid \escape" and discards the whole response. Match any backslash that is
|
||||
# not part of a valid JSON escape so we can repair those before parsing.
|
||||
_INVALID_ESCAPE_RE: Final = re.compile(r'\\(?!["\\/bfnrt]|u[0-9a-fA-F]{4})')
|
||||
|
||||
|
||||
def _loads_lenient(text: str) -> dict:
|
||||
"""Parse a ScreenScraper JSON payload, repairing invalid escapes on failure.
|
||||
|
||||
A single unescaped backslash would otherwise sink an entire response (and thus
|
||||
the match), so on a decode error we double any backslash that isn't a valid
|
||||
JSON escape and try once more.
|
||||
"""
|
||||
try:
|
||||
return json.loads(text)
|
||||
except json.JSONDecodeError:
|
||||
return json.loads(_INVALID_ESCAPE_RE.sub(r"\\\\", text))
|
||||
|
||||
|
||||
# ScreenScraper enforces a per-account *thread* (concurrency) cap rather than a
|
||||
# request rate. Because a request can take several seconds, spacing out request
|
||||
# starts is not enough, as overlapping requests would exceed the cap and get
|
||||
@@ -140,7 +161,7 @@ class ScreenScraperService:
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid ScreenScraper credentials",
|
||||
)
|
||||
data = await res.json()
|
||||
data = await res.json(loads=_loads_lenient)
|
||||
_update_thread_allowance(data)
|
||||
return data
|
||||
except aiohttp.ServerTimeoutError:
|
||||
@@ -213,7 +234,7 @@ class ScreenScraperService:
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid ScreenScraper credentials",
|
||||
)
|
||||
data = await res.json()
|
||||
data = await res.json(loads=_loads_lenient)
|
||||
_update_thread_allowance(data)
|
||||
return data
|
||||
except (aiohttp.ClientResponseError, aiohttp.ServerTimeoutError) as err:
|
||||
|
||||
33
backend/alembic/versions/0097_roms_platform_fs_size_index.py
Normal file
33
backend/alembic/versions/0097_roms_platform_fs_size_index.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""Add composite index on roms (platform_id, fs_size_bytes)
|
||||
|
||||
Revision ID: 0097_roms_platform_fs_size_index
|
||||
Revises: 0096_fix_virtual_collections
|
||||
Create Date: 2026-07-16 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = "0097_roms_platform_fs_size_index"
|
||||
down_revision = "0096_fix_virtual_collections"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
INDEX_NAME = "idx_roms_platform_fs_size"
|
||||
INDEX_COLUMNS = ["platform_id", "fs_size_bytes"]
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("roms", schema=None) as batch_op:
|
||||
batch_op.create_index(
|
||||
INDEX_NAME,
|
||||
INDEX_COLUMNS,
|
||||
unique=False,
|
||||
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)
|
||||
@@ -1105,7 +1105,7 @@ def get_rom_simple(
|
||||
fetched on user-driven detail interactions (game details page, quick-
|
||||
note dialog open, achievements panel)."""
|
||||
|
||||
rom = db_rom_handler.get_rom(id)
|
||||
rom = db_rom_handler.get_rom_simple(id)
|
||||
|
||||
if not rom:
|
||||
raise RomNotFoundInDatabaseException(id)
|
||||
|
||||
@@ -243,6 +243,50 @@ def with_details(func):
|
||||
return wrapper
|
||||
|
||||
|
||||
def with_simple_details(func):
|
||||
"""Lightweight eager-load for the `SimpleRomSchema` (v2 gallery card).
|
||||
|
||||
Loads only the relationships `SimpleRomSchema` serializes (rom_users,
|
||||
files, sibling_roms + their rom_users, notes) and the deferred file-count
|
||||
columns, skipping the `saves` / `states` / `screenshots` / `collections`
|
||||
arrays that `with_details` pulls for the detail view. Keeps per-card
|
||||
hydration cheap on low-power hosts.
|
||||
"""
|
||||
|
||||
@functools.wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
kwargs["query"] = select(Rom).options(
|
||||
selectinload(Rom.platform),
|
||||
selectinload(Rom.rom_users).options(noload(RomUser.rom)),
|
||||
selectinload(Rom.metadatum).options(noload(RomMetadata.rom)),
|
||||
selectinload(Rom.files).options(
|
||||
joinedload(RomFile.rom).load_only(Rom.fs_path, Rom.fs_name),
|
||||
selectinload(RomFile.track_meta),
|
||||
),
|
||||
selectinload(Rom.sibling_roms).options(
|
||||
noload(Rom.platform),
|
||||
noload(Rom.metadatum),
|
||||
# Per-sibling is_main_sibling resolution needs each sibling's
|
||||
# RomUser (relationship is `lazy="raise"`).
|
||||
selectinload(Rom.rom_users).options(noload(RomUser.rom)),
|
||||
load_only(
|
||||
Rom.id,
|
||||
Rom.name,
|
||||
Rom.platform_id,
|
||||
Rom.fs_name_no_tags,
|
||||
Rom.fs_name_no_ext,
|
||||
),
|
||||
),
|
||||
selectinload(Rom.notes),
|
||||
undefer(Rom.multi_file),
|
||||
undefer(Rom.top_level_file_count),
|
||||
undefer(Rom.has_soundtrack),
|
||||
)
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
class DBRomsHandler(DBBaseHandler):
|
||||
@begin_session
|
||||
@with_details
|
||||
@@ -268,6 +312,18 @@ class DBRomsHandler(DBBaseHandler):
|
||||
) -> Rom | None:
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_simple_details
|
||||
def get_rom_simple(
|
||||
self,
|
||||
id: int,
|
||||
*,
|
||||
query: Query = None, # type: ignore
|
||||
session: Session = None, # type: ignore
|
||||
) -> Rom | None:
|
||||
"""Get a rom by ID with only the loads `SimpleRomSchema` needs."""
|
||||
return session.scalar(query.filter_by(id=id).limit(1))
|
||||
|
||||
@begin_session
|
||||
@with_details
|
||||
def get_roms_by_ids(
|
||||
|
||||
@@ -268,6 +268,7 @@ class Rom(BaseModel):
|
||||
"tgdb_id",
|
||||
"id",
|
||||
),
|
||||
Index("idx_roms_platform_fs_size", "platform_id", "fs_size_bytes"),
|
||||
Index("idx_roms_name", "name"),
|
||||
Index("idx_roms_name_sort_key", "name_sort_key"),
|
||||
Index("idx_roms_igdb_id", "igdb_id"),
|
||||
|
||||
@@ -11,6 +11,7 @@ from fastapi import HTTPException, status
|
||||
from adapters.services.screenscraper import (
|
||||
LOGIN_ERROR_CHECK,
|
||||
ScreenScraperService,
|
||||
_loads_lenient,
|
||||
auth_middleware,
|
||||
is_daily_quota_exhausted,
|
||||
reset_daily_quota,
|
||||
@@ -1124,3 +1125,23 @@ class TestScreenScraperServiceEdgeCases:
|
||||
assert exc_info.value.status_code == status.HTTP_401_UNAUTHORIZED
|
||||
assert "Invalid ScreenScraper credentials" in exc_info.value.detail
|
||||
assert mock_session.get.call_count == 2
|
||||
|
||||
|
||||
class TestLoadsLenient:
|
||||
"""Test tolerant parsing of ScreenScraper's occasionally malformed JSON."""
|
||||
|
||||
def test_parses_valid_json(self):
|
||||
assert _loads_lenient('{"a": 1, "b": "x"}') == {"a": 1, "b": "x"}
|
||||
|
||||
def test_repairs_invalid_backslash_escape(self):
|
||||
# ScreenScraper sometimes emits raw backslashes in text fields, which the
|
||||
# strict parser rejects with "Invalid \escape".
|
||||
raw = '{"synopsis": "path C:\\emu\\games"}'
|
||||
with pytest.raises(json.JSONDecodeError):
|
||||
json.loads(raw)
|
||||
assert _loads_lenient(raw) == {"synopsis": "path C:\\emu\\games"}
|
||||
|
||||
def test_preserves_valid_escapes(self):
|
||||
assert _loads_lenient('{"s": "line\\nbreak \\"quoted\\" \\u00e9"}') == {
|
||||
"s": 'line\nbreak "quoted" é'
|
||||
}
|
||||
|
||||
@@ -44,6 +44,32 @@ def test_get_rom(client: TestClient, access_token: str, rom: Rom):
|
||||
assert body["id"] == rom.id
|
||||
|
||||
|
||||
def test_get_rom_simple(client: TestClient, access_token: str, rom: Rom):
|
||||
response = client.get(
|
||||
f"/api/roms/{rom.id}/simple",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
|
||||
body = response.json()
|
||||
assert body["id"] == rom.id
|
||||
# SimpleRomSchema stays lightweight: none of the detail-only arrays are
|
||||
# present, so the endpoint must not eager-load them.
|
||||
assert "user_saves" not in body
|
||||
assert "user_states" not in body
|
||||
assert "user_screenshots" not in body
|
||||
assert "user_collections" not in body
|
||||
assert "all_user_notes" not in body
|
||||
|
||||
|
||||
def test_get_rom_simple_missing_returns_404(client: TestClient, access_token: str):
|
||||
response = client.get(
|
||||
"/api/roms/999999/simple",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
assert response.status_code == status.HTTP_404_NOT_FOUND
|
||||
|
||||
|
||||
def test_download_multi_file_rom_content(
|
||||
client: TestClient, access_token: str, multi_file_rom: Rom
|
||||
):
|
||||
|
||||
@@ -182,9 +182,10 @@ export interface GetRomsParams {
|
||||
playerCountsLogic?: string | null;
|
||||
metadataProvidersLogic?: string | null;
|
||||
tagsLogic?: string | null;
|
||||
// Cancellation: pass an AbortSignal to let the caller abort an
|
||||
// in-flight request (e.g. search-typing → previous query aborted,
|
||||
// gallery-context switch → previous platform's windows aborted).
|
||||
// Skip the char index / filter-value aggregations server-side
|
||||
withCharIndex?: boolean;
|
||||
withFilterValues?: boolean;
|
||||
// Cancel an in-flight request
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
@@ -231,6 +232,8 @@ async function getRoms({
|
||||
playerCountsLogic = null,
|
||||
metadataProvidersLogic = null,
|
||||
tagsLogic = null,
|
||||
withCharIndex = undefined,
|
||||
withFilterValues = undefined,
|
||||
signal = undefined,
|
||||
}: GetRomsParams) {
|
||||
const params = {
|
||||
@@ -336,6 +339,10 @@ async function getRoms({
|
||||
...(filterSaves !== null ? { has_saves: filterSaves } : {}),
|
||||
...(filterStates !== null ? { has_states: filterStates } : {}),
|
||||
...(filterVerified !== null ? { verified: filterVerified } : {}),
|
||||
...(withCharIndex !== undefined ? { with_char_index: withCharIndex } : {}),
|
||||
...(withFilterValues !== undefined
|
||||
? { with_filter_values: withFilterValues }
|
||||
: {}),
|
||||
};
|
||||
|
||||
return api.get<GetRomsResponse>(`/roms`, {
|
||||
|
||||
@@ -551,25 +551,26 @@ const currentLetter = computed<string>(() => {
|
||||
return "";
|
||||
});
|
||||
|
||||
// Per-card viewport-driven fetch. The shell tracks which positions
|
||||
// are currently visible (from the rows in `viewportRange`) and keeps
|
||||
// `byPosition` in sync via per-card `getRom(id)` calls — pure by-id
|
||||
// DB lookups on the backend, much faster than the paginated
|
||||
// `getRoms(limit/offset)` pipeline. Each fetch is independent, so
|
||||
// covers stream in as their individual responses land.
|
||||
// Viewport-driven fetch. The shell collects the positions currently in
|
||||
// view (rows in `viewportRange`) and hands them to the store, which keeps
|
||||
// `byPosition` in sync by fetching the 72-item windows those positions
|
||||
// fall into. Windows are shared across cards and cached, so a full
|
||||
// viewport resolves in a handful of paginated requests rather than one
|
||||
// per card. (Fetching per-card instead issued one request plus one DB
|
||||
// lookup per visible card, so ~100 simultaneous round-trips on a full
|
||||
// grid, which the browser's per-host connection cap then serialized into
|
||||
// slow waves on low-power devices.)
|
||||
//
|
||||
// No idle-time prefetch: when the user stops scrolling, no new
|
||||
// requests are fired. Cards already in the viewport that are still
|
||||
// missing keep loading; everything off-screen waits until the user
|
||||
// scrolls there.
|
||||
// The store also aborts windows that scrolled out of view, so paging
|
||||
// through a large library doesn't leave departed windows downloading.
|
||||
//
|
||||
// Cancellation: positions that leave the viewport while their fetch
|
||||
// is in flight are aborted via `cancelFetchAt`. A small debounce on
|
||||
// viewport changes prevents fire-and-cancel storms during smooth
|
||||
// scrolling — only when the viewport settles for `FETCH_DEBOUNCE_MS`
|
||||
// do we sync.
|
||||
// No idle-time prefetch: when the user stops scrolling, no new requests
|
||||
// are fired for off-screen positions.
|
||||
//
|
||||
// A small debounce on viewport changes prevents request storms during
|
||||
// smooth scrolling: only when the viewport settles for
|
||||
// `FETCH_DEBOUNCE_MS` do we sync.
|
||||
const FETCH_DEBOUNCE_MS = 80;
|
||||
const visiblePositions = new Set<number>();
|
||||
let fetchDebounceTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let pendingRange: { first: number; last: number } | null = null;
|
||||
|
||||
@@ -589,27 +590,7 @@ function collectVisiblePositions(range: {
|
||||
}
|
||||
|
||||
function syncFetches(range: { first: number; last: number }) {
|
||||
const next = collectVisiblePositions(range);
|
||||
|
||||
// Cancel positions that left the viewport before their fetch
|
||||
// resolved. The store's per-position controller handles the network
|
||||
// abort; idempotent if nothing was in flight.
|
||||
for (const p of visiblePositions) {
|
||||
if (!next.has(p) && !galleryRoms.byPosition.has(p)) {
|
||||
galleryRoms.cancelFetchAt(p);
|
||||
}
|
||||
}
|
||||
|
||||
// Fire per-card fetches for positions that just entered. The store
|
||||
// dedupes against in-flight + already-loaded internally.
|
||||
for (const p of next) {
|
||||
if (!galleryRoms.byPosition.has(p)) {
|
||||
void galleryRoms.fetchRomAt(p);
|
||||
}
|
||||
}
|
||||
|
||||
visiblePositions.clear();
|
||||
for (const p of next) visiblePositions.add(p);
|
||||
galleryRoms.syncVisibleWindows(collectVisiblePositions(range));
|
||||
}
|
||||
|
||||
function scheduleFetchSync(range: { first: number; last: number }) {
|
||||
@@ -625,11 +606,10 @@ function scheduleFetchSync(range: { first: number; last: number }) {
|
||||
}
|
||||
|
||||
// When the virtualItems list itself changes (gallery context switch,
|
||||
// search invalidate), drop the visible-position bookkeeping. The
|
||||
// store's `invalidateWindows` / `resetGallery` already aborts every
|
||||
// in-flight request, so we just clear local state.
|
||||
// search invalidate), drop the pending debounced sync. The store's
|
||||
// `invalidateWindows` / `resetGallery` already aborts every in-flight
|
||||
// request, so we just clear local state.
|
||||
watch(virtualItems, () => {
|
||||
visiblePositions.clear();
|
||||
if (fetchDebounceTimer) {
|
||||
clearTimeout(fetchDebounceTimer);
|
||||
fetchDebounceTimer = null;
|
||||
@@ -792,13 +772,10 @@ onBeforeUnmount(() => {
|
||||
gallerySelection.clear();
|
||||
if (searchDebounce) clearTimeout(searchDebounce);
|
||||
if (fetchDebounceTimer) clearTimeout(fetchDebounceTimer);
|
||||
// Cancel any per-position fetches still in flight for our last
|
||||
// visible set — `invalidateWindows` / `resetGallery` already aborts
|
||||
// window-level fetches; this covers per-card cleanup on unmount.
|
||||
for (const p of visiblePositions) {
|
||||
if (!galleryRoms.byPosition.has(p)) galleryRoms.cancelFetchAt(p);
|
||||
}
|
||||
visiblePositions.clear();
|
||||
// When leaving the gallery entirely, stop any window fetches still
|
||||
// downloading so navigating away mid-scroll doesn't keep the network /
|
||||
// backend busy. Keeps the loaded cache so returning to the same gallery is instant.
|
||||
galleryRoms.abortInFlight();
|
||||
inflowResizeObserver?.disconnect();
|
||||
inflowResizeObserver = null;
|
||||
// Drop the debug stats so the overlay doesn't show stale gallery numbers
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
// GameListRow — single row of the list-mode gallery.
|
||||
//
|
||||
// Owns:
|
||||
// * Per-row lazy fetch — onMount fires `fetchRomAt(position)`; the
|
||||
// store dedupes against in-flight + already-loaded. onUnmount aborts
|
||||
// the fetch via `cancelFetchAt(position)` so a fast scroll past
|
||||
// mid-flight doesn't keep server work queued for invisible rows.
|
||||
// Mirror of the per-card flow in grid mode — same "row mount =
|
||||
// * Per-row lazy fetch: onMount fires `fetchWindowAt(position)` and
|
||||
// the store aligns the position to its 72-item window, deduping
|
||||
// against pending + loaded windows, so rows sharing a window share
|
||||
// one request. Mirror of the grid flow, with the same "row mount =
|
||||
// entered viewport" contract via the shell's RVirtualScroller
|
||||
// overscan window.
|
||||
//
|
||||
@@ -27,7 +26,7 @@ import {
|
||||
RSkeletonBlock,
|
||||
RTooltip,
|
||||
} from "@v2/lib";
|
||||
import { computed, onBeforeUnmount, onMounted } from "vue";
|
||||
import { computed, onMounted } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { useRouter } from "vue-router";
|
||||
import storePlatforms from "@/stores/platforms";
|
||||
@@ -266,19 +265,9 @@ onMounted(() => {
|
||||
// Static mode (rom passed as prop) skips the gallery's per-row fetch
|
||||
// entirely — the consumer already owns the rom data.
|
||||
if (isStatic.value || props.position === undefined) return;
|
||||
// Entered the overscan window — kick the per-row fetch. Store dedupes
|
||||
// against in-flight + already-loaded.
|
||||
void galleryRoms.fetchRomAt(props.position);
|
||||
});
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
if (isStatic.value || props.position === undefined) return;
|
||||
// Left the overscan window before the fetch resolved — abort so the
|
||||
// server doesn't keep building a row the user already scrolled past.
|
||||
// Idempotent if nothing was in flight.
|
||||
if (!galleryRoms.byPosition.has(props.position)) {
|
||||
galleryRoms.cancelFetchAt(props.position);
|
||||
}
|
||||
// Entered the overscan window, so kick the window fetch. Store aligns
|
||||
// to the window grid and dedupes against pending + loaded windows.
|
||||
void galleryRoms.fetchWindowAt(props.position);
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ const dataProviders = computed(() =>
|
||||
PROVIDERS.map((p) => {
|
||||
const id = providerId(props.rom, p);
|
||||
if (id === null) return null;
|
||||
return { name: p.name, href: p.url ? p.url(id) : null };
|
||||
return { name: p.name, href: p.url ? p.url(id, props.rom) : null };
|
||||
}).filter((e): e is { name: string; href: string | null } => e !== null),
|
||||
);
|
||||
|
||||
|
||||
@@ -27,7 +27,7 @@ const entries = computed<Entry[]>(() => {
|
||||
accent: p.color,
|
||||
logo: p.logo,
|
||||
id,
|
||||
href: id !== null && p.url ? p.url(id) : null,
|
||||
href: id !== null && p.url ? p.url(id, props.rom) : null,
|
||||
};
|
||||
});
|
||||
// Linked first; the cards know how to dim themselves when unlinked.
|
||||
|
||||
@@ -13,8 +13,10 @@ export type Provider = {
|
||||
color: string;
|
||||
/** Optional favicon for the provider's identity. */
|
||||
logo: string | null;
|
||||
/** Optional URL builder; when null the card renders unlinked. */
|
||||
url: ((id: string | number) => string) | null;
|
||||
/** Optional URL builder; when null the card renders unlinked. The ROM is
|
||||
* passed so builders can reach fields beyond the provider ID (e.g. IGDB
|
||||
* links by slug, not by numeric ID). */
|
||||
url: ((id: string | number, rom: DetailedRom) => string) | null;
|
||||
};
|
||||
|
||||
export const PROVIDERS: Provider[] = [
|
||||
@@ -23,7 +25,13 @@ export const PROVIDERS: Provider[] = [
|
||||
name: "IGDB",
|
||||
color: "var(--r-color-provider-igdb)",
|
||||
logo: "/assets/scrappers/igdb.png",
|
||||
url: (id) => `https://www.igdb.com/search?type=1&q=${id}`,
|
||||
// IGDB game pages live at /games/<slug>; the numeric ID only feeds a text
|
||||
// search that returns nothing. Fall back to the ID search when the slug
|
||||
// (populated from the IGDB match) is missing.
|
||||
url: (id, rom) =>
|
||||
rom.slug
|
||||
? `https://www.igdb.com/games/${rom.slug}`
|
||||
: `https://www.igdb.com/search?type=1&q=${id}`,
|
||||
},
|
||||
{
|
||||
key: "moby_id",
|
||||
@@ -65,7 +73,8 @@ export const PROVIDERS: Provider[] = [
|
||||
name: "Hasheous",
|
||||
color: "var(--r-color-provider-hasheous)",
|
||||
logo: "/assets/scrappers/hasheous.png",
|
||||
url: null,
|
||||
url: (id) =>
|
||||
`https://hasheous.org/index.html?page=dataobjectdetail&type=game&id=${id}`,
|
||||
},
|
||||
{
|
||||
key: "flashpoint_id",
|
||||
|
||||
@@ -61,18 +61,48 @@ type GalleryFilterStore = ExtractPiniaStoreType<typeof storeGalleryFilter>;
|
||||
// fewer requests but each one downloads more.
|
||||
const WINDOW_SIZE = 72;
|
||||
|
||||
// In-flight `AbortController`s keyed by request — `window:${offset}`
|
||||
// for the windowed initial fetch, `range:${offset}:${limit}` for the
|
||||
// per-row dwell prefetch. Lives outside store state so Pinia doesn't
|
||||
// In-flight `AbortController`s keyed by request: `window:${offset}`
|
||||
// for a windowed fetch, `bootstrap` for the lightweight metadata
|
||||
// bootstrap. Lives outside store state so Pinia doesn't
|
||||
// try to proxy native abort objects (which break under reactivity).
|
||||
// `invalidateWindows()` / `resetGallery()` abort every pending request,
|
||||
// so a fast-typed search box or a platform-switch mid-load doesn't
|
||||
// leave server work going for results we'll throw away.
|
||||
const inFlightControllers = new Map<string, AbortController>();
|
||||
|
||||
// A failed window is only refetched when `fetchWindowAt` is called for it
|
||||
// again, which for a static viewport (no scroll) never happens on its own.
|
||||
// So a transient failure would strand up to `WINDOW_SIZE` visible cards as
|
||||
// skeletons. To self-heal, a failed window schedules a bounded, backing-off
|
||||
// retry; `retryTimers` holds the pending timeouts (keyed by offset) and
|
||||
// `retryCounts` the attempts so far. Both are cleared by `abortAllInFlight`
|
||||
// on any gallery-context switch so we never retry against a stale context.
|
||||
const RETRY_BACKOFF_MS = 2000;
|
||||
const MAX_WINDOW_RETRIES = 3;
|
||||
const retryTimers = new Map<number, ReturnType<typeof setTimeout>>();
|
||||
const retryCounts = new Map<number, number>();
|
||||
|
||||
function clearRetry(offset: number) {
|
||||
const timer = retryTimers.get(offset);
|
||||
if (timer !== undefined) clearTimeout(timer);
|
||||
retryTimers.delete(offset);
|
||||
retryCounts.delete(offset);
|
||||
}
|
||||
|
||||
function abortAllInFlight() {
|
||||
for (const ctrl of inFlightControllers.values()) ctrl.abort();
|
||||
inFlightControllers.clear();
|
||||
for (const timer of retryTimers.values()) clearTimeout(timer);
|
||||
retryTimers.clear();
|
||||
retryCounts.clear();
|
||||
}
|
||||
|
||||
// Abort a single in-flight window fetch. The rejected request is caught
|
||||
// as a cancel in `fetchWindowAt` (no `failedWindows` entry, no retry) and
|
||||
// its `finally` clears the pending/controller bookkeeping.
|
||||
function cancelWindow(offset: number) {
|
||||
const ctrl = inFlightControllers.get(`window:${offset}`);
|
||||
if (ctrl) ctrl.abort();
|
||||
}
|
||||
|
||||
// Apply items to `byPosition` in row-sized batches with a rAF yield
|
||||
@@ -140,10 +170,10 @@ interface State {
|
||||
// phase.
|
||||
initialFetching: boolean;
|
||||
// True once total / charIndex / romIdIndex / filter_values have been
|
||||
// populated — either by the lightweight `fetchInitialMetadata()`
|
||||
// bootstrap or by `fetchWindowAt(0)`. Used to gate the initial fetch
|
||||
// dedup independently of `loadedWindows` (metadata bootstrap doesn't
|
||||
// load any window).
|
||||
// populated, either by the lightweight `fetchInitialMetadata()`
|
||||
// bootstrap or by `fetchWindowAt(0)`. Used to gate the initial
|
||||
// bootstrap dedup independently of `loadedWindows` (metadata
|
||||
// bootstrap doesn't load any window).
|
||||
metadataLoaded: boolean;
|
||||
// Order params — gallery-list scoped (separate from v1's localStorage
|
||||
// keys so v1/v2 don't fight over the same value).
|
||||
@@ -363,15 +393,14 @@ export default defineStore("v2GalleryRoms", {
|
||||
|
||||
/** Lightweight bootstrap: fetch only the gallery's metadata (total,
|
||||
* char_index, rom_id_index, filter_values) without loading any
|
||||
* items. Use this when items will be hydrated lazily through the
|
||||
* per-card `fetchRomAt(p)` viewport sync — e.g. grid-mode galleries.
|
||||
* items. Sizes the virtualiser (via `total`) before any window
|
||||
* lands, so both layouts can render skeleton rows immediately and
|
||||
* then hydrate them through the viewport-driven `fetchWindowAt`
|
||||
* sync.
|
||||
*
|
||||
* The backend's `limit` minimum is 1, so we still pay for one
|
||||
* `SimpleRomSchema` build server-side, but we discard the item
|
||||
* client-side: every position (including 0) loads through the
|
||||
* unified per-card path so the staggered fade-in applies to the
|
||||
* first rows the same as the rest. List mode still wants
|
||||
* `fetchWindowAt(0)` because the table reads `byPosition` directly. */
|
||||
* `SimpleRomSchema` build server-side, but the item is discarded
|
||||
* client-side. */
|
||||
async fetchInitialMetadata(): Promise<void> {
|
||||
if (this.metadataLoaded) return;
|
||||
if (this.initialFetching) return;
|
||||
@@ -434,6 +463,10 @@ export default defineStore("v2GalleryRoms", {
|
||||
try {
|
||||
const response = await romApi.getRoms({
|
||||
...params,
|
||||
// Skip char index / filter-value aggregations when initial data is loaded
|
||||
...(this.metadataLoaded
|
||||
? { withCharIndex: false, withFilterValues: false }
|
||||
: {}),
|
||||
signal: controller.signal,
|
||||
});
|
||||
// Re-check that this window is still relevant — invalidateWindows
|
||||
@@ -467,15 +500,32 @@ export default defineStore("v2GalleryRoms", {
|
||||
);
|
||||
|
||||
this.loadedWindows.add(offset);
|
||||
// Recovered — drop any retry bookkeeping for this window.
|
||||
clearRetry(offset);
|
||||
} catch (err) {
|
||||
// An explicit abort isn't a failure — keep `failedWindows`
|
||||
// clean so the window is eligible to refetch under the new
|
||||
// gallery context without the UI flagging it as broken.
|
||||
if (axios.isCancel(err)) return;
|
||||
this.failedWindows.add(offset);
|
||||
// Surface in console; UI keeps the skeletons in place — the
|
||||
// window can be retried by re-entering the row.
|
||||
// Surface in console; UI keeps the skeletons in place until the
|
||||
// retry below (or a viewport / gallery-state change) refetches.
|
||||
console.error("[v2GalleryRoms] window fetch failed", offset, err);
|
||||
// Self-heal a stranded viewport: schedule a bounded, backing-off
|
||||
// refetch so a transient blip doesn't leave the window's cards as
|
||||
// skeletons until the user happens to scroll.
|
||||
const attempts = retryCounts.get(offset) ?? 0;
|
||||
if (attempts < MAX_WINDOW_RETRIES && !retryTimers.has(offset)) {
|
||||
retryCounts.set(offset, attempts + 1);
|
||||
const timer = setTimeout(
|
||||
() => {
|
||||
retryTimers.delete(offset);
|
||||
void this.fetchWindowAt(offset);
|
||||
},
|
||||
RETRY_BACKOFF_MS * (attempts + 1),
|
||||
);
|
||||
retryTimers.set(offset, timer);
|
||||
}
|
||||
} finally {
|
||||
inFlightControllers.delete(ctrlKey);
|
||||
this.pendingWindows.delete(offset);
|
||||
@@ -483,74 +533,43 @@ export default defineStore("v2GalleryRoms", {
|
||||
}
|
||||
},
|
||||
|
||||
/** Fetch an arbitrary `[offset, offset + limit)` range. Used by the
|
||||
* per-row dwell prefetch in the gallery views — instead of always
|
||||
* pulling the full 72-item window, a row asks for exactly its 8
|
||||
* positions, so visible rows can resolve in parallel and the user
|
||||
* sees covers stream in row-by-row.
|
||||
*
|
||||
* Skips the request when every position in the range is already
|
||||
* loaded; dedupes concurrent identical requests by (offset, limit)
|
||||
* key. The initial window — total / charIndex bootstrapping — still
|
||||
* goes through `fetchWindowAt(0)`. */
|
||||
/** Fetch the single ROM at `position` via `GET /roms/{id}/simple` —
|
||||
* the lightweight schema endpoint that skips the eager `user_saves`
|
||||
* / `user_states` / `user_screenshots` / `user_collections` /
|
||||
* `all_user_notes` arrays (those are 5 separate DB queries each;
|
||||
* dropping them takes the call from ~500ms to a typical by-id
|
||||
* lookup). The gallery card only needs the `has_*` indicator
|
||||
* flags + cover paths + platform info — all on `SimpleRomSchema`.
|
||||
* Detailed arrays are pulled on demand by the game-details page
|
||||
* or by quick-action dialogs (note editor, achievements panel)
|
||||
* when the user actually opens them.
|
||||
*
|
||||
* Requires `romIdIndex[position]` — populated by the first
|
||||
* `fetchWindowAt(0)` for the active gallery. Returns silently
|
||||
* if the index isn't loaded yet.
|
||||
*
|
||||
* Per-position `AbortController` allows the shell to cancel
|
||||
* fetches for cards that left the viewport before resolving.
|
||||
* `cancelFetchAt(position)` is the cancel side. */
|
||||
async fetchRomAt(position: number): Promise<void> {
|
||||
if (position < 0) return;
|
||||
if (this.total > 0 && position >= this.total) return;
|
||||
if (this.byPosition.has(position)) return;
|
||||
const romId = this.romIdIndex[position];
|
||||
if (!romId) return;
|
||||
|
||||
const ctrlKey = `rom:${position}`;
|
||||
if (inFlightControllers.has(ctrlKey)) return;
|
||||
|
||||
const controller = new AbortController();
|
||||
inFlightControllers.set(ctrlKey, controller);
|
||||
|
||||
try {
|
||||
const response = await romApi.getRomSimple({
|
||||
romId,
|
||||
signal: controller.signal,
|
||||
});
|
||||
// Re-check that the shell still wants this position — a fast
|
||||
// scroll past + cancel races against the response landing.
|
||||
if (!inFlightControllers.has(ctrlKey)) return;
|
||||
this.byPosition.set(position, response.data);
|
||||
} catch (err) {
|
||||
if (axios.isCancel(err)) return;
|
||||
console.error("[v2GalleryRoms] rom fetch failed", position, romId, err);
|
||||
} finally {
|
||||
inFlightControllers.delete(ctrlKey);
|
||||
/** Reconcile in-flight window fetches with the currently visible
|
||||
* positions. Starts any window covering a visible position (deduped
|
||||
* inside `fetchWindowAt`) and aborts any in-flight or retry-pending
|
||||
* window that no longer covers one. Without the abort, scrolling
|
||||
* through a large library would leave every window it passed
|
||||
* downloading and applying in the background — the exact wasted
|
||||
* network / backend / render work this store exists to avoid on
|
||||
* low-power devices. Driven by the shell's debounced viewport sync. */
|
||||
syncVisibleWindows(positions: Iterable<number>) {
|
||||
const wanted = new Set<number>();
|
||||
for (const p of positions) {
|
||||
if (p < 0) continue;
|
||||
if (this.total > 0 && p >= this.total) continue;
|
||||
wanted.add(alignToWindow(p));
|
||||
}
|
||||
// Cancel windows that drifted out of view. Snapshot first: aborting
|
||||
// settles a fetch's `finally` (which mutates these sets) on a later
|
||||
// microtask, but iterate a copy to stay safe regardless.
|
||||
for (const offset of [...this.pendingWindows]) {
|
||||
if (!wanted.has(offset)) cancelWindow(offset);
|
||||
}
|
||||
for (const offset of [...retryTimers.keys()]) {
|
||||
if (!wanted.has(offset)) clearRetry(offset);
|
||||
}
|
||||
for (const offset of wanted) {
|
||||
void this.fetchWindowAt(offset);
|
||||
}
|
||||
},
|
||||
|
||||
/** Cancel an in-flight per-position fetch — typically called by
|
||||
* the shell when a card leaves the viewport before its request
|
||||
* resolves. No-op if nothing is in flight for that position. */
|
||||
cancelFetchAt(position: number) {
|
||||
const ctrlKey = `rom:${position}`;
|
||||
const ctrl = inFlightControllers.get(ctrlKey);
|
||||
if (ctrl) {
|
||||
ctrl.abort();
|
||||
inFlightControllers.delete(ctrlKey);
|
||||
}
|
||||
/** Abort every in-flight window fetch + pending retry without wiping
|
||||
* the loaded cache. The shell calls this when the gallery unmounts so
|
||||
* navigating away mid-scroll doesn't leave downloads running; a
|
||||
* return to the same gallery still reuses `loadedWindows`. */
|
||||
abortInFlight() {
|
||||
abortAllInFlight();
|
||||
this.pendingWindows = new Set();
|
||||
this.initialFetching = false;
|
||||
},
|
||||
|
||||
/** Apply (in place) an updated ROM to whatever position currently
|
||||
|
||||
Reference in New Issue
Block a user