mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 10:33:22 +01:00
fix(player): drop stale writes around a save load and clean evicted screenshots (review round 2)
Writes that start while a save load is in flight are dropped, since the bytes they read predate the load, and forced writes capture the write generation before waiting on the queue so a load that lands meanwhile voids them. The tracker clears its boot baseline after the first upload so a return to those bytes still syncs, and a forced write is skipped only when the SRAM matches a slotted save loaded from the server, so a slot-less legacy save still reaches the slot on an unchanged Save & Quit. Autocleanup removes an evicted save's screenshot row and file through the same helper the delete endpoint uses. The launch screen's save list grows with the page outside viewport-fit mode instead of nesting a second scrollbar. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XXrMndq8eYexafm6nhajLo
This commit is contained in:
@@ -103,6 +103,22 @@ def _syncs_for_save(
|
||||
DATETIME_TAG_PATTERN = re.compile(r" \[\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\]")
|
||||
|
||||
|
||||
async def _remove_save_screenshot(save: Save) -> None:
|
||||
screenshot = save.screenshot
|
||||
if not screenshot:
|
||||
return
|
||||
db_screenshot_handler.delete_screenshot(screenshot.id)
|
||||
try:
|
||||
await fs_asset_handler.remove_file(
|
||||
file_path=f"{screenshot.file_path}/{screenshot.file_name}"
|
||||
)
|
||||
except FileNotFoundError:
|
||||
log.error(
|
||||
f"Screenshot file {hl(screenshot.file_name)} not found for save "
|
||||
f"{hl(save.file_name)}[{hl(save.rom.platform_slug)}]"
|
||||
)
|
||||
|
||||
|
||||
def _apply_datetime_tag(filename: str) -> str:
|
||||
name, ext = os.path.splitext(filename)
|
||||
timestamp = datetime.now(timezone.utc).strftime("%Y-%m-%d_%H-%M-%S")
|
||||
@@ -345,6 +361,7 @@ async def add_save(
|
||||
await fs_asset_handler.remove_file(old_save.full_path)
|
||||
except FileNotFoundError:
|
||||
log.warning(f"Could not delete old save file: {old_save.full_path}")
|
||||
await _remove_save_screenshot(old_save)
|
||||
|
||||
if screenshotFile and screenshotFile.filename:
|
||||
try:
|
||||
@@ -760,15 +777,7 @@ async def delete_saves(
|
||||
error = f"Save file {hl(save.file_name)} not found for platform {hl(save.rom.platform_display_name, color=BLUE)}[{hl(save.rom.platform_slug)}]"
|
||||
log.error(error)
|
||||
|
||||
if save.screenshot:
|
||||
db_screenshot_handler.delete_screenshot(save.screenshot.id)
|
||||
|
||||
try:
|
||||
file_path = f"{save.screenshot.file_path}/{save.screenshot.file_name}"
|
||||
await fs_asset_handler.remove_file(file_path=file_path)
|
||||
except FileNotFoundError:
|
||||
error = f"Screenshot file {hl(save.screenshot.file_name)} not found for save {hl(save.file_name)}[{hl(save.rom.platform_slug)}]"
|
||||
log.error(error)
|
||||
await _remove_save_screenshot(save)
|
||||
|
||||
refresh_affected_smart_collections(list(affected_rom_ids), membership_only=True)
|
||||
|
||||
|
||||
@@ -1982,6 +1982,104 @@ class TestAutocleanup:
|
||||
mock_remove.assert_not_called()
|
||||
|
||||
|
||||
class TestAutocleanupScreenshots:
|
||||
@mock.patch(
|
||||
"endpoints.saves.fs_asset_handler.write_file", new_callable=mock.AsyncMock
|
||||
)
|
||||
@mock.patch(
|
||||
"endpoints.saves.fs_asset_handler.remove_file", new_callable=mock.AsyncMock
|
||||
)
|
||||
@mock.patch("endpoints.saves.scan_save", new_callable=mock.AsyncMock)
|
||||
def test_autocleanup_removes_evicted_screenshots(
|
||||
self,
|
||||
mock_scan,
|
||||
mock_remove,
|
||||
mock_write,
|
||||
client,
|
||||
access_token: str,
|
||||
rom: Rom,
|
||||
platform: Platform,
|
||||
admin_user: User,
|
||||
):
|
||||
from handler.database import db_save_handler, db_screenshot_handler
|
||||
from models.assets import Screenshot
|
||||
|
||||
base_time = rom.created_at
|
||||
for i in range(3):
|
||||
save = db_save_handler.add_save(
|
||||
Save(
|
||||
file_name=f"autosave_{i}.sav",
|
||||
file_name_no_tags=f"autosave_{i}",
|
||||
file_name_no_ext=f"autosave_{i}",
|
||||
file_extension="sav",
|
||||
file_path=f"{platform.slug}/saves",
|
||||
file_size_bytes=100,
|
||||
rom_id=rom.id,
|
||||
user_id=admin_user.id,
|
||||
slot="autosave",
|
||||
)
|
||||
)
|
||||
db_save_handler.update_save(
|
||||
save.id, {"updated_at": base_time + timedelta(hours=i)}
|
||||
)
|
||||
db_screenshot_handler.add_screenshot(
|
||||
Screenshot(
|
||||
file_name=f"autosave_{i}.png",
|
||||
file_name_no_tags=f"autosave_{i}",
|
||||
file_name_no_ext=f"autosave_{i}",
|
||||
file_extension="png",
|
||||
file_path=f"{platform.slug}/screenshots",
|
||||
file_size_bytes=10,
|
||||
rom_id=rom.id,
|
||||
user_id=admin_user.id,
|
||||
)
|
||||
)
|
||||
|
||||
mock_scan.return_value = Save(
|
||||
file_name="autosave_new.sav",
|
||||
file_name_no_tags="autosave_new",
|
||||
file_name_no_ext="autosave_new",
|
||||
file_extension="sav",
|
||||
file_path=f"{platform.slug}/saves",
|
||||
file_size_bytes=100,
|
||||
rom_id=rom.id,
|
||||
user_id=admin_user.id,
|
||||
slot="autosave",
|
||||
)
|
||||
response = client.post(
|
||||
f"/api/saves?rom_id={rom.id}&slot=autosave&autocleanup=true&autocleanup_limit=2",
|
||||
files={
|
||||
"saveFile": (
|
||||
"autosave_new.sav",
|
||||
BytesIO(b"new"),
|
||||
"application/octet-stream",
|
||||
)
|
||||
},
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
|
||||
assert response.status_code == status.HTTP_200_OK
|
||||
remaining = {
|
||||
save.file_name_no_ext
|
||||
for save in db_save_handler.get_saves(
|
||||
user_id=admin_user.id, rom_ids=[rom.id], slot="autosave"
|
||||
)
|
||||
}
|
||||
assert len(remaining) == 2
|
||||
evicted = [i for i in range(3) if f"autosave_{i}" not in remaining]
|
||||
assert len(evicted) >= 1
|
||||
# Every evicted save took its screenshot row and file with it.
|
||||
assert mock_remove.call_count == (4 - len(remaining)) + len(evicted)
|
||||
for i in range(3):
|
||||
screenshot = db_screenshot_handler.get_screenshot(
|
||||
rom_id=rom.id,
|
||||
user_id=admin_user.id,
|
||||
file_name=f"autosave_{i}.sav",
|
||||
file_name_no_ext=f"autosave_{i}",
|
||||
)
|
||||
assert (screenshot is None) == (i in evicted)
|
||||
|
||||
|
||||
class TestUploadSizeLimit:
|
||||
def test_rejects_oversized_save_file(self, client, access_token: str, rom: Rom):
|
||||
with mock.patch.object(uploads, "MAX_ASSET_UPLOAD_SIZE_BYTES", 32):
|
||||
|
||||
@@ -57,7 +57,6 @@ import AssetList from "@/v2/components/shared/AssetList.vue";
|
||||
import AssetStrip from "@/v2/components/shared/AssetStrip.vue";
|
||||
import GameCover from "@/v2/components/shared/GameCover.vue";
|
||||
import { useActivityPresence } from "@/v2/composables/useActivityPresence";
|
||||
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
|
||||
import { useCoverArt } from "@/v2/composables/useCoverArt";
|
||||
import { useFullscreenPref } from "@/v2/composables/useFullscreenPref";
|
||||
import { useInputModality } from "@/v2/composables/useInputModality";
|
||||
@@ -109,10 +108,6 @@ const configStore = storeConfig();
|
||||
const { playing, fullScreen } = storeToRefs(playingStore);
|
||||
const { fullscreenOnPlay } = useFullscreenPref();
|
||||
const { modality } = useInputModality();
|
||||
// Wide and tall enough for the hero column: the pre-game screen fits the
|
||||
// viewport and the asset list, not the page, scrolls.
|
||||
const { lgAndUp, tall } = useBreakpoint();
|
||||
const fitsViewport = computed(() => lgAndUp.value && tall.value);
|
||||
const playSession = usePlaySession();
|
||||
|
||||
// Ref the Play CTA so we can imperatively focus it on enter (and again
|
||||
@@ -669,7 +664,7 @@ const saveSlot = computed(() =>
|
||||
:assets="activeAssets"
|
||||
type="save"
|
||||
:selected-id="selectedAssetId"
|
||||
:scrollable="!fitsViewport"
|
||||
:scrollable="false"
|
||||
@select="pickAsset"
|
||||
/>
|
||||
<AssetStrip
|
||||
@@ -1063,7 +1058,9 @@ const saveSlot = computed(() =>
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
/* ── Viewport fit (see fitsViewport) ─────────────────────── */
|
||||
/* ── Viewport fit ────────────────────────────────────────── */
|
||||
/* Wide and tall enough for the hero column, the pre-game screen fits the
|
||||
viewport and only the asset list scrolls. */
|
||||
html[data-bp~="lg-and-up"][data-bp~="tall"] .r-v2-ejs--config {
|
||||
height: calc(100vh - var(--r-nav-h));
|
||||
height: calc(100dvh - var(--r-nav-h));
|
||||
|
||||
@@ -72,14 +72,16 @@ function baselineSaveTrackerFromEmulator() {
|
||||
);
|
||||
}
|
||||
// Writes run one at a time so concurrent writers cannot both open a version;
|
||||
// loading a save bumps the generation, which voids writes queued before it.
|
||||
// loading a save bumps the generation, which voids writes queued before it,
|
||||
// and bytes read while a load is in flight are stale, so they are dropped.
|
||||
let saveWrite: Promise<unknown> = Promise.resolve();
|
||||
let saveGeneration = 0;
|
||||
function writeSave(file: {
|
||||
saveFile: ArrayBuffer;
|
||||
screenshotFile?: ArrayBuffer;
|
||||
}): Promise<SaveSchema | null> {
|
||||
const generation = saveGeneration;
|
||||
let saveLoading = false;
|
||||
function writeSave(
|
||||
file: { saveFile: ArrayBuffer; screenshotFile?: ArrayBuffer },
|
||||
generation = saveGeneration,
|
||||
): Promise<SaveSchema | null> {
|
||||
if (saveLoading) return Promise.resolve(null);
|
||||
const write = saveWrite.then(async () => {
|
||||
if (generation !== saveGeneration) return null;
|
||||
const save = await saveSave({
|
||||
@@ -99,19 +101,22 @@ function writeSave(file: {
|
||||
return write;
|
||||
}
|
||||
// Forced writes (Save button, Save & Quit) wait for the queue, then skip only
|
||||
// when no version was opened yet and the SRAM still matches the loaded save.
|
||||
// when no version was opened yet and the SRAM still matches a slotted save
|
||||
// loaded from the server (a slot-less one still has to reach the slot).
|
||||
async function writeSaveIfChanged(file: {
|
||||
saveFile: ArrayBuffer;
|
||||
screenshotFile?: ArrayBuffer;
|
||||
}): Promise<boolean> {
|
||||
const generation = saveGeneration;
|
||||
await saveWrite;
|
||||
if (
|
||||
!sessionSaveRef.value &&
|
||||
loadedSave?.slot &&
|
||||
saveTracker.isUploaded(new Uint8Array(file.saveFile))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
return (await writeSave(file)) !== null;
|
||||
return (await writeSave(file, generation)) !== null;
|
||||
}
|
||||
const theme = useTheme();
|
||||
const emitter = inject<Emitter<Events>>("emitter");
|
||||
@@ -370,26 +375,31 @@ function installAutoSaveSync() {
|
||||
// Saves management
|
||||
async function loadSave(save: SaveSchema) {
|
||||
saveGeneration += 1;
|
||||
saveLoading = true;
|
||||
loadedSave = save;
|
||||
sessionSaveRef.value = null;
|
||||
|
||||
const { data } = await api.get(save.download_path.replace("/api", ""), {
|
||||
responseType: "arraybuffer",
|
||||
params: { device_id: deviceIDRef.value },
|
||||
});
|
||||
if (data) {
|
||||
const bytes = new Uint8Array(data);
|
||||
loadEmulatorJSSave(bytes);
|
||||
saveTracker.seed(bytes);
|
||||
displayMessage("Save loaded from server", {
|
||||
duration: 3000,
|
||||
icon: "mdi-cloud-download-outline",
|
||||
try {
|
||||
const { data } = await api.get(save.download_path.replace("/api", ""), {
|
||||
responseType: "arraybuffer",
|
||||
params: { device_id: deviceIDRef.value },
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (data) {
|
||||
const bytes = new Uint8Array(data);
|
||||
loadEmulatorJSSave(bytes);
|
||||
saveTracker.seed(bytes);
|
||||
displayMessage("Save loaded from server", {
|
||||
duration: 3000,
|
||||
icon: "mdi-cloud-download-outline",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const file = await window.EJS_emulator.selectFile();
|
||||
loadEmulatorJSSave(new Uint8Array(await file.arrayBuffer()));
|
||||
const file = await window.EJS_emulator.selectFile();
|
||||
loadEmulatorJSSave(new Uint8Array(await file.arrayBuffer()));
|
||||
} finally {
|
||||
saveLoading = false;
|
||||
}
|
||||
}
|
||||
|
||||
window.EJS_onLoadSave = async function () {
|
||||
|
||||
@@ -218,6 +218,11 @@ describe("createSaveSyncTracker", () => {
|
||||
|
||||
expect(tracker.shouldUpload(bytes(9))).toBe(false);
|
||||
expect(tracker.shouldUpload(bytes(9))).toBe(true);
|
||||
|
||||
// Once something was uploaded, returning to the baseline bytes is a change.
|
||||
tracker.markUploaded(bytes(9));
|
||||
expect(tracker.shouldUpload(bytes(1, 2, 3))).toBe(false);
|
||||
expect(tracker.shouldUpload(bytes(1, 2, 3))).toBe(true);
|
||||
});
|
||||
|
||||
it("compares content, not identity, and treats a resize as a change", () => {
|
||||
|
||||
@@ -175,6 +175,7 @@ export function createSaveSyncTracker() {
|
||||
},
|
||||
markUploaded(save: Uint8Array) {
|
||||
lastUploaded = save;
|
||||
baseline = null;
|
||||
},
|
||||
// Whether the server already holds these exact bytes.
|
||||
isUploaded(save: Uint8Array): boolean {
|
||||
|
||||
Reference in New Issue
Block a user