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): reject lone surrogates in content at load, EndTurn failure rejects the queued commands
eyalgolanb89ab1d11d0d
diff --git a/sim/Statecraft.Sim.Tests/ContentLoaderTests.cs b/sim/Statecraft.Sim.Tests/ContentLoaderTests.csindex fad5be946..6dbdd4516 100644--- a/sim/Statecraft.Sim.Tests/ContentLoaderTests.cs+++ b/sim/Statecraft.Sim.Tests/ContentLoaderTests.cs@@ -191,3 +191,28 @@ public class ContentLoaderTestsAssert.Equal(viaDir.Field, viaReader.Field);}}++public class ContentTextTests+{+ static Func<string, string?> Reader(string file, string text)+ {+ var dir = Fixture.Write(); // a file on disk would turn the lone surrogate into U+FFFD, so the bad file is served from memory+ return rel => { if (rel == file) return text; var f = Path.Combine(dir, rel); return File.Exists(f) ? File.ReadAllText(f) : null; };+ }++ // (<S> stands for a lone surrogate: xUnit would mangle a real one in theory data.) A lone surrogate in a string handed to the loader (not through a YAML escape, which YamlDotNet rejects itself)+ // cannot be saved; it must be a load error naming file and field, not a crash later in End Turn.+ [Theory]+ [InlineData("offices.yaml", "id: finance_minister", "id: fin<S>", "offices[")]+ [InlineData("people.yaml", "name: Def Two", "name: Def<S>", "people[")]+ [InlineData("rules.yaml", "budget_start: { finance_minister: 1.0 }", "budget_start: { fin<S>: 1.0 }", "budget_start")]+ public void ATextThatIsNotValidIsALoadError(string file, string from, string to, string field)+ {+ var bad = Fixture.Files[file].Replace(from, to.Replace("<S>", "\uD800"));+ Assert.NotEqual(Fixture.Files[file], bad);+ var ex = Assert.Throws<ContentException>(() => ContentLoader.Load(Reader(file, bad), new string[0]));+ Assert.Equal(file, ex.File);+ Assert.Contains("valid text", ex.Message);+ Assert.Contains(field, ex.Field);+ }+}diff --git a/sim/Statecraft.Sim/ContentLoader.cs b/sim/Statecraft.Sim/ContentLoader.csindex 378c3937f..3632b3169 100644--- a/sim/Statecraft.Sim/ContentLoader.cs+++ b/sim/Statecraft.Sim/ContentLoader.cs@@ -93,7 +93,7 @@ namespace Statecraft.Simvar key = (path == "" ? "" : path + ".") + UnderscoredNamingConvention.Instance.Apply(p.Name);var t = p.PropertyType;var v = p.GetValue(o);- if (t == typeof(string)) { if (v == null) p.SetValue(o, ""); }+ if (t == typeof(string)) { if (v == null) p.SetValue(o, ""); else Encodable(file, key, (string)v); }else if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(List<>)){if (v == null) throw new ContentException(file, key, "must be a list");@@ -102,6 +102,7 @@ namespace Statecraft.Sim{var item = list[i];if (item == null) throw new ContentException(file, FormattableString.Invariant($"{key}[{i}]"), "empty entry");+ if (item is string si) Encodable(file, FormattableString.Invariant($"{key}[{i}]"), si);if (!IsContentType(item.GetType())) continue;var id = item.GetType().GetProperty("Id")?.GetValue(item) as string;CheckNulls(file, string.IsNullOrEmpty(id) ? FormattableString.Invariant($"{key}[{i}]") : $"{key}[{id}]", item);@@ -110,11 +111,23 @@ namespace Statecraft.Simelse if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Dictionary<,>)){if (v == null) throw new ContentException(file, key, "must be a map");+ foreach (DictionaryEntry kv in (IDictionary)v)+ {+ if (kv.Key is string sk) Encodable(file, key + "." + sk, sk);+ if (kv.Value is string sv) Encodable(file, key + "." + kv.Key, sv);+ }}else if (v != null && IsContentType(t)) CheckNulls(file, key, v);}}+ /// <summary>Every id and text must be valid Unicode (no lone surrogate), or orders and saves that carry it would fail+ /// later. Uses the same check as the save format.</summary>+ static void Encodable(string file, string field, string s)+ {+ if (!SaveText.IsEncodable(s)) throw new ContentException(file, field, "must be valid text (no lone surrogate)");+ }+static bool IsContentType(Type t) => t.IsClass && t != typeof(string) && t.Namespace == typeof(Content).Namespace;/// <summary>Loads content through <paramref name="readFile"/>, which takes a path relative to the content rootdiff --git a/unity/Assets/Scripts/UI/SimBridge.cs b/unity/Assets/Scripts/UI/SimBridge.csindex 609a3e097..8d50dd93c 100644--- a/unity/Assets/Scripts/UI/SimBridge.cs+++ b/unity/Assets/Scripts/UI/SimBridge.cs@@ -28,9 +28,13 @@ namespace Statecraft.Game.UIpublic event Action<string>? Refused;readonly UiText text;+ readonly Func<GameSession, IReadOnlyList<Command>, StepResult> step;- public SimBridge(GameSession session, UiText text)+ /// <param name="step">How a turn is run; the default is Session.Step. Tests pass a stepper that throws, to prove+ /// that a batch the simulation refuses outright cannot soft-lock the game.</param>+ public SimBridge(GameSession session, UiText text, Func<GameSession, IReadOnlyList<Command>, StepResult>? step = null){+ this.step = step ?? ((s, cmds) => s.Step(cmds));Session = session ?? throw new ArgumentNullException(nameof(session));this.text = text ?? throw new ArgumentNullException(nameof(text));}@@ -109,11 +113,13 @@ namespace Statecraft.Game.UI{StepResult r;var before = Session.Last;- try { r = Session.Step(queue.ToList()); }+ var batch = queue.ToList();+ try { r = step(Session, batch); }catch (ArgumentException e){queue.Clear();- var failed = new StepResult(State, new Cause[0], new[] { new Rejection(new SecurityOrder(0), text.Format("order.failed", e.Message)) });+ var reason = text.Format("order.failed", e.Message);+ var failed = new StepResult(State, new Cause[0], batch.Select(x => new Rejection(x, reason)).ToList());Changed?.Invoke();TurnEnded?.Invoke(failed.Rejected);return failed;diff --git a/unity/Assets/Tests/EditMode/HudTests.cs b/unity/Assets/Tests/EditMode/HudTests.csindex ac3926288..78a9d1a47 100644--- a/unity/Assets/Tests/EditMode/HudTests.cs+++ b/unity/Assets/Tests/EditMode/HudTests.cs@@ -248,4 +248,23 @@ public class HudTestsAssert.IsNull(bridge.BeforeLast);Assert.AreEqual(0, bridge.State.Turn);}++ [Test]+ public void ABatchTheSimRefusesOutrightKeepsTheStateAndShowsTheReason()+ {+ using var ui = new UiTestKit();+ var bridge = new SimBridge(GameSession.New(C, GoldenRun.Seed, Mode.Historical), Text, (s, cmds) => throw new System.ArgumentException("boom"));+ new ToastPresenter(ui.Root, bridge, Text);+ var order = new SecurityOrder(-1);+ Assert.IsNull(bridge.Queue(order));+ System.Collections.Generic.IReadOnlyList<Rejection>? seen = null;+ bridge.TurnEnded += r => seen = r;+ var hash = bridge.State.Hash();+ Assert.DoesNotThrow(() => bridge.EndTurn());+ Assert.AreEqual(hash, bridge.State.Hash());+ Assert.AreEqual(0, bridge.Queued.Count);+ Assert.IsNull(bridge.BeforeLast);+ Assert.AreSame(order, seen![0].Command);+ Assert.AreEqual("Not done: The turn could not run: boom", ui.Q<Label>("toast").text);+ }}