diff --git a/backend/endpoints/roms/upload.py b/backend/endpoints/roms/upload.py index 58c09c83c..b69d93ae0 100644 --- a/backend/endpoints/roms/upload.py +++ b/backend/endpoints/roms/upload.py @@ -269,16 +269,23 @@ async def start_chunked_upload( ], total_size: Annotated[ int, - Header(alias="x-upload-total-size", ge=1), + Header(alias="x-upload-total-size", ge=0), ], total_chunks: Annotated[ int, - Header(alias="x-upload-total-chunks", ge=1), + Header(alias="x-upload-total-chunks", ge=0), ], target: UploadTargetPayload | None = None, ) -> dict: """Initiate a chunked ROM upload session.""" + # An empty file takes no chunks and goes straight to /complete. + if total_size > 0 and total_chunks == 0: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, + detail="A non-empty file needs at least one chunk", + ) + db_platform = db_platform_handler.get_platform(platform_id) if not db_platform: raise HTTPException( diff --git a/backend/tests/endpoints/roms/test_upload.py b/backend/tests/endpoints/roms/test_upload.py index a51c834bb..3e76c69ce 100644 --- a/backend/tests/endpoints/roms/test_upload.py +++ b/backend/tests/endpoints/roms/test_upload.py @@ -134,6 +134,48 @@ def test_upload_chunk_complete_success( assert final_file.read_bytes() == b"ABCDEFGHIJK" +def test_upload_empty_file_without_chunks( + client: TestClient, + access_token: str, + platform: Platform, + upload_fs: dict, +): + start_response = _start_upload( + client, + access_token, + platform.id, + filename="empty.nsp", + total_size=0, + total_chunks=0, + ) + assert start_response.status_code == status.HTTP_201_CREATED + upload_id = start_response.json()["upload_id"] + + complete = client.post( + f"/api/roms/upload/{upload_id}/complete", + headers=_auth_headers(access_token), + ) + + assert complete.status_code == status.HTTP_201_CREATED + final_file = upload_fs["final_dir"] / "empty.nsp" + assert final_file.exists() + assert final_file.read_bytes() == b"" + + +def test_start_non_empty_file_without_chunks_returns_400( + client: TestClient, + access_token: str, + platform: Platform, + upload_fs: dict, +): + response = _start_upload( + client, access_token, platform.id, total_size=11, total_chunks=0 + ) + + assert response.status_code == status.HTTP_400_BAD_REQUEST + assert response.json()["detail"] == "A non-empty file needs at least one chunk" + + def test_upload_chunk_invalid_upload_id(client: TestClient, access_token: str): response = client.put( "/api/roms/upload/not-a-uuid", diff --git a/frontend/src/services/api/rom.test.ts b/frontend/src/services/api/rom.test.ts index b215c99af..6cc9d8575 100644 --- a/frontend/src/services/api/rom.test.ts +++ b/frontend/src/services/api/rom.test.ts @@ -1,6 +1,7 @@ import { createPinia, setActivePinia } from "pinia"; import { beforeEach, describe, expect, it, vi } from "vitest"; import romApi, { type UpdateRom } from "@/services/api/rom"; +import storeUpload from "@/stores/upload"; const { get, post, put } = vi.hoisted(() => ({ get: vi.fn(), @@ -163,6 +164,26 @@ describe("romApi.uploadRoms", () => { expect(startCall().body).toEqual({ filename: "readme.txt", rom_id: 42 }); }); + + it("completes an empty file without sending chunks", async () => { + const results = await romApi.uploadRoms({ + platformId: 3, + filesToUpload: [new File([], "empty.nsp")], + }); + + expect(results[0].status).toBe("fulfilled"); + expect(startCall().headers).toMatchObject({ + "X-Upload-Total-Size": "0", + "X-Upload-Total-Chunks": "0", + }); + expect(put).not.toHaveBeenCalled(); + expect(post).toHaveBeenCalledWith( + "/roms/upload/u-1/complete", + null, + expect.anything(), + ); + expect(storeUpload().files[0].finished).toBe(true); + }); }); describe("getRoms game-length range", () => { diff --git a/frontend/src/services/api/rom.ts b/frontend/src/services/api/rom.ts index 7020d3561..2cdd167b6 100644 --- a/frontend/src/services/api/rom.ts +++ b/frontend/src/services/api/rom.ts @@ -78,6 +78,9 @@ async function uploadRomChunked({ }); const { upload_id } = startData; + // An empty file sends no chunks, so no chunk ever reports it done. + if (totalChunks === 0) uploadStore.updateChunkProgress(file.name, 100, 0); + for (let i = 0; i < totalChunks; i++) { const start = i * UPLOAD_CHUNK_SIZE; const chunk = file.slice( diff --git a/frontend/src/services/api/save.ts b/frontend/src/services/api/save.ts index ed05abbae..f108ea6b7 100644 --- a/frontend/src/services/api/save.ts +++ b/frontend/src/services/api/save.ts @@ -32,6 +32,24 @@ export function sessionSaveFile( ); } +/** + * A save's picture. An update reuses the picture's name so it is replaced in + * place; a save without one takes the save's stem, which links the two. + */ +export function sessionScreenshotFile( + rom: { fs_name_no_ext: string }, + save: SaveSchema | null, + bytes: ArrayBuffer, +): File { + return new File( + [bytes], + save + ? (save.screenshot?.file_name ?? `${save.file_name_no_ext}.png`) + : `${rom.fs_name_no_ext.trim()}.png`, + { type: "application/octet-stream" }, + ); +} + type SaveUploadInput = Omit & { saveFile: File; screenshotFile?: File; diff --git a/frontend/src/services/api/state.ts b/frontend/src/services/api/state.ts index f4399aea7..2816e2ce4 100644 --- a/frontend/src/services/api/state.ts +++ b/frontend/src/services/api/state.ts @@ -22,6 +22,23 @@ export function sessionStateName( return `${rom.fs_name_no_ext.trim()} [${timestamp}]`; } +/** A state and its picture, both named after the moment of the capture. */ +export function sessionStateFiles( + rom: { fs_name_no_ext: string }, + capturedAt: Date, + stateBytes: ArrayBuffer, + screenshotBytes?: ArrayBuffer, +): { stateFile: File; screenshotFile?: File } { + const name = sessionStateName(rom, capturedAt); + const type = "application/octet-stream"; + return { + stateFile: new File([stateBytes], `${name}.state`, { type }), + screenshotFile: screenshotBytes + ? new File([screenshotBytes], `${name}.png`, { type }) + : undefined, + }; +} + type StateUploadInput = Omit & { stateFile: File; screenshotFile?: File; diff --git a/frontend/src/services/pending-asset.ts b/frontend/src/services/pending-asset.ts index 0996bf82b..38e538c0d 100644 --- a/frontend/src/services/pending-asset.ts +++ b/frontend/src/services/pending-asset.ts @@ -6,13 +6,16 @@ import axios from "axios"; import type { DetailedRomSchema } from "@/__generated__"; import { isCsrfFailure } from "@/services/api"; import romApi from "@/services/api/rom"; -import saveApi, { AUTOSAVE_SLOT, sessionSaveFile } from "@/services/api/save"; -import stateApi, { sessionStateName } from "@/services/api/state"; +import saveApi, { + AUTOSAVE_SLOT, + sessionSaveFile, + sessionScreenshotFile, +} from "@/services/api/save"; +import stateApi, { sessionStateFiles } from "@/services/api/state"; import storeAuth from "@/stores/auth"; +import { errorMessage } from "@/v2/utils/errorMessage"; const DB_NAME = "romm-player"; -// A row cannot be rekeyed or reshaped in place, so every upgrade rebuilds the -// store rather than migrating it. const DB_VERSION = 4; const STORE_NAME = "pending-assets"; @@ -51,22 +54,21 @@ export function pendingAssetId(romId: number): string { return `${romId}:${randomToken()}`; } -export interface PendingAssetStore { - list(): Promise; - write(entry: PendingAsset): Promise; - clear(id: string): Promise; -} - function openDatabase(): Promise { return new Promise((resolve, reject) => { const request = indexedDB.open(DB_NAME, DB_VERSION); let abandoned = false; + // The rows are the player's unsynced progress, so an upgrade keeps them: + // it only drops the stores this version has stopped using. request.onupgradeneeded = () => { const db = request.result; - for (const name of Array.from(db.objectStoreNames)) { - db.deleteObjectStore(name); + const names = Array.from(db.objectStoreNames); + for (const name of names) { + if (name !== STORE_NAME) db.deleteObjectStore(name); + } + if (!names.includes(STORE_NAME)) { + db.createObjectStore(STORE_NAME, { keyPath: "id" }); } - db.createObjectStore(STORE_NAME, { keyPath: "id" }); }; request.onsuccess = () => { // The open landed after the wait was given up on; nothing holds the @@ -123,23 +125,27 @@ function currentUserId(): number | null { return storeAuth().user?.id ?? null; } -const pendingAssetStore: PendingAssetStore = { +// Rows the server has taken. A delete that does not stick would otherwise have +// this upload the same progress again on the next pass, and again after that. +const accepted = new Set(); + +const pendingAssetStore = { // A browser is shared: rows belong to the account that captured them, or one // user's progress lands in the account of whoever signs in next. - async list() { + async list(): Promise { const rows = (await withStore("readonly", (store) => store.getAll(), )) ?? []; const userId = currentUserId(); - return rows.filter((row) => row.userId === userId); + return rows.filter((row) => row.userId === userId && !accepted.has(row.id)); }, - async write(entry) { + async write(entry: PendingAsset) { await withStore("readwrite", (store) => store.put({ ...entry, userId: currentUserId() }), ); }, - async clear(id) { + async clear(id: string) { await withStore("readwrite", (store) => store.delete(id)); }, }; @@ -152,22 +158,16 @@ export async function pendingAssetKinds( ): Promise> { const entries = await pendingAssetStore.list(); return new Set( - entries - .filter((entry) => entry.romId === romId && !accepted.has(entry.id)) - .map((entry) => entry.kind), + entries.filter((entry) => entry.romId === romId).map((entry) => entry.kind), ); } -// Rows the server has taken. A delete that does not stick would otherwise have -// this upload the same progress again on the next pass, and again after that. -const accepted = new Set(); - async function uploadSave( entry: PendingAsset, rom: DetailedRomSchema, ): Promise | undefined> { const slot = entry.slot ?? AUTOSAVE_SLOT; - const uploaded = await saveApi.uploadSaves({ + const [uploaded] = await saveApi.uploadSaves({ rom, emulator: entry.emulator, deviceId: entry.deviceId, @@ -180,16 +180,12 @@ async function uploadSave( { saveFile: sessionSaveFile(rom, null, entry.bytes), screenshotFile: entry.screenshotBytes - ? new File( - [entry.screenshotBytes], - `${rom.fs_name_no_ext.trim()}.png`, - { type: "application/octet-stream" }, - ) + ? sessionScreenshotFile(rom, null, entry.screenshotBytes) : undefined, }, ], }); - return uploaded[0]; + return uploaded; } async function uploadState( @@ -198,24 +194,19 @@ async function uploadState( ): Promise | undefined> { // The backend files a state under the row already at that name, so pinning // the name to the capture has a retry update it rather than duplicate it. - const name = sessionStateName(rom, new Date(entry.capturedAt)); - const uploaded = await stateApi.uploadStates({ + const [uploaded] = await stateApi.uploadStates({ rom, emulator: entry.emulator, statesToUpload: [ - { - stateFile: new File([entry.bytes], `${name}.state`, { - type: "application/octet-stream", - }), - screenshotFile: entry.screenshotBytes - ? new File([entry.screenshotBytes], `${name}.png`, { - type: "application/octet-stream", - }) - : undefined, - }, + sessionStateFiles( + rom, + new Date(entry.capturedAt), + entry.bytes, + entry.screenshotBytes, + ), ], }); - return uploaded[0]; + return uploaded; } // A server that is failing, a network that is down and an expired session all @@ -230,18 +221,11 @@ const RETRYABLE_STATUSES = new Set([401, 408, 425, 429]); */ function permanentRefusal(error: unknown): string | null { if (!axios.isAxiosError(error) || !error.response) return null; - const { status, statusText, data } = error.response; + const { status } = error.response; if (status >= 500 || RETRYABLE_STATUSES.has(status)) return null; // The interceptor has already fetched a fresh token for this one. if (isCsrfFailure(error)) return null; - const detail = data?.detail; - return (typeof detail === "string" && detail) || statusText || error.message; -} - -interface AssetOutcome { - asset: SyncedAsset; - /** Set when the server refused it for good and the row was dropped. */ - reason?: string; + return errorMessage(error); } // A row the server has answered for is no longer owed, refused as much as @@ -249,26 +233,21 @@ interface AssetOutcome { async function settle( entry: PendingAsset, rom: DetailedRomSchema | null, - reason?: string, -): Promise { +): Promise { accepted.add(entry.id); await pendingAssetStore.clear(entry.id); return { - asset: { - kind: entry.kind, - romId: entry.romId, - name: rom?.name ?? rom?.fs_name_no_ext ?? entry.romName, - cover: rom?.path_cover_small, - }, - reason, + kind: entry.kind, + romId: entry.romId, + name: rom?.name ?? rom?.fs_name_no_ext ?? entry.romName, + cover: rom?.path_cover_small, }; } async function uploadPendingAsset( entry: PendingAsset, roms: Map, -): Promise { - if (accepted.has(entry.id)) return null; +): Promise { if (!entry.bytes?.byteLength) { await pendingAssetStore.clear(entry.id); return null; @@ -283,14 +262,13 @@ async function uploadPendingAsset( ? await uploadState(entry, rom) : await uploadSave(entry, rom); if (upload?.status === "fulfilled") return settle(entry, rom); - - const refusal = permanentRefusal( - upload?.status === "rejected" ? upload.reason : null, - ); - return refusal ? settle(entry, rom, refusal) : null; + // A refusal is judged in the same place as a request that never landed. + throw upload?.status === "rejected" + ? upload.reason + : new Error("The server returned no upload result"); } catch (error) { - const refusal = permanentRefusal(error); - if (refusal) return settle(entry, rom, refusal); + const reason = permanentRefusal(error); + if (reason) return { ...(await settle(entry, rom)), reason }; console.error("Pending asset sync failed", error); return null; } @@ -336,14 +314,16 @@ export async function syncPendingAssets( if (!kinds.includes(entry.kind)) continue; const outcome = await uploadPendingAsset(entry, roms); if (!outcome) continue; - if (outcome.reason === undefined) synced.push(outcome.asset); - else dropped.push({ ...outcome.asset, reason: outcome.reason }); + if ("reason" in outcome) dropped.push(outcome); + else synced.push(outcome); } return { synced, dropped }; } -/** Whether anything is still owed, ignoring rows a delete failed to remove. */ -export async function hasPendingAssets(): Promise { +/** Whether anything of these kinds is still owed. */ +export async function hasPendingAssets( + kinds: readonly PendingAssetKind[] = ["save", "state"], +): Promise { const entries = await pendingAssetStore.list(); - return entries.some((entry) => !accepted.has(entry.id)); + return entries.some((entry) => kinds.includes(entry.kind)); } diff --git a/frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts b/frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts index c3b55276f..42ee2193a 100644 --- a/frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts +++ b/frontend/src/v2/components/AppShell/BackendStatusBanner.test.ts @@ -61,7 +61,6 @@ describe("BackendStatusBanner", () => { expect(banner().classes()).not.toContain("r-backend-banner--in-game"); expect(wrapper!.find(".r-backend-banner__retry").exists()).toBe(true); // The message is right there to read, so nothing hovers over it. - expect(banner().attributes("title")).toBeUndefined(); expect(wrapper!.find(".r-tooltip-stub").exists()).toBe(false); }); @@ -81,7 +80,6 @@ describe("BackendStatusBanner", () => { expect(body().exists()).toBe(false); expect(banner().classes()).toContain("r-backend-banner--collapsed"); // Only the icon is left, so the message moves into a tooltip of our own. - expect(banner().attributes("title")).toBeUndefined(); expect(wrapper!.find(".r-tooltip-stub").exists()).toBe(true); }); diff --git a/frontend/src/v2/components/AppShell/BackendStatusBanner.vue b/frontend/src/v2/components/AppShell/BackendStatusBanner.vue index 9392afed7..8d0930478 100644 --- a/frontend/src/v2/components/AppShell/BackendStatusBanner.vue +++ b/frontend/src/v2/components/AppShell/BackendStatusBanner.vue @@ -13,9 +13,9 @@ // the auth and main shells. import { RBtn, RIcon, RTooltip } from "@v2/lib"; import { storeToRefs } from "pinia"; -import { onBeforeUnmount, ref, watch } from "vue"; import { useI18n } from "vue-i18n"; import storePlaying from "@/stores/playing"; +import { useDelayedFlag } from "@/v2/composables/useDelayedFlag"; import { useServerConnection } from "@/v2/composables/useServerConnection"; defineOptions({ inheritAttrs: false }); @@ -29,27 +29,10 @@ const { playing } = storeToRefs(storePlaying()); // A notice that cannot be dismissed has no business sitting over a running // game, so it says its piece and then shrinks to its icon. -const collapsed = ref(false); -let collapseTimer: ReturnType | null = null; - -function stopCollapsing() { - if (collapseTimer === null) return; - clearTimeout(collapseTimer); - collapseTimer = null; -} - -watch( - [isOffline, playing], - ([offline, inGame]) => { - stopCollapsing(); - collapsed.value = false; - if (!offline || !inGame) return; - collapseTimer = setTimeout(() => (collapsed.value = true), COLLAPSE_MS); - }, - { immediate: true }, +const collapsed = useDelayedFlag( + () => isOffline.value && playing.value, + COLLAPSE_MS, ); - -onBeforeUnmount(stopCollapsing);