Commit Graph

163 Commits

Author SHA1 Message Date
Georges-Antoine Assi
c67e49c461 fix(tasks): gate the orphaned-resources cleanup on its config flag
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-30 18:21:39 -04:00
Georges-Antoine Assi
426be64dc7 fix(security): close three permission gaps from the 5.1.0 audit
Restrict ROM file deletion to the ROMS/DELETE grant. The new
DELETE /roms/{rom_id}/files/{file_id} route gated on ROMS_WRITE alone and,
unlike its manual/soundtrack/screenshot siblings, carried no category guard,
so a group holding write-but-not-delete could remove game files from disk
while whole-ROM deletion still required ROMS/DELETE.

Gate mutating streaming routes on ROMS_USER_WRITE instead of ROMS_READ,
matching the play-session routes. ROMS_USER_WRITE is always-on for
authenticated users, but absent from READ_SCOPES, which is all KIOSK_MODE
grants an anonymous visitor. Kiosk visitors all share user_id=-1, so session
ownership could not separate them and any visitor could claim sessions and
overwrite another's save states.

Restore the ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES gate on the cleanup
task's cron_string. It was dropped in 06cafd4b1, whose message refers to
update_switch_titledb, leaving the documented opt-out inert and scheduling a
destructive task nightly. That commit also broke two of the task's own tests.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-29 18:28:04 -04:00
Georges-Antoine Assi
06cafd4b10 fix cron_string in update_switch_titledb 2026-07-29 17:41:52 -04:00
Georges-Antoine Assi
ff8d4d0d5d Merge pull request #3986 from rommapp/fix/launchbox-cloud-empty-store
fix(launchbox): stop the cloud provider from silently matching nothing
2026-07-28 23:09:10 -04:00
Georges-Antoine Assi
8c12ac86a1 fix(launchbox): keep the heartbeat honest during a first import
The store is written in batches, so an initial import answers for the
names committed so far long before it holds the whole dump. Checking
that the name index exists reported the provider healthy off a fraction
of the entries, and a run that died partway left it that way for good.

Flag the initial import and clear it once a run completes, so only a
finished import counts as healthy. A refresh keeps serving the previous
dump, so it is not flagged.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 22:22:06 -04:00
Georges-Antoine Assi
52940ea3d4 fix(launchbox): stop the cloud provider from silently matching nothing
LaunchBox cloud lookups read from a Redis store that only the metadata
update task fills, but nothing surfaced when that store was empty. The
provider reported healthy, every search returned zero results, and the
logs said nothing.

- heartbeat now reports unhealthy until the store is populated, and an
  empty store logs what to set to fix it
- the update task can be run manually whenever LAUNCHBOX_API_ENABLED is
  on, instead of also requiring the scheduled-update flag
- the ~600k entry dump was buffered into a single pipeline, peaking at
  1.7GB of RSS and writing nothing at all if the job was killed part way
  through. Writes now go out in batches and parsed elements are dropped
  as they are consumed, which caps the run at ~260MB. The task also gets
  its own timeout, since the default 5 minutes does not cover a 100MB
  download plus a 500MB parse
- alternate name lookups ignored the platform, so "Super Mario World" on
  PlayStation matched Super Mario Bros.
- Coleco ADAM was spelled wrong, and Famicom / Super Famicom pointed at
  platform names LaunchBox does not use

Fixes #3981

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 19:55:16 -04:00
Georges-Antoine Assi
ae46dc64c2 fix(tasks): make the upload tmp cleanup importable by the RQ worker
Importing the task module first, as the worker does when it resolves the job,
pulled endpoints.roms in and closed an import cycle through decorators.database.
RQ hides the ImportError behind "Invalid attribute name: run", so the cleanup
never ran and orphaned chunked-upload directories piled up.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-28 18:41:51 -04:00
Georges-Antoine Assi
345610afad Merge pull request #3974 from XenuIsWatching/fix/scan-concurrency-and-stop
fix(scan): refuse concurrent scans and stop queued ones
2026-07-28 18:19:48 -04:00
Ryan McClelland
903df17f6e fix(scan): detect scans on every queue and entry point
Scan job discovery only looked at the high priority queue and only
recognised scan_platforms, so two kinds of in-flight scan went unseen.

