A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.
fix(unity): dispose in-flight requests on a failed fetch, verify the content copy, fuller parity test
eyalgolan0a3826ddd4dc
diff --git a/unity/Assets/Editor/ContentSync.cs b/unity/Assets/Editor/ContentSync.csindex e209e4ca2..915a8e8b5 100644--- a/unity/Assets/Editor/ContentSync.cs+++ b/unity/Assets/Editor/ContentSync.cs@@ -11,7 +11,7 @@ namespace Statecraft.Game.EditorTools/// Run alone: Unity -batchmode -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.ContentSync.Sync</summary>public sealed class ContentSync : IPreprocessBuildWithReport{- public const string Target = "Assets/StreamingAssets/content";+ public static string Target => Path.Combine(UnityEngine.Application.dataPath, "StreamingAssets", "content");public int callbackOrder => 0;@@ -19,7 +19,9 @@ namespace Statecraft.Game.EditorToolspublic static void Sync(){- var files = ContentManifest.Copy(Path.Combine(Paths.RepoRoot, "content"), Target);+ var files = ContentManifest.Copy(Paths.Content, Target);+ try { ContentManifest.Verify(Paths.Content, Target); }+ catch (InvalidDataException e) { throw new BuildFailedException("ContentSync: " + e.Message); }UnityEngine.Debug.Log($"ContentSync: {files.Count} files to {Target}");}}diff --git a/unity/Assets/Scripts/Boot/ContentManifest.cs b/unity/Assets/Scripts/Boot/ContentManifest.csindex 35d89b36d..8c6979b3f 100644--- a/unity/Assets/Scripts/Boot/ContentManifest.cs+++ b/unity/Assets/Scripts/Boot/ContentManifest.cs@@ -13,8 +13,8 @@ namespace Statecraft.Game.Bootpublic static class ContentManifest{public const string FileName = "manifest.json";- /// <summary>The map files players read: hexes.json and every map/*.yaml (settlements; settlement hexes for the sim).- /// The precipitation files are tool inputs only.</summary>+ /// <summary>The map's hex table, always in the manifest. The map files players read are this and every map/*.yaml+ /// (settlements); the precipitation files are tool inputs only.</summary>public const string HexesJson = "map/hexes.json";[Serializable] sealed class ManifestJson { public string[] files = new string[0]; }@@ -41,6 +41,18 @@ namespace Statecraft.Game.Bootreturn m.files.ToList();}+ /// <summary>Checks a copy made by Copy: manifest.json equals Collect(contentDir) and every listed file exists.+ /// Throws InvalidDataException naming the problem.</summary>+ public static void Verify(string contentDir, string targetDir)+ {+ var expected = Collect(contentDir);+ var written = Parse(File.ReadAllText(Path.Combine(targetDir, FileName)));+ if (!expected.SequenceEqual(written))+ throw new InvalidDataException($"{FileName} in {targetDir} does not match the content files ({written.Count} listed, {expected.Count} expected)");+ foreach (var f in written)+ if (!File.Exists(Path.Combine(targetDir, f))) throw new InvalidDataException($"{f}: listed in {FileName} but missing from {targetDir}");+ }+/// <summary>Replaces <paramref name="targetDir"/> with a copy of the collected files plus manifest.json.</summary>public static List<string> Copy(string contentDir, string targetDir){diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.csindex 794a6bad6..a40a60d06 100644--- a/unity/Assets/Scripts/Boot/GameInputs.cs+++ b/unity/Assets/Scripts/Boot/GameInputs.cs@@ -56,45 +56,60 @@ namespace Statecraft.Game.Bootpublic static string StreamingUrl() =>Application.streamingAssetsPath.Contains("://") ? Application.streamingAssetsPath : new Uri(Application.streamingAssetsPath).AbsoluteUri;+ static readonly HashSet<UnityWebRequest> open = new HashSet<UnityWebRequest>();+ /// <summary>Requests started and not yet released (diagnostic; 0 once a fetch has ended, whether it succeeded or failed).</summary>+ public static int OpenRequests => open.Count;+static UnityWebRequest Start(string url){var r = UnityWebRequest.Get(url);+ open.Add(r);r.SendWebRequest();return r;}- /// <summary>Waits a frame at a time (no threads on WebGL; an Awaitable is never awaited twice).</summary>- static async Awaitable<UnityWebRequest> Done(UnityWebRequest r, string name)+ /// <summary>Aborts (when still running) and disposes a request; safe to call twice.</summary>+ static void Release(UnityWebRequest r)+ {+ if (!open.Remove(r)) return;+ if (!r.isDone) r.Abort();+ r.Dispose();+ }++ /// <summary>Waits a frame at a time (no threads on WebGL; an Awaitable is never awaited twice). The caller releases r.</summary>+ static async Awaitable Done(UnityWebRequest r, string name){while (!r.isDone) await Awaitable.NextFrameAsync();- if (r.result != UnityWebRequest.Result.Success)- {- var error = $"{name}: {r.error} ({r.url})";- r.Dispose();- throw new IOException(error);- }- return r;+ if (r.result != UnityWebRequest.Result.Success) throw new IOException($"{name}: {r.error} ({r.url})");}static async Awaitable<string> Text(UnityWebRequest r, string name){- using var done = await Done(r, name);- return done.downloadHandler.text;+ try { await Done(r, name); return r.downloadHandler.text; }+ finally { Release(r); }}- /// <summary>Fetches the manifest, then starts every download before awaiting any (parallel), then loads.</summary>+ /// <summary>Fetches the manifest, then starts every download before awaiting any (parallel), then loads. When one+ /// download fails, the others still running are aborted and disposed.</summary>public static async Awaitable<GameInputs> FetchAsync(string baseUrl){var manifest = ContentManifest.Parse(await Text(Start(baseUrl + "/content/" + ContentManifest.FileName), ContentManifest.FileName));var requests = manifest.Select(f => (file: f, request: Start(baseUrl + "/content/" + f))).ToList();var meta = Start(baseUrl + "/map/heightmap.json");var r16 = Start(baseUrl + "/map/heightmap.r16");- var texts = new Dictionary<string, string>();- foreach (var (file, request) in requests) texts[file] = await Text(request, file);- var metaText = await Text(meta, "heightmap.json");- byte[] bytes;- using (var done = await Done(r16, "heightmap.r16")) bytes = done.downloadHandler.data;- return FromTexts(texts, manifest, metaText, bytes);+ try+ {+ var texts = new Dictionary<string, string>();+ foreach (var (file, request) in requests) texts[file] = await Text(request, file);+ var metaText = await Text(meta, "heightmap.json");+ await Done(r16, "heightmap.r16");+ return FromTexts(texts, manifest, metaText, r16.downloadHandler.data);+ }+ finally+ {+ foreach (var (_, request) in requests) Release(request);+ Release(meta); Release(r16);+ }}}}diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.csindex 9dbfdd110..c97943975 100644--- a/unity/Assets/Tests/EditMode/GameInputsTests.cs+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs@@ -48,7 +48,9 @@ public class GameInputsTestsAssert.IsTrue(fetch.IsCompleted, "fetch did not finish in 600 editor frames");var fetched = fetch.GetResult();var disk = GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);- Assert.AreEqual(disk.Map.HeightmapR16.Length, fetched.Map.HeightmapR16.Length);+ CollectionAssert.AreEqual(disk.Map.HeightmapR16, fetched.Map.HeightmapR16);+ Assert.AreEqual(disk.Map.HeightmapJson, fetched.Map.HeightmapJson);+ Assert.AreEqual(disk.Map.SettlementsYaml, fetched.Map.SettlementsYaml);Assert.AreEqual(disk.Map.HexesJson, fetched.Map.HexesJson);Assert.AreEqual(disk.Content.Events.Count, fetched.Content.Events.Count);Assert.AreEqual(Simulation.NewGame(disk.Content, 7, Mode.Historical).Hash(), Simulation.NewGame(fetched.Content, 7, Mode.Historical).Hash());@@ -67,4 +69,34 @@ public class GameInputsTestsStringAssert.StartsWith("people.yaml: ", ex.Message);Directory.Delete(site, true);}++ [UnityTest]+ public IEnumerator AFailedFetchLeavesNoRequestOpen()+ {+ var site = StagedSite();+ File.Delete(Path.Combine(site, "content", "people.yaml"));+ var fetch = GameInputs.FetchAsync(new System.Uri(site).AbsoluteUri.TrimEnd('/')).GetAwaiter();+ for (int i = 0; i < 600 && !fetch.IsCompleted; i++) yield return null;+ Assert.IsTrue(fetch.IsCompleted);+ Assert.Throws<IOException>(() => fetch.GetResult());+ Assert.AreEqual(0, GameInputs.OpenRequests, "requests still in flight after a failed fetch were not disposed");+ Directory.Delete(site, true);+ }++ [Test]+ public void VerifyAcceptsACopyAndRejectsAMissingFileOrManifestMismatch()+ {+ var target = Path.Combine(Path.GetTempPath(), "statecraft-verify-" + System.Guid.NewGuid().ToString("N"));+ try+ {+ ContentManifest.Copy(Paths.Content, target);+ ContentManifest.Verify(Paths.Content, target);+ File.Delete(Path.Combine(target, "people.yaml"));+ StringAssert.Contains("people.yaml", Assert.Throws<InvalidDataException>(() => ContentManifest.Verify(Paths.Content, target)).Message);+ ContentManifest.Copy(Paths.Content, target);+ File.WriteAllText(Path.Combine(target, ContentManifest.FileName), ContentManifest.Write(new[] { "people.yaml" }));+ StringAssert.Contains("does not match", Assert.Throws<InvalidDataException>(() => ContentManifest.Verify(Paths.Content, target)).Message);+ }+ finally { if (Directory.Exists(target)) Directory.Delete(target, true); }+ }}