Files
romm/backend/handler/filesystem/sync_handler.py
Georges-Antoine Assi e232a52656 fix(docker): boot when the container runs as a non-default UID (#5189)
* fix(docker): boot when the container runs as a non-default UID

Unraid runs the container as 99:100, which can't write to the image's
/romm (owned by 1000, mode 755), only to the mounted subfolders. The
PSP pending dir at /romm/cache/retroarch_sync was created at import
time, so every gunicorn worker failed to boot.

- Buffer pending PSP save files under the user's assets folder
  (assets/users/<user>/retroarch/psp_pending/), beside the other
  RetroArch Cloud Sync files and outside the client-reachable blob
  categories.
- Move the zip and rom-converto download caches to /tmp/romm/cache,
  and point nginx's internal /cache/ alias there.
- Put gunicorn's control socket in /tmp/gunicorn instead of
  $HOME/.gunicorn, since HOME is / for that UID.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): honor ROMM_TMP_PATH for caches, explain an unwritable sync folder

- The download caches live under $ROMM_TMP_PATH/cache when it's set,
  so installs with a small Docker disk (Unraid's docker.img) can point
  them at a share. The entrypoint exports the same path for nginx's
  /cache/ alias.
- With ENABLE_SYNC_FOLDER_WATCHER on and /romm/sync not writable, /init
  warns and skips the watcher instead of dying on mkdir under errexit.
- The compose example lists the /romm/sync mount the sync features need.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* test(sync): cover reading back and clearing buffered PSP files

Addresses Greptile's review on #5189.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): apply code-review findings to PSP pending buffer

Remove the emptied psp_pending folder after a merge, define the sync
folder path once in init, update the architecture doc's PSP and blob
locations, and drop a stale .gitignore entry.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor(sync): apply simplify findings to PSP pending cleanup

Clear the buffered folder with remove_directory, let the startup check
own creating the sync folder, and reword the test fixture docstring.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): cap buffered PSP files and drop them on delete

Buffered files for an unresolved save folder now count against the
bundle limits, so a folder can't fill the assets share and then fail
every merge once it resolves. A DELETE also removes the buffered copy,
so a deleted file isn't merged back when the folder resolves.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): check the sync folder for push-pull sync too

ENABLE_SYNC_PUSH_PULL keeps SSH keys and device saves under /romm/sync
as well, so an unwritable folder now disables it with the watcher and
warns at boot instead of failing when the task runs.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(docker): strip whitespace from env vars like the backend does

The backend strips every variable it reads, while the init script and
nginx templates used raw values, so a padded ROMM_TMP_PATH sent nginx's
/cache/ alias somewhere the backend never writes.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* chore(config): drop the CACHE_BASE_PATH comment

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(docker): say which backend config strips env whitespace

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* revert(docker): drop the entrypoint env whitespace trimming

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(sync): apply pr-ready code-review findings

Gate push-pull on its SSH keys path rather than a writable sync folder,
accept the same truthy values as the backend, and clear only the merged
PSP pending files so another worker's buffered file survives.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* refactor: apply pr-ready simplify findings

Share one truthy pattern across init's flag checks (the watcher gates
now accept the same values as the backend), disable gunicorn's unused
control socket instead of placing it, derive the converts redirect from
its own cache path, and factor the unknown PSP folder in tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* docs(docker): apply pr-ready humanizer pass to the sync mount note

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

* fix(fs): create handler base folders on first write, skip leftover temp files

FSHandler no longer mkdirs its base path when constructed, so a module-level
handler rooted at an unmounted or unwritable folder can't take down boot;
every write path already creates its parent folders. Blob listings skip
.romm_tmp_ files a crashed write left behind, so they are never merged into
a PSP bundle or advertised in the sync manifest. The prefix now lives in one
TEMP_FILE_PREFIX constant.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-08 16:48:50 -04:00

117 lines
4.0 KiB
Python

import functools
import os
from pathlib import Path
from typing import Any
from config import SYNC_BASE_PATH
from logger.logger import log
from .assets_handler import hash_save_file
from .base_handler import FSHandler
class FSSyncHandler(FSHandler):
"""Filesystem handler for sync folder operations (File Transfer mode)."""
def __init__(self) -> None:
super().__init__(base_path=SYNC_BASE_PATH)
def build_incoming_path(
self, device_id: str, platform_slug: str | None = None
) -> str:
parts = [device_id, "incoming"]
if platform_slug:
parts.append(platform_slug)
return os.path.join(*parts)
def build_outgoing_path(
self, device_id: str, platform_slug: str | None = None
) -> str:
parts = [device_id, "outgoing"]
if platform_slug:
parts.append(platform_slug)
return os.path.join(*parts)
def build_conflicts_path(
self, device_id: str, platform_slug: str | None = None
) -> str:
parts = [device_id, "conflicts"]
if platform_slug:
parts.append(platform_slug)
return os.path.join(*parts)
def ensure_device_directories(self, device_id: str) -> None:
incoming = self.base_path / self.build_incoming_path(device_id)
outgoing = self.base_path / self.build_outgoing_path(device_id)
incoming.mkdir(parents=True, exist_ok=True)
outgoing.mkdir(parents=True, exist_ok=True)
log.info(f"Ensured sync directories for device {device_id}")
def list_incoming_files(self, device_id: str) -> list[dict[str, Any]]:
"""List all files in a device's incoming directory.
Returns list of dicts with keys: platform_slug, file_name, full_path, file_size, mtime
"""
incoming_dir = self.base_path / self.build_incoming_path(device_id)
if not incoming_dir.exists():
return []
results = []
for platform_dir in incoming_dir.iterdir():
if not platform_dir.is_dir():
continue
platform_slug = platform_dir.name
for file_path in platform_dir.rglob("*"):
if not file_path.is_file():
continue
stat = file_path.stat()
results.append(
{
"platform_slug": platform_slug,
"file_name": file_path.name,
"full_path": str(file_path),
"relative_path": str(file_path.relative_to(incoming_dir)),
"file_size": stat.st_size,
"mtime": stat.st_mtime,
}
)
return results
def compute_file_hash(self, file_path: str) -> str | None:
"""Hash a device file synchronously (for watcher context)."""
return hash_save_file(file_path)
def write_outgoing_file(
self, device_id: str, platform_slug: str, file_name: str, data: bytes
) -> str:
"""Write a file to a device's outgoing directory."""
outgoing_dir = self.base_path / self.build_outgoing_path(
device_id, platform_slug
)
outgoing_dir.mkdir(parents=True, exist_ok=True)
file_path = outgoing_dir / file_name
file_path.write_bytes(data)
return str(file_path)
def remove_incoming_file(self, full_path: str) -> None:
"""Remove a processed file from the incoming directory."""
path = Path(full_path)
if path.exists() and path.is_file():
# Validate the file is within our base path
try:
path.resolve().relative_to(self.base_path.resolve())
except ValueError as e:
raise ValueError(
f"Path {full_path} is outside the sync base directory"
) from e
path.unlink()
@functools.cache
def get_fs_sync_handler() -> FSSyncHandler:
"""Lazily instantiate the sync folder handler on first use."""
return FSSyncHandler()