Watcher scans are delayed through the scheduler and land in the low
priority queue, so the concurrency guard let a manual scan start
alongside one and the stop handler left it queued to run afterwards.

The scheduled rescan enqueues its own task and calls scan_platforms in
process, so the worker reports the task's name. That made stopping it a
silent no-op: with no running job matched, the stop flag it polls was
never set.

Discovery now spans both queues plus the scheduler and matches either
function name. The scheduler registry also holds the standing cron entry
for the scheduled rescan, which is a schedule rather than a pending
scan, so only delayed scan_platforms jobs count as queued.

Clearing the stop flag at scan start is now scoped to the scan that owns
it, so a scan starting next to one that has not yet polled the flag
cannot drop a stop request meant for it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 12:47:31 -07:00
Ryan McClelland
4bf8f5a15c perf(tasks): walk resource directories with os.scandir
The orphaned resource cleanup listed the resource tree through
`anyio.Path`, which dispatches to a worker thread for every entry it
yields and again for every `is_dir()` call. On a library with ~30k ROM
resource directories that is ~60k thread round trips to read data the
directory listing already contains.

Measured on a 30,262-directory library (Raspberry Pi 4, ext4):

    anyio iterdir + is_dir()   50.3s
    os.scandir                  0.15s

`os.scandir` reports the entry type from the directory read itself, so
no per-entry stat is needed. The walk moves into a helper run once via
`asyncio.to_thread`, keeping the event loop free while doing the whole
traversal in a single thread hop rather than tens of thousands.

Cold and warm runs of the old code were within 1% of each other, so this
was thread-dispatch overhead rather than disk I/O.

A directory that cannot be listed now logs and yields an empty set
instead of aborting the walk, so one unreadable platform cannot strand
every other platform's orphans.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 15:48:30 -07:00
Georges-Antoine Assi
e885792aa1 fix(tasks): skip orphaned resource cleanup when the database looks empty
`cleanup_orphaned_resources` decides what to delete purely by asking whether
a resource directory's id is absent from the database, with no sanity floor.
If `get_platforms()` ever comes back empty while artwork is still on disk
(database unavailable, mid-migration, half-restored backup), every platform
directory is treated as orphaned and removed in a single pass.

That was tolerable when the task only ran on an admin's click. Now that it
can run unattended at 5 AM via `ENABLE_SCHEDULED_CLEANUP_ORPHANED_RESOURCES`,
nobody is watching when it happens.

Bail out when the database reports zero platforms but platform directories
exist on disk, and log a warning saying so. A genuinely emptied library can
still be cleaned by running the task manually with `{"force": true}`, which
the run-task endpoint already forwards to `run()`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-27 17:06:28 -04:00
Ryan McClelland
90d1c72256 feat(tasks): allow orphaned resource cleanup to run on a schedule
Orphaned covers and screenshots left behind by deleted ROMs accumulate
indefinitely, because the only way to reclaim them is to trigger the
cleanup task by hand. On a long-lived instance the resources directory
grows without bound, which is a problem when it shares a filesystem with
the database.

Move the task to `tasks/scheduled/` and turn it into a `PeriodicTask`
with an opt-in cron schedule, defaulting to 5:00 AM so it runs after the
nightly scan and metadata tasks have settled.

`enabled` stays `True` rather than tracking the new env var, because the
run-task endpoint requires both `enabled` and `manual_run`. Gating it
would have silently removed the ability to run the cleanup by hand,
which is how it works today. The cron string is what is opt-in, and
`init()` unschedules when it is unset.

