Skip to content

A Civilization-style strategy game about governing Israel from 15 May 1948. Real ministers, real map, every fact sourced. Unity + deterministic C# sim.

Web: retry every boot fetch through one helper and pack the content into one file: 70 StreamingAssets requests to 9 (Fixes #1054) (#1076)

Eyal Golandb343093494c
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7ee79025c..798416845 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -139,6 +139,13 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
keep the floor too (26 px at 360x800, 30 px at 375x667): there the bar grows to its rows' height and the panels
under it follow. On a phone held upright the decision card now starts right of the left rail and hangs under the bar instead of sitting centred, so no
rail button sits under it (Why? and Settings did), and the rail's buttons are 60 px, at least 24 px on screen.
+- The web build no longer loses its boot or its 1948 Collection models to a rate-limited host (players got HTTP 429
+ from itch.io, #1054). The content texts are packed into one file at build time (`content/bundle.json`), so a boot
+ makes 9 StreamingAssets requests instead of 70 (main, measured headless); the content hash is unchanged. Every
+ StreamingAssets fetch at boot, the collection's checks file and bundles included (they had no retry), now goes
+ through one retry helper (`StreamingFetch`): 408, 429, 5xx and no response are retried after 0.5, 1 and 2 s, or a
+ longer `Retry-After` up to 10 s, four attempts in all, and then fail as before. Desktop and the editor still read
+ the files.
## [0.1.1] - 2026-10-18
diff --git a/unity/Assets/Editor/ContentSync.cs b/unity/Assets/Editor/ContentSync.cs
index 84f21f9be..65fd70dae 100644
--- a/unity/Assets/Editor/ContentSync.cs
+++ b/unity/Assets/Editor/ContentSync.cs
@@ -6,8 +6,9 @@ using UnityEditor.Build.Reporting;
namespace Statecraft.Game.EditorTools
{
- /// <summary>Copies the repository's content/ into Assets/StreamingAssets/content with a manifest.json before every
- /// player build (git-ignored output), so players read the same content the editor reads from the repo.
+ /// <summary>Copies the repository's content/ into Assets/StreamingAssets/content with a manifest.json and a bundle.json
+ /// (every text in one file, which the web boot fetches: #1054) before every player build (git-ignored output), so
+ /// players read the same content the editor reads from the repo.
/// Run alone: Unity -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -executeMethod Statecraft.Game.EditorTools.ContentSync.Sync</summary>
public sealed class ContentSync : IPreprocessBuildWithReport
{
diff --git a/unity/Assets/Scripts/Boot/ContentManifest.cs b/unity/Assets/Scripts/Boot/ContentManifest.cs
index 14249d852..49a22e884 100644
--- a/unity/Assets/Scripts/Boot/ContentManifest.cs
+++ b/unity/Assets/Scripts/Boot/ContentManifest.cs
@@ -9,10 +9,14 @@ namespace Statecraft.Game.Boot
{
/// <summary>The list of content files a player needs, so a WebGL build (no directory listing over HTTP) can fetch
/// them: content/manifest.json in StreamingAssets, {"files": [...]} with paths relative to content/, '/' separated,
- /// ordinal order. The editor build step (ContentSync) copies the files and writes the manifest.</summary>
+ /// ordinal order. The editor build step (ContentSync) copies the files and writes the manifest, and packs every listed
+ /// file's text into content/bundle.json, which is what the web boot fetches: one request instead of one per file
+ /// (#1054). Desktop players and the editor read the files themselves.</summary>
public static class ContentManifest
{
public const string FileName = "manifest.json";
+ /// <summary>Every listed file's text in one file: {"files": [...], "texts": [...]}, the same order (#1054).</summary>
+ public const string BundleFileName = "bundle.json";
/// <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";
@@ -29,6 +33,7 @@ namespace Statecraft.Game.Boot
"map/subdistrict_hexes_1948.tsv", "map/armistice_hexes_1949.tsv", "map/control_hexes_1948_49.tsv" };
[Serializable] sealed class ManifestJson { public string[] files = new string[0]; }
+ [Serializable] sealed class BundleJson { public string[] files = new string[0]; public string[] texts = new string[0]; }
/// <summary>Every *.yaml in <paramref name="contentDir"/>, events/, map/ and rules/ (era rule overrides, #58; the folder may be absent) (but <see cref="ToolInputs"/>), plus
/// map/hexes.json; ordinal order.</summary>
@@ -54,8 +59,33 @@ namespace Statecraft.Game.Boot
return 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>
+ /// <summary>bundle.json for <paramref name="files"/> (paths relative to <paramref name="contentDir"/>), each text
+ /// read as the disk path reads it (File.ReadAllText), so the content hash is the disk's.</summary>
+ public static string WriteBundle(string contentDir, IReadOnlyList<string> files) => JsonUtility.ToJson(new BundleJson
+ {
+ files = files.ToArray(),
+ texts = files.Select(f => File.ReadAllText(Path.Combine(contentDir, f))).ToArray(),
+ });
+
+ /// <summary>Parses bundle.json into the file list (as manifest.json lists it) and each file's text; throws
+ /// InvalidDataException when it is not a bundle.</summary>
+ public static (List<string> Files, Dictionary<string, string> Texts) ParseBundle(string json)
+ {
+ BundleJson? b;
+ try { b = JsonUtility.FromJson<BundleJson>(json); }
+ catch (ArgumentException e) { throw new InvalidDataException($"{BundleFileName}: malformed JSON ({e.Message})", e); }
+ if (b?.files == null || b.files.Length == 0) throw new InvalidDataException($"{BundleFileName}: no files");
+ if (b.texts == null || b.texts.Length != b.files.Length)
+ throw new InvalidDataException($"{BundleFileName}: {b.files.Length} files but {b.texts?.Length ?? 0} texts");
+ var texts = new Dictionary<string, string>(StringComparer.Ordinal);
+ for (var i = 0; i < b.files.Length; i++)
+ if (!texts.TryAdd(b.files[i], b.texts[i])) throw new InvalidDataException($"{BundleFileName}: {b.files[i]} twice");
+ return (b.files.ToList(), texts);
+ }
+
+ /// <summary>Checks a copy made by Copy: manifest.json equals Collect(contentDir) and every listed file exists, and
+ /// bundle.json lists the same files with each one's text as the source has it. Throws InvalidDataException naming
+ /// the problem.</summary>
public static void Verify(string contentDir, string targetDir)
{
var expected = Collect(contentDir);
@@ -64,9 +94,16 @@ namespace Statecraft.Game.Boot
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}");
+ var bundle = Path.Combine(targetDir, BundleFileName);
+ if (!File.Exists(bundle)) throw new InvalidDataException($"{BundleFileName}: missing from {targetDir}");
+ var (files, texts) = ParseBundle(File.ReadAllText(bundle));
+ if (!expected.SequenceEqual(files))
+ throw new InvalidDataException($"{BundleFileName} in {targetDir} does not match the content files ({files.Count} listed, {expected.Count} expected)");
+ foreach (var f in files)
+ if (texts[f] != File.ReadAllText(Path.Combine(contentDir, f))) throw new InvalidDataException($"{f}: its text in {BundleFileName} differs from the source");
}
- /// <summary>Replaces <paramref name="targetDir"/> with a copy of the collected files plus manifest.json.</summary>
+ /// <summary>Replaces <paramref name="targetDir"/> with a copy of the collected files plus manifest.json and bundle.json.</summary>
public static List<string> Copy(string contentDir, string targetDir)
{
var files = Collect(contentDir);
@@ -78,6 +115,7 @@ namespace Statecraft.Game.Boot
File.Copy(Path.Combine(contentDir, f), to);
}
File.WriteAllText(Path.Combine(targetDir, FileName), Write(files));
+ File.WriteAllText(Path.Combine(targetDir, BundleFileName), WriteBundle(contentDir, files));
return files;
}
}
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index de41cb963..8e2344289 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -6,7 +6,6 @@ using System.Linq;
using Statecraft.Game.Map;
using Statecraft.Sim;
using UnityEngine;
-using UnityEngine.Networking;
namespace Statecraft.Game.Boot
{
@@ -45,7 +44,7 @@ namespace Statecraft.Game.Boot
/// <summary>Everything the game loads at start: the sim content and the map inputs. Desktop and the editor read
/// files (FromDisk); WebGL cannot read StreamingAssets with System.IO, so it fetches them with UnityWebRequest from
- /// the manifest (FetchAsync, tech notes section 2).</summary>
+ /// the content bundle (FetchAsync, tech notes section 2; one file for every content text, #1054).</summary>
public sealed class GameInputs
{
public Content Content = null!;
@@ -118,92 +117,18 @@ namespace Statecraft.Game.Boot
public 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>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>Attempts per file, the first included. The boot fetches every file at once; one transient failure
- /// (a reset connection, a busy server) used to fail the whole boot (BOOT FAIL israel_bonds.yaml under load).</summary>
- internal const int MaxAttempts = 4;
-
- /// <summary>Seconds to wait before attempt <paramref name="attempt"/> + 1: 0.5, 1, 2.</summary>
- internal static float Backoff(int attempt) => 0.5f * (1 << (attempt - 1));
-
- /// <summary>Worth another attempt: no response at all (reset, refused, timed out) or a server-side status (408, 429,
- /// 5xx). A 404 or any other client error, and a body that failed to decode, fail at once.</summary>
- internal static bool Transient(UnityWebRequest.Result result, long status) =>
- result == UnityWebRequest.Result.ConnectionError
- || (result == UnityWebRequest.Result.ProtocolError && (status >= 500 || status == 408 || status == 429));
-
- /// <summary>Seconds a download may go without receiving a byte before it is aborted as stalled and retried like a
- /// dropped connection (#911). A limit on silence, not on the whole download: the 4 MB heightmap on a slow
- /// connection keeps receiving bytes and is never cut off, while a server that accepts the request and never
- /// answers reaches the retry and then BOOT FAIL instead of leaving the loading screen up forever. A fixed limit on
- /// the whole fetch failed slow but healthy fetches before (#503). The value needs the maintainer's sign-off (#911).</summary>
- internal const float StallSeconds = 30f;
-
- /// <summary>Waits a frame at a time (no threads on WebGL; an Awaitable is never awaited twice) until r is done, or
- /// aborts it when no byte has arrived for <paramref name="stallSeconds"/>. On a transient failure (a stall counts as
- /// a connection error) r is released and its URL fetched again after Backoff, up to MaxAttempts in all. Returns the
- /// request that succeeded (the caller releases it); on a final failure every attempt is released and an
- /// IOException names the file. Retrying changes only when a file arrives, never its bytes or the parse order.</summary>
- static async Awaitable<UnityWebRequest> Done(UnityWebRequest r, string name, float stallSeconds)
- {
- for (var attempt = 1; ; attempt++)
- {
- var stalled = false;
- var bytes = r.downloadedBytes;
- var lastByte = Time.realtimeSinceStartup;
- while (!r.isDone)
- {
- if (r.downloadedBytes != bytes) { bytes = r.downloadedBytes; lastByte = Time.realtimeSinceStartup; }
- else if (Time.realtimeSinceStartup - lastByte > stallSeconds) { stalled = true; break; }
- await Awaitable.NextFrameAsync();
- }
- if (!stalled && r.result == UnityWebRequest.Result.Success) return r;
- var error = stalled
- ? FormattableString.Invariant($"{name}: no data for {stallSeconds:0.#} s ({r.url})")
- : $"{name}: {r.error} ({r.url})";
- var retry = attempt < MaxAttempts
- && (stalled ? Transient(UnityWebRequest.Result.ConnectionError, 0) : Transient(r.result, r.responseCode));
- var url = r.url;
- Release(r);
- if (!retry) throw new IOException(attempt > 1 ? $"{error} after {attempt} attempts" : error);
- Debug.LogWarning($"{error}; attempt {attempt + 1} of {MaxAttempts} in {Backoff(attempt):0.#} s");
- var until = Time.realtimeSinceStartup + Backoff(attempt);
- while (Time.realtimeSinceStartup < until) await Awaitable.NextFrameAsync();
- r = Start(url);
- }
- }
-
- static async Awaitable<string> Text(UnityWebRequest r, string name, float stallSeconds)
+ static async Awaitable<string> Text(StreamingFetch.Download d, string name, float stallSeconds)
{
- r = await Done(r, name, stallSeconds);
- try { return r.downloadHandler.text; }
- finally { Release(r); }
+ await StreamingFetch.Done(d, name, stallSeconds);
+ try { return d.Request.downloadHandler.text; }
+ finally { d.Release(); }
}
- static async Awaitable<byte[]> Bytes(UnityWebRequest r, string name, float stallSeconds)
+ static async Awaitable<byte[]> Bytes(StreamingFetch.Download d, string name, float stallSeconds)
{
- r = await Done(r, name, stallSeconds);
- try { return r.downloadHandler.data; }
- finally { Release(r); }
+ await StreamingFetch.Done(d, name, stallSeconds);
+ try { return d.Request.downloadHandler.data; }
+ finally { d.Release(); }
}
/// <summary>Issue #437: <paramref name="url"/> with b=<paramref name="buildId"/> added to its query when it is an
@@ -213,29 +138,30 @@ namespace Statecraft.Game.Boot
buildId.Length == 0 || !(url.StartsWith("http://", StringComparison.OrdinalIgnoreCase) || url.StartsWith("https://", StringComparison.OrdinalIgnoreCase))
? url : url + (url.IndexOf('?') >= 0 ? "&" : "?") + "b=" + Uri.EscapeDataString(buildId);
- /// <summary>Fetches the manifest, then starts every download before awaiting any (parallel), then loads. A transient
- /// failure is retried (Done). When one download fails for good, the others still running are aborted and disposed.
- /// Every URL carries <paramref name="buildId"/> (WithBuildId; the player passes Application.buildGUID).</summary>
- public static Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId = "") => FetchAsync(baseUrl, buildId, StallSeconds);
+ /// <summary>Fetches the content bundle (every content text in one file, ContentManifest.BundleFileName, so the boot
+ /// makes a handful of requests and not one per file: #1054) and the heightmap's two files at once, then loads. A
+ /// transient failure is retried (StreamingFetch.Done). When one download fails for good, the others still running are
+ /// aborted and disposed. Every URL carries <paramref name="buildId"/> (WithBuildId; the player passes
+ /// Application.buildGUID).</summary>
+ public static Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId = "") => FetchAsync(baseUrl, buildId, StreamingFetch.StallSeconds);
/// <summary>FetchAsync with another stall limit (the stalled-server test uses a short one).</summary>
internal static async Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId, float stallSeconds)
{
- var manifest = ContentManifest.Parse(await Text(Start(WithBuildId(baseUrl + "/content/" + ContentManifest.FileName, buildId)), ContentManifest.FileName, stallSeconds));
- var goldenText = GoldenCheck.Requested()
- ? await Text(Start(WithBuildId(baseUrl + "/golden/manifest.txt", buildId)), "golden/manifest.txt", stallSeconds) : "";
- var scenarioNames = goldenText.Length == 0 ? new List<string>() : GoldenData.Parse(goldenText).Select(x => x.name).Where(n => n.StartsWith("scenario-", StringComparison.Ordinal)).Select(n => n.Substring("scenario-".Length)).ToList();
- var requests = manifest.Select(f => (file: f, request: Start(WithBuildId(baseUrl + "/content/" + f, buildId)))).ToList();
- var scenarioRequests = scenarioNames.Select(n => (name: n, request: Start(WithBuildId(baseUrl + "/golden/scenarios/" + n + ".yaml", buildId)))).ToList();
- var meta = Start(WithBuildId(baseUrl + "/map/heightmap.json", buildId));
- var r16z = Start(WithBuildId(baseUrl + "/map/" + HeightmapCodec.FileName, buildId));
+ StreamingFetch.Download Get(string path) => StreamingFetch.Get(WithBuildId(baseUrl + "/" + path, buildId));
+ var bundle = Get("content/" + ContentManifest.BundleFileName);
+ var meta = Get("map/heightmap.json");
+ var r16z = Get("map/" + HeightmapCodec.FileName);
+ var scenarioRequests = new List<(string name, StreamingFetch.Download request)>();
try
{
- var texts = new Dictionary<string, string>();
- foreach (var (file, request) in requests) texts[file] = await Text(request, file, stallSeconds);
+ var goldenText = GoldenCheck.Requested() ? await Text(Get("golden/manifest.txt"), "golden/manifest.txt", stallSeconds) : "";
+ var scenarioNames = goldenText.Length == 0 ? new List<string>() : GoldenData.Parse(goldenText).Select(x => x.name).Where(n => n.StartsWith("scenario-", StringComparison.Ordinal)).Select(n => n.Substring("scenario-".Length)).ToList();
+ foreach (var n in scenarioNames) scenarioRequests.Add((n, Get("golden/scenarios/" + n + ".yaml")));
+ var (manifest, texts) = ContentManifest.ParseBundle(await Text(bundle, ContentManifest.BundleFileName, stallSeconds));
var metaText = await Text(meta, "heightmap.json", stallSeconds);
var r16zBytes = await Bytes(r16z, HeightmapCodec.FileName, stallSeconds);
- DiagLog.BootPhase($"downloaded {texts.Count + 3} files");
+ DiagLog.BootPhase($"downloaded {texts.Count + 2} files");
var inputs = FromTexts(texts, manifest, metaText, r16zBytes);
inputs.Goldens = new GoldenData { Manifest = goldenText };
foreach (var (name, request) in scenarioRequests) inputs.Goldens.Scenarios[name] = await Text(request, "golden/scenarios/" + name + ".yaml", stallSeconds);
@@ -244,9 +170,8 @@ namespace Statecraft.Game.Boot
}
finally
{
- foreach (var (_, request) in requests) Release(request);
- foreach (var (_, request) in scenarioRequests) Release(request);
- Release(meta); Release(r16z);
+ foreach (var (_, request) in scenarioRequests) request.Release();
+ bundle.Release(); meta.Release(); r16z.Release();
}
}
}
diff --git a/unity/Assets/Scripts/Boot/StreamingFetch.cs b/unity/Assets/Scripts/Boot/StreamingFetch.cs
new file mode 100644
index 000000000..a7f1016cc
--- /dev/null
+++ b/unity/Assets/Scripts/Boot/StreamingFetch.cs
@@ -0,0 +1,157 @@
+#nullable enable
+using System;
+using System.Collections.Generic;
+using System.Globalization;
+using System.IO;
+using UnityEngine;
+using UnityEngine.Networking;
+
+namespace Statecraft.Game.Boot
+{
+ /// <summary>The one retry policy for every StreamingAssets download the game makes as it starts (issue #1054): the content
+ /// bundle, the heightmap and the golden files (GameInputs.FetchAsync), and The 1948 Collection's checks file and bundles
+ /// (CollectionStream.BundleSource). A download that gets no response (reset, refused, or no byte for the stall limit) or
+ /// a server-side status (408, 429, 5xx) is started again after Backoff, or after the response's Retry-After when that is
+ /// longer (at most MaxRetryAfter), up to MaxAttempts in all. Then the caller fails as before: the boot shows BOOT FAIL
+ /// naming the file, and the collection leaves that bundle's models off the map. Retrying changes only when a file
+ /// arrives, never its bytes.</summary>
+ public static class StreamingFetch
+ {
+ /// <summary>Attempts per file, the first included. The boot fetches its files at once; one transient failure (a reset
+ /// connection, a busy server, a 429 from a rate-limited host) used to fail the whole boot.</summary>
+ internal const int MaxAttempts = 4;
+
+ /// <summary>Seconds to wait before attempt <paramref name="attempt"/> + 1: 0.5, 1, 2.</summary>
+ internal static float Backoff(int attempt) => 0.5f * (1 << (attempt - 1));
+
+ /// <summary>The longest wait a Retry-After header can ask for (seconds); a longer one waits this long. Without a
+ /// limit, a host that answers "Retry-After: 3600" would leave the loading screen up for an hour. The value needs the
+ /// maintainer's sign-off (#1054).</summary>
+ internal const float MaxRetryAfter = 10f;
+
+ /// <summary>Seconds a download may go without receiving a byte before it is aborted as stalled and retried like a
+ /// dropped connection (#911). A limit on silence, not on the whole download: the 4 MB heightmap on a slow
+ /// connection keeps receiving bytes and is never cut off, while a server that accepts the request and never
+ /// answers reaches the retry and then BOOT FAIL instead of leaving the loading screen up forever. A fixed limit on
+ /// the whole fetch failed slow but healthy fetches before (#503). The value needs the maintainer's sign-off (#911).</summary>
+ internal const float StallSeconds = 30f;
+
+ /// <summary>Worth another attempt: no response at all (reset, refused, timed out) or a server-side status (408, 429,
+ /// 5xx). A 404 or any other client error, and a body that failed to decode, fail at once.</summary>
+ internal static bool Transient(UnityWebRequest.Result result, long status) =>
+ result == UnityWebRequest.Result.ConnectionError
+ || (result == UnityWebRequest.Result.ProtocolError && (status >= 500 || status == 408 || status == 429));
+
+ /// <summary>Seconds a Retry-After header asks for at <paramref name="nowUtc"/>: delay-seconds or an HTTP-date (RFC 9110
+ /// section 10.2.3); 0 when absent, malformed or in the past.</summary>
+ internal static float RetryAfterSeconds(string? value, DateTime nowUtc)
+ {
+ if (string.IsNullOrWhiteSpace(value)) return 0f;
+ var v = value!.Trim();
+ if (long.TryParse(v, NumberStyles.None, CultureInfo.InvariantCulture, out var seconds)) return seconds;
+ if (DateTime.TryParseExact(v, "r", CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var at))
+ return (float)Math.Max(0, (at - nowUtc).TotalSeconds);
+ return 0f;
+ }
+
+ /// <summary>Seconds to wait before attempt <paramref name="attempt"/> + 1: Backoff, or the Retry-After when it is
+ /// longer, capped at MaxRetryAfter.</summary>
+ internal static float Delay(int attempt, string? retryAfter, DateTime nowUtc) =>
+ Math.Max(Backoff(attempt), Math.Min(RetryAfterSeconds(retryAfter, nowUtc), MaxRetryAfter));
+
+ /// <summary>One file's download, attempt by attempt, as the retry loop sees it (Download in the game, a fake in the
+ /// tests).</summary>
+ internal interface IDownload
+ {
+ bool IsDone { get; }
+ ulong DownloadedBytes { get; }
+ UnityWebRequest.Result Result { get; }
+ long Status { get; }
+ string? Error { get; }
+ string Url { get; }
+ /// <summary>The response's Retry-After header (null when it has none).</summary>
+ string? RetryAfter { get; }
+ /// <summary>Aborts (when still running) and disposes the current attempt; safe to call twice.</summary>
+ void Release();
+ /// <summary>Starts the next attempt (after Release).</summary>
+ void Restart();
+ }
+
+ 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;
+
+ /// <summary>A UnityWebRequest made by <c>make</c> and sent at once; Restart makes and sends a new one. The caller
+ /// reads <see cref="Request"/> once Done returns and then calls Release.</summary>
+ public sealed class Download : IDownload
+ {
+ readonly Func<UnityWebRequest> make;
+ public UnityWebRequest Request { get; private set; }
+
+ internal Download(Func<UnityWebRequest> make) { this.make = make; Request = Send(make()); }
+
+ static UnityWebRequest Send(UnityWebRequest r)
+ {
+ open.Add(r);
+ r.SendWebRequest();
+ return r;
+ }
+
+ public bool IsDone => Request.isDone;
+ public ulong DownloadedBytes => Request.downloadedBytes;
+ public UnityWebRequest.Result Result => Request.result;
+ public long Status => Request.responseCode;
+ public string? Error => Request.error;
+ public string Url => Request.url;
+ public string? RetryAfter => Request.GetResponseHeader("Retry-After");
+
+ public void Release()
+ {
+ if (!open.Remove(Request)) return;
+ if (!Request.isDone) Request.Abort();
+ Request.Dispose();
+ }
+
+ public void Restart() { Release(); Request = Send(make()); }
+ }
+
+ /// <summary>A GET of <paramref name="url"/>, sent now (so a caller can start every download before awaiting any).</summary>
+ public static Download Get(string url) => new Download(() => UnityWebRequest.Get(url));
+
+ /// <summary>A request <paramref name="make"/> builds (for example an AssetBundle request), sent now.</summary>
+ public static Download Start(Func<UnityWebRequest> make) => new Download(make);
+
+ /// <summary>Waits a frame at a time (no threads on WebGL; an Awaitable is never awaited twice) until the download is
+ /// done, or aborts it when no byte has arrived for <paramref name="stallSeconds"/>. On a transient failure (a stall
+ /// counts as a dropped connection) the attempt is released and another started after Delay, up to MaxAttempts in
+ /// all. Returns once an attempt succeeded (the caller reads it, then releases it); on a final failure the attempt is
+ /// released and an IOException names the file.</summary>
+ internal static async Awaitable Done(IDownload d, string name, float stallSeconds)
+ {
+ for (var attempt = 1; ; attempt++)
+ {
+ var stalled = false;
+ var bytes = d.DownloadedBytes;
+ var lastByte = Time.realtimeSinceStartup;
+ while (!d.IsDone)
+ {
+ if (d.DownloadedBytes != bytes) { bytes = d.DownloadedBytes; lastByte = Time.realtimeSinceStartup; }
+ else if (Time.realtimeSinceStartup - lastByte > stallSeconds) { stalled = true; break; }
+ await Awaitable.NextFrameAsync();
+ }
+ if (!stalled && d.Result == UnityWebRequest.Result.Success) return;
+ var error = stalled
+ ? FormattableString.Invariant($"{name}: no data for {stallSeconds:0.#} s ({d.Url})")
+ : $"{name}: {d.Error} ({d.Url})";
+ var retry = attempt < MaxAttempts && (stalled || Transient(d.Result, d.Status));
+ var wait = retry ? Delay(attempt, stalled ? null : d.RetryAfter, DateTime.UtcNow) : 0f;
+ d.Release();
+ if (!retry) throw new IOException(attempt > 1 ? $"{error} after {attempt} attempts" : error);
+ Debug.LogWarning(FormattableString.Invariant($"{error}; attempt {attempt + 1} of {MaxAttempts} in {wait:0.#} s"));
+ var until = Time.realtimeSinceStartup + wait;
+ while (Time.realtimeSinceStartup < until) await Awaitable.NextFrameAsync();
+ d.Restart();
+ }
+ }
+ }
+}
diff --git a/unity/Assets/Scripts/Boot/StreamingFetch.cs.meta b/unity/Assets/Scripts/Boot/StreamingFetch.cs.meta
new file mode 100644
index 000000000..097808233
--- /dev/null
+++ b/unity/Assets/Scripts/Boot/StreamingFetch.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 52c2ad23d23654ecab9ca9b450e5a3ea
\ No newline at end of file
diff --git a/unity/Assets/Scripts/Map/Collection/CollectionStream.cs b/unity/Assets/Scripts/Map/Collection/CollectionStream.cs
index 074c01223..a255d025a 100644
--- a/unity/Assets/Scripts/Map/Collection/CollectionStream.cs
+++ b/unity/Assets/Scripts/Map/Collection/CollectionStream.cs
@@ -3,6 +3,7 @@ using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
+using Statecraft.Game.Boot;
using UnityEngine;
using UnityEngine.Networking;
@@ -158,9 +159,9 @@ namespace Statecraft.Game.Map.Collection
static IEnumerator Done() { yield break; }
- /// <summary>Reads the bundles from a folder: by URL on WebGL (StreamingAssets is served beside the page), from disk
- /// elsewhere. Each bundle must match its line of <see cref="CollectionCatalog.ChecksFile"/>, written by the bundle
- /// build: Unity is given the bundle's CRC on both paths, and on disk a missing file, one that is not a whole
+ /// <summary>Reads the bundles from a folder: by URL on WebGL (StreamingAssets is served beside the page; StreamingFetch
+ /// retries a dropped connection, a 429 or a 5xx, #1054), from disk elsewhere. Each bundle must match its line of
+ /// <see cref="CollectionCatalog.ChecksFile"/>, written by the bundle build: Unity is given the bundle's CRC on both paths, and on disk a missing file, one that is not a whole
/// AssetBundle by its header (<see cref="CheckHeader"/>) or one whose size or SHA-256 differs from the build fails at
/// once without asking Unity to open it, so it logs this class's one warning and not Unity's own errors too.</summary>
public sealed class BundleSource : ISource
@@ -182,11 +183,16 @@ namespace Statecraft.Game.Map.Collection
yield return ReadChecks();
var (check, why) = Lookup(bundle);
if (check == null) { done(why); yield break; }
- // Unity checks the CRC as it reads, and refuses a bundle that does not match (the request then fails).
- using var req = UnityWebRequestAssetBundle.GetAssetBundle(folder + "/" + bundle, check.Value.Crc);
- yield return req.SendWebRequest();
- if (req.result != UnityWebRequest.Result.Success) { done(req.error ?? "request failed"); yield break; }
- b = DownloadHandlerAssetBundle.GetContent(req);
+ // Unity checks the CRC as it reads, and refuses a bundle that does not match (the request then fails,
+ // and is not retried: only no response or a server-side status is, StreamingFetch).
+ var url = folder + "/" + bundle;
+ var crc = check.Value.Crc;
+ var download = StreamingFetch.Start(() => UnityWebRequestAssetBundle.GetAssetBundle(url, crc));
+ string? failed = null;
+ yield return Await(StreamingFetch.Done(download, bundle, StreamingFetch.StallSeconds), e => failed = e);
+ if (failed != null) { done(failed); yield break; }
+ try { b = DownloadHandlerAssetBundle.GetContent(download.Request); }
+ finally { download.Release(); }
}
else
{
@@ -221,10 +227,15 @@ namespace Statecraft.Game.Map.Collection
string? text = null;
if (folder.Contains("://"))
{
- using var req = UnityWebRequest.Get(folder + "/" + CollectionCatalog.ChecksFile);
- yield return req.SendWebRequest();
- if (req.result == UnityWebRequest.Result.Success) text = req.downloadHandler.text;
- else checksError = $"no {CollectionCatalog.ChecksFile} ({req.error})";
+ var download = StreamingFetch.Get(folder + "/" + CollectionCatalog.ChecksFile);
+ string? failed = null;
+ yield return Await(StreamingFetch.Done(download, CollectionCatalog.ChecksFile, StreamingFetch.StallSeconds), e => failed = e);
+ if (failed != null) checksError = $"no {CollectionCatalog.ChecksFile} ({failed})";
+ else
+ {
+ try { text = download.Request.downloadHandler.text; }
+ finally { download.Release(); }
+ }
}
else
{
@@ -236,6 +247,16 @@ namespace Statecraft.Game.Map.Collection
checksError = $"a damaged {CollectionCatalog.ChecksFile}";
}
+ /// <summary>Waits a frame at a time for a StreamingFetch download (with its retries) to end; a final failure
+ /// (the IOException naming the file) goes to <paramref name="failed"/>.</summary>
+ static IEnumerator Await(Awaitable fetch, Action<string> failed)
+ {
+ var a = fetch.GetAwaiter();
+ while (!a.IsCompleted) yield return null;
+ try { a.GetResult(); }
+ catch (IOException e) { failed(e.Message); }
+ }
+
/// <summary>The bundle's line of the checks file, or null and why not.</summary>
(CollectionCatalog.BundleCheck? Check, string Why) Lookup(string bundle)
{
diff --git a/unity/Assets/Tests/EditMode/CollectionStreamTests.cs b/unity/Assets/Tests/EditMode/CollectionStreamTests.cs
index a940b77df..c7012379c 100644
--- a/unity/Assets/Tests/EditMode/CollectionStreamTests.cs
+++ b/unity/Assets/Tests/EditMode/CollectionStreamTests.cs
@@ -395,4 +395,60 @@ public class CollectionStreamTests
Directory.Delete(folder, true);
}
}
+
+ /// <summary>#1054: on WebGL the bundles come by URL from a host that may rate-limit (itch.io). The checks file and the
+ /// bundle each answer 429 twice (the bundle with a Retry-After), then 200: the shared retry (StreamingFetch) gets
+ /// both through and the sheep is served, where before the first 429 left the animals off the map.</summary>
+ [UnityTest]
+ public IEnumerator ABundleOverHttpIsServedAfterTwoTooManyRequests()
+ {
+ var folder = Path.Combine(Path.GetTempPath(), "statecraft-http-collection-" + Guid.NewGuid().ToString("N"));
+ Directory.CreateDirectory(folder);
+ var animals = CollectionCatalog.Bundles.Single(b => b.Bundle == CollectionCatalog.Animals);
+ var build = new AssetBundleBuild
+ {
+ assetBundleName = animals.Bundle,
+ assetNames = animals.Ids.SelectMany(id => new[] { CollectionCatalog.PrefabPath(id, CollectionDetail.Far), CollectionCatalog.PrefabPath(id, CollectionDetail.Near) }).ToArray(),
+ };
+ var manifest = BuildPipeline.BuildAssetBundles(folder, new[] { build }, BuildAssetBundleOptions.ChunkBasedCompression | BuildAssetBundleOptions.StrictMode,
+ EditorUserBuildSettings.activeBuildTarget);
+ Assert.IsNotNull(manifest, "bundle build");
+ WriteChecks(folder, manifest.GetAllAssetBundles());
+ var faults = new Dictionary<string, (string, int)> { [CollectionCatalog.ChecksFile] = ("429", 2), [animals.Bundle] = ("429|Retry-After: 1", 2) };
+ var server = new FlakySite(folder, faults);
+ var source = new CollectionStream.BundleSource(server.BaseUrl);
+ try
+ {
+ var stream = new CollectionStream(source);
+ var got = new List<GameObject?>();
+ stream.Enqueue(Sheep, CollectionDetail.Near, got.Add);
+ var stack = new Stack<IEnumerator>();
+ stack.Push(stream.Run());
+ var started = Time.realtimeSinceStartup;
+ while (got.Count < 1 && Time.realtimeSinceStartup - started < 60f)
+ {
+ while (stack.Count > 0)
+ {
+ var top = stack.Peek();
+ if (!top.MoveNext()) { stack.Pop(); continue; }
+ if (top.Current is IEnumerator nested) { stack.Push(nested); continue; }
+ if (top.Current is AsyncOperation op) while (!op.isDone) yield return null;
+ break;
+ }
+ EditorApplication.QueuePlayerLoopUpdate(); // a batch-mode editor resumes the retry's frame waits only on a player-loop update
+ yield return null;
+ }
+ Assert.AreEqual(1, got.Count, "the request was answered");
+ Assert.AreEqual(Sheep + "-near", got[0]?.name, "the bundle got through the 429s");
+ Assert.AreEqual(3, server.Hits(CollectionCatalog.ChecksFile));
+ Assert.AreEqual(3, server.Hits(animals.Bundle));
+ Assert.AreEqual(0, Statecraft.Game.Boot.StreamingFetch.OpenRequests);
+ }
+ finally
+ {
+ server.Dispose();
+ source.UnloadAll();
+ Directory.Delete(folder, true);
+ }
+ }
}
diff --git a/unity/Assets/Tests/EditMode/FlakySite.cs b/unity/Assets/Tests/EditMode/FlakySite.cs
new file mode 100644
index 000000000..9744f5d10
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/FlakySite.cs
@@ -0,0 +1,115 @@
+using System;
+using System.Collections.Concurrent;
+using System.Collections.Generic;
+using System.IO;
+using System.Net;
+using System.Net.Sockets;
+using System.Threading;
+
+/// <summary>A minimal HTTP/1.0 server over a staged site (one connection per request, like web_check's) that fails
+/// chosen files for their first <c>times</c> requests: "drop" resets the connection before any response (what
+/// macOS did to web_check's server when its listen backlog overflowed on a loaded machine: BOOT FAIL
+/// israel_bonds.yaml), a number answers with that status. HttpListener cannot model a drop: Mono's Abort() sends an
+/// empty 200. A status may carry one header line after a '|' (e.g. "429|Retry-After: 1"). Shared by the boot's fetch
+/// tests (GameInputsTests) and the collection's (CollectionStreamTests).</summary>
+sealed class FlakySite : IDisposable
+{
+ public const int TrickleChunks = 10, TrickleGapMs = 300;
+
+ readonly TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
+ readonly string root;
+ readonly Dictionary<string, (string fault, int times)> faults;
+ readonly ConcurrentDictionary<string, int> hits = new ConcurrentDictionary<string, int>();
+ readonly ManualResetEventSlim stopped = new ManualResetEventSlim();
+ /// <summary>Every request target as sent, query included (e.g. "/content/people.yaml?b=..."), in arrival order.</summary>
+ public readonly ConcurrentQueue<string> Targets = new ConcurrentQueue<string>();
+ public readonly string BaseUrl;
+
+ public FlakySite(string root, Dictionary<string, (string fault, int times)> faults)
+ {
+ this.root = root; this.faults = faults;
+ listener.Start();
+ BaseUrl = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}";
+ // Own threads, not the thread pool: a "stall" answer blocks its thread until Dispose, so on pool threads stalled
+ // handlers can hold up the accept loop (the suspected cause of a stall test once counting 3 hits for 4 attempts).
+ new Thread(Loop) { IsBackground = true, Name = "FlakySite accept" }.Start();
+ }
+
+ /// <summary>Requests seen for a site path (e.g. "content/people.yaml").</summary>
+ public int Hits(string rel) => hits.TryGetValue(rel, out var n) ? n : 0;
+
+ void Loop()
+ {
+ while (true)
+ {
+ TcpClient client;
+ try { client = listener.AcceptTcpClient(); }
+ catch (Exception) { return; } // stopped
+ new Thread(() => ServeQuietly(client)) { IsBackground = true, Name = "FlakySite request" }.Start();
+ }
+ }
+
+ /// <summary>Serve, where a client that hangs up mid-answer (the fetch aborts its other downloads once one fails for
+ /// good) ends that request quietly: on a thread of its own the exception would reach Unity's log and fail the test
+ /// that happens to be running.</summary>
+ void ServeQuietly(TcpClient client)
+ {
+ try { Serve(client); }
+ catch (Exception e) when (e is IOException || e is SocketException || e is ObjectDisposedException) { }
+ }
+
+ void Serve(TcpClient client)
+ {
+ using (client)
+ {
+ var stream = client.GetStream();
+ var head = new List<byte>();
+ var one = new byte[1];
+ while (head.Count < 4 || head[head.Count - 4] != '\r' || head[head.Count - 3] != '\n' || head[head.Count - 2] != '\r' || head[head.Count - 1] != '\n')
+ {
+ if (stream.Read(one, 0, 1) == 0) return;
+ head.Add(one[0]);
+ }
+ var target = System.Text.Encoding.ASCII.GetString(head.ToArray()).Split(' ')[1];
+ Targets.Enqueue(target);
+ var rel = Uri.UnescapeDataString(target.Split('?')[0].TrimStart('/'));
+ var n = hits.AddOrUpdate(rel, 1, (_, v) => v + 1);
+ if (faults.TryGetValue(rel, out var f) && n <= f.times)
+ {
+ if (f.fault == "drop") { client.Client.LingerState = new LingerOption(true, 0); client.Client.Close(); return; } // RST
+ if (f.fault == "stall") { stopped.Wait(); return; } // Accept the request but never answer it.
+ if (f.fault == "trickle") { Trickle(stream, File.ReadAllBytes(Path.Combine(root, rel))); return; }
+ var status = f.fault.Split('|');
+ Respond(stream, int.Parse(status[0]), new byte[0], status.Length > 1 ? status[1] : null);
+ return;
+ }
+ var path = Path.Combine(root, rel);
+ if (File.Exists(path)) Respond(stream, 200, File.ReadAllBytes(path));
+ else Respond(stream, 404, new byte[0]);
+ }
+ }
+
+ static void Respond(NetworkStream stream, int status, byte[] body, string header = null)
+ {
+ var extra = header == null ? "" : header + "\r\n";
+ var head = System.Text.Encoding.ASCII.GetBytes($"HTTP/1.0 {status} {(status == 200 ? "OK" : "Fault")}\r\nContent-Length: {body.Length}\r\n{extra}Connection: close\r\n\r\n");
+ stream.Write(head, 0, head.Length);
+ stream.Write(body, 0, body.Length);
+ }
+
+ /// <summary>A slow but healthy download: the whole file, in TrickleChunks parts TrickleGapMs apart.</summary>
+ static void Trickle(NetworkStream stream, byte[] body)
+ {
+ var head = System.Text.Encoding.ASCII.GetBytes($"HTTP/1.0 200 OK\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
+ stream.Write(head, 0, head.Length);
+ var part = (body.Length + TrickleChunks - 1) / TrickleChunks;
+ for (var at = 0; at < body.Length; at += part)
+ {
+ Thread.Sleep(TrickleGapMs);
+ stream.Write(body, at, Math.Min(part, body.Length - at));
+ stream.Flush();
+ }
+ }
+
+ public void Dispose() { stopped.Set(); listener.Stop(); }
+}
diff --git a/unity/Assets/Tests/EditMode/FlakySite.cs.meta b/unity/Assets/Tests/EditMode/FlakySite.cs.meta
new file mode 100644
index 000000000..941d14f95
--- /dev/null
+++ b/unity/Assets/Tests/EditMode/FlakySite.cs.meta
@@ -0,0 +1,2 @@
+fileFormatVersion: 2
+guid: 4058ca63b6b7c44d383cee59e690958d
\ No newline at end of file
diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.cs
index 4b309e12e..4bf6a16bc 100644
--- a/unity/Assets/Tests/EditMode/GameInputsTests.cs
+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs
@@ -84,14 +84,14 @@ public class GameInputsTests
}
[UnityTest, Timeout(FetchTestTimeoutMs)]
- public IEnumerator AMissingFileNamesTheFile()
+ public IEnumerator AMissingBundleNamesTheFile()
{
var site = StagedSite();
- File.Delete(Path.Combine(site, "content", "people.yaml"));
+ File.Delete(Path.Combine(site, "content", ContentManifest.BundleFileName));
var fetch = GameInputs.FetchAsync(new System.Uri(site).AbsoluteUri.TrimEnd('/')).GetAwaiter();
yield return Await(fetch);
var ex = Assert.Throws<IOException>(() => fetch.GetResult());
- StringAssert.StartsWith("people.yaml: ", ex.Message);
+ StringAssert.StartsWith("bundle.json: ", ex.Message);
Directory.Delete(site, true);
}
@@ -99,106 +99,14 @@ public class GameInputsTests
public IEnumerator AFailedFetchLeavesNoRequestOpen()
{
var site = StagedSite();
- File.Delete(Path.Combine(site, "content", "people.yaml"));
+ File.Delete(Path.Combine(site, "content", ContentManifest.BundleFileName));
var fetch = GameInputs.FetchAsync(new System.Uri(site).AbsoluteUri.TrimEnd('/')).GetAwaiter();
yield return Await(fetch);
Assert.Throws<IOException>(() => fetch.GetResult());
- Assert.AreEqual(0, GameInputs.OpenRequests, "requests still in flight after a failed fetch were not disposed");
+ Assert.AreEqual(0, StreamingFetch.OpenRequests, "requests still in flight after a failed fetch were not disposed");
Directory.Delete(site, true);
}
- /// <summary>A minimal HTTP/1.0 server over a staged site (one connection per request, like web_check's) that fails
- /// chosen files for their first <c>times</c> requests: "drop" resets the connection before any response (what
- /// macOS did to web_check's server when its listen backlog overflowed on a loaded machine: BOOT FAIL
- /// israel_bonds.yaml), a number answers with that status. HttpListener cannot model a drop: Mono's Abort() sends an
- /// empty 200.</summary>
- sealed class FlakySite : IDisposable
- {
- readonly TcpListener listener = new TcpListener(IPAddress.Loopback, 0);
- readonly string root;
- readonly Dictionary<string, (string fault, int times)> faults;
- readonly ConcurrentDictionary<string, int> hits = new ConcurrentDictionary<string, int>();
- readonly ManualResetEventSlim stopped = new ManualResetEventSlim();
- /// <summary>Every request target as sent, query included (e.g. "/content/people.yaml?b=..."), in arrival order.</summary>
- public readonly ConcurrentQueue<string> Targets = new ConcurrentQueue<string>();
- public readonly string BaseUrl;
-
- public FlakySite(string root, Dictionary<string, (string fault, int times)> faults)
- {
- this.root = root; this.faults = faults;
- listener.Start();
- BaseUrl = $"http://127.0.0.1:{((IPEndPoint)listener.LocalEndpoint).Port}";
- Task.Run(Loop);
- }
-
- /// <summary>Requests seen for a site path (e.g. "content/people.yaml").</summary>
- public int Hits(string rel) => hits.TryGetValue(rel, out var n) ? n : 0;
-
- async Task Loop()
- {
- while (true)
- {
- TcpClient client;
- try { client = await listener.AcceptTcpClientAsync(); }
- catch (Exception) { return; } // stopped
- _ = Task.Run(() => Serve(client));
- }
- }
-
- void Serve(TcpClient client)
- {
- using (client)
- {
- var stream = client.GetStream();
- var head = new List<byte>();
- var one = new byte[1];
- while (head.Count < 4 || head[head.Count - 4] != '\r' || head[head.Count - 3] != '\n' || head[head.Count - 2] != '\r' || head[head.Count - 1] != '\n')
- {
- if (stream.Read(one, 0, 1) == 0) return;
- head.Add(one[0]);
- }
- var target = System.Text.Encoding.ASCII.GetString(head.ToArray()).Split(' ')[1];
- Targets.Enqueue(target);
- var rel = Uri.UnescapeDataString(target.Split('?')[0].TrimStart('/'));
- var n = hits.AddOrUpdate(rel, 1, (_, v) => v + 1);
- if (faults.TryGetValue(rel, out var f) && n <= f.times)
- {
- if (f.fault == "drop") { client.Client.LingerState = new LingerOption(true, 0); client.Client.Close(); return; } // RST
- if (f.fault == "stall") { stopped.Wait(); return; } // Accept the request but never answer it.
- if (f.fault == "trickle") { Trickle(stream, File.ReadAllBytes(Path.Combine(root, rel))); return; }
- Respond(stream, int.Parse(f.fault), new byte[0]);
- return;
- }
- var path = Path.Combine(root, rel);
- if (File.Exists(path)) Respond(stream, 200, File.ReadAllBytes(path));
- else Respond(stream, 404, new byte[0]);
- }
- }
-
- static void Respond(NetworkStream stream, int status, byte[] body)
- {
- var head = System.Text.Encoding.ASCII.GetBytes($"HTTP/1.0 {status} {(status == 200 ? "OK" : "Fault")}\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
- stream.Write(head, 0, head.Length);
- stream.Write(body, 0, body.Length);
- }
-
- /// <summary>A slow but healthy download: the whole file, in TrickleChunks parts TrickleGapMs apart.</summary>
- static void Trickle(NetworkStream stream, byte[] body)
- {
- var head = System.Text.Encoding.ASCII.GetBytes($"HTTP/1.0 200 OK\r\nContent-Length: {body.Length}\r\nConnection: close\r\n\r\n");
- stream.Write(head, 0, head.Length);
- var part = (body.Length + TrickleChunks - 1) / TrickleChunks;
- for (var at = 0; at < body.Length; at += part)
- {
- Thread.Sleep(TrickleGapMs);
- stream.Write(body, at, Math.Min(part, body.Length - at));
- stream.Flush();
- }
- }
-
- public void Dispose() { stopped.Set(); listener.Stop(); }
- }
-
/// <summary>Seconds a fetch may go without progress before it counts as hung. Not a limit on the whole fetch: under
/// heavy load (several Unity batch runs, load average 46-97) fetches that pass when run alone failed a fixed 60 s limit
/// on the whole fetch (issue #503), while a hang shows as no request finishing, retrying or starting for a long time.</summary>
@@ -211,7 +119,7 @@ public class GameInputsTests
/// progress reaches the cap, and with a bare timeout message instead of the wait's own.</summary>
const int FetchTestTimeoutMs = (int)(CapSeconds * 1000) + 60_000;
- /// <summary>Waits for a fetch for as long as it makes progress: it fails when GameInputs.OpenRequests (requests
+ /// <summary>Waits for a fetch for as long as it makes progress: it fails when StreamingFetch.OpenRequests (requests
/// started and not yet released) has not changed for StallSeconds, or once CapSeconds have passed in all. The
/// manifest's request is released and every file's started, then each file's request is released as the fetch takes
/// it (a retry releases one and starts another), so the count keeps moving while the fetch works.
@@ -219,7 +127,7 @@ public class GameInputsTests
/// retry's 0.5 s backoff measured 57 s over 2 frames. Each tick queues a player-loop update, as a player runs one
/// every frame.</summary>
static IEnumerator Await(Awaitable<GameInputs>.Awaiter fetch) =>
- WaitWhileProgressing(() => fetch.IsCompleted, () => GameInputs.OpenRequests, StallSeconds, CapSeconds, () => Time.realtimeSinceStartup, "fetch");
+ WaitWhileProgressing(() => fetch.IsCompleted, () => StreamingFetch.OpenRequests, StallSeconds, CapSeconds, () => Time.realtimeSinceStartup, "fetch");
/// <summary>Yields until <paramref name="done"/>; throws a TimeoutException once <paramref name="progress"/> has not
/// changed for <paramref name="stallSeconds"/> by <paramref name="clock"/>, or once <paramref name="capSeconds"/> have
@@ -290,7 +198,7 @@ public class GameInputsTests
Assert.AreEqual(disk.Content.Hash, fetched.Content.Hash);
Assert.AreEqual(Simulation.NewGame(disk.Content, 7, Mode.Historical).Hash(), Simulation.NewGame(fetched.Content, 7, Mode.Historical).Hash());
CollectionAssert.AreEqual(disk.Map.HeightmapR16z, fetched.Map.HeightmapR16z);
- Assert.AreEqual(0, GameInputs.OpenRequests);
+ Assert.AreEqual(0, StreamingFetch.OpenRequests);
check(server);
}
}
@@ -299,41 +207,172 @@ public class GameInputsTests
[UnityTest, Timeout(FetchTestTimeoutMs)]
public IEnumerator DroppedConnectionsAreRetried() =>
- FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/events/israel_bonds.yaml"] = ("drop", 2) },
- server => Assert.AreEqual(3, server.Hits("content/events/israel_bonds.yaml")));
+ FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/bundle.json"] = ("drop", 2) },
+ server => Assert.AreEqual(3, server.Hits("content/bundle.json")));
[UnityTest, Timeout(FetchTestTimeoutMs)]
public IEnumerator AServerErrorIsRetried() =>
- FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/people.yaml"] = ("503", 1), ["map/heightmap.r16z"] = ("500", 2) },
+ FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/bundle.json"] = ("503", 1), ["map/heightmap.r16z"] = ("500", 2) },
server =>
{
- Assert.AreEqual(2, server.Hits("content/people.yaml"));
+ Assert.AreEqual(2, server.Hits("content/bundle.json"));
Assert.AreEqual(3, server.Hits("map/heightmap.r16z"));
});
+ /// <summary>#1054: a rate-limited host (itch.io) answers 429, some with a Retry-After. Twice for the bundle and the
+ /// heightmap, then 200: the boot still loads the disk's content.</summary>
+ [UnityTest, Timeout(FetchTestTimeoutMs)]
+ public IEnumerator TooManyRequestsTwiceThenOkStillBoots() =>
+ FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/bundle.json"] = ("429|Retry-After: 1", 2), ["map/heightmap.r16z"] = ("429", 2) },
+ server =>
+ {
+ Assert.AreEqual(3, server.Hits("content/bundle.json"));
+ Assert.AreEqual(3, server.Hits("map/heightmap.r16z"));
+ });
+
+ /// <summary>#1054: a 429 with "Retry-After: 3" is fetched again no sooner than 3 s later (the backoff alone is 0.5 s).</summary>
+ [UnityTest, Timeout(FetchTestTimeoutMs)]
+ public IEnumerator ARetryAfterIsWaitedOut()
+ {
+ var started = Time.realtimeSinceStartup;
+ yield return FetchesTheDiskContentDespite(new Dictionary<string, (string, int)> { ["content/bundle.json"] = ("429|Retry-After: 3", 1) },
+ server => Assert.AreEqual(2, server.Hits("content/bundle.json")));
+ Assert.GreaterOrEqual(Time.realtimeSinceStartup - started, 3f, "the second attempt came before the Retry-After");
+ }
+
+ /// <summary>A scripted download for StreamingFetch.Done: each attempt answers the next (status, Retry-After) at once;
+ /// status 0 is no response at all.</summary>
+ sealed class FakeDownload : StreamingFetch.IDownload
+ {
+ readonly Queue<(long status, string retryAfter)> answers;
+ (long status, string retryAfter) now;
+ public int Attempts = 1, Releases;
+
+ public FakeDownload(params (long, string)[] answers)
+ {
+ this.answers = new Queue<(long, string)>(answers);
+ now = this.answers.Dequeue();
+ }
+
+ public bool IsDone => true;
+ public ulong DownloadedBytes => 0;
+ public UnityWebRequest.Result Result => now.status == 0 ? UnityWebRequest.Result.ConnectionError
+ : now.status == 200 ? UnityWebRequest.Result.Success : UnityWebRequest.Result.ProtocolError;
+ public long Status => now.status;
+ public string Error => "HTTP " + now.status;
+ public string Url => "fake://site/x.yaml";
+ public string RetryAfter => now.retryAfter;
+ public void Release() => Releases++;
+ public void Restart() { Attempts++; now = answers.Dequeue(); }
+ }
+
+ /// <summary>Runs StreamingFetch.Done on a fake to its end; the exception it ended with, or null.</summary>
+ static IEnumerator RunDone(FakeDownload d, Action<Exception> ended)
+ {
+ var done = StreamingFetch.Done(d, "x.yaml", StreamingFetch.StallSeconds).GetAwaiter();
+ while (!done.IsCompleted)
+ {
+ UnityEditor.EditorApplication.QueuePlayerLoopUpdate();
+ yield return null;
+ }
+ try { done.GetResult(); ended(null); }
+ catch (Exception e) { ended(e); }
+ }
+
+ /// <summary>#1054, the shared helper with a fake transport: 429, 429, then 200 succeeds at the third attempt.</summary>
+ [UnityTest, Timeout(120_000)]
+ public IEnumerator TheRetryHelperGetsThroughTwoTooManyRequests()
+ {
+ var d = new FakeDownload((429, null), (429, "1"), (200, null));
+ Exception error = new Exception("not run");
+ yield return RunDone(d, e => error = e);
+ Assert.IsNull(error);
+ Assert.AreEqual(3, d.Attempts);
+ Assert.AreEqual(2, d.Releases, "each failed attempt is released before the next (the caller releases the good one)");
+ }
+
+ /// <summary>The helper gives up after MaxAttempts with an IOException naming the file, and never retries a 404.</summary>
+ [UnityTest, Timeout(120_000)]
+ public IEnumerator TheRetryHelperStopsAfterMaxAttemptsAndOnAClientError()
+ {
+ var d = new FakeDownload((429, null), (0, null), (503, null), (429, null));
+ Exception error = null;
+ yield return RunDone(d, e => error = e);
+ Assert.IsInstanceOf<IOException>(error);
+ Assert.AreEqual("x.yaml: HTTP 429 (fake://site/x.yaml) after 4 attempts", error.Message);
+ Assert.AreEqual(StreamingFetch.MaxAttempts, d.Attempts);
+ Assert.AreEqual(StreamingFetch.MaxAttempts, d.Releases);
+
+ var notFound = new FakeDownload((404, null), (200, null));
+ yield return RunDone(notFound, e => error = e);
+ Assert.AreEqual("x.yaml: HTTP 404 (fake://site/x.yaml)", error.Message);
+ Assert.AreEqual(1, notFound.Attempts);
+ }
+
+ /// <summary>The wait before the next attempt: the backoff, or a longer Retry-After (seconds or an HTTP-date), at most
+ /// MaxRetryAfter; a malformed or past one is ignored.</summary>
+ [Test]
+ public void ARetryAfterLongerThanTheBackoffIsHonouredUpToTheCap()
+ {
+ var now = new DateTime(2026, 10, 18, 12, 0, 0, DateTimeKind.Utc);
+ Assert.AreEqual(0.5f, StreamingFetch.Delay(1, null, now));
+ Assert.AreEqual(3f, StreamingFetch.Delay(1, "3", now));
+ Assert.AreEqual(3f, StreamingFetch.Delay(1, " 3 ", now));
+ Assert.AreEqual(2f, StreamingFetch.Delay(3, "1", now)); // the backoff is longer
+ Assert.AreEqual(StreamingFetch.MaxRetryAfter, StreamingFetch.Delay(1, "3600", now));
+ Assert.AreEqual(5f, StreamingFetch.Delay(1, "Sun, 18 Oct 2026 12:00:05 GMT", now));
+ Assert.AreEqual(0.5f, StreamingFetch.Delay(1, "Sun, 18 Oct 2026 11:00:00 GMT", now)); // in the past
+ Assert.AreEqual(1f, StreamingFetch.Delay(2, "soon", now));
+ Assert.AreEqual(1f, StreamingFetch.Delay(2, "-5", now));
+ }
+
+ /// <summary>#1054: the content packed into one file at build time gives back every file's text as the disk path reads
+ /// it, so the web boot loads the same content with the same content hash.</summary>
+ [Test]
+ public void ThePackedBundleRoundTripsToTheSameTextsAndContentHash()
+ {
+ var files = ContentManifest.Collect(Paths.Content);
+ var (listed, texts) = ContentManifest.ParseBundle(ContentManifest.WriteBundle(Paths.Content, files));
+ CollectionAssert.AreEqual(files, listed);
+ Assert.AreEqual(files.Count, texts.Count);
+ foreach (var f in files) Assert.AreEqual(File.ReadAllText(Path.Combine(Paths.Content, f)), texts[f], f);
+ var packed = GameInputs.FromTexts(texts, listed, "", new byte[0]);
+ var disk = ContentLoader.Load(Paths.Content);
+ Assert.AreEqual(disk.Hash, packed.Content.Hash);
+ Assert.AreEqual(Simulation.NewGame(disk, 7, Mode.Historical).Hash(), Simulation.NewGame(packed.Content, 7, Mode.Historical).Hash());
+ }
+
+ [Test]
+ public void ABrokenBundleIsAClearError()
+ {
+ Assert.AreEqual("bundle.json: no files", Assert.Throws<InvalidDataException>(() => ContentManifest.ParseBundle("{\"files\": []}")).Message);
+ Assert.AreEqual("bundle.json: 2 files but 1 texts",
+ Assert.Throws<InvalidDataException>(() => ContentManifest.ParseBundle("{\"files\": [\"a.yaml\", \"b.yaml\"], \"texts\": [\"x\"]}")).Message);
+ Assert.AreEqual("bundle.json: a.yaml twice",
+ Assert.Throws<InvalidDataException>(() => ContentManifest.ParseBundle("{\"files\": [\"a.yaml\", \"a.yaml\"], \"texts\": [\"x\", \"y\"]}")).Message);
+ }
+
[UnityTest, Timeout(FetchTestTimeoutMs)]
public IEnumerator AConnectionThatKeepsDroppingFailsNamingTheFileWithNothingLeftOpen()
{
var site = StagedSite();
try
{
- var faults = new Dictionary<string, (string, int)> { ["content/events/israel_bonds.yaml"] = ("drop", int.MaxValue) };
+ var faults = new Dictionary<string, (string, int)> { ["content/bundle.json"] = ("drop", int.MaxValue) };
using (var server = new FlakySite(site, faults))
{
var fetch = GameInputs.FetchAsync(server.BaseUrl).GetAwaiter();
yield return Await(fetch);
var ex = Assert.Throws<IOException>(() => fetch.GetResult());
- StringAssert.StartsWith("events/israel_bonds.yaml: ", ex.Message);
- StringAssert.EndsWith($"after {GameInputs.MaxAttempts} attempts", ex.Message);
- Assert.AreEqual(GameInputs.MaxAttempts, server.Hits("content/events/israel_bonds.yaml"));
- Assert.AreEqual(0, GameInputs.OpenRequests, "requests still in flight after a failed fetch were not disposed");
+ StringAssert.StartsWith("bundle.json: ", ex.Message);
+ StringAssert.EndsWith($"after {StreamingFetch.MaxAttempts} attempts", ex.Message);
+ Assert.AreEqual(StreamingFetch.MaxAttempts, server.Hits("content/bundle.json"));
+ Assert.AreEqual(0, StreamingFetch.OpenRequests, "requests still in flight after a failed fetch were not disposed");
}
}
finally { Directory.Delete(site, true); }
}
- const int TrickleChunks = 10, TrickleGapMs = 300;
-
/// <summary>#911: the stall limit is on silence, not on the whole download. A file that takes 3 s to arrive, a part every
/// 0.3 s, passes a 2 s stall limit at its first attempt (a fixed per-request timeout would cut it off).</summary>
[UnityTest, Timeout(FetchTestTimeoutMs)]
@@ -342,7 +381,7 @@ public class GameInputsTests
var site = StagedSite();
try
{
- var faults = new Dictionary<string, (string, int)> { ["content/manifest.json"] = ("trickle", 1) };
+ var faults = new Dictionary<string, (string, int)> { ["content/bundle.json"] = ("trickle", 1) };
using (var server = new FlakySite(site, faults))
{
var started = Time.realtimeSinceStartup;
@@ -350,9 +389,9 @@ public class GameInputsTests
yield return Await(fetch);
var fetched = fetch.GetResult();
Assert.AreEqual(GameInputs.FromDisk(Paths.Content, Paths.StreamingMap).Content.Hash, fetched.Content.Hash);
- Assert.AreEqual(1, server.Hits("content/manifest.json"), "the slow download was aborted and retried");
- Assert.Greater(Time.realtimeSinceStartup - started, TrickleChunks * TrickleGapMs / 1000f, "the download was slower than the stall limit");
- Assert.AreEqual(0, GameInputs.OpenRequests);
+ Assert.AreEqual(1, server.Hits("content/bundle.json"), "the slow download was aborted and retried");
+ Assert.Greater(Time.realtimeSinceStartup - started, FlakySite.TrickleChunks * FlakySite.TrickleGapMs / 1000f, "the download was slower than the stall limit");
+ Assert.AreEqual(0, StreamingFetch.OpenRequests);
}
}
finally { Directory.Delete(site, true); }
@@ -369,14 +408,14 @@ public class GameInputsTests
var bootObject = new GameObject("StalledBoot");
try
{
- var faults = new Dictionary<string, (string, int)> { ["content/manifest.json"] = ("stall", int.MaxValue) };
+ var faults = new Dictionary<string, (string, int)> { ["content/bundle.json"] = ("stall", int.MaxValue) };
using (var server = new FlakySite(site, faults))
{
var boot = bootObject.AddComponent<GameBoot>();
string failure = null;
boot.Failed += reason => failure = reason;
- LogAssert.Expect(LogType.Error, new System.Text.RegularExpressions.Regex("BOOT FAIL manifest.json: .* after 4 attempts"));
- LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("manifest.json: .* after 4 attempts"));
+ LogAssert.Expect(LogType.Error, new System.Text.RegularExpressions.Regex("BOOT FAIL bundle.json: .* after 4 attempts"));
+ LogAssert.Expect(LogType.Exception, new System.Text.RegularExpressions.Regex("bundle.json: .* after 4 attempts"));
var started = Time.realtimeSinceStartup;
var run = boot.BootAsync(() => GameInputs.FetchAsync(server.BaseUrl, "", testStallSeconds)).GetAwaiter();
@@ -387,12 +426,12 @@ public class GameInputsTests
}
run.GetResult();
- StringAssert.StartsWith("manifest.json: ", failure);
- StringAssert.EndsWith($"after {GameInputs.MaxAttempts} attempts", failure);
- Assert.AreEqual(GameInputs.MaxAttempts, server.Hits("content/manifest.json"));
+ StringAssert.StartsWith("bundle.json: ", failure);
+ StringAssert.EndsWith($"after {StreamingFetch.MaxAttempts} attempts", failure);
+ Assert.AreEqual(StreamingFetch.MaxAttempts, server.Hits("content/bundle.json"));
Assert.Less(Time.realtimeSinceStartup - started,
- GameInputs.MaxAttempts * testStallSeconds + 10f, "boot failure was not visible within the stated retry time");
- Assert.AreEqual(0, GameInputs.OpenRequests);
+ StreamingFetch.MaxAttempts * testStallSeconds + 10f, "boot failure was not visible within the stated retry time");
+ Assert.AreEqual(0, StreamingFetch.OpenRequests);
}
}
finally
@@ -419,23 +458,25 @@ public class GameInputsTests
GameInputs.WithBuildId("/Applications/Statecraft.app/Contents/Resources/Data/StreamingAssets/video/a.mp4", "0123abcd"));
}
+ /// <summary>#1054: the web boot makes three requests (the content bundle and the heightmap's two files), not one per
+ /// content file (66 StreamingAssets requests on the live v0.1.1 build), and every one carries the build id.</summary>
[UnityTest, Timeout(FetchTestTimeoutMs)]
public IEnumerator EveryFetchCarriesTheBuildIdRetriesIncluded()
{
var site = StagedSite();
try
{
- var faults = new Dictionary<string, (string, int)> { ["content/people.yaml"] = ("503", 1) };
+ var faults = new Dictionary<string, (string, int)> { ["content/bundle.json"] = ("503", 1) };
using (var server = new FlakySite(site, faults))
{
var fetch = GameInputs.FetchAsync(server.BaseUrl, "0123abcd").GetAwaiter();
yield return Await(fetch);
fetch.GetResult();
var targets = server.Targets.ToArray();
- var manifest = ContentManifest.Collect(Paths.Content);
- Assert.AreEqual(manifest.Count + 4, targets.Length); // the manifest, every file, heightmap.json and .r16z, one retry
+ CollectionAssert.AreEquivalent(new[] { "/content/bundle.json", "/content/bundle.json", "/map/heightmap.json", "/map/heightmap.r16z" },
+ targets.Select(t => t.Split('?')[0]).ToArray()); // the bundle (once retried) and the heightmap's two files
foreach (var t in targets) StringAssert.EndsWith("?b=0123abcd", t);
- Assert.AreEqual(2, server.Hits("content/people.yaml"));
+ Assert.AreEqual(2, server.Hits("content/bundle.json"));
}
}
finally { Directory.Delete(site, true); }
@@ -444,35 +485,38 @@ public class GameInputsTests
[Test]
public void OnlyNoResponseAndServerSideStatusesAreRetried()
{
- Assert.IsTrue(GameInputs.Transient(UnityWebRequest.Result.ConnectionError, 0));
+ Assert.IsTrue(StreamingFetch.Transient(UnityWebRequest.Result.ConnectionError, 0));
foreach (var status in new long[] { 500, 502, 503, 504, 408, 429 })
- Assert.IsTrue(GameInputs.Transient(UnityWebRequest.Result.ProtocolError, status), status.ToString());
+ Assert.IsTrue(StreamingFetch.Transient(UnityWebRequest.Result.ProtocolError, status), status.ToString());
foreach (var status in new long[] { 400, 403, 404, 410 })
- Assert.IsFalse(GameInputs.Transient(UnityWebRequest.Result.ProtocolError, status), status.ToString());
- Assert.IsFalse(GameInputs.Transient(UnityWebRequest.Result.DataProcessingError, 200));
- Assert.AreEqual(4, GameInputs.MaxAttempts);
- CollectionAssert.AreEqual(new[] { 0.5f, 1f, 2f }, new[] { GameInputs.Backoff(1), GameInputs.Backoff(2), GameInputs.Backoff(3) });
+ Assert.IsFalse(StreamingFetch.Transient(UnityWebRequest.Result.ProtocolError, status), status.ToString());
+ Assert.IsFalse(StreamingFetch.Transient(UnityWebRequest.Result.DataProcessingError, 200));
+ Assert.AreEqual(4, StreamingFetch.MaxAttempts);
+ CollectionAssert.AreEqual(new[] { 0.5f, 1f, 2f }, new[] { StreamingFetch.Backoff(1), StreamingFetch.Backoff(2), StreamingFetch.Backoff(3) });
}
[UnityTest, Timeout(FetchTestTimeoutMs)]
public IEnumerator ANotFoundFileIsNotRetried()
{
var site = StagedSite();
- File.Delete(Path.Combine(site, "content", "people.yaml"));
+ File.Delete(Path.Combine(site, "content", ContentManifest.BundleFileName));
try
{
using (var server = new FlakySite(site, new Dictionary<string, (string, int)>()))
{
var fetch = GameInputs.FetchAsync(server.BaseUrl).GetAwaiter();
yield return Await(fetch);
- StringAssert.StartsWith("people.yaml: ", Assert.Throws<IOException>(() => fetch.GetResult()).Message);
- Assert.AreEqual(1, server.Hits("content/people.yaml"));
- Assert.AreEqual(0, GameInputs.OpenRequests);
+ StringAssert.StartsWith("bundle.json: ", Assert.Throws<IOException>(() => fetch.GetResult()).Message);
+ Assert.AreEqual(1, server.Hits("content/bundle.json"));
+ Assert.AreEqual(0, StreamingFetch.OpenRequests);
}
}
finally { Directory.Delete(site, true); }
}
+ /// <summary>bundle.json's shape (ContentManifest.BundleJson is private), to write a tampered one.</summary>
+ [Serializable] sealed class PackedForTest { public string[] files; public string[] texts; }
+
[Test]
public void VerifyAcceptsACopyAndRejectsAMissingFileOrManifestMismatch()
{
@@ -486,6 +530,16 @@ public class GameInputsTests
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);
+ ContentManifest.Copy(Paths.Content, target);
+ var files = ContentManifest.Collect(Paths.Content);
+ var (_, texts) = ContentManifest.ParseBundle(File.ReadAllText(Path.Combine(target, ContentManifest.BundleFileName)));
+ texts["people.yaml"] += "\n# edited after the copy\n";
+ File.WriteAllText(Path.Combine(target, ContentManifest.BundleFileName),
+ JsonUtility.ToJson(new PackedForTest { files = files.ToArray(), texts = files.Select(f => texts[f]).ToArray() }));
+ Assert.AreEqual("people.yaml: its text in bundle.json differs from the source",
+ Assert.Throws<InvalidDataException>(() => ContentManifest.Verify(Paths.Content, target)).Message);
+ File.Delete(Path.Combine(target, ContentManifest.BundleFileName));
+ StringAssert.StartsWith("bundle.json: missing", Assert.Throws<InvalidDataException>(() => ContentManifest.Verify(Paths.Content, target)).Message);
}
finally { if (Directory.Exists(target)) Directory.Delete(target, true); }
}