mirror of
https://github.com/rommapp/romm.git
synced 2026-12-03 02:24:09 +01:00
refactor(player): one restore window, one write path, one home per rule
simplify findings (reuse, simplification, efficiency, altitude). Behaviour it fixes along the way: - A state load held back the screen and the sound but not the writes, and dumping the SRAM for the new baseline fires a tick of its own: a tick that had already read the restored SRAM found it stable and changed, and uploaded the restore before the baseline landed. A state now closes the same write gate a save load does, and quick load goes through the same window. - Save & Quit rewrote the held row without the frame the tick had stored. The write now owns which frame goes with the bytes it is given, so no caller can pass the wrong one, and it does not write out again bytes already held. - A save whose first capture failed took a new screenshot on every retry. - The shell kept polling the store every 30s while offline, and in game kept a timer armed for a save only the running session would hand over. - A store upgrade wiped every row, which after release would drop users' unsynced progress. It now keeps them and only drops stores it stopped using. Reuse and one home per rule: - The save, state and screenshot files are built by the API modules for both the live uploads and the retries. - The core compatibility rule is shared by the launch screen and the in-game picker. - The banner uses useDelayedFlag, the toast host useEventListener, the retry refresh useRomSync().refetchRom, the refusal text errorMessage(), and the player's notices useSnackbar. - The ledger of rows the server took is read in list() alone, and the retry judges a refused upload and a failed request in one place. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01QTsTgdoBinvvxzXeLUjBmV
This commit is contained in:
@@ -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(
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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", () => {
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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<AddSaveInput, "saveFile" | "screenshotFile"> & {
|
||||
saveFile: File;
|
||||
screenshotFile?: File;
|
||||
|
||||
@@ -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<AddStateInput, "stateFile" | "screenshotFile"> & {
|
||||
stateFile: File;
|
||||
screenshotFile?: File;
|
||||
|
||||
@@ -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<PendingAsset[]>;
|
||||
write(entry: PendingAsset): Promise<void>;
|
||||
clear(id: string): Promise<void>;
|
||||
}
|
||||
|
||||
function openDatabase(): Promise<IDBDatabase> {
|
||||
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<string>();
|
||||
|
||||
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<PendingAsset[]> {
|
||||
const rows =
|
||||
(await withStore<PendingAsset[]>("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<Set<PendingAssetKind>> {
|
||||
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<string>();
|
||||
|
||||
async function uploadSave(
|
||||
entry: PendingAsset,
|
||||
rom: DetailedRomSchema,
|
||||
): Promise<PromiseSettledResult<unknown> | 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<PromiseSettledResult<unknown> | 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<AssetOutcome> {
|
||||
): Promise<SyncedAsset> {
|
||||
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<number, DetailedRomSchema>,
|
||||
): Promise<AssetOutcome | null> {
|
||||
if (accepted.has(entry.id)) return null;
|
||||
): Promise<SyncedAsset | DroppedAsset | null> {
|
||||
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<boolean> {
|
||||
/** Whether anything of these kinds is still owed. */
|
||||
export async function hasPendingAssets(
|
||||
kinds: readonly PendingAssetKind[] = ["save", "state"],
|
||||
): Promise<boolean> {
|
||||
const entries = await pendingAssetStore.list();
|
||||
return entries.some((entry) => !accepted.has(entry.id));
|
||||
return entries.some((entry) => kinds.includes(entry.kind));
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
|
||||
|
||||
@@ -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<typeof setTimeout> | 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);
|
||||
</script>
|
||||
|
||||
<template>
|
||||
@@ -132,8 +115,8 @@ onBeforeUnmount(stopCollapsing);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
/* A running game owns the screen, so the notice takes the corner the player
|
||||
already puts its own messages in and leaves the middle of the screen alone. */
|
||||
/* A running game owns the screen, so the notice moves out of its middle and
|
||||
into a corner the player's own toasts leave free. */
|
||||
.r-backend-banner--in-game {
|
||||
top: 16px;
|
||||
left: 16px;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// emission — v2 stacks so fast successive messages don't overwrite each
|
||||
// other. Stored colour/icon fields are preserved so existing emitters work.
|
||||
import { RIcon } from "@v2/lib";
|
||||
import { useEventListener } from "@vueuse/core";
|
||||
import type { Emitter } from "mitt";
|
||||
import { inject, onBeforeUnmount, ref } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
@@ -23,8 +24,6 @@ type Toast = {
|
||||
msg: string;
|
||||
icon?: string;
|
||||
image?: string | null;
|
||||
/** Artwork the browser could not load, so the tone's icon stands in. */
|
||||
imageBroken?: boolean;
|
||||
tone: ToastTone;
|
||||
timer?: number;
|
||||
};
|
||||
@@ -92,13 +91,12 @@ const fullscreenHost = ref<HTMLElement | null>(null);
|
||||
function trackFullscreen() {
|
||||
fullscreenHost.value = document.fullscreenElement as HTMLElement | null;
|
||||
}
|
||||
document.addEventListener("fullscreenchange", trackFullscreen);
|
||||
useEventListener(document, "fullscreenchange", trackFullscreen);
|
||||
// A host mounted while a game already owns the screen gets no event of its own.
|
||||
trackFullscreen();
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
emitter?.off("snackbarShow", openHandler);
|
||||
document.removeEventListener("fullscreenchange", trackFullscreen);
|
||||
toasts.value.forEach((t) => t.timer && window.clearTimeout(t.timer));
|
||||
});
|
||||
</script>
|
||||
@@ -115,11 +113,11 @@ onBeforeUnmount(() => {
|
||||
role="alert"
|
||||
>
|
||||
<img
|
||||
v-if="toast.image && !toast.imageBroken"
|
||||
v-if="toast.image"
|
||||
:src="toast.image"
|
||||
alt=""
|
||||
class="r-v2-toast__art"
|
||||
@error="toast.imageBroken = true"
|
||||
@error="toast.image = null"
|
||||
/>
|
||||
<RIcon
|
||||
v-else-if="toast.icon"
|
||||
|
||||
@@ -12,7 +12,7 @@ import type { DetailedRom } from "@/stores/roms";
|
||||
import type { Events } from "@/types/emitter";
|
||||
import AssetStrip from "@/v2/components/shared/AssetStrip.vue";
|
||||
import { useBreakpoint } from "@/v2/composables/useBreakpoint";
|
||||
import type { Asset } from "@/v2/utils/assets";
|
||||
import { isCoreCompatible, type Asset } from "@/v2/utils/assets";
|
||||
|
||||
defineOptions({ inheritAttrs: false });
|
||||
|
||||
@@ -30,10 +30,9 @@ emitter?.on("selectStateDialog", openHandler);
|
||||
onBeforeUnmount(() => emitter?.off("selectStateDialog", openHandler));
|
||||
|
||||
// A state another core wrote stays listed, disabled, so the count adds up.
|
||||
function stateDisabledReason(asset: Asset) {
|
||||
const emulator = "emulator" in asset ? asset.emulator : null;
|
||||
if (!emulator || emulator === window.EJS_core) return null;
|
||||
return t("play.state-incompatible-core", { emulator });
|
||||
function stateDisabledReason(asset: { emulator?: string | null }) {
|
||||
if (isCoreCompatible(asset, window.EJS_core)) return null;
|
||||
return t("play.state-incompatible-core", { emulator: asset.emulator });
|
||||
}
|
||||
|
||||
function onSelect(asset: Asset) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import type {
|
||||
PendingSyncResult,
|
||||
} from "@/services/pending-asset";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import storeRoms, { type DetailedRom } from "@/stores/roms";
|
||||
import { installPendingAssetSync } from "./index";
|
||||
|
||||
type Entry = { id: string; romId: number; kind: PendingAssetKind };
|
||||
@@ -30,9 +31,10 @@ async function acceptAll(
|
||||
const syncPendingAssets = vi.fn(acceptAll);
|
||||
|
||||
vi.mock("@/services/pending-asset", () => ({
|
||||
default: { list: async () => queue.entries },
|
||||
syncPendingAssets: (kinds?: PendingAssetKind[]) => syncPendingAssets(kinds),
|
||||
hasPendingAssets: async () => queue.entries.length > 0,
|
||||
hasPendingAssets: async (
|
||||
kinds: readonly PendingAssetKind[] = ["save", "state"],
|
||||
) => queue.entries.some((entry) => kinds.includes(entry.kind)),
|
||||
}));
|
||||
|
||||
const success = vi.fn();
|
||||
@@ -50,8 +52,9 @@ vi.mock("vue-i18n", () => ({
|
||||
useI18n: () => ({ t: (key: string) => key }),
|
||||
}));
|
||||
|
||||
vi.mock("@/services/api/rom", () => ({
|
||||
default: { getRom: vi.fn(async () => ({ data: { id: 1 } })) },
|
||||
const refetchRom = vi.fn(async () => null);
|
||||
vi.mock("@/v2/composables/useRomSync", () => ({
|
||||
useRomSync: () => ({ refetchRom }),
|
||||
}));
|
||||
|
||||
const isOffline = ref(false);
|
||||
@@ -87,6 +90,7 @@ describe("installPendingAssetSync", () => {
|
||||
isOffline.value = false;
|
||||
syncPendingAssets.mockReset();
|
||||
syncPendingAssets.mockImplementation(acceptAll);
|
||||
refetchRom.mockClear();
|
||||
success.mockClear();
|
||||
error.mockClear();
|
||||
});
|
||||
@@ -245,4 +249,39 @@ describe("installPendingAssetSync", () => {
|
||||
|
||||
expect(syncPendingAssets).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Nothing gets through offline, and reconnecting starts a pass of its own.
|
||||
it("stops asking while the server is away", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "save" as const }];
|
||||
isOffline.value = true;
|
||||
|
||||
install();
|
||||
await settle();
|
||||
await vi.advanceTimersByTimeAsync(120_000);
|
||||
await settle();
|
||||
|
||||
expect(syncPendingAssets).not.toHaveBeenCalled();
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
// The running session retries its own save, so there is nothing to wait for.
|
||||
it("stops asking in game when only the session's save is held", async () => {
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "save" as const }];
|
||||
storePlaying().setPlaying(true);
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(vi.getTimerCount()).toBe(0);
|
||||
});
|
||||
|
||||
it("refreshes the details view of a game that just synced", async () => {
|
||||
storeRoms().setCurrentRom({ id: 1 } as DetailedRom);
|
||||
queue.entries = [{ id: "1:a", romId: 1, kind: "state" as const }];
|
||||
|
||||
install();
|
||||
await settle();
|
||||
|
||||
expect(refetchRom).toHaveBeenCalledWith(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,9 +2,9 @@
|
||||
// wherever the user is in the app. Doing it at launch instead would be too
|
||||
// late: by then the player has already drawn its picker, so the asset would
|
||||
// land behind the choice the user just made.
|
||||
import { uniqBy } from "lodash";
|
||||
import { onScopeDispose, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import romApi from "@/services/api/rom";
|
||||
import {
|
||||
hasPendingAssets,
|
||||
syncPendingAssets,
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
} from "@/services/pending-asset";
|
||||
import storePlaying from "@/stores/playing";
|
||||
import storeRoms from "@/stores/roms";
|
||||
import { useRomSync } from "@/v2/composables/useRomSync";
|
||||
import { useServerConnection } from "@/v2/composables/useServerConnection";
|
||||
import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
|
||||
@@ -33,15 +34,7 @@ const REFUSED_MESSAGE: Record<PendingAssetKind, string> = {
|
||||
// A session that queued several captures owes the player one line per game,
|
||||
// not one per capture.
|
||||
function firstPerGame<T extends SyncedAsset>(assets: T[]): T[] {
|
||||
const seen = new Set<string>();
|
||||
const first: T[] = [];
|
||||
for (const asset of assets) {
|
||||
const key = `${asset.kind}:${asset.romId}`;
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
first.push(asset);
|
||||
}
|
||||
return first;
|
||||
return uniqBy(assets, (asset) => `${asset.kind}:${asset.romId}`);
|
||||
}
|
||||
|
||||
// Two shells must not both be draining the same rows into the same server.
|
||||
@@ -53,6 +46,7 @@ export function installPendingAssetSync() {
|
||||
const snackbar = useSnackbar();
|
||||
const { t } = useI18n();
|
||||
const { isOffline } = useServerConnection();
|
||||
const { refetchRom } = useRomSync();
|
||||
|
||||
let timer: ReturnType<typeof setTimeout> | null = null;
|
||||
let disposed = false;
|
||||
@@ -89,20 +83,14 @@ export function installPendingAssetSync() {
|
||||
// An asset that just landed is one the open details view is showing stale.
|
||||
async function refresh(synced: SyncedAsset[]) {
|
||||
const current = romsStore.currentRom?.id;
|
||||
if (!current || !synced.some((asset) => asset.romId === current)) return;
|
||||
try {
|
||||
const { data } = await romApi.getRom({ romId: current });
|
||||
romsStore.setCurrentRom(data);
|
||||
} catch (error) {
|
||||
console.error(
|
||||
"Failed to refresh a rom after a pending asset synced",
|
||||
error,
|
||||
);
|
||||
if (current && synced.some((asset) => asset.romId === current)) {
|
||||
await refetchRom(current);
|
||||
}
|
||||
}
|
||||
|
||||
async function drain() {
|
||||
if (draining) return;
|
||||
// Offline nothing gets through, and reconnecting starts a pass of its own.
|
||||
if (draining || isOffline.value) return;
|
||||
draining = true;
|
||||
try {
|
||||
// A running session retries its own save every second, and a version
|
||||
@@ -111,16 +99,14 @@ export function installPendingAssetSync() {
|
||||
const kinds: PendingAssetKind[] = playingStore.playing
|
||||
? ["state"]
|
||||
: ["save", "state"];
|
||||
if (!isOffline.value) {
|
||||
const { synced, dropped } = await syncPendingAssets(kinds);
|
||||
announce(synced);
|
||||
reportRefused(dropped);
|
||||
await refresh(synced);
|
||||
}
|
||||
const { synced, dropped } = await syncPendingAssets(kinds);
|
||||
announce(synced);
|
||||
reportRefused(dropped);
|
||||
await refresh(synced);
|
||||
stopRetrying();
|
||||
// The shell can go while a pass is on the wire, and a retry armed after
|
||||
// that would outlive it and keep firing for the life of the document.
|
||||
if (!disposed && (await hasPendingAssets())) {
|
||||
if (!disposed && (await hasPendingAssets(kinds))) {
|
||||
timer = setTimeout(() => void drain(), RETRY_MS);
|
||||
}
|
||||
} finally {
|
||||
|
||||
@@ -24,6 +24,14 @@ export function screenshotOf(asset: Asset): string | null {
|
||||
return asset.screenshot?.download_path ?? null;
|
||||
}
|
||||
|
||||
/** A state loads only in the core that wrote it; one naming no core is anyone's. */
|
||||
export function isCoreCompatible(
|
||||
asset: { emulator?: string | null },
|
||||
core: string | null | undefined,
|
||||
): boolean {
|
||||
return !asset.emulator || asset.emulator === core;
|
||||
}
|
||||
|
||||
/** ISO timestamps sort lexically. */
|
||||
export function byUpdatedDesc(a: Asset, b: Asset): number {
|
||||
return b.updated_at.localeCompare(a.updated_at);
|
||||
|
||||
@@ -73,6 +73,7 @@ import { useSnackbar } from "@/v2/composables/useSnackbar";
|
||||
import { useStageActive } from "@/v2/composables/useStageActive";
|
||||
import { useUnloadGuard } from "@/v2/composables/useUnloadGuard";
|
||||
import type { SliderBtnGroupItem } from "@/v2/lib/primitives/RSliderBtnGroup/types";
|
||||
import { isCoreCompatible } from "@/v2/utils/assets";
|
||||
import { shouldClaimFocusOnModality } from "@/v2/utils/autofocus";
|
||||
import {
|
||||
resolveBezelHost,
|
||||
@@ -215,11 +216,11 @@ declare global {
|
||||
}
|
||||
}
|
||||
|
||||
function isCoreCompatible(asset: { emulator?: string | null }): boolean {
|
||||
return !asset.emulator || asset.emulator === selectedCore.value;
|
||||
}
|
||||
const compatibleStates = computed(
|
||||
() => rom.value?.user_states.filter(isCoreCompatible) ?? [],
|
||||
() =>
|
||||
rom.value?.user_states.filter((state) =>
|
||||
isCoreCompatible(state, selectedCore.value),
|
||||
) ?? [],
|
||||
);
|
||||
const stateCount = computed(() => rom.value?.user_states.length ?? 0);
|
||||
const allStatesCompatible = computed(
|
||||
@@ -227,7 +228,7 @@ const allStatesCompatible = computed(
|
||||
);
|
||||
// Other emulators' states stay listed, disabled, so the count adds up.
|
||||
function stateDisabledReason(asset: { emulator?: string | null }) {
|
||||
if (isCoreCompatible(asset)) return null;
|
||||
if (isCoreCompatible(asset, selectedCore.value)) return null;
|
||||
return t("play.state-incompatible-core", { emulator: asset.emulator });
|
||||
}
|
||||
|
||||
|
||||
@@ -28,13 +28,14 @@ import {
|
||||
getControlSchemeForPlatform,
|
||||
getDownloadPath,
|
||||
} from "@/utils";
|
||||
import { useSnackbar, type SnackbarTone } from "@/v2/composables/useSnackbar";
|
||||
import {
|
||||
saveSave,
|
||||
captureScreenshot,
|
||||
dumpSaveFile,
|
||||
exitEmulatorOnce,
|
||||
heldFor,
|
||||
resolveScreenshot,
|
||||
storedScreenshotFor,
|
||||
saveState,
|
||||
loadEmulatorJSSave,
|
||||
loadEmulatorJSState,
|
||||
@@ -81,8 +82,9 @@ function baselineSaveTrackerFromEmulator() {
|
||||
saveTracker.baseline(dumpSaveFile());
|
||||
}
|
||||
// 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,
|
||||
// and bytes read while a load is in flight are stale, so they are dropped.
|
||||
// restoring a save or a state bumps the generation, which voids writes queued
|
||||
// before it, and bytes read while a restore is in flight are stale, so they
|
||||
// are dropped.
|
||||
let saveWrite: Promise<unknown> = Promise.resolve();
|
||||
let saveGeneration = 0;
|
||||
let saveLoading = false;
|
||||
@@ -95,6 +97,9 @@ let pendingSave: PendingAsset | null = null;
|
||||
// One row per session: a save an earlier session never got through still owes
|
||||
// the server its own version, so this must not write over it.
|
||||
const pendingSaveId = pendingAssetId(romRef.value.id);
|
||||
function currentSlot(): string | undefined {
|
||||
return loadedSave?.slot || props.saveSlot || undefined;
|
||||
}
|
||||
async function rememberPendingSave(
|
||||
saveBytes: ArrayBuffer,
|
||||
screenshotBytes?: ArrayBuffer,
|
||||
@@ -106,7 +111,7 @@ async function rememberPendingSave(
|
||||
romName: romRef.value.name ?? romRef.value.fs_name_no_ext,
|
||||
bytes: saveBytes,
|
||||
screenshotBytes,
|
||||
slot: loadedSave?.slot || props.saveSlot || undefined,
|
||||
slot: currentSlot(),
|
||||
emulator: window.EJS_core,
|
||||
deviceId: deviceIDRef.value,
|
||||
capturedAt: Date.now(),
|
||||
@@ -117,14 +122,6 @@ async function forgetPendingSave() {
|
||||
pendingSave = null;
|
||||
await pendingAssetStore.clear(pendingSaveId);
|
||||
}
|
||||
// Whether the browser is holding these exact bytes, so a notice only promises
|
||||
// a later sync for a save that really was kept.
|
||||
function isSaveHeld(saveFile: Uint8Array): boolean {
|
||||
return (
|
||||
pendingSave !== null &&
|
||||
bytesEqual(new Uint8Array(pendingSave.bytes), saveFile)
|
||||
);
|
||||
}
|
||||
// The tick re-offers a save whose upload failed on every pass, so what was
|
||||
// said for these bytes is remembered: every save the game writes is announced,
|
||||
// every retry of the same one is not.
|
||||
@@ -147,16 +144,21 @@ function writeSave(
|
||||
const bytes = new Uint8Array(file.saveFile);
|
||||
inFlightSave = bytes;
|
||||
try {
|
||||
// Held before the attempt and dropped once the server answers, so no
|
||||
// path can upload a save without the browser keeping a copy, and none
|
||||
// can succeed while an older capture stays behind to be synced later.
|
||||
await rememberPendingSave(file.saveFile, file.screenshotFile);
|
||||
// Held before the attempt and dropped once the server takes it, so no
|
||||
// path uploads without a copy kept. Bytes already held keep the frame
|
||||
// taken when the game wrote them, and are not written out again.
|
||||
const held = heldFor(pendingSave, bytes);
|
||||
const screenshotFile = held?.screenshotBytes ?? file.screenshotFile;
|
||||
if (!held || held.screenshotBytes !== screenshotFile) {
|
||||
await rememberPendingSave(file.saveFile, screenshotFile);
|
||||
}
|
||||
const save = await saveSave({
|
||||
rom: romRef.value,
|
||||
save: sessionSaveRef.value,
|
||||
deviceId: deviceIDRef.value,
|
||||
slot: loadedSave?.slot || props.saveSlot || undefined,
|
||||
...file,
|
||||
slot: currentSlot(),
|
||||
saveFile: file.saveFile,
|
||||
screenshotFile,
|
||||
});
|
||||
if (save && generation === saveGeneration) {
|
||||
sessionSaveRef.value = save;
|
||||
@@ -189,13 +191,15 @@ async function writeSaveIfChanged(file: {
|
||||
}
|
||||
return (await writeSave(file, generation)) !== null;
|
||||
}
|
||||
// A state restores the machine mid-scene, so every frame the core renders and
|
||||
// every note it plays on the way there belong to a moment the player did not
|
||||
// pick. Both are held back until the state has landed.
|
||||
// A state restores the machine mid-scene, so every frame the core renders,
|
||||
// every note it plays and every save it writes on the way there belong to a
|
||||
// moment the player did not pick. All three are held back until it has landed.
|
||||
const applyingState = ref(false);
|
||||
let restoreVolume: (() => void) | null = null;
|
||||
function silenceUntilStateApplied() {
|
||||
applyingState.value = true;
|
||||
saveLoading = true;
|
||||
saveGeneration += 1;
|
||||
const emulator = window.EJS_emulator;
|
||||
if (restoreVolume || typeof emulator?.setVolume !== "function") return;
|
||||
const { volume, muted } = emulator;
|
||||
@@ -209,6 +213,7 @@ function silenceUntilStateApplied() {
|
||||
}
|
||||
function stateApplied() {
|
||||
applyingState.value = false;
|
||||
saveLoading = false;
|
||||
restoreVolume?.();
|
||||
restoreVolume = null;
|
||||
}
|
||||
@@ -402,10 +407,9 @@ onBeforeUnmount(async () => {
|
||||
playing.value = false;
|
||||
});
|
||||
|
||||
type MessageTone = "success" | "error" | "warning" | "info";
|
||||
|
||||
// The app's own toast host: it stacks, so two notices raised together read as
|
||||
// two, and it draws its icons as components rather than through a font class.
|
||||
const snackbar = useSnackbar();
|
||||
function displayMessage(
|
||||
message: string,
|
||||
{
|
||||
@@ -414,16 +418,11 @@ function displayMessage(
|
||||
icon,
|
||||
}: {
|
||||
duration: number;
|
||||
tone?: MessageTone;
|
||||
tone?: SnackbarTone;
|
||||
icon?: string;
|
||||
},
|
||||
) {
|
||||
emitter?.emit("snackbarShow", {
|
||||
msg: message,
|
||||
color: tone,
|
||||
icon,
|
||||
timeout: duration,
|
||||
});
|
||||
snackbar.show(tone, message, { icon, timeout: duration });
|
||||
}
|
||||
|
||||
// Poll until EmulatorJS' gameManager is ready to accept save/state
|
||||
@@ -458,19 +457,26 @@ function installAutoSaveSync() {
|
||||
autoSaveSyncEmulator = emulator;
|
||||
let uploading = false;
|
||||
emulator.on("saveSaveFiles", async (saveFile: Uint8Array | null) => {
|
||||
if (autoSaveSyncEmulator !== emulator || uploading || !saveFile?.byteLength)
|
||||
if (
|
||||
autoSaveSyncEmulator !== emulator ||
|
||||
uploading ||
|
||||
saveLoading ||
|
||||
!saveFile?.byteLength
|
||||
)
|
||||
return;
|
||||
if (!saveTracker.shouldUpload(saveFile)) return;
|
||||
uploading = true;
|
||||
try {
|
||||
const saveBytes = toArrayBuffer(saveFile);
|
||||
// The capture needs the game running, so it happens on the tick. A retry
|
||||
// reuses the frame stored for these bytes instead of taking a new one,
|
||||
// which would picture the moment the network came back.
|
||||
const screenshotFile =
|
||||
storedScreenshotFor(pendingSave, saveBytes) ??
|
||||
(await captureScreenshot());
|
||||
const save = await writeSave({ saveFile: saveBytes, screenshotFile });
|
||||
// The capture needs the game running, so it happens on the tick, once
|
||||
// per save: a retry of held bytes keeps the frame taken when the game
|
||||
// wrote them rather than picturing the moment the network came back.
|
||||
const screenshotFile = heldFor(pendingSave, saveFile)
|
||||
? undefined
|
||||
: await captureScreenshot();
|
||||
const save = await writeSave({
|
||||
saveFile: toArrayBuffer(saveFile),
|
||||
screenshotFile,
|
||||
});
|
||||
if (save) {
|
||||
heldBackSave = null;
|
||||
romsStore.update(romRef.value);
|
||||
@@ -479,9 +485,12 @@ function installAutoSaveSync() {
|
||||
tone: "success",
|
||||
icon: "mdi-cloud-sync",
|
||||
});
|
||||
// A write voided by a save being loaded holds nothing back, so there
|
||||
// is nothing to promise for it either.
|
||||
} else if (isSaveHeld(saveFile) && !bytesEqual(saveFile, heldBackSave)) {
|
||||
// A write voided by a restore holds nothing back, so there is nothing
|
||||
// to promise for it either.
|
||||
} else if (
|
||||
heldFor(pendingSave, saveFile) &&
|
||||
!bytesEqual(saveFile, heldBackSave)
|
||||
) {
|
||||
announceSaveHeldBack(saveFile);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -507,12 +516,10 @@ async function flushPendingSave() {
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const saveFile: Uint8Array | null = emulator.gameManager.getSaveFile();
|
||||
if (!saveFile?.byteLength || !saveTracker.hasChanges(saveFile)) return;
|
||||
const saveBytes = toArrayBuffer(saveFile);
|
||||
// The exit takes no frame of its own; it carries the one stored when the
|
||||
// game wrote these bytes, if a sync got that far.
|
||||
const screenshotFile = storedScreenshotFor(pendingSave, saveBytes);
|
||||
try {
|
||||
if (await writeSave({ saveFile: saveBytes, screenshotFile })) {
|
||||
// The exit takes no frame of its own: the write carries the one held for
|
||||
// these bytes, if a sync got that far.
|
||||
if (await writeSave({ saveFile: toArrayBuffer(saveFile) })) {
|
||||
romsStore.update(romRef.value);
|
||||
}
|
||||
} catch (error) {
|
||||
@@ -554,7 +561,7 @@ function onPageHide() {
|
||||
save: sessionSaveRef.value,
|
||||
saveFile: toArrayBuffer(unloadSave),
|
||||
deviceId: deviceIDRef.value,
|
||||
slot: loadedSave?.slot || props.saveSlot || undefined,
|
||||
slot: currentSlot(),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -610,7 +617,7 @@ window.EJS_onSaveSave = async function ({
|
||||
tone: "success",
|
||||
icon: "mdi-cloud-sync",
|
||||
});
|
||||
} else if (isSaveHeld(new Uint8Array(saveFile))) {
|
||||
} else if (heldFor(pendingSave, new Uint8Array(saveFile))) {
|
||||
// Asked for by hand, so it answers every time, and the tick behind it
|
||||
// knows these bytes have been spoken for.
|
||||
announceSaveHeldBack(new Uint8Array(saveFile));
|
||||
@@ -618,32 +625,39 @@ window.EJS_onSaveSave = async function ({
|
||||
};
|
||||
|
||||
// States management
|
||||
// A state restores the SRAM along with the rest of the machine, so the bytes
|
||||
// the tick reads next belong to the state, not to progress the player made.
|
||||
async function rebaselineAfterState() {
|
||||
await new Promise((resolve) => setTimeout(resolve, STATE_APPLY_SETTLE_MS));
|
||||
baselineSaveTrackerFromEmulator();
|
||||
// Every way a state arrives goes through here. It restores the SRAM along with
|
||||
// the rest of the machine, so the bytes the tick reads next belong to the
|
||||
// state, not to progress the player made: they become the new baseline.
|
||||
async function applyState(state: Uint8Array) {
|
||||
silenceUntilStateApplied();
|
||||
try {
|
||||
loadEmulatorJSState(state);
|
||||
await new Promise((resolve) => setTimeout(resolve, STATE_APPLY_SETTLE_MS));
|
||||
baselineSaveTrackerFromEmulator();
|
||||
} finally {
|
||||
stateApplied();
|
||||
}
|
||||
}
|
||||
|
||||
async function loadState(state: StateSchema) {
|
||||
// Raised before the download, since the picker resumes the game meanwhile.
|
||||
silenceUntilStateApplied();
|
||||
try {
|
||||
const { data } = await api.get(state.download_path.replace("/api", ""), {
|
||||
responseType: "arraybuffer",
|
||||
});
|
||||
const bytes = data
|
||||
? new Uint8Array(data)
|
||||
: new Uint8Array(
|
||||
await (await window.EJS_emulator.selectFile()).arrayBuffer(),
|
||||
);
|
||||
await applyState(bytes);
|
||||
if (data) {
|
||||
loadEmulatorJSState(new Uint8Array(data));
|
||||
displayMessage("State loaded from server", {
|
||||
duration: 3000,
|
||||
icon: "mdi-cloud-download-outline",
|
||||
});
|
||||
await rebaselineAfterState();
|
||||
return;
|
||||
}
|
||||
|
||||
const file = await window.EJS_emulator.selectFile();
|
||||
loadEmulatorJSState(new Uint8Array(await file.arrayBuffer()));
|
||||
await rebaselineAfterState();
|
||||
} finally {
|
||||
stateApplied();
|
||||
}
|
||||
@@ -691,8 +705,7 @@ window.EJS_onGameStart = async () => {
|
||||
// EmulatorJS' own notices (its browser save-state slots) go through the
|
||||
// same host, so nothing of ours is overwritten by one of theirs.
|
||||
const emulator = window.EJS_emulator;
|
||||
if (emulator && !emulator.__rommMessageStack) {
|
||||
emulator.__rommMessageStack = true;
|
||||
if (emulator) {
|
||||
emulator.displayMessage = (text: string, duration?: number) =>
|
||||
displayMessage(text, { duration: duration ?? 3000 });
|
||||
}
|
||||
@@ -783,12 +796,11 @@ window.EJS_onGameStart = async () => {
|
||||
window.EJS_emulator.storage.states
|
||||
.get(window.EJS_emulator.getBaseFileName() + ".state")
|
||||
.then(async (e: Uint8Array) => {
|
||||
loadEmulatorJSState(e);
|
||||
await applyState(e);
|
||||
displayMessage("Quick load from server", {
|
||||
duration: 3000,
|
||||
icon: "mdi-flash",
|
||||
});
|
||||
await rebaselineAfterState();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -7,7 +7,7 @@ import {
|
||||
buildStateFormData,
|
||||
captureScreenshot,
|
||||
dumpSaveFile,
|
||||
storedScreenshotFor,
|
||||
heldFor,
|
||||
createSaveSyncTracker,
|
||||
installEJSDefaultOptionsTrap,
|
||||
pollSaveFiles,
|
||||
@@ -28,7 +28,6 @@ const stateApiMocks = vi.hoisted(() => ({
|
||||
const pendingAssetMocks = vi.hoisted(() => ({
|
||||
write: vi.fn(),
|
||||
clear: vi.fn(),
|
||||
list: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/services/api/save", async (importOriginal) => ({
|
||||
@@ -455,61 +454,32 @@ describe("resolveScreenshot", () => {
|
||||
/* eslint-enable @typescript-eslint/no-explicit-any */
|
||||
});
|
||||
|
||||
describe("storedScreenshotFor", () => {
|
||||
const shot = new Uint8Array([9, 9]).buffer;
|
||||
const pendingFor = (bytes: ArrayBuffer) => ({
|
||||
describe("heldFor", () => {
|
||||
const held = (bytes: ArrayBuffer) => ({
|
||||
id: "1:a",
|
||||
kind: "save" as const,
|
||||
romId: 1,
|
||||
romName: "Game",
|
||||
bytes,
|
||||
screenshotBytes: shot,
|
||||
screenshotBytes: new Uint8Array([9, 9]).buffer,
|
||||
capturedAt: 0,
|
||||
});
|
||||
|
||||
it("hands back the frame kept for these exact bytes", () => {
|
||||
const saveBytes = new Uint8Array([1, 2, 3]).buffer;
|
||||
it("hands back the row holding these exact bytes", () => {
|
||||
const row = held(new Uint8Array([1, 2, 3]).buffer);
|
||||
|
||||
expect(
|
||||
storedScreenshotFor(
|
||||
pendingFor(saveBytes),
|
||||
new Uint8Array([1, 2, 3]).buffer,
|
||||
),
|
||||
).toBe(shot);
|
||||
expect(heldFor(row, new Uint8Array([1, 2, 3]))).toBe(row);
|
||||
});
|
||||
|
||||
// The game wrote again, so the stored frame pictures a moment that has passed.
|
||||
it("drops the frame once the save has moved on", () => {
|
||||
const saveBytes = new Uint8Array([1, 2, 3]).buffer;
|
||||
// The game wrote again, so the row pictures a moment that has passed.
|
||||
it("lets go once the save has moved on", () => {
|
||||
const row = held(new Uint8Array([1, 2, 3]).buffer);
|
||||
|
||||
expect(
|
||||
storedScreenshotFor(
|
||||
pendingFor(saveBytes),
|
||||
new Uint8Array([1, 2, 4]).buffer,
|
||||
),
|
||||
).toBeUndefined();
|
||||
expect(heldFor(row, new Uint8Array([1, 2, 4]))).toBeNull();
|
||||
});
|
||||
|
||||
it("has nothing to offer without a pending save", () => {
|
||||
expect(
|
||||
storedScreenshotFor(null, new Uint8Array([1]).buffer),
|
||||
).toBeUndefined();
|
||||
});
|
||||
|
||||
it("keeps bytes that were stored without a frame frameless", () => {
|
||||
const bytes = new Uint8Array([1, 2, 3]).buffer;
|
||||
const pending = {
|
||||
id: "1:a",
|
||||
kind: "save" as const,
|
||||
romId: 1,
|
||||
romName: "Game",
|
||||
bytes,
|
||||
capturedAt: 0,
|
||||
};
|
||||
|
||||
expect(
|
||||
storedScreenshotFor(pending, new Uint8Array([1, 2, 3]).buffer),
|
||||
).toBeUndefined();
|
||||
it("has nothing to offer when nothing is held", () => {
|
||||
expect(heldFor(null, new Uint8Array([1]))).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -4,8 +4,12 @@ import {
|
||||
type SaveSchema,
|
||||
type StateSchema,
|
||||
} from "@/__generated__";
|
||||
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 pendingAssetStore, {
|
||||
pendingAssetId,
|
||||
type PendingAsset,
|
||||
@@ -96,21 +100,18 @@ export async function resolveScreenshot(
|
||||
}
|
||||
|
||||
/**
|
||||
* The frame already held for these exact save bytes, if a sync stored one.
|
||||
* The held row, when it holds these exact bytes.
|
||||
*
|
||||
* Returns:
|
||||
* The stored picture, or undefined when the bytes have moved on since.
|
||||
* The row, or null when there is none or the bytes have moved on since.
|
||||
*/
|
||||
export function storedScreenshotFor(
|
||||
export function heldFor(
|
||||
pending: PendingAsset | null,
|
||||
saveBytes: ArrayBuffer,
|
||||
): ArrayBuffer | undefined {
|
||||
if (!pending) return undefined;
|
||||
const sameBytes = bytesEqual(
|
||||
new Uint8Array(pending.bytes),
|
||||
new Uint8Array(saveBytes),
|
||||
);
|
||||
return sameBytes ? pending.screenshotBytes : undefined;
|
||||
bytes: Uint8Array,
|
||||
): PendingAsset | null {
|
||||
return pending && bytesEqual(new Uint8Array(pending.bytes), bytes)
|
||||
? pending
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Console-mode state upload; without a picture there is no screenshot part. */
|
||||
@@ -148,7 +149,6 @@ export async function saveState({
|
||||
}
|
||||
|
||||
const capturedAt = new Date();
|
||||
const filename = sessionStateName(rom, capturedAt);
|
||||
// Held in the browser until the server takes it, so a state captured with
|
||||
// no connection reaches the server on a later pass instead of being lost.
|
||||
const pendingId = pendingAssetId(rom.id);
|
||||
@@ -168,16 +168,7 @@ export async function saveState({
|
||||
rom: rom,
|
||||
emulator: window.EJS_core,
|
||||
statesToUpload: [
|
||||
{
|
||||
stateFile: new File([stateFile], `${filename}.state`, {
|
||||
type: "application/octet-stream",
|
||||
}),
|
||||
screenshotFile: screenshotFile
|
||||
? new File([screenshotFile], `${filename}.png`, {
|
||||
type: "application/octet-stream",
|
||||
})
|
||||
: undefined,
|
||||
},
|
||||
sessionStateFiles(rom, capturedAt, stateFile, screenshotFile),
|
||||
],
|
||||
});
|
||||
|
||||
@@ -216,14 +207,8 @@ export async function saveSave({
|
||||
const { data: updatedSave } = await saveApi.updateSave({
|
||||
save: save,
|
||||
saveFile: sessionSaveFile(rom, save, saveFile),
|
||||
// Reuse the picture's name so an update replaces it in place; a
|
||||
// version without one takes the save's stem, which links the two.
|
||||
screenshotFile: screenshotFile
|
||||
? new File(
|
||||
[screenshotFile],
|
||||
save.screenshot?.file_name ?? `${save.file_name_no_ext}.png`,
|
||||
{ type: "application/octet-stream" },
|
||||
)
|
||||
? sessionScreenshotFile(rom, save, screenshotFile)
|
||||
: undefined,
|
||||
deviceId,
|
||||
});
|
||||
@@ -240,7 +225,6 @@ export async function saveSave({
|
||||
}
|
||||
|
||||
// The backend timestamps slotted uploads, tagging save and screenshot alike.
|
||||
const filename = rom.fs_name_no_ext.trim();
|
||||
try {
|
||||
const uploadedSaves = await saveApi.uploadSaves({
|
||||
rom: rom,
|
||||
@@ -257,9 +241,7 @@ export async function saveSave({
|
||||
{
|
||||
saveFile: sessionSaveFile(rom, null, saveFile),
|
||||
screenshotFile: screenshotFile
|
||||
? new File([screenshotFile], `${filename}.png`, {
|
||||
type: "application/octet-stream",
|
||||
})
|
||||
? sessionScreenshotFile(rom, null, screenshotFile)
|
||||
: undefined,
|
||||
},
|
||||
],
|
||||
|
||||
Reference in New Issue
Block a user