Add the new flag to the init script's scheduler condition, so enabling
only this schedule still starts `rqscheduler`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-27 13:53:30 -07:00
Georges-Antoine Assi
cf1420bd5d Merge branch 'master' into fix/mod-zip-range-requests 2026-07-18 18:15:39 -04:00
Georges-Antoine Assi
3348d9bb29 cleanup 2026-07-06 22:17:56 -04:00
Georges-Antoine Assi
ae60d14f81 Merge branch 'master' into feat/composite-hashing-archives 2026-05-29 11:50:17 -04:00
nendo
41c91fdd5b SaveSync: push null-slot exclusion into the SQL query
Three sync callsites (endpoints/sync.py, sync_watcher.py, and both
branches of tasks/sync_push_pull_task.py) ran get_saves(...) and then
discarded archival null-slot rows in a Python list comprehension. On
libraries with many archival/web-UI uploads that's a strict waste:
those rows are pulled from MariaDB, hydrated into Save model instances,
and then immediately filtered out.

Add a slot_not_null bool kwarg to DBSavesHandler.get_saves and apply
the filter in the SQL query. Update all four callsites to use it and
drop the Python-side comprehension. Default stays False so unrelated
callers keep the current behavior.
2026-05-29 17:40:18 +09:00
nendo
5bb10dacd1 SaveSync: paginate recompute task scan by primary key
get_all_saves() materialized every Save row across all users into a
single .all() list. On instances with very large libraries that's a
real RAM ceiling and pins every row for the lifetime of the recompute
run.

Replace it with get_saves_after_id(after_id, limit) and have the
recompute task drive keyset pagination in PAGE_SIZE-row chunks. SQLAlchemy
streaming via .execution_options(yield_per=...) is incompatible with the
per-call session lifetime that @begin_session enforces (the session
exits before the consumer iterates), so keyset paging from the caller is
the cleanest fit.

Behavior is unchanged: same row coverage, same idempotency, same
counters. Memory usage drops from O(all saves) to O(PAGE_SIZE).
2026-05-29 17:38:49 +09:00
nendo
edb5d15420 Fix save-sync hash drift, archival save leak, and dedupe scoping
Cleanup pass on save-sync addressing three independent failure modes
that interact in production data: content_hash drift between client
and server, null-slot archival saves leaking into sync flows, and
content-hash dedupe collapsing legitimately-distinct slots.

Bug fixes
- compute_content_hash dispatched on zipfile.is_zipfile(relative_path),
  which silently returned False whenever the process's CWD wasn't
  ASSETS_BASE_PATH. Every zip save fell through to the raw-MD5 branch,
  persisting hashes that disagreed with clients computing the intended
  per-entry zip-hash. Resolve to a full path before the dispatch.
- _build_negotiate_plan, sync_push_pull_task, and sync_watcher all
  treated null-slot saves as sync-eligible. Null-slot saves represent
  web-UI / archival uploads; including them in negotiate plans matched
  them against device pushes by filename and overwrote archival data.
  Filter null-slot saves at all three call sites.
- get_save_by_content_hash matched on (rom_id, user_id, content_hash)
  only, so identical bytes uploaded to different slots collapsed into
  one record. Scope the lookup by slot when provided so clone-save-
  to-new-slot creates a distinct row per slot.
- get_save_by_filename matched on (rom_id, user_id, file_name) only.
  When two uploads to different slots happened in the same wall-clock
  second (the datetime tag is per-second), the second upload UPDATED
  the first record's slot instead of creating a distinct row. Scope
  the filename lookup by slot too.

One-shot recovery
- New recompute_save_content_hashes manual task walks every Save row,
  recomputes via the fixed dispatch, and updates rows whose values
  differ. Idempotent; safe to re-run.
- Backend startup runs a COUNT(content_hash IS NULL) query and, if
  any rows exist, enqueues the recompute task on the low-priority
  RQ queue. The API process moves on; the worker handles the
  recompute out-of-band. Subsequent restarts find zero NULL hashes
  and skip. Admins can also trigger the task manually.

Test infrastructure
- Added tests/_zipfile_shim.reload_zipfile() mirroring the pattern
  from utils/zip_cache.py for the same zipfile-inflate64 + CPython
  3.13.5 incompatibility. Test fixtures that build ZIPs call it
  immediately before opening the archive.
