mirror of
https://github.com/rommapp/romm.git
synced 2026-12-02 10:08:40 +01:00
Merge pull request #3316 from rommapp/copilot/fix-chunked-uploads-ram-issue
Fix chunked uploads writing to RAM/tmpfs and upload speed showing 0 B/s
This commit is contained in:
@@ -1,6 +1,5 @@
|
||||
import json
|
||||
import shutil
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
from typing import Annotated
|
||||
from uuid import UUID, uuid4
|
||||
@@ -9,6 +8,7 @@ from anyio import open_file
|
||||
from fastapi import Header, HTTPException, Request, status
|
||||
from starlette.responses import Response
|
||||
|
||||
from config import ROMM_BASE_PATH, ROMM_TMP_PATH
|
||||
from decorators.auth import protected_route
|
||||
from handler.auth.constants import Scope
|
||||
from handler.database import db_platform_handler
|
||||
@@ -22,7 +22,10 @@ router = APIRouter(
|
||||
tags=["upload"],
|
||||
)
|
||||
|
||||
ROM_UPLOAD_TMP_BASE = Path(tempfile.gettempdir()) / "romm" / "uploads"
|
||||
# Store upload chunks under ROMM_BASE_PATH (disk-backed) by default.
|
||||
# Users can override the tmp location with the ROMM_TMP_PATH env variable.
|
||||
_tmp_root = Path(ROMM_TMP_PATH) if ROMM_TMP_PATH else Path(ROMM_BASE_PATH)
|
||||
ROM_UPLOAD_TMP_BASE = _tmp_root / "tmp" / "uploads"
|
||||
ROM_UPLOAD_TTL = 86400 # 24 hours
|
||||
ROM_ASSEMBLY_CHUNK_SIZE = 8192 # 8KB read buffer during assembly
|
||||
ROM_UPLOAD_MAX_CHUNK_SIZE = 64 * 1024 * 1024 # 64MB hard cap per chunk
|
||||
|
||||
@@ -27,6 +27,7 @@ from handler.redis_handler import async_cache
|
||||
from logger.logger import log
|
||||
from models.firmware import FIRMWARE_FIXTURES_DIR, KNOWN_BIOS_KEY
|
||||
from tasks.scheduled.cleanup_netplay import cleanup_netplay_task
|
||||
from tasks.scheduled.cleanup_upload_tmp import cleanup_upload_tmp_task
|
||||
from tasks.scheduled.convert_images_to_webp import convert_images_to_webp_task
|
||||
from tasks.scheduled.scan_library import scan_library_task
|
||||
from tasks.scheduled.sync_retroachievements_progress import (
|
||||
@@ -51,6 +52,7 @@ async def main() -> None:
|
||||
|
||||
# Initialize scheduled tasks
|
||||
cleanup_netplay_task.init()
|
||||
cleanup_upload_tmp_task.init()
|
||||
|
||||
if ENABLE_SCHEDULED_RESCAN:
|
||||
log.info("Starting scheduled rescan")
|
||||
|
||||
48
backend/tasks/scheduled/cleanup_upload_tmp.py
Normal file
48
backend/tasks/scheduled/cleanup_upload_tmp.py
Normal file
@@ -0,0 +1,48 @@
|
||||
import shutil
|
||||
import time
|
||||
|
||||
from endpoints.roms.upload import ROM_UPLOAD_TMP_BASE, ROM_UPLOAD_TTL
|
||||
from logger.logger import log
|
||||
from tasks.tasks import PeriodicTask, TaskType
|
||||
|
||||
|
||||
class CleanupUploadTmpTask(PeriodicTask):
|
||||
def __init__(self):
|
||||
super().__init__(
|
||||
title="Scheduled upload tmp cleanup",
|
||||
description="Cleans up orphaned chunked-upload temp directories",
|
||||
task_type=TaskType.CLEANUP,
|
||||
enabled=True,
|
||||
manual_run=False,
|
||||
cron_string="0 * * * *", # Every hour
|
||||
func="tasks.scheduled.cleanup_upload_tmp.cleanup_upload_tmp_task.run",
|
||||
)
|
||||
|
||||
async def run(self) -> None:
|
||||
if not self.enabled:
|
||||
self.unschedule()
|
||||
return
|
||||
|
||||
if not ROM_UPLOAD_TMP_BASE.exists():
|
||||
return
|
||||
|
||||
cutoff = time.time() - ROM_UPLOAD_TTL
|
||||
removed = 0
|
||||
|
||||
for entry in ROM_UPLOAD_TMP_BASE.iterdir():
|
||||
if not entry.is_dir():
|
||||
continue
|
||||
try:
|
||||
if entry.stat().st_mtime < cutoff:
|
||||
shutil.rmtree(entry, ignore_errors=True)
|
||||
removed += 1
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
if removed:
|
||||
log.info(
|
||||
f"Cleaned up {removed} orphaned upload tmp director{'y' if removed == 1 else 'ies'}"
|
||||
)
|
||||
|
||||
|
||||
cleanup_upload_tmp_task = CleanupUploadTmpTask()
|
||||
86
backend/tests/tasks/test_cleanup_upload_tmp.py
Normal file
86
backend/tests/tasks/test_cleanup_upload_tmp.py
Normal file
@@ -0,0 +1,86 @@
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from tasks.scheduled.cleanup_upload_tmp import CleanupUploadTmpTask
|
||||
|
||||
|
||||
class TestCleanupUploadTmpTask:
|
||||
@pytest.fixture
|
||||
def task(self):
|
||||
return CleanupUploadTmpTask()
|
||||
|
||||
def test_init(self, task):
|
||||
"""Test task initialization"""
|
||||
assert (
|
||||
task.func
|
||||
== "tasks.scheduled.cleanup_upload_tmp.cleanup_upload_tmp_task.run"
|
||||
)
|
||||
assert task.enabled is True
|
||||
assert task.cron_string == "0 * * * *"
|
||||
|
||||
async def test_run_no_tmp_dir(self, task, monkeypatch, tmp_path):
|
||||
"""Task is a no-op when the uploads tmp directory does not exist."""
|
||||
import tasks.scheduled.cleanup_upload_tmp as mod
|
||||
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TMP_BASE", tmp_path / "nonexistent")
|
||||
# Should complete without error
|
||||
await task.run()
|
||||
|
||||
async def test_run_removes_expired_dirs(self, task, monkeypatch, tmp_path):
|
||||
"""Directories whose mtime is older than ROM_UPLOAD_TTL should be removed."""
|
||||
import tasks.scheduled.cleanup_upload_tmp as mod
|
||||
|
||||
uploads = tmp_path / "uploads"
|
||||
uploads.mkdir()
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TMP_BASE", uploads)
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TTL", 3600)
|
||||
|
||||
old_dir = uploads / "old-upload"
|
||||
old_dir.mkdir()
|
||||
# Backdate mtime to 2 hours ago
|
||||
old_ts = time.time() - 7200
|
||||
import os
|
||||
|
||||
os.utime(old_dir, (old_ts, old_ts))
|
||||
|
||||
await task.run()
|
||||
|
||||
assert not old_dir.exists()
|
||||
|
||||
async def test_run_keeps_recent_dirs(self, task, monkeypatch, tmp_path):
|
||||
"""Directories whose mtime is within ROM_UPLOAD_TTL should be kept."""
|
||||
import tasks.scheduled.cleanup_upload_tmp as mod
|
||||
|
||||
uploads = tmp_path / "uploads"
|
||||
uploads.mkdir()
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TMP_BASE", uploads)
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TTL", 3600)
|
||||
|
||||
recent_dir = uploads / "recent-upload"
|
||||
recent_dir.mkdir()
|
||||
# mtime is now (within TTL)
|
||||
|
||||
await task.run()
|
||||
|
||||
assert recent_dir.exists()
|
||||
|
||||
async def test_run_skips_files(self, task, monkeypatch, tmp_path):
|
||||
"""Files (not directories) in the uploads root are left untouched."""
|
||||
import tasks.scheduled.cleanup_upload_tmp as mod
|
||||
|
||||
uploads = tmp_path / "uploads"
|
||||
uploads.mkdir()
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TMP_BASE", uploads)
|
||||
monkeypatch.setattr(mod, "ROM_UPLOAD_TTL", 3600)
|
||||
|
||||
stale_file = uploads / "stale.tmp"
|
||||
stale_file.write_bytes(b"data")
|
||||
old_ts = time.time() - 7200
|
||||
import os
|
||||
|
||||
os.utime(stale_file, (old_ts, old_ts))
|
||||
|
||||
await task.run()
|
||||
|
||||
assert stale_file.exists()
|
||||
@@ -67,7 +67,12 @@ async function uploadRomChunked({
|
||||
onUploadProgress: (progressEvent: AxiosProgressEvent) => {
|
||||
const chunkFraction = progressEvent.progress ?? 0;
|
||||
const overall = ((i + chunkFraction) / totalChunks) * 100;
|
||||
uploadStore.updateChunkProgress(file.name, overall, file.size);
|
||||
uploadStore.updateChunkProgress(
|
||||
file.name,
|
||||
overall,
|
||||
file.size,
|
||||
progressEvent.rate,
|
||||
);
|
||||
},
|
||||
});
|
||||
lastError = null;
|
||||
|
||||
@@ -47,6 +47,7 @@ export default defineStore("upload", {
|
||||
filename: string,
|
||||
overallPercent: number,
|
||||
totalBytes: number,
|
||||
rate?: number,
|
||||
) {
|
||||
const file = this.files.find((f) => f.filename === filename);
|
||||
if (!file) return;
|
||||
@@ -54,6 +55,7 @@ export default defineStore("upload", {
|
||||
file.progress = overallPercent;
|
||||
file.total = totalBytes;
|
||||
file.loaded = (overallPercent / 100) * totalBytes;
|
||||
file.rate = rate ?? file.rate;
|
||||
file.finished = overallPercent >= 100;
|
||||
},
|
||||
fail(filename: string, reason: string) {
|
||||
|
||||
Reference in New Issue
Block a user