A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(ui): crash-safe autosave recovery, New Game prompt disarms on any change, deterministic R4 fault injection
eyalgolan746207491f1e
diff --git a/unity/Assets/Scripts/SaveStore.cs b/unity/Assets/Scripts/SaveStore.csindex 197a5e53c..93901d6be 100644--- a/unity/Assets/Scripts/SaveStore.cs+++ b/unity/Assets/Scripts/SaveStore.cs@@ -8,7 +8,7 @@ namespace Statecraft.Game/// /idbfs IndexedDB mount, not Application.persistentDataPath, because that path hashes the page's URL and itch.io/// serves every upload from a new URL, which would hide old saves (tech notes section 3). The template sets/// autoSyncPersistentDataPath, so closing the file persists it. Writes go to a .tmp file first, then replace.</summary>- public sealed class SaveStore+ public class SaveStore{public const string WebDirectory = "/idbfs/statecraft-saves";public const string AutosaveName = "autosave.txt";@@ -16,12 +16,16 @@ namespace Statecraft.Gamepublic string Directory { get; }public SaveStore(string directory) { Directory = directory; }- public static SaveStore ForPlatform() => new SaveStore(Application.platform == RuntimePlatform.WebGLPlayer- ? WebDirectory : Path.Combine(Application.persistentDataPath, "saves"));+ public static SaveStore ForPlatform() => new SaveStore(DirectoryFor(Application.platform, Application.persistentDataPath));++ /// <summary>The save folder for a platform. On the web it is the fixed folder and ignores persistentDataPath, which+ /// is /idbfs/<hash of the page URL>.</summary>+ public static string DirectoryFor(RuntimePlatform platform, string persistentDataPath) =>+ platform == RuntimePlatform.WebGLPlayer ? WebDirectory : Path.Combine(persistentDataPath, "saves");public string AutosavePath => Path.Combine(Directory, AutosaveName);- public void WriteAutosave(string text)+ public virtual void WriteAutosave(string text){System.IO.Directory.CreateDirectory(Directory);var tmp = AutosavePath + ".tmp";@@ -30,10 +34,22 @@ namespace Statecraft.GameFile.Move(tmp, AutosavePath);}- public string? ReadAutosave() => File.Exists(AutosavePath) ? File.ReadAllText(AutosavePath) : null;+ /// <summary>The autosave text, or null. WriteAutosave deletes the old file only after the .tmp is completely written, so+ /// a crash between the delete and the move leaves just the .tmp, which is complete: it is read and promoted. When both+ /// exist the .tmp may be partial and is ignored.</summary>+ public virtual string? ReadAutosave()+ {+ if (File.Exists(AutosavePath)) return File.ReadAllText(AutosavePath);+ var tmp = AutosavePath + ".tmp";+ if (!File.Exists(tmp)) return null;+ var text = File.ReadAllText(tmp);+ try { File.Move(tmp, AutosavePath); } catch (IOException) { } // promoting is a convenience; the text is already read+ catch (System.UnauthorizedAccessException) { }+ return text;+ }/// <summary>Moves an unreadable autosave aside (autosave.bad.txt) so it is kept for a bug report.</summary>- public void SetAsideAutosave()+ public virtual void SetAsideAutosave(){if (!File.Exists(AutosavePath)) return;var bad = Path.Combine(Directory, "autosave.bad.txt");@@ -41,6 +57,6 @@ namespace Statecraft.GameFile.Move(AutosavePath, bad);}- public void DeleteAutosave() { if (File.Exists(AutosavePath)) File.Delete(AutosavePath); }+ public virtual void DeleteAutosave() { if (File.Exists(AutosavePath)) File.Delete(AutosavePath); }}}diff --git a/unity/Assets/Scripts/UI/GameStart.cs b/unity/Assets/Scripts/UI/GameStart.csindex 897b125ce..256e57103 100644--- a/unity/Assets/Scripts/UI/GameStart.cs+++ b/unity/Assets/Scripts/UI/GameStart.cs@@ -7,27 +7,32 @@ namespace Statecraft.Game.UI{/// <summary>Starting a session: continue the autosave when there is one (replayed to the same state hash), else a new/// Historical game. Anything the player should know (a content-change warning, an unreadable save) goes to notes.- /// No failure while reading or replaying the autosave stops the game from starting: the file is set aside.</summary>+ /// No failure while reading or replaying the autosave stops the game from starting: the file is set aside.+ /// <paramref name="fresh"/> is used only by tests (New Game goes through SimBridge.Replace); it ignores the autosave.</summary>public static class GameStart{public static ulong NewSeed() => (ulong)DateTime.UtcNow.Ticks;- public static GameSession Begin(Content c, SaveStore store, Func<ulong> newSeed, List<string> notes, bool fresh = false)+ public static GameSession Begin(Content c, SaveStore store, Func<ulong> newSeed, List<string> notes, UiText text, bool fresh = false){if (!fresh){try{- var text = store.ReadAutosave();- if (text == null) return GameSession.New(c, newSeed(), Mode.Historical);- var loaded = GameSession.Load(c, text, out var warnings);+ var saved = store.ReadAutosave();+ if (saved == null) return GameSession.New(c, newSeed(), Mode.Historical);+ var loaded = GameSession.Load(c, saved, out var warnings);notes.AddRange(warnings);return loaded;}catch (Exception e) // any failure (a bad save, a replay that throws): never block the start{try { store.SetAsideAutosave(); } catch (Exception) { /* even this must not stop the start */ }- notes.Add($"Your saved game could not be loaded ({e.Message}). A new game has started.");+ // A SaveException's message is about the save's own text (line numbers); anything else can carry file paths, so+ // the player gets a short reason and the full exception goes to the log.+ if (!(e is SaveException)) UnityEngine.Debug.LogWarning("Autosave could not be loaded: " + e);+ else UnityEngine.Debug.LogWarning("Autosave rejected: " + e.Message);+ notes.Add(text.Format("save.unreadable", e is SaveException ? e.Message : text["save.reason_other"]));}}return GameSession.New(c, newSeed(), Mode.Historical);@@ -35,12 +40,16 @@ namespace Statecraft.Game.UI/// <summary>Writes the save after every turn. A write that fails (a full or read-only disk) never stops the game:/// the reason goes to <paramref name="onError"/>. Dispose the result to stop autosaving.</summary>- public static IDisposable Autosave(SimBridge bridge, SaveStore store, Action<string>? onError = null)+ public static IDisposable Autosave(SimBridge bridge, SaveStore store, UiText text, Action<string>? onError = null){void Save(IReadOnlyList<Rejection> _){try { store.WriteAutosave(bridge.Session.Save.Write()); }- catch (Exception e) { onError?.Invoke($"Your game could not be saved ({e.Message})."); }+ catch (Exception e)+ {+ UnityEngine.Debug.LogWarning("Autosave could not be written: " + e);+ onError?.Invoke(text["save.write_failed"]);+ }}bridge.TurnEnded += Save;return new Unsubscribe(() => bridge.TurnEnded -= Save);diff --git a/unity/Assets/Scripts/UI/NewGamePresenter.cs b/unity/Assets/Scripts/UI/NewGamePresenter.csindex 79380ef67..b9da72311 100644--- a/unity/Assets/Scripts/UI/NewGamePresenter.cs+++ b/unity/Assets/Scripts/UI/NewGamePresenter.cs@@ -1,6 +1,5 @@#nullable enableusing System;-using System.Collections.Generic;using Statecraft.Sim;using UnityEngine.UIElements;@@ -17,15 +16,16 @@ namespace Statecraft.Game.UIthis.root = root; this.bridge = bridge; this.store = store; this.toast = toast; this.text = text; this.seed = seed;button = root.Q<Button>("new-game");button.clicked += Press;- bridge.TurnEnded += Disarm;+ bridge.Changed += Disarm;}readonly Button button;- void Disarm(IReadOnlyList<Rejection> _) => Armed = false;+ // Any change (an order, a turn, a new session) means the prompt no longer describes what is on screen.+ void Disarm() => Armed = false;/// <summary>Unsubscribes from the bridge and the button (the owner calls this when disabled).</summary>- public void Dispose() { button.clicked -= Press; bridge.TurnEnded -= Disarm; }+ public void Dispose() { button.clicked -= Press; bridge.Changed -= Disarm; }public bool Armed { get; private set; }@@ -33,9 +33,11 @@ namespace Statecraft.Game.UI{if (!Armed) { Armed = true; toast.Show(text["newgame.confirm"]); return; }Armed = false;- store.DeleteAutosave();+ bool deleted = true;+ // An old autosave that cannot be deleted is overwritten by the next turn's autosave anyway, so the new game still starts.+ try { store.DeleteAutosave(); } catch (Exception e) { deleted = false; UnityEngine.Debug.LogWarning("Autosave could not be deleted: " + e); }bridge.Replace(GameSession.New(bridge.Content, seed(), Mode.Historical));- toast.Clear();+ if (deleted) toast.Clear(); else toast.Show(text["newgame.delete_failed"]);}}}diff --git a/unity/Assets/Tests/EditMode/SaveUiTests.cs b/unity/Assets/Tests/EditMode/SaveUiTests.csindex ba1086da3..8240e47d4 100644--- a/unity/Assets/Tests/EditMode/SaveUiTests.cs+++ b/unity/Assets/Tests/EditMode/SaveUiTests.cs@@ -7,25 +7,49 @@ using Statecraft.Sim;using UnityEditor;using UnityEngine.UIElements;using UnityEngine;+using UnityEngine.TestTools;public class SaveUiTests{static readonly Content C = ContentLoader.Load(Paths.Content);static UiText Text => UiText.Parse(AssetDatabase.LoadAssetAtPath<TextAsset>(UiPaths.Strings).text);- static SaveStore TempStore() => new SaveStore(Path.Combine(Path.GetTempPath(), "statecraft-saves-" + System.Guid.NewGuid().ToString("N")));+ static readonly List<string> TempFolders = new List<string>();+ static SaveStore TempStore()+ {+ var dir = Path.Combine(Path.GetTempPath(), "statecraft-saves-" + System.Guid.NewGuid().ToString("N"));+ TempFolders.Add(dir);+ return new SaveStore(dir);+ }++ [TearDown]+ public void RemoveTempFolders()+ {+ foreach (var d in TempFolders) { try { if (Directory.Exists(d)) Directory.Delete(d, true); } catch (System.Exception) { } }+ TempFolders.Clear();+ }++ /// <summary>A store whose reads and set-asides fail the way a broken disk does, deterministically.</summary>+ sealed class FaultyStore : SaveStore+ {+ readonly string? text;+ public bool SetAsideCalled;+ public FaultyStore(string? text) : base(Path.Combine(Path.GetTempPath(), "statecraft-faulty")) { this.text = text; }+ public override string? ReadAutosave() => text ?? throw new IOException("disk gone");+ public override void SetAsideAutosave() { SetAsideCalled = true; throw new System.UnauthorizedAccessException("no permission"); }+ }[Test]public void EveryTurnIsAutosavedAndTheNextStartContinuesIt(){var store = TempStore();var notes = new List<string>();- var bridge = new SimBridge(GameStart.Begin(C, store, () => 77UL, notes), Text);- GameStart.Autosave(bridge, store);+ var bridge = new SimBridge(GameStart.Begin(C, store, () => 77UL, notes, Text), Text);+ GameStart.Autosave(bridge, store, Text);bridge.Queue(new SetMobilization(1.0));bridge.EndTurn(); bridge.EndTurn();Assert.IsTrue(File.Exists(store.AutosavePath));Assert.IsFalse(File.Exists(store.AutosavePath + ".tmp"));- var resumed = GameStart.Begin(C, store, () => 1UL, notes);+ var resumed = GameStart.Begin(C, store, () => 1UL, notes, Text);Assert.IsEmpty(notes);Assert.AreEqual(bridge.State.Hash(), resumed.State.Hash());Assert.AreEqual(2, resumed.State.Turn);@@ -37,7 +61,7 @@ public class SaveUiTestsvar store = TempStore();store.WriteAutosave("statecraft-save 9\ncontent x\nseed 1\nmode Historical\nend x\n");var notes = new List<string>();- var session = GameStart.Begin(C, store, () => 5UL, notes);+ var session = GameStart.Begin(C, store, () => 5UL, notes, Text);Assert.AreEqual(0, session.State.Turn);StringAssert.StartsWith("Your saved game could not be loaded (line 1: save schema version 9 is newer", notes[0]);Assert.IsFalse(File.Exists(store.AutosavePath));@@ -51,26 +75,124 @@ public class SaveUiTestsvar good = GameSession.New(C, 9, Mode.Historical).Save.Write();store.WriteAutosave(good.Replace("mode Historical", "mode Open"));var notes = new List<string>();- var session = GameStart.Begin(C, store, () => 6UL, notes);+ var session = GameStart.Begin(C, store, () => 6UL, notes, Text);Assert.AreEqual(0, session.State.Turn);StringAssert.StartsWith("Your saved game could not be loaded (line 4: mode Open is not supported)", notes[0]);Assert.IsTrue(File.Exists(Path.Combine(store.Directory, "autosave.bad.txt")));}[Test]- public void AFailureThatIsNotASaveExceptionNeverStopsTheStart()+ public void AReadThatFailsAndASetAsideThatFailsNeverStopTheStart()+ {+ var store = new FaultyStore(null);+ var notes = new List<string>();+ LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("disk gone"));+ GameSession? session = null;+ Assert.DoesNotThrow(() => session = GameStart.Begin(C, store, () => 6UL, notes, Text));+ Assert.AreEqual(0, session!.State.Turn);+ Assert.AreEqual(1, notes.Count);+ Assert.AreEqual("Your saved game could not be loaded (the file could not be read or replayed). A new game has started.", notes[0]);+ StringAssert.DoesNotContain("disk gone", notes[0]); // raw exception text can carry file paths: it is logged, not shown+ Assert.IsTrue(store.SetAsideCalled);+ }++ [Test]+ public void AnUnparseableSaveWhoseSetAsideFailsNeverStopsTheStartEither(){- // Another process holds the file: reading it throws IOException, not SaveException, and even setting it aside may fail.+ var store = new FaultyStore("this is not a save\n");+ var notes = new List<string>();+ LogAssert.Expect(LogType.Warning, new System.Text.RegularExpressions.Regex("Autosave rejected"));+ GameSession? session = null;+ Assert.DoesNotThrow(() => session = GameStart.Begin(C, store, () => 6UL, notes, Text));+ Assert.AreEqual(0, session!.State.Turn);+ Assert.AreEqual(1, notes.Count);+ StringAssert.StartsWith("Your saved game could not be loaded (Not a Statecraft save", notes[0]);+ Assert.IsTrue(store.SetAsideCalled);+ }++ [Test]+ public void ACrashBetweenDeletingAndMovingLosesNothing()+ {+ // WriteAutosave deletes the old file only after the .tmp is completely written; a crash after the delete leaves just the .tmp.var store = TempStore();- store.WriteAutosave(GameSession.New(C, 9, Mode.Historical).Save.Write());- using (new FileStream(store.AutosavePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))- {- var notes = new List<string>();- GameSession? session = null;- Assert.DoesNotThrow(() => session = GameStart.Begin(C, store, () => 6UL, notes));- Assert.AreEqual(0, session!.State.Turn);- StringAssert.StartsWith("Your saved game could not be loaded (", notes[0]);- }+ var played = new SimBridge(GameSession.New(C, 9, Mode.Historical), Text);+ played.EndTurn(); played.EndTurn();+ Directory.CreateDirectory(store.Directory);+ File.WriteAllText(store.AutosavePath + ".tmp", played.Session.Save.Write());+ var notes = new List<string>();+ var resumed = GameStart.Begin(C, store, () => 1UL, notes, Text);+ Assert.IsEmpty(notes);+ Assert.AreEqual(2, resumed.State.Turn);+ Assert.AreEqual(played.State.Hash(), resumed.State.Hash());+ Assert.IsTrue(File.Exists(store.AutosavePath), "the .tmp was promoted");+ Assert.IsFalse(File.Exists(store.AutosavePath + ".tmp"));+ }++ [Test]+ public void ALeftOverTmpIsIgnoredWhenTheAutosaveExists()+ {+ var store = TempStore();+ var played = new SimBridge(GameSession.New(C, 9, Mode.Historical), Text);+ played.EndTurn();+ store.WriteAutosave(played.Session.Save.Write());+ File.WriteAllText(store.AutosavePath + ".tmp", "half a sav"); // a partial write+ var resumed = GameStart.Begin(C, store, () => 1UL, new List<string>(), Text);+ Assert.AreEqual(1, resumed.State.Turn);+ Assert.AreEqual(played.State.Hash(), resumed.State.Hash());+ }++ [Test]+ public void ADisposedAutosaveStopsWriting()+ {+ var store = TempStore();+ var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);+ var autosave = GameStart.Autosave(bridge, store, Text);+ bridge.EndTurn();+ var before = File.ReadAllText(store.AutosavePath);+ autosave.Dispose();+ bridge.EndTurn();+ Assert.AreEqual(before, File.ReadAllText(store.AutosavePath));+ }++ [Test]+ public void AnOpenPromptIsClearedByAnyChange()+ {+ using var ui = new UiTestKit();+ var store = TempStore();+ var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);+ var toast = new ToastPresenter(ui.Root, bridge, Text);+ var newGame = new NewGamePresenter(ui.Root, bridge, store, toast, Text, () => 4UL);+ var session = bridge.Session;+ ui.Press("new-game");+ Assert.IsTrue(newGame.Armed);+ bridge.Queue(new SecurityOrder(-1)); // any change: the prompt no longer applies+ Assert.IsFalse(newGame.Armed);+ ui.Press("new-game");+ Assert.AreSame(session, bridge.Session, "one press after a change only arms again");+ Assert.IsTrue(newGame.Armed);+ Assert.AreEqual("Press New Game again to abandon this game and start over.", ui.Q<Label>("toast").text);+ Assert.AreEqual(1, bridge.Queued.Count);+ }++ [Test]+ public void AFailedDeleteStillStartsTheNewGame()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);+ bridge.EndTurn();+ var toast = new ToastPresenter(ui.Root, bridge, Text);+ var store = new DeleteFailsStore();+ new NewGamePresenter(ui.Root, bridge, store, toast, Text, () => 4UL);+ ui.Press("new-game");+ Assert.DoesNotThrow(() => ui.Press("new-game"));+ Assert.AreEqual(0, bridge.State.Turn);+ StringAssert.StartsWith("The old saved game could not be removed", ui.Q<Label>("toast").text);+ }++ sealed class DeleteFailsStore : SaveStore+ {+ public DeleteFailsStore() : base(Path.Combine(Path.GetTempPath(), "statecraft-faulty")) { }+ public override void DeleteAutosave() => throw new IOException("locked");}[Test]@@ -79,7 +201,7 @@ public class SaveUiTestsusing var ui = new UiTestKit();var store = TempStore();var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);- GameStart.Autosave(bridge, store);+ GameStart.Autosave(bridge, store, Text);bridge.EndTurn();var toast = new ToastPresenter(ui.Root, bridge, Text);var newGame = new NewGamePresenter(ui.Root, bridge, store, toast, Text, () => 4UL);@@ -93,8 +215,16 @@ public class SaveUiTests}[Test]- public void TheWebSaveFolderDoesNotDependOnThePageUrl() =>- Assert.AreEqual("/idbfs/statecraft-saves", SaveStore.WebDirectory);+ public void TheWebSaveFolderDoesNotDependOnThePageUrl()+ {+ // On the web Application.persistentDataPath is /idbfs/<hash of the page URL>; the save folder must not be under it.+ var persistent = "/idbfs/0a1b2c3d4e5f60718293a4b5c6d7e8f9";+ var web = SaveStore.DirectoryFor(RuntimePlatform.WebGLPlayer, persistent);+ Assert.AreEqual(SaveStore.WebDirectory, web);+ StringAssert.DoesNotContain(persistent, web);+ Assert.AreEqual(web, SaveStore.DirectoryFor(RuntimePlatform.WebGLPlayer, "/idbfs/ffffffffffffffffffffffffffffffff"));+ Assert.AreEqual(Path.Combine("/home/x/.config/game", "saves"), SaveStore.DirectoryFor(RuntimePlatform.OSXPlayer, "/home/x/.config/game"));+ }[Test]public void AFailingAutosaveWriteNeverStopsATurn()@@ -105,7 +235,7 @@ public class SaveUiTests{var bridge = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);var errors = new List<string>();- GameStart.Autosave(bridge, new SaveStore(file), errors.Add);+ GameStart.Autosave(bridge, new SaveStore(file), Text, errors.Add);Assert.DoesNotThrow(() => bridge.EndTurn());Assert.AreEqual(1, bridge.State.Turn);Assert.AreEqual(1, errors.Count);@@ -119,9 +249,9 @@ public class SaveUiTests{var store = TempStore();var played = new SimBridge(GameSession.New(C, 3, Mode.Historical), Text);- GameStart.Autosave(played, store);+ GameStart.Autosave(played, store, Text);played.EndTurn();- var session = GameStart.Begin(C, store, () => 8UL, new List<string>(), fresh: true);+ var session = GameStart.Begin(C, store, () => 8UL, new List<string>(), Text, fresh: true);Assert.AreEqual(0, session.State.Turn);Assert.IsTrue(File.Exists(store.AutosavePath), "an ignored save is left alone");}@@ -133,10 +263,10 @@ public class SaveUiTestsvar text = GameSession.New(C, 9, Mode.Historical).Save.Write().Replace("content " + C.Hash, "content " + new string('0', C.Hash.Length));store.WriteAutosave(text);var notes = new List<string>();- var session = GameStart.Begin(C, store, () => 1UL, notes);+ var session = GameStart.Begin(C, store, () => 1UL, notes, Text);Assert.AreEqual(1, notes.Count);StringAssert.Contains("different game content", notes[0]);- Assert.IsTrue(File.Exists(store.AutosavePath), "a warning is not a failure: the save is kept");+ Assert.IsTrue(File.Exists(store.AutosavePath), "a warning is not a failure: the file is kept until the next turn's autosave replaces it");Assert.AreEqual(0, session.State.Turn);}diff --git a/unity/Assets/UI/strings.en.yaml b/unity/Assets/UI/strings.en.yamlindex 7bc8bdb11..8280ce2a8 100644--- a/unity/Assets/UI/strings.en.yaml+++ b/unity/Assets/UI/strings.en.yaml@@ -85,3 +85,7 @@ info.biome.mountains: "Mountains"info.biome.valley: "Valley"info.biome.desert: "Desert"newgame.confirm: "Press New Game again to abandon this game and start over."+newgame.delete_failed: "The old saved game could not be removed; it will be replaced after your next turn."+save.unreadable: "Your saved game could not be loaded ({0}). A new game has started."+save.reason_other: "the file could not be read or replayed"+save.write_failed: "Your game could not be saved."