2026-05-29 17:00:01 +09:00
Georges-Antoine Assi
a1194dc5e0 changes from bot review 2026-05-28 09:02:26 -04:00
Georges-Antoine Assi
bb2b99099b fix(sync): isolate SSH handler init errors to per-device failure
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-24 16:12:10 -04:00
Claude
26bdc11e13 refactor(filesystem): lazy-init launchbox + sync handlers, drop tolerate_missing_base
Apply the same lazy-factory pattern to FSLaunchboxHandler and FSSyncHandler
that ssh_sync_handler now uses. With both opt-in features deferred to
first-use, the tolerate_missing_base escape hatch on FSHandler is no longer
needed — every handler now fails loudly on mkdir failure, which is the
right behavior for the always-on core paths (assets, library, resources).

Touched call sites:
  - resources_handler._resolve_local_file_uri (launchbox)
  - sync_watcher.py, endpoints/device.py, tasks/manual/sync_folder_scan.py
    (fs_sync)

Net effect:
  - Default installs never poke /romm/launchbox or /romm/sync at startup.
  - Misconfigured opt-in users get a clear, actionable PermissionError at
    the call site instead of a silent warning followed by mystery failures.
  - tolerate_missing_base, its tests, and one stale log import are gone.
2026-05-24 14:59:03 +00:00
Claude
1890958ff2 refactor(sync): make SSH sync handler lazy-initialized
The module-level SSHSyncHandler() singleton ran filesystem side effects
(mkdir on SYNC_SSH_KEYS_PATH) at import time, which meant even default
installs with push-pull sync disabled would touch /romm/sync — and the
previous tolerate-and-warn fallback could leave users wondering why
sync silently does nothing.

Replace the eager singleton with a functools.cache'd factory. The
handler is now constructed on first use, so:

  - Default-install users (ENABLE_SYNC_PUSH_PULL=false, no manual sync
    triggered) never touch /romm/sync.
  - Users opting in get a clear, actionable RuntimeError pointing at
    the unwritable path and the env var to override, at the call site
    rather than buried in a startup stack trace.

Also document in env.template that enabling either sync mode requires
a writable volume at $ROMM_BASE_PATH/sync.
2026-05-24 14:49:53 +00:00
Georges-Antoine Assi
715ec658bd changes from bot review 2026-05-23 07:37:23 -04:00
Georges-Antoine Assi
8c3d82784f fix cleanup orphaned resources 2026-05-18 20:30:18 -04:00
Georges-Antoine Assi
832447bbb1 rnu fmt 2026-04-29 14:30:48 -04:00
copilot-swe-agent[bot]
80b5fdf21f fix: add periodic janitor to clean up orphaned upload tmp directories
Agent-Logs-Url: https://github.com/rommapp/romm/sessions/2e55dd7f-d99d-48a2-ae15-0b8c4817cc6e

Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com>
2026-04-29 16:42:12 +00:00
Georges-Antoine Assi
4928041593 manual cleanu 2026-04-12 11:04:12 -04:00
Georges-Antoine Assi
10f3b25a05 Merge branch 'master' into fix/mod-zip-range-requests 2026-04-07 22:58:10 -04:00
nendo
18864a54f9 Add bulk download caching, LRU eviction, tiered TTL
- Bulk /download endpoint now caches ZIPs for Range requests (max 100 ROMs)
- LRU eviction frees space by removing oldest cached ZIPs (>1h old)
- Tiered TTL: 48h default, 12h for ZIPs over 8GB
- Generalize cache paths from rom_id to namespace (supports bulk-{ids})
2026-03-24 06:34:26 +09:00
nendo
0273d5832c Support Range requests for multi-file ROM downloads
Cache ZIPs to disk on Range requests so nginx can serve 206 natively.
Non-Range requests still stream via mod_zip as before.

Refs: rommapp/romm#3160
2026-03-24 05:56:15 +09:00
Georges-Antoine Assi
f107dc2752 changes from bot rview 2026-03-22 17:17:14 -04:00
Georges-Antoine Assi
4c97eddfc3 fix trunk check 2026-03-22 16:30:14 -04:00
nendo
4edb1710a5 fix: address review feedback on session handler and counter
- Restore NoResultFound behavior on update_session, complete_session,
  fail_session when row is missing (scalar returns None, old .one()
  raised -- silent None is a semantic regression)
- Remove redundant get_session call from _increment_session_counter;
  the atomic SQL increment is already a no-op on missing rows
- Log warning when passed session_id is not found in _sync_device
  instead of silently creating an orphan session
2026-03-16 10:59:49 +09:00
nendo
55638d15dc fix: address bugs, security issues, and convention violations in save-sync
- Fix broken path construction in FSSyncHandler: build_* methods now
  return relative paths; sync_watcher uses paths relative to sync base
  instead of CWD (was completely non-functional in production)
- Fix SSH connection leak in push-pull task: conn.close() now in finally
- Add log.warning for disabled SSH host key verification
- Fix race condition in session operation counter: use atomic SQL
  increment instead of read-then-write
- Extract _increment_session_counter helper, add exc_info to warnings
- Replace legacy session.query() with select() in sync_sessions_handler
- Fix orphaned session: trigger_push_pull now passes session_id to job
- Fix wasteful SSH download when no matched_save exists
- Fix BaseModel import collision in sync.py (pydantic -> project base)
- Fix ORM mutation in UserSchema.from_orm_with_request: set field on
  schema instance instead of mutating live ORM object
- Mask ssh_password and ssh_key_path in DeviceSchema API response
- Fix migration PostgreSQL compatibility: condition ON UPDATE clause
  on MySQL, drop enum in downgrade
- Rename copy-paste artifact rom_user_status_enum
2026-03-16 10:56:43 +09:00
Georges-Antoine Assi
f13f929d7d tweaks based on self review 2026-03-14 22:26:53 -04:00
Georges-Antoine Assi
e6ddc5da11 bot attempt at save sync 2026-03-14 22:13:38 -04:00
Georges-Antoine Assi
7146081d75 dont update user set statutuses 2026-03-12 20:26:30 -04:00
Georges-Antoine Assi
72e884a83c run fmt 2026-03-12 19:02:24 -04:00
copilot-swe-agent[bot]
4234ca3953 fix: always update rom_user status from RA award on each sync run
Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com>
2026-03-12 22:59:47 +00:00
copilot-swe-agent[bot]
da30e4daf1 feat: auto-update game status from RetroAchievements award kind
Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com>
2026-03-11 02:27:38 +00:00
Georges-Antoine Assi
8f8ef1f700 some changes from review 2026-03-10 16:13:21 -04:00
copilot-swe-agent[bot]
f938e627b4 Move cleanup-all missing ROMs to background task to prevent browser hang
Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com>
2026-03-10 02:25:58 +00:00
Georges-Antoine Assi
0c1ea31856 retrun still 2026-03-09 22:06:29 -04:00
copilot-swe-agent[bot]
5e1a4bf35e Fix: automatic library scan blocked when no metadata sources configured
Co-authored-by: gantoine <3247106+gantoine@users.noreply.github.com>
2026-03-10 01:56:47 +00:00
Georges-Antoine Assi
eda88b70d1 get claude to refactor launchbox_handler 2026-03-07 16:02:39 -05:00
Georges-Antoine Assi
395b857592 changes from self review 2026-03-07 14:44:02 -05:00
Georges-Antoine Assi
6de46eb067 Merge branch 'master' into launchbox-handler 2026-03-07 11:31:03 -05:00
Georges-Antoine Assi
ee8b55e6ef last set of changes 2026-03-07 09:56:17 -05:00
Georges-Antoine Assi
7c2c964c32 fix check issues 2026-01-28 16:05:19 -05:00
Georges-Antoine Assi
2a1583e504 Merge branch 'master' into launchbox-handler 2026-01-28 15:01:01 -05:00