From 17186f7029ddb99b24b2f72b4326ee020d2d2536 Mon Sep 17 00:00:00 2001 From: Zacharias Xenakis Date: Wed, 25 Nov 2026 17:15:34 +0200 Subject: [PATCH 1/2] Cloud saves: a game's sync notes belong to the account they were made under --- src-tauri/src/cloud.rs | 78 ++++++++++++ src-tauri/src/saves.rs | 266 ++++++++++++++++++++++++++++++++++++++++- 2 files changed, 339 insertions(+), 5 deletions(-) diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index e2655700..4c0e3718 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -114,6 +114,43 @@ pub fn signed_in(dir: &Path) -> bool { load(dir).is_some() } +/// The signed-in account's id, empty when nobody is. For the save notes (saves::state), which +/// are read often: it reads account.json only, never the sealed token. +pub(crate) fn account_uid(dir: &Path) -> String { + let _guard = ACCOUNT_FILE.lock().unwrap(); + let Some(a) = std::fs::read(file(dir)).ok().and_then(|b| serde_json::from_slice::(&b).ok()) else { + return String::new(); + }; + if a.token.is_empty() && a.sealed.is_empty() { + return String::new(); + } + a.user.uid +} + +/// Tests sign in by writing account.json as it is kept off Windows (a plain token). Only +/// `account_uid` reads it there, so no test reaches Windows' Credential Manager. +#[cfg(test)] +pub(crate) fn sign_in_for_tests(dir: &Path, uid: &str) { + let a = Account { token: format!("test-token-{uid}"), user: User { uid: uid.into(), ..Default::default() }, ..Default::default() }; + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(file(dir), serde_json::to_vec(&a).unwrap()).unwrap(); +} + +#[cfg(test)] +pub(crate) fn sign_out_for_tests(dir: &Path) { + let _ = std::fs::remove_file(file(dir)); +} + +/// Whether the account a cloud request went out under is still the one signed in. A save that +/// went up to (or came down from) one account must not be noted as synced for the next. +fn still_signed_in_as(dir: &Path, a: &Account, id: &str) -> bool { + let same = account_uid(dir) == a.user.uid; + if !same { + crate::trail::note(format!("Cloud saves: {id}'s sync finished after the account changed, so it isn't noted as synced")); + } + same +} + /// The website said this PC's token is no good any more (signed out from the website). fn forget(app: &AppHandle) { let st = app.state::(); @@ -878,6 +915,9 @@ async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64) -> Re return Err(e); } copy_went_up(id, name); + if !still_signed_in_as(&st.dir, &a, id) { + return Ok(()); + } let mut s = saves::state(&st.dir, id); s.mark_synced(&man.hash, made_at, &man.device); // The copy waiting is this one or an older one: what's in the cloud now is newer, so it @@ -1138,6 +1178,12 @@ async fn take_cloud(app: &AppHandle, id: &str, c: &CloudCopy, checked: Option<&s let _ = tokio::fs::remove_file(&tmp).await; let n = n??; let mut s = saves::state(&st.dir, id); + // The save is in place either way; only the new account's notes must not claim it as synced. + if !still_signed_in_as(&st.dir, &a, id) { + s.last_hash = c.hash.clone(); + saves::set_state(&st.dir, id, &s); + return Ok(n); + } s.mark_synced(&c.hash, c.made, &c.device); s.last_hash = c.hash.clone(); saves::set_state(&st.dir, id, &s); @@ -2201,6 +2247,7 @@ mod child_retry_tests { async fn retries_find_each_games_queued_save_under_its_full_id() { let fixture = Fixture::new(games()); let st = &fixture.0; + sign_in_for_tests(&st.dir, "A"); saves::set_state(&st.dir, "series", &saves::State { pending: Some("100.zip".into()), ..Default::default() }); saves::set_state(&st.dir, "series--first", &saves::State { pending: Some("101.zip".into()), ..Default::default() }); saves::set_state(&st.dir, "series--second", &saves::State { pending: Some("102.zip".into()), ..Default::default() }); @@ -2296,6 +2343,7 @@ mod child_retry_tests { async fn a_waiting_child_retry_inherits_its_installs_cloud_setting() { let fixture = Fixture::new(games()); let st = &fixture.0; + sign_in_for_tests(&st.dir, "A"); assert_eq!(game(st, "series--first").unwrap().cloud, Some(true)); saves::set_state(&st.dir, "series--first", &saves::State { pending: Some("101.zip".into()), ..Default::default() }); let busy = BUSY.lock().await; @@ -2312,6 +2360,32 @@ mod child_retry_tests { let (_busy, pending) = pending_copy(&st.dir, "series--first", &st.lib).await; assert_eq!(pending.as_deref(), Some("101.zip")); } + + #[tokio::test] + async fn a_copy_queued_under_one_account_is_not_sent_for_the_next() { + let fixture = Fixture::new(games()); + let st = &fixture.0; + sign_in_for_tests(&st.dir, "A"); + saves::set_state(&st.dir, "series", &saves::State { pending: Some("100.zip".into()), ..Default::default() }); + sign_in_for_tests(&st.dir, "B"); + let (_busy, copy) = pending_copy(&st.dir, "series", &st.lib).await; + assert_eq!(copy, None); + } + + #[test] + fn another_accounts_sync_point_does_not_bring_in_this_accounts_cloud_save() { + let fixture = Fixture::new(games()); + let st = &fixture.0; + sign_in_for_tests(&st.dir, "A"); + let mut s = saves::State { last_hash: "unchanged".into(), ..Default::default() }; + s.mark_synced("unchanged", 100, "Desk-PC"); + saves::set_state(&st.dir, "series", &s); + sign_in_for_tests(&st.dir, "B"); + let s = saves::state(&st.dir, "series"); + let b_cloud = [CloudCopy { v: "b1".into(), hash: "b-save".into(), ..Default::default() }]; + assert!(incoming(&s, &b_cloud).is_none()); + assert!(!should_restore(&s.last_hash, &s.synced_hash, "b-save", false)); + } } #[cfg(test)] @@ -2526,6 +2600,7 @@ mod sync_tests { let mut library = crate::library::Library::default(); library.installed.insert("g".into(), Installed { cloud: Some(true), ..Default::default() }); let library = Mutex::new(library); + sign_in_for_tests(&dir, "A"); saves::set_state(&dir, "g", &saves::State { pending: Some("123.zip".into()), ..Default::default() }); let busy = BUSY.lock().await; let retry = pending_copy(&dir, "g", &library); @@ -2696,6 +2771,7 @@ mod status_tests { #[test] fn a_failed_upload_is_remembered() { let d = tmp("failed"); + sign_in_for_tests(&d, "A"); note_failure(&d, "g", &Error::Net("Can't reach recomplauncher.com right now.".into())); let p = saves::state(&d, "g").problem.unwrap(); assert_eq!(p.kind, "offline"); @@ -2714,6 +2790,7 @@ mod status_tests { #[test] fn a_readable_folder_again_clears_the_folder_problem() { let d = tmp("folder"); + sign_in_for_tests(&d, "A"); note_folder_too_big(&d, "g", Some(SYNC_PAUSED.into())); assert_eq!(saves::state(&d, "g").problem.unwrap().kind, "too-big-folder"); note_folder_too_big(&d, "g", None); @@ -2724,6 +2801,7 @@ mod status_tests { #[test] fn a_readable_folder_keeps_other_problems() { let d = tmp("folder-other"); + sign_in_for_tests(&d, "A"); note_failure(&d, "g", &Error::Msg(FULL_TEXT.into())); note_folder_too_big(&d, "g", None); assert_eq!(saves::state(&d, "g").problem.unwrap().kind, "full"); diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index ef673ea4..a1c85875 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -770,6 +770,11 @@ pub struct State { /// next start makes the copy and sends it. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub after_play: bool, + /// The sign-in this note was read under (see `state`): a note read under one sign-in is never + /// written under another, so work that ends after a switch can't stamp the old account's + /// cloud news on the new one. None for a note made in code: it's written under the sign-in now. + #[serde(skip)] + pub(crate) read_under: Option, } /// Why a game's saves didn't reach the cloud. `kind` is one of: offline, full, paused, @@ -792,6 +797,34 @@ impl State { self.problem = None; } + /// Another account (or nobody signed in): nothing the note says about the cloud holds for it + /// (what was synced, the queue, a conflict, a problem). What this PC knows about its own + /// saves stays, so changes to them are still noticed. + pub fn forget_cloud(&mut self) { + self.synced_hash.clear(); + self.pending = None; + self.synced_at = 0; + self.synced_made = 0; + self.synced_device.clear(); + self.conflict = None; + self.problem = None; + } + + fn knows_cloud(&self) -> bool { + let synced = !self.synced_hash.is_empty() || self.synced_at != 0 || self.synced_made != 0 || !self.synced_device.is_empty(); + synced || self.pending.is_some() || self.conflict.is_some() || self.problem.is_some() + } + + fn take_cloud_from(&mut self, other: &State) { + self.synced_hash = other.synced_hash.clone(); + self.pending = other.pending.clone(); + self.synced_at = other.synced_at; + self.synced_made = other.synced_made; + self.synced_device = other.synced_device.clone(); + self.conflict = other.conflict.clone(); + self.problem = other.problem.clone(); + } + /// The newest copy on this PC isn't the one in the cloud: it's queued, or it goes up after /// the next session. A copy put back from the cloud sets both hashes, so it isn't behind. pub fn behind(&self) -> bool { @@ -835,19 +868,91 @@ fn state_file(app_dir: &Path, id: &str) -> PathBuf { app_dir.join("saves").join(id).join("state.json") } -pub fn state(app_dir: &Path, id: &str) -> State { - let read = |p: PathBuf| fs::read(p).ok().and_then(|b| serde_json::from_slice(&b).ok()); +/// The key in state.json naming the sign-in its cloud fields belong to. Same name and form as the +/// Google Drive draft (PR #228) uses, ":", so the two read each other's notes. +const SCOPE_KEY: &str = "cloud_scope"; + +/// The sign-in a note's cloud fields are written under now. Read from account.json without +/// opening the sealed token, so it costs no trip to Windows' Credential Manager. +fn scope_now(app_dir: &Path) -> String { + format!("recompstore:{}", crate::cloud::account_uid(app_dir)) +} + +/// A scope with no account id after the colon is nobody's: nothing in the cloud belongs to it. +fn owned(scope: &str) -> bool { + scope.split_once(':').is_some_and(|(_, who)| !who.is_empty()) +} + +/// The note as written, with the scope it was written under (None: from before notes had one). +fn read_note(app_dir: &Path, id: &str) -> Option<(State, Option)> { + let read = |p: PathBuf| fs::read(p).ok().and_then(|b| serde_json::from_slice::(&b).ok()); // One from before the notes moved, beside the copies in the player's folder. let beside = || chosen_root().and_then(|r| read(r.join(id).join("state.json"))); - read(state_file(app_dir, id)).or_else(beside).unwrap_or_default() + let value = read(state_file(app_dir, id)).or_else(beside)?; + let scope = value.get(SCOPE_KEY).and_then(|v| v.as_str()).map(String::from); + let state = serde_json::from_value(value).unwrap_or_default(); + Some((state, scope)) } -pub fn set_state(app_dir: &Path, id: &str, s: &State) { +fn write_note(app_dir: &Path, id: &str, s: &State, scope: &str) { let f = state_file(app_dir, id); if let Some(d) = f.parent() { let _ = fs::create_dir_all(d); } - let _ = fs::write(f, serde_json::to_vec_pretty(s).unwrap_or_default()); + let mut value = serde_json::to_value(s).unwrap_or_default(); + value[SCOPE_KEY] = scope.into(); + let _ = fs::write(f, serde_json::to_vec_pretty(&value).unwrap_or_default()); +} + +/// What this PC knows about a game's saves, for whoever is signed in now. The cloud fields only +/// count for the account they were written under: after a switch (or signed out) the game has +/// nothing synced, nothing queued, no conflict and no problem, so another account's upload is +/// never sent and its sync point never decides a restore. The account's own notes come back if +/// it signs in again before the other one syncs this game. +/// +/// A note from before notes had an account belongs to the account signed in when this version +/// first reads it: an account switch was rare, and dropping every player's queue and sync point +/// at the update would turn their next sync into a "which save?" question. Read with nobody +/// signed in, it belongs to no account, since who wrote it can't be known. +pub fn state(app_dir: &Path, id: &str) -> State { + let now = scope_now(app_dir); + let Some((mut s, written)) = read_note(app_dir, id) else { + return State { read_under: Some(now), ..Default::default() }; + }; + s.read_under = Some(now.clone()); + let Some(written) = written else { + if !owned(&now) { + s.forget_cloud(); + } + write_note(app_dir, id, &s, &now); + return s; + }; + if written != now || !owned(&now) { + s.forget_cloud(); + } + s +} + +pub fn set_state(app_dir: &Path, id: &str, s: &State) { + let now = scope_now(app_dir); + if s.read_under.as_ref().is_some_and(|r| *r != now) { + crate::trail::note(format!("Saves: {id}'s sync note wasn't kept, the account changed meanwhile")); + return; + } + // A note that says nothing about the cloud (signed out, or an account that hasn't synced this + // game) keeps what the file says for the account it belongs to: playing signed out, or a + // look from another account, doesn't cost that account its sync point. + let mut keep = s.clone(); + let mut scope = now.clone(); + if !s.knows_cloud() { + if let Some((written, Some(owner))) = read_note(app_dir, id) { + if owner != now && owned(&owner) { + keep.take_cloud_from(&written); + scope = owner; + } + } + } + write_note(app_dir, id, &keep, &scope); } /// Copies go where they belong now: from the launcher's own folder (where they were kept before @@ -2001,6 +2106,7 @@ mod tests { assert!(queued.when > chosen.when); let queued_path = dir_of(&app, "g", &g).join(&queued.name); let queued_bytes = fs::read(&queued_path).unwrap(); + crate::cloud::sign_in_for_tests(&app, "A"); set_state(&app, "g", &State { last_hash: queued.hash.clone(), synced_hash: "previous cloud".into(), pending: Some(queued.name.clone()), ..Default::default() }); set_state(&app, "other", &State { pending: Some("123.zip".into()), ..Default::default() }); @@ -2030,6 +2136,7 @@ mod tests { let g = game(&inst); let spots = vec![Spot { template: "{install}/slot.sav".into(), from: "developer" }]; let queued = backup(&app, "g", &spots, &g).unwrap().unwrap(); + crate::cloud::sign_in_for_tests(&app, "A"); set_state(&app, "g", &State { last_hash: queued.hash, pending: Some(queued.name.clone()), ..Default::default() }); let invalid = d.join("broken.zip"); fs::write(&invalid, b"not a save archive").unwrap(); @@ -2552,3 +2659,152 @@ mod sync_state_tests { assert_eq!((s.synced_at, s.conflict.is_none(), s.problem.is_none()), (0, true, true)); } } + +#[cfg(test)] +mod account_scope_tests { + use super::{set_state, state, state_file, State}; + use crate::cloud::{sign_in_for_tests as sign_in, sign_out_for_tests as sign_out}; + use std::path::PathBuf; + + struct AppDir(PathBuf); + + impl AppDir { + fn new(name: &str) -> Self { + let d = std::env::temp_dir().join(format!("rl-saves-scope-{name}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + Self(d) + } + } + + impl Drop for AppDir { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } + } + + // What account A left behind: a copy queued, a sync point, and where it was made. + fn synced_under_a(app: &std::path::Path) { + sign_in(app, "A"); + let mut s = State { last_hash: "local".into(), pending: Some("200.zip".into()), ..Default::default() }; + s.mark_synced("a-cloud", 100, "Desk-PC"); + set_state(app, "g", &s); + } + + #[test] + fn a_copy_queued_under_one_account_is_not_queued_for_the_next() { + let d = AppDir::new("queue"); + synced_under_a(&d.0); + sign_in(&d.0, "B"); + assert_eq!(state(&d.0, "g").pending, None); + } + + #[test] + fn after_switching_accounts_nothing_shows_as_synced() { + let d = AppDir::new("status"); + synced_under_a(&d.0); + sign_in(&d.0, "B"); + let s = state(&d.0, "g"); + assert_eq!((s.synced_hash.as_str(), s.synced_at, s.synced_device.as_str()), ("", 0, "")); + } + + #[test] + fn after_switching_accounts_this_pcs_own_save_is_still_known() { + let d = AppDir::new("local"); + synced_under_a(&d.0); + sign_in(&d.0, "B"); + assert_eq!(state(&d.0, "g").last_hash, "local"); + } + + #[test] + fn signed_out_nothing_shows_as_synced() { + let d = AppDir::new("signed-out"); + synced_under_a(&d.0); + sign_out(&d.0); + let s = state(&d.0, "g"); + assert_eq!((s.synced_hash.as_str(), s.pending.as_deref()), ("", None)); + } + + #[test] + fn switching_back_finds_the_first_accounts_notes_when_the_other_did_not_sync() { + let d = AppDir::new("back"); + synced_under_a(&d.0); + sign_in(&d.0, "B"); + let mut looked = state(&d.0, "g"); + looked.after_play = true; + set_state(&d.0, "g", &looked); + sign_in(&d.0, "A"); + assert_eq!(state(&d.0, "g").pending.as_deref(), Some("200.zip")); + } + + #[test] + fn switching_back_finds_nothing_once_the_other_account_synced() { + let d = AppDir::new("replaced"); + synced_under_a(&d.0); + sign_in(&d.0, "B"); + let mut s = state(&d.0, "g"); + s.mark_synced("b-cloud", 300, "Laptop"); + set_state(&d.0, "g", &s); + sign_in(&d.0, "A"); + let s = state(&d.0, "g"); + assert_eq!((s.synced_hash.as_str(), s.pending.as_deref()), ("", None)); + } + + #[test] + fn playing_signed_out_keeps_the_accounts_sync_point() { + let d = AppDir::new("offline-play"); + synced_under_a(&d.0); + sign_out(&d.0); + let mut s = state(&d.0, "g"); + s.last_hash = "played signed out".into(); + set_state(&d.0, "g", &s); + sign_in(&d.0, "A"); + let s = state(&d.0, "g"); + assert_eq!((s.synced_hash.as_str(), s.last_hash.as_str()), ("a-cloud", "played signed out")); + } + + #[test] + fn a_note_read_before_a_switch_is_not_written_after_it() { + let d = AppDir::new("late-write"); + synced_under_a(&d.0); + let mut s = state(&d.0, "g"); + sign_in(&d.0, "B"); + s.mark_synced("a-cloud-newer", 400, "Desk-PC"); + set_state(&d.0, "g", &s); + assert_eq!(state(&d.0, "g").synced_hash, ""); + } + + fn old_note(app: &std::path::Path) { + let f = state_file(app, "g"); + std::fs::create_dir_all(f.parent().unwrap()).unwrap(); + std::fs::write(f, br#"{"last_hash":"local","synced_hash":"old-cloud","pending":"100.zip"}"#).unwrap(); + } + + #[test] + fn a_note_from_before_accounts_belongs_to_the_account_signed_in() { + let d = AppDir::new("old-signed-in"); + old_note(&d.0); + sign_in(&d.0, "A"); + assert_eq!(state(&d.0, "g").pending.as_deref(), Some("100.zip")); + } + + #[test] + fn a_note_from_before_accounts_stays_with_that_account_after_a_switch() { + let d = AppDir::new("old-then-switch"); + old_note(&d.0); + sign_in(&d.0, "A"); + let _ = state(&d.0, "g"); + sign_in(&d.0, "B"); + assert_eq!(state(&d.0, "g").pending, None); + } + + #[test] + fn a_note_from_before_accounts_read_signed_out_belongs_to_nobody() { + let d = AppDir::new("old-signed-out"); + old_note(&d.0); + let _ = state(&d.0, "g"); + sign_in(&d.0, "B"); + let s = state(&d.0, "g"); + assert_eq!((s.synced_hash.as_str(), s.pending.as_deref(), s.last_hash.as_str()), ("", None, "local")); + } +} From ae1ea22a4b1b616b610c0c6099417eb74ff9f6e0 Mon Sep 17 00:00:00 2001 From: Zacharias Xenakis Date: Wed, 25 Nov 2026 17:31:48 +0200 Subject: [PATCH 2/2] Cloud saves: a restore cancels any account's queued upload, and an account without an id keeps its notes --- src-tauri/src/cloud.rs | 47 ++++++++++++++++++++++++---- src-tauri/src/saves.rs | 70 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 109 insertions(+), 8 deletions(-) diff --git a/src-tauri/src/cloud.rs b/src-tauri/src/cloud.rs index 4c0e3718..25196a22 100644 --- a/src-tauri/src/cloud.rs +++ b/src-tauri/src/cloud.rs @@ -114,6 +114,9 @@ pub fn signed_in(dir: &Path) -> bool { load(dir).is_some() } +/// The id used for an account signed in without one (account_uid). +const NO_UID: &str = "signed-in-without-id"; + /// The signed-in account's id, empty when nobody is. For the save notes (saves::state), which /// are read often: it reads account.json only, never the sealed token. pub(crate) fn account_uid(dir: &Path) -> String { @@ -124,6 +127,11 @@ pub(crate) fn account_uid(dir: &Path) -> String { if a.token.is_empty() && a.sealed.is_empty() { return String::new(); } + // Signed in, but the website gave no id: still somebody, so what this account syncs sticks. + // Its notes start fresh once an id comes, which is the safe first-sync path. + if a.user.uid.is_empty() { + return NO_UID.into(); + } a.user.uid } @@ -538,6 +546,9 @@ pub async fn account_poll(app: AppHandle) -> Res { if token.is_empty() { return Err(Error::Msg("The website didn't answer properly. Try again in a moment.".into())); } + if user.uid.is_empty() { + crate::trail::note("Account: signed in, but the website gave no account id"); + } let st = app.state::(); store(&st.dir, Some(&Account { token, user: user.clone(), ..Default::default() })); *LINK.lock().unwrap() = None; @@ -574,7 +585,12 @@ pub async fn account_state(app: AppHandle, fresh: bool) -> Res { }; match r { Ok(v) => { - let user: User = serde_json::from_value(v.get("account").cloned().unwrap_or(Value::Null)).unwrap_or(a.user.clone()); + let mut user: User = serde_json::from_value(v.get("account").cloned().unwrap_or(Value::Null)).unwrap_or(a.user.clone()); + // The id ties the save notes to this account (saves::state): an answer without one + // must not make them look like another account's. + if user.uid.is_empty() { + user.uid = a.user.uid.clone(); + } store(&st.dir, Some(&Account { token: a.token, user: user.clone(), ..Default::default() })); Ok(json!({"signedIn": true, "user": user, "used": v.pointer("/saves/used"), "quota": v.pointer("/saves/quota")})) } @@ -823,11 +839,19 @@ async fn upload(app: &AppHandle, id: &str, name: &str) -> Res<()> { async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { let st = app.state::(); + // One account from the note to the request: a switch meanwhile must not send this note's + // copy with the next account's token. + let a = load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; let mut state = saves::state(&st.dir, id); + // Signed in to another account just now: this note isn't that account's to send (the log + // says so). The copy stays on this PC and goes up with the new account's own sync. + if !still_signed_in_as(&st.dir, &a, id) { + return Ok(()); + } let copy = saves::manifest(&copies_dir(&st, id).join(name)) .ok_or_else(|| Error::Msg("That copy is gone.".into()))?; let (list, _) = cloud_list(app, id).await?; - let Some(top) = list.first() else { return upload_copy(app, id, name, 0).await }; + let Some(top) = list.first() else { return upload_copy(app, id, name, 0, &a).await }; if top.hash == copy.hash { state.mark_synced(©.hash, top.made, &top.device); if state.pending.as_deref() == Some(name) { @@ -841,10 +865,10 @@ async fn upload_one(app: &AppHandle, id: &str, name: &str) -> Res<()> { saves::set_state(&st.dir, id, &state); return Err(Error::Msg(SYNC_CONFLICT.into())); } - upload_copy(app, id, name, top.made.saturating_add(1)).await + upload_copy(app, id, name, top.made.saturating_add(1), &a).await } -async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64) -> Res<()> { +async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64, a: &Account) -> Res<()> { let st = app.state::(); let path = copies_dir(&st, id).join(name); let man = saves::manifest(&path).ok_or_else(|| Error::Msg("That copy is gone.".into()))?; @@ -875,7 +899,6 @@ async fn upload_copy(app: &AppHandle, id: &str, name: &str, earliest: u64) -> Re crate::trail::note(format!("Cloud saves: {id}'s copy is {} MB, too big to send", body.len() / (1024 * 1024))); return Err(Error::Msg(why.into())); } - let a = load(&st.dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; let made_at = man.made.max(earliest); let (made, played) = (made_at.to_string(), man.played.to_string()); let size = body.len() as u64; @@ -1238,7 +1261,8 @@ async fn upload_current(app: &AppHandle, id: &str, g: Installed, spots: Vec().dir).ok_or_else(|| Error::Msg("Sign in first.".into()))?; + let r = upload_copy(app, id, ©.name, after.saturating_add(1), &a).await; if let Err(e) = &r { note_failure(&app.state::().dir, id, e); } @@ -2372,6 +2396,17 @@ mod child_retry_tests { assert_eq!(copy, None); } + #[test] + fn a_sync_that_finishes_after_an_account_switch_is_not_noted_for_the_new_one() { + let fixture = Fixture::new(games()); + let st = &fixture.0; + let a = Account { token: "a-token".into(), user: User { uid: "A".into(), ..Default::default() }, ..Default::default() }; + sign_in_for_tests(&st.dir, "A"); + assert!(still_signed_in_as(&st.dir, &a, "series")); + sign_in_for_tests(&st.dir, "B"); + assert!(!still_signed_in_as(&st.dir, &a, "series")); + } + #[test] fn another_accounts_sync_point_does_not_bring_in_this_accounts_cloud_save() { let fixture = Fixture::new(games()); diff --git a/src-tauri/src/saves.rs b/src-tauri/src/saves.rs index a1c85875..7ae17092 100644 --- a/src-tauri/src/saves.rs +++ b/src-tauri/src/saves.rs @@ -934,6 +934,16 @@ pub fn state(app_dir: &Path, id: &str) -> State { } pub fn set_state(app_dir: &Path, id: &str, s: &State) { + write_state(app_dir, id, s, false); +} + +/// After the saves here were replaced (a restore, a shared save): the copy queued to go up is +/// superseded, whichever account it was queued for, so signing in to it again doesn't send it. +fn set_state_saves_replaced(app_dir: &Path, id: &str, s: &State) { + write_state(app_dir, id, s, true); +} + +fn write_state(app_dir: &Path, id: &str, s: &State, saves_replaced: bool) { let now = scope_now(app_dir); if s.read_under.as_ref().is_some_and(|r| *r != now) { crate::trail::note(format!("Saves: {id}'s sync note wasn't kept, the account changed meanwhile")); @@ -948,6 +958,9 @@ pub fn set_state(app_dir: &Path, id: &str, s: &State) { if let Some((written, Some(owner))) = read_note(app_dir, id) { if owner != now && owned(&owner) { keep.take_cloud_from(&written); + if saves_replaced { + keep.pending = None; + } scope = owner; } } @@ -1224,7 +1237,7 @@ pub fn restore(app_dir: &Path, id: &str, zip_file: &Path, spots_now: &[Spot], g: // A successful restore replaces the save that was queued for upload. Keep its archive in // local history, but do not let a retry send it over the player's restored selection. st.pending = None; - set_state(app_dir, id, &st); + set_state_saves_replaced(app_dir, id, &st); Ok(n) } @@ -1478,7 +1491,7 @@ pub fn share_save(app_dir: &Path, id: &str, spot: &Spot, g: &Installed, source: let mut s = state(app_dir, id); s.pending = None; - set_state(app_dir, id, &s); + set_state_saves_replaced(app_dir, id, &s); Ok(()) } @@ -2126,6 +2139,42 @@ mod tests { fs::remove_dir_all(d).unwrap(); } + // Account A queues the newest copy; the older one is restored with `who` signed in (None: + // nobody); then A signs in again and looks at what's queued. + fn restored_while_away(name: &str, who: Option<&str>) -> Option { + let d = tmp(name); + let app = d.join("app"); + let inst = d.join("inst"); + fs::create_dir_all(&inst).unwrap(); + let g = game(&inst); + let spots = vec![Spot { template: "{install}/slot.sav".into(), from: "developer" }]; + fs::write(inst.join("slot.sav"), "older save").unwrap(); + let older = backup(&app, "g", &spots, &g).unwrap().unwrap(); + fs::write(inst.join("slot.sav"), "newer save queued for A").unwrap(); + let queued = backup(&app, "g", &spots, &g).unwrap().unwrap(); + crate::cloud::sign_in_for_tests(&app, "A"); + set_state(&app, "g", &State { last_hash: queued.hash, synced_hash: "a-cloud".into(), pending: Some(queued.name), ..Default::default() }); + match who { + Some(uid) => crate::cloud::sign_in_for_tests(&app, uid), + None => crate::cloud::sign_out_for_tests(&app), + } + restore(&app, "g", &dir_of(&app, "g", &g).join(&older.name), &spots, &g).unwrap(); + crate::cloud::sign_in_for_tests(&app, "A"); + let pending = state(&app, "g").pending; + fs::remove_dir_all(d).unwrap(); + pending + } + + #[test] + fn restoring_signed_out_cancels_the_accounts_queued_upload() { + assert_eq!(restored_while_away("restore-signed-out", None), None); + } + + #[test] + fn restoring_as_another_account_cancels_the_first_accounts_queued_upload() { + assert_eq!(restored_while_away("restore-as-b", Some("B")), None); + } + #[test] fn a_failed_restore_keeps_the_pending_upload() { let d = tmp("restore-pending-error"); @@ -2763,6 +2812,23 @@ mod account_scope_tests { assert_eq!((s.synced_hash.as_str(), s.last_hash.as_str()), ("a-cloud", "played signed out")); } + #[test] + fn an_account_signed_in_without_an_id_keeps_its_queue() { + let d = AppDir::new("no-id"); + sign_in(&d.0, ""); + set_state(&d.0, "g", &State { pending: Some("200.zip".into()), ..Default::default() }); + assert_eq!(state(&d.0, "g").pending.as_deref(), Some("200.zip")); + } + + #[test] + fn an_account_signed_in_without_an_id_is_not_nobody() { + let d = AppDir::new("no-id-vs-nobody"); + sign_in(&d.0, ""); + set_state(&d.0, "g", &State { pending: Some("200.zip".into()), ..Default::default() }); + sign_out(&d.0); + assert_eq!(state(&d.0, "g").pending, None); + } + #[test] fn a_note_read_before_a_switch_is_not_written_after_it() { let d = AppDir::new("late-write");