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.

build(webgl): hashed Build/ file names, and a cached page loads the current build (refs #437) (#501)

Eyal Golan961e66ee0ebb
diff --git a/CHANGELOG.md b/CHANGELOG.md
index db7f7a05c..549d82c58 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -417,6 +417,20 @@ adds a line under **Unreleased**; CI's `Changelog` job checks this (see `CONTRIB
to the Education Department, both already in the Education Ministry. Moshe Sharett's birth date is 16 October 1894,
from the Knesset member pages (Wikipedia gave 15 October); the sim reads `born` only to validate content. The items
that would move a golden wait for the GDD rebaseline (#315).
+- The browser build names the files under `Build/` by their content hash (Unity's Name Files As Hashes), so the names
+ change with every build and a browser that cached an earlier build can no longer mix its loader, code or data into a
+ newer one (the startup failure "InternalError: too much recursion" without a hard refresh). Found by @Chaiky3 (#437,
+ reported in #43). `tools/package_release.py` now zips exactly the `Build/` files the build's `index.html` names, and
+ refuses a folder that is missing one.
+- The browser page itself can still come from the browser's cache after an update (a server that sends no
+ Cache-Control, such as `python3 -m http.server`, allows it), and it then named the previous build's files, which are
+ gone: the start failed with "Unknown data format". The page now asks the server for its current copy and loads the
+ files that copy names, keeping its own names only when it cannot (offline, `file://`). Refs #437.
+- The files the browser build fetches from StreamingAssets (the content, the heightmap, the event clips and the start
+ screen's recording) keep fixed
+ names, so a returning browser could pair new code with the previous build's cached content. Every such URL now
+ carries the build's id (`?b=<Application.buildGUID>`), so each build fetches its own copies; desktop file paths are
+ unchanged. Refs #437.
- The Provisional Government, the first three governments, the Provisional State Council and the First and Second
Knessets now cite the Knesset's records: its position, faction and session data, the plenum minutes of each opening
sitting and confidence vote, the 1951 transition and election-day laws, its make-up pages for the First and Second
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index e2a81ba44..27ab0da48 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -31,6 +31,18 @@ GitHub Releases page (and, from M4, on itch.io). Steps 1–3 are a normal pull r
so) or that carries an unreviewed sensitive event photograph. It then lists the zip, and prints the SHA-256 and `OK: notices inside …`. If it prints anything
else, stop. This one zip is the file for GitHub Releases and for the M4 itch.io upload (`docs/m3-release.md`); never
zip a build by hand.
+
+ The files under `Build/` are named by their content hash (`webGLNameFilesAsHashes: 1`, set by `ProjectSetup.Apply`;
+ issue #437), so their names change with every build that changes them. Only the build's `index.html` says which ones
+ belong to it: never refer to them by a fixed name. Unity empties `Build/` on each build; `package_release.py` zips
+ only the `Build/` files `index.html` names (it prints `LEFT OUT Build/<name>` for any other) and refuses the folder
+ when one of them is missing.
+
+ With `webGLDataCaching: 1`, Unity's loader also keeps each build's `.data` in the browser's IndexedDB (UnityCache),
+ keyed by its URL. Its clean-up drops entries made under another `productVersion` (`bundleVersion`), and otherwise
+ trims the least recently used above 1 GiB (`MaximumCacheSize=1073741824` in the 6000.3 loader). With hashed names,
+ every build with the same `bundleVersion` adds one more `.data` there until that cap; the version bump in step 2
+ clears them at each release.
6. **Tag and publish (owner):**
```bash
diff --git a/docs/m3-release.md b/docs/m3-release.md
index 5c0ef0325..40af53953 100644
--- a/docs/m3-release.md
+++ b/docs/m3-release.md
@@ -5,6 +5,14 @@ start of M4, as a private Draft (owner ruling, 2026-10-10); their sections below
## What ships
- **Folder and zip:** `unity/Builds/Web-brotli/` uses Brotli compression with no decompression fallback. It is zipped as `unity/Builds/statecraft-m3-web.zip`, with `index.html` at the zip root. Both are build output and are not committed.
+- **File names:** the files under `Build/` are named by their content hash (issue #437), for example
+ `Build/814d5f9032ce4b5847cf75e492700bbb.loader.js`, so a browser that cached an earlier build cannot mix its files into
+ this one. The build's `index.html` names them; nothing else may assume a name. `index.html` keeps its fixed name and
+ a browser may show a cached copy of it (no host this project uses is known to forbid that), so the page asks the
+ server for its current copy (`fetch` with `cache: "reload"`, which also stores that copy for the next visit) and loads the files that copy names. The StreamingAssets
+ files (`content/`, `map/`, `video/` and the start screen's recording) keep their names; the player adds the build's
+ id to every URL it fetches them by (`?b=<Application.buildGUID>`,
+ `GameInputs.WithBuildId`), so a browser cannot serve one build's cached content to another.
- **Built by:** `"$UNITY" -batchmode -CI false -GITHUB_ACTIONS false -TF_BUILD false -quit -projectPath unity -buildTarget WebGL -executeMethod Statecraft.Game.EditorTools.Build.Web -compression brotli -shareable -logFile "$PWD/unity-build-web-br.log"`, then `python3 tools/package_release.py` (it zips the folder, `index.html` at the root, and refuses while any sensitive event is not sensitivity-reviewed, and when the build's `event-photos.json` is missing, says the build was not `-shareable`, or lists an unreviewed sensitive event photograph). Never zip by hand.
- **After building:** drop the build's rewrites of the settings with
`git checkout -- unity/Assets/Settings unity/ProjectSettings/ProjectSettings.asset` (as in `dev-setup.md`), so no
@@ -270,7 +278,10 @@ Published at: (owner fills in)
Re-uploading the same build is enough to isolate the changed upload URL. Record both upload/build IDs. Confirm B has
a different upload URL but the same actual game-frame origin. If its origin differs, record that separately: this
fixed-folder test cannot prove persistence between origins, because IndexedDB is origin-scoped.
- 4. Open B with a hard reload. **Pass** only if date, turn and full state hash match the baseline. Copy the complete
+ 4. First open B with a normal load, not a hard reload (issue #437: a returning player's browser has A cached). It must
+ start and print `GAME OK`, and DevTools' Network panel must show the `Build/` file names that B's `index.html`
+ names, not A's. Record the result, and any `BOOT FAIL` line, as a separate row. Then open B with a hard reload.
+ **Pass** only if date, turn and full state hash match the baseline. Copy the complete
`GAME OK` line, the old `TURN` line and any load warning/error. A date/turn match alone is not a pass. Reload B once
more and check the same tuple, so a one-time replay is not mistaken for a durable save.
5. If B starts again on 15 May 1948, or the state hash differs with unchanged content, record fail with both build IDs,
@@ -299,6 +310,7 @@ Result: not run on itch.io (owner step).
| State hash after | pending |
| Full TURN / GAME OK lines and warnings | pending |
| Reload B result | pending |
+| B opened without a hard reload: `GAME OK`, and B's `Build/` names (issue #437) | pending |
| Pass / fail and fallback issue if needed | pending |
Review basis: `unity/Assets/Scripts/SaveStore.cs` fixes the WebGL directory; `sim/Statecraft.Sim/SaveGame.cs` records the
diff --git a/tools/README.md b/tools/README.md
index f37b6174f..4a90e65fd 100644
--- a/tools/README.md
+++ b/tools/README.md
@@ -27,7 +27,9 @@ Offline data tools (uv inline-script Python). Run from the repo root.
- `web_check.py` serves a WebGL build on http://localhost and opens it in headless Chrome for Testing (Playwright's
cache; macOS only, arm64 or x64); it passes when the console shows the expected lines (`GOLDEN OK ...`, `SMOKE OK ...`).
- `package_release.py` zips a Brotli WebGL build for sharing (`unity/Builds/statecraft-m3-web.zip`) and refuses
- (exit 1) until every sensitive event is `sensitivity-reviewed` (docs/m3-release.md).
+ (exit 1) until every sensitive event is `sensitivity-reviewed` (docs/m3-release.md). The files under `Build/` are
+ named by their content hash (issue #437); it reads their names from the build's `index.html`, zips only those and
+ refuses a build that is missing one.
- `preview_map.py` renders the geography check image `tools/.cache/map-preview.png`.
- `terrain_bake.py` writes `unity/Assets/Textures/Map/terrain_bake.png` (AO, curvature, sky-view), `ao.png` (the AO
alone, imported uncompressed) and `coast.png`
diff --git a/tools/package_release.py b/tools/package_release.py
index 5b05b01c0..a42d14fda 100644
--- a/tools/package_release.py
+++ b/tools/package_release.py
@@ -11,9 +11,15 @@ The event-card photographs are packed into Unity's data files, where this script
what it carries into event-photos.json (Build.PhotoManifestName, review I1). The zip is refused when that file is
missing or unreadable, when the build was not made with -shareable, or when any photograph in it is sensitive and not
sensitivity-reviewed (docs/event-images.md).
+
+Build.Web names the files under Build/ by their content hash (issue #437), so their names change from build to build and
+index.html is what says which ones belong to this build. The zip carries exactly the Build/ files index.html names: it
+is refused when one is missing, and a file it does not name (an earlier build's, left in the folder) is left out with a
+"LEFT OUT Build/<name>" line.
"""
import argparse
import json
+import re
import subprocess
import sys
import zipfile
@@ -55,6 +61,14 @@ def photo_refusal(build: Path):
return None
+BUILD_FILE = re.compile(r'"Build/([^"/]+)"') # as the WebGL template writes them (src="Build/..", dataUrl: "Build/..")
+
+
+def build_files(build: Path) -> list[str]:
+ """The names of the files under Build/ that the build's index.html loads, sorted."""
+ return sorted(set(BUILD_FILE.findall((build / "index.html").read_text(encoding="utf-8"))))
+
+
def package(build: Path, zip_path: Path) -> int:
if not (build / "index.html").is_file():
print(f"PACKAGE REFUSED: {build} has no index.html (not a WebGL build folder)")
@@ -63,6 +77,11 @@ def package(build: Path, zip_path: Path) -> int:
if not content.is_dir():
print(f"PACKAGE REFUSED: {build} has no StreamingAssets/content")
return 1
+ named = build_files(build)
+ if missing := [n for n in named if not (build / "Build" / n).is_file()]:
+ print("PACKAGE REFUSED: index.html names files that are not in the build: " + ", ".join("Build/" + n for n in missing))
+ return 1
+ stale = {p for p in (build / "Build").glob("*") if p.is_file() and p.name not in named}
if (photos := photo_refusal(build)) is not None:
print(f"PACKAGE REFUSED: {photos}")
return 1
@@ -73,8 +92,10 @@ def package(build: Path, zip_path: Path) -> int:
return 1
zip_path.unlink(missing_ok=True)
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as z: # index.html at the zip root, as itch.io needs
- for f in sorted(p for p in build.rglob("*") if p.is_file()):
+ for f in sorted(p for p in build.rglob("*") if p.is_file() and p not in stale):
z.write(f, f.relative_to(build).as_posix())
+ for f in sorted(stale):
+ print(f"LEFT OUT Build/{f.name} (index.html does not name it: a file of an earlier build)")
print(f"PACKAGED {zip_path} {zip_path.stat().st_size} bytes")
return 0
diff --git a/tools/tests/test_package_release.py b/tools/tests/test_package_release.py
index 2a8ba170f..38fee345c 100644
--- a/tools/tests/test_package_release.py
+++ b/tools/tests/test_package_release.py
@@ -89,3 +89,51 @@ def test_a_malformed_photo_manifest_is_refused(tmp_path, capsys):
for bad in ["{", '{"shareable": true}', '{"shareable": "yes", "photos": []}', '{"shareable": true, "photos": [{"event_id": "x"}]}']:
(build / package_release.PHOTO_MANIFEST).write_text(bad)
assert "not a valid photo manifest" in refused(build, tmp_path, capsys)
+
+
+# Issue #437: Build.Web names the files under Build/ by their content hash, so the names differ from build to build and
+# index.html is the only place that says which files belong to this build.
+HASHED = ["0a1b2c3d4e5f60718293a4b5c6d7e8f9.loader.js", "11112222333344445555666677778888.framework.js.br",
+ "9999aaaabbbbccccddddeeeeffff0000.data.br", "abcdefabcdefabcdefabcdefabcdefab.wasm.br"]
+
+
+def hashed_build(tmp_path):
+ """fake_build with a Build/ folder of hashed names and an index.html that names them, as the template writes it."""
+ build = fake_build(tmp_path, reviewed=True)
+ loader, framework, data, code = HASHED
+ (build / "index.html").write_text(
+ f'<html><script src="Build/{loader}"></script><script>var config = {{\n dataUrl: "Build/{data}",\n'
+ f' frameworkUrl: "Build/{framework}",\n codeUrl: "Build/{code}",\n streamingAssetsUrl: "StreamingAssets",\n}};'
+ "</script></html>")
+ (build / "Build").mkdir()
+ for name in HASHED:
+ (build / "Build" / name).write_bytes(b"\x00")
+ return build
+
+
+def test_the_build_files_are_read_from_index_html(tmp_path):
+ assert package_release.build_files(hashed_build(tmp_path)) == sorted(HASHED)
+ assert package_release.build_files(fake_build(tmp_path / "plain", reviewed=True)) == []
+
+
+def test_the_zip_carries_the_hashed_files_index_html_names(tmp_path, capsys):
+ build, zip_path = hashed_build(tmp_path), tmp_path / "out.zip"
+ assert package_release.main(["--build", str(build), "--zip", str(zip_path)]) == 0
+ with zipfile.ZipFile(zip_path) as z:
+ assert sorted(n for n in z.namelist() if n.startswith("Build/")) == sorted("Build/" + n for n in HASHED)
+
+
+def test_files_of_an_earlier_build_are_left_out_of_the_zip(tmp_path, capsys):
+ """A second build into the same folder leaves the earlier build's files beside the new ones under other names."""
+ build, zip_path = hashed_build(tmp_path), tmp_path / "out.zip"
+ (build / "Build" / "ffffffffffffffffffffffffffffffff.data.br").write_bytes(b"old")
+ assert package_release.main(["--build", str(build), "--zip", str(zip_path)]) == 0
+ with zipfile.ZipFile(zip_path) as z:
+ assert sorted(n for n in z.namelist() if n.startswith("Build/")) == sorted("Build/" + n for n in HASHED)
+ assert "LEFT OUT Build/ffffffffffffffffffffffffffffffff.data.br" in capsys.readouterr().out
+
+
+def test_a_build_missing_a_file_index_html_names_is_refused(tmp_path, capsys):
+ build = hashed_build(tmp_path)
+ (build / "Build" / HASHED[3]).unlink()
+ assert "Build/" + HASHED[3] in refused(build, tmp_path, capsys)
diff --git a/tools/tests/test_webgl_stale_page.py b/tools/tests/test_webgl_stale_page.py
new file mode 100644
index 000000000..9cc0cf7df
--- /dev/null
+++ b/tools/tests/test_webgl_stale_page.py
@@ -0,0 +1,85 @@
+"""Issue #437: the WebGL page names its build's hashed Build/ files, and a browser may show a cached copy of the page after a
+newer build replaced them. The page therefore asks the server for its current copy and loads the files that copy names.
+These check the template's text (no Unity, no browser); the cached-browser run itself is described in the PR."""
+import json
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+import package_release
+
+TEMPLATE = Path(__file__).resolve().parents[2] / "unity/Assets/WebGLTemplates/Statecraft/index.html"
+FILES = {"LOADER_FILENAME": "aaaa.loader.js", "DATA_FILENAME": "bbbb.data", "FRAMEWORK_FILENAME": "cccc.framework.js",
+ "WORKER_FILENAME": "dddd.worker.js", "CODE_FILENAME": "eeee.wasm", "SYMBOLS_FILENAME": "ffff.symbols.json"}
+
+
+def page() -> str:
+ return TEMPLATE.read_text(encoding="utf-8")
+
+
+def rendered() -> str:
+ """The page as Unity writes it for a single-threaded wasm build: variables filled in, directives resolved."""
+ out, keep = [], [True]
+ for line in page().splitlines():
+ if line.startswith("#if "):
+ keep.append(keep[-1] and line.split()[1] in ("USE_WASM",))
+ elif line.startswith("#endif"):
+ keep.pop()
+ elif keep[-1]:
+ out.append(re.sub(r"\{\{\{ (\w+) \}\}\}", lambda m: FILES.get(m.group(1), m.group(0)), line))
+ return "\n".join(out)
+
+
+def test_the_loader_is_not_a_static_script_tag():
+ """A static <script src="Build/..loader.js"> in a cached page would load the old loader before any check could run."""
+ assert not re.search(r"<script[^>]*\ssrc=", page())
+
+
+def test_the_page_fetches_its_own_current_copy_before_loading_the_build():
+ text = page()
+ assert re.search(r'fetch\(location\.href[^\n]*\{\s*cache:\s*"reload"\s*\}\)', text)
+ assert re.search(r"\.then\(start\);\s*</script>", text) # the build starts only after that fetch settles
+ start = re.search(r"function start\(\) \{.*?\n \}\n", text, re.S).group(0)
+ assert text.count("createUnityInstance(") == 1 and "createUnityInstance(" in start
+
+
+def test_every_build_file_the_page_names_is_read_back_from_the_current_copy():
+ text = page()
+ named = set(re.findall(r'(\w+)\s*[:=]\s*"Build/\{\{\{', text))
+ assert named == {"loaderUrl", "dataUrl", "frameworkUrl", "workerUrl", "codeUrl", "symbolsUrl"}
+ reread = set(re.findall(r'"(\w+Url)"', re.search(r"FRESH_KEYS = \[([^\]]*)\]", text).group(1)))
+ assert named == reread
+
+
+def test_the_packager_still_finds_every_file_of_a_rendered_page(tmp_path):
+ (tmp_path / "index.html").write_text(rendered())
+ assert package_release.build_files(tmp_path) == sorted(["aaaa.loader.js", "bbbb.data", "cccc.framework.js", "eeee.wasm"])
+
+
+def run_use_current_page(page_html: str, current_html: str) -> dict:
+ """Runs the page's own script (up to its fetch) in node, feeds useCurrentPage the current copy, and returns the
+ names the page would then load."""
+ script = re.search(r"<script>(.*)</script>", page_html, re.S).group(1).split("fetch(location.href")[0]
+ driver = (script + "\nuseCurrentPage(" + json.dumps(current_html) + ");\n"
+ "console.log(JSON.stringify({loaderUrl: loaderUrl, config: config}));\n")
+ out = subprocess.run(["node", "-e", driver], capture_output=True, text=True, check=True).stdout
+ return json.loads(out)
+
+
[email protected](shutil.which("node") is None, reason="needs node to run the page's script")
+def test_a_stale_page_loads_the_files_the_current_copy_names():
+ """Review of #501: the text checks above pass with useCurrentPage's assignments removed; this runs it."""
+ stale = re.sub(r"\{\{\{ JSON\.stringify\((\w+)\) \}\}\}", r'"\1"', rendered())
+ current = stale.replace("aaaa", "1111").replace("bbbb", "2222").replace("cccc", "3333").replace("eeee", "5555")
+ got = run_use_current_page(stale, current)
+ assert got["loaderUrl"] == "Build/1111.loader.js"
+ assert {k: got["config"].get(k) for k in ("dataUrl", "frameworkUrl", "codeUrl", "workerUrl", "symbolsUrl")} == {
+ "dataUrl": "Build/2222.data", "frameworkUrl": "Build/3333.framework.js", "codeUrl": "Build/5555.wasm",
+ "workerUrl": None, "symbolsUrl": None}
+ assert got["config"]["streamingAssetsUrl"] == "StreamingAssets" and got["config"]["autoSyncPersistentDataPath"] is True
+ # A copy that is not this template's (an error page, say) leaves the page's own names.
+ kept = run_use_current_page(stale, "<html><body>Not Found</body></html>")
+ assert kept["loaderUrl"] == "Build/aaaa.loader.js" and kept["config"]["dataUrl"] == "Build/bbbb.data"
diff --git a/unity/Assets/Editor/ProjectSetup.cs b/unity/Assets/Editor/ProjectSetup.cs
index 38577d2e0..2dfb75300 100644
--- a/unity/Assets/Editor/ProjectSetup.cs
+++ b/unity/Assets/Editor/ProjectSetup.cs
@@ -22,6 +22,9 @@ namespace Statecraft.Game.EditorTools
PlayerSettings.WebGL.template = WebTemplate;
PlayerSettings.WebGL.compressionFormat = WebGLCompressionFormat.Disabled;
PlayerSettings.WebGL.decompressionFallback = false;
+ // Issue #437: the files under Build/ are named by their content hash, so a browser that cached an earlier build
+ // cannot mix its files into this one; the build's index.html names its own files.
+ PlayerSettings.WebGL.nameFilesAsHashes = true;
// Debug.Log lines (GAME OK, TURN, PROFILE) without a script stack trace; warnings and errors keep theirs (Task 24 review M9).
PlayerSettings.SetStackTraceLogType(LogType.Log, StackTraceLogType.None);
var player = new SerializedObject(AssetDatabase.LoadAllAssetsAtPath("ProjectSettings/ProjectSettings.asset")[0]);
diff --git a/unity/Assets/Scripts/Boot/GameBoot.cs b/unity/Assets/Scripts/Boot/GameBoot.cs
index 116b5a083..a0d62f497 100644
--- a/unity/Assets/Scripts/Boot/GameBoot.cs
+++ b/unity/Assets/Scripts/Boot/GameBoot.cs
@@ -49,7 +49,7 @@ namespace Statecraft.Game.Boot
}
static async Awaitable<GameInputs> LoadAsync() => Application.platform == RuntimePlatform.WebGLPlayer
- ? await GameInputs.FetchAsync(GameInputs.StreamingUrl())
+ ? await GameInputs.FetchAsync(GameInputs.StreamingUrl(), Application.buildGUID)
: GameInputs.FromDisk(Paths.Content, Paths.StreamingMap);
/// <summary>The boot Start runs, with the loader passed in so a test can drive the real failure path.</summary>
diff --git a/unity/Assets/Scripts/Boot/GameInputs.cs b/unity/Assets/Scripts/Boot/GameInputs.cs
index 64f1b8a4f..122b63c08 100644
--- a/unity/Assets/Scripts/Boot/GameInputs.cs
+++ b/unity/Assets/Scripts/Boot/GameInputs.cs
@@ -158,14 +158,22 @@ namespace Statecraft.Game.Boot
finally { Release(r); }
}
+ /// <summary>Issue #437: <paramref name="url"/> with b=<paramref name="buildId"/> added to its query when it is an
+ /// http(s) URL and the id is not empty; a file path or file:// URI (desktop, the editor) is returned unchanged.
+ /// StreamingAssets keep fixed names, so without it a browser could serve this build a previous build's cached file.</summary>
+ public static string WithBuildId(string url, string buildId) =>
+ 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.</summary>
- public static async Awaitable<GameInputs> FetchAsync(string baseUrl)
+ /// 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 async Awaitable<GameInputs> FetchAsync(string baseUrl, string buildId = "")
{
- 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 r16z = Start(baseUrl + "/map/" + HeightmapCodec.FileName);
+ var manifest = ContentManifest.Parse(await Text(Start(WithBuildId(baseUrl + "/content/" + ContentManifest.FileName, buildId)), ContentManifest.FileName));
+ var requests = manifest.Select(f => (file: f, request: Start(WithBuildId(baseUrl + "/content/" + f, buildId)))).ToList();
+ var meta = Start(WithBuildId(baseUrl + "/map/heightmap.json", buildId));
+ var r16z = Start(WithBuildId(baseUrl + "/map/" + HeightmapCodec.FileName, buildId));
try
{
var texts = new Dictionary<string, string>();
diff --git a/unity/Assets/Scripts/UI/CardVideo.cs b/unity/Assets/Scripts/UI/CardVideo.cs
index f5bfef731..4e39f1190 100644
--- a/unity/Assets/Scripts/UI/CardVideo.cs
+++ b/unity/Assets/Scripts/UI/CardVideo.cs
@@ -36,8 +36,8 @@ namespace Statecraft.Game.UI
public static bool ForcedOff() =>
ForcedOff(Application.absoluteURL, Environment.GetCommandLineArgs(), Application.platform == RuntimePlatform.WebGLPlayer);
- /// <summary>The clip's URL in the build's StreamingAssets/video folder.</summary>
- public static string Url(string file) => Application.streamingAssetsPath + "/video/" + file;
+ /// <summary>The clip's URL in the build's StreamingAssets/video folder, with the build's id on the web (issue #437).</summary>
+ public static string Url(string file) => Boot.GameInputs.WithBuildId(Application.streamingAssetsPath + "/video/" + file, Application.buildGUID);
/// <summary>The URL playing (or being prepared), or null.</summary>
public string? Current { get; private set; }
diff --git a/unity/Assets/Scripts/UI/DeclarationRecording.cs b/unity/Assets/Scripts/UI/DeclarationRecording.cs
index 0a67c5d09..c318aef51 100644
--- a/unity/Assets/Scripts/UI/DeclarationRecording.cs
+++ b/unity/Assets/Scripts/UI/DeclarationRecording.cs
@@ -86,11 +86,11 @@ namespace Statecraft.Game.UI
caption.style.display = DisplayStyle.None;
}
- /// <summary>The URL the button fetches.</summary>
+ /// <summary>The URL the button fetches, with the build's id on the web (issue #437).</summary>
public static string Url()
{
var url = Application.streamingAssetsPath + "/" + File;
- return url.Contains("://") ? url : "file://" + url;
+ return url.Contains("://") ? Boot.GameInputs.WithBuildId(url, Application.buildGUID) : "file://" + url;
}
/// <summary>The button: play; or, while loading or playing, stop.</summary>
diff --git a/unity/Assets/Tests/EditMode/GameInputsTests.cs b/unity/Assets/Tests/EditMode/GameInputsTests.cs
index 5f0d614b4..8268ffb36 100644
--- a/unity/Assets/Tests/EditMode/GameInputsTests.cs
+++ b/unity/Assets/Tests/EditMode/GameInputsTests.cs
@@ -117,6 +117,8 @@ public class GameInputsTests
readonly string root;
readonly Dictionary<string, (string fault, int times)> faults;
readonly ConcurrentDictionary<string, int> hits = new ConcurrentDictionary<string, int>();
+ /// <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)
@@ -154,6 +156,7 @@ public class GameInputsTests
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)
@@ -311,6 +314,45 @@ public class GameInputsTests
finally { Directory.Delete(site, true); }
}
+ /// <summary>Issue #437: StreamingAssets keep fixed names, so a returning browser could pair a new build's code with the
+ /// previous build's cached content files. Every URL the player fetches carries the build's id; a file path (desktop,
+ /// the editor) or an empty id is left alone.</summary>
+ [Test]
+ public void TheBuildIdGoesOnHttpUrlsOnly()
+ {
+ Assert.AreEqual("http://localhost:8000/StreamingAssets/content/people.yaml?b=0123abcd",
+ GameInputs.WithBuildId("http://localhost:8000/StreamingAssets/content/people.yaml", "0123abcd"));
+ Assert.AreEqual("https://html.itch.zone/html/1/StreamingAssets/video/a.mp4?b=0123abcd",
+ GameInputs.WithBuildId("https://html.itch.zone/html/1/StreamingAssets/video/a.mp4", "0123abcd"));
+ Assert.AreEqual("http://x/a.yaml?v=1&b=0123abcd", GameInputs.WithBuildId("http://x/a.yaml?v=1", "0123abcd"));
+ Assert.AreEqual("http://x/a.yaml", GameInputs.WithBuildId("http://x/a.yaml", ""));
+ Assert.AreEqual("file:///tmp/site/content/people.yaml", GameInputs.WithBuildId("file:///tmp/site/content/people.yaml", "0123abcd"));
+ Assert.AreEqual("/Applications/Statecraft.app/Contents/Resources/Data/StreamingAssets/video/a.mp4",
+ GameInputs.WithBuildId("/Applications/Statecraft.app/Contents/Resources/Data/StreamingAssets/video/a.mp4", "0123abcd"));
+ }
+
+ [UnityTest, Timeout(FetchTestTimeoutMs)]
+ public IEnumerator EveryFetchCarriesTheBuildIdRetriesIncluded()
+ {
+ var site = StagedSite();
+ try
+ {
+ var faults = new Dictionary<string, (string, int)> { ["content/people.yaml"] = ("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
+ foreach (var t in targets) StringAssert.EndsWith("?b=0123abcd", t);
+ Assert.AreEqual(2, server.Hits("content/people.yaml"));
+ }
+ }
+ finally { Directory.Delete(site, true); }
+ }
+
[Test]
public void OnlyNoResponseAndServerSideStatusesAreRetried()
{
diff --git a/unity/Assets/Tests/EditMode/ProjectSettingsTests.cs b/unity/Assets/Tests/EditMode/ProjectSettingsTests.cs
index e20cec378..29cb721f0 100644
--- a/unity/Assets/Tests/EditMode/ProjectSettingsTests.cs
+++ b/unity/Assets/Tests/EditMode/ProjectSettingsTests.cs
@@ -18,6 +18,14 @@ public class ProjectSettingsTests
Assert.AreEqual(new[] { "Assets/Map.unity" }, EditorBuildSettings.scenes.Select(s => s.path).ToArray());
}
+ /// <summary>Issue #437: every WebGL build names the files under Build/ by their content hash, so a browser that cached
+ /// an earlier build cannot mix its files into a newer one; index.html names the files of its own build.</summary>
+ [Test]
+ public void WebBuildFilesAreNamedByTheirContentHash()
+ {
+ Assert.IsTrue(PlayerSettings.WebGL.nameFilesAsHashes);
+ }
+
[Test]
public void TheNewSceneTemplateDoesNotPointAtTheDeletedSampleScene()
{
diff --git a/unity/Assets/WebGLTemplates/Statecraft/index.html b/unity/Assets/WebGLTemplates/Statecraft/index.html
index ffaa65934..05a2a9ab5 100644
--- a/unity/Assets/WebGLTemplates/Statecraft/index.html
+++ b/unity/Assets/WebGLTemplates/Statecraft/index.html
@@ -20,10 +20,10 @@
<canvas id="unity-canvas" tabindex="-1"></canvas>
<div id="loading">Statecraft: Israel<div id="bar"><div id="fill"></div></div></div>
<div id="error"></div>
- <script src="Build/{{{ LOADER_FILENAME }}}"></script>
<script>
// Full-window canvas: Unity keeps the render size matched to the canvas's CSS size, so the UI Toolkit panel
// (ScaleWithScreenSize, 1920x1080, match 0.5) rescales on every browser resize.
+ var loaderUrl = "Build/{{{ LOADER_FILENAME }}}";
var config = {
arguments: [],
dataUrl: "Build/{{{ DATA_FILENAME }}}",
@@ -44,16 +44,48 @@
// Persist writes under /idbfs to IndexedDB when a file is closed (tech notes section 3): saves need no manual sync.
autoSyncPersistentDataPath: true,
};
- createUnityInstance(document.querySelector("#unity-canvas"), config, function (progress) {
- document.getElementById("fill").style.width = (100 * progress) + "%";
- }).then(function () {
- document.getElementById("loading").style.display = "none";
- }).catch(function (message) {
+ // Issue #437: the Build/ files are named by their content hash, and this page names its build's files. A browser may
+ // show this page from its cache after a newer build replaced them (a server that sends no Cache-Control, such as
+ // python3 -m http.server, lets it), so ask the server for the current page and load the files that one names. The
+ // fetch skips the cache and stores the copy it gets ("reload"), so the next visit runs the current page. When it
+ // fails (file://, offline, or not this template), keep this page's own names.
+ var FRESH_KEYS = ["loaderUrl", "dataUrl", "frameworkUrl", "workerUrl", "codeUrl", "symbolsUrl"];
+ function useCurrentPage(html) {
+ var found = {};
+ FRESH_KEYS.forEach(function (key) {
+ var m = html.match(new RegExp("\\b" + key + '\\s*[:=]\\s*"(Build/[^"]+)"'));
+ if (m) found[key] = m[1];
+ });
+ if (!found.loaderUrl || !found.dataUrl) return;
+ loaderUrl = found.loaderUrl;
+ FRESH_KEYS.slice(1).forEach(function (key) {
+ if (found[key]) config[key] = found[key]; else delete config[key];
+ });
+ }
+ function fail(message) {
var e = document.getElementById("error");
e.textContent = "Statecraft could not start:\n" + message;
e.style.display = "block";
console.error("BOOT FAIL " + message);
- });
+ }
+ function start() {
+ var script = document.createElement("script");
+ script.src = loaderUrl;
+ script.onerror = function () { fail("could not load " + loaderUrl); };
+ script.onload = function () {
+ createUnityInstance(document.querySelector("#unity-canvas"), config, function (progress) {
+ document.getElementById("fill").style.width = (100 * progress) + "%";
+ }).then(function () {
+ document.getElementById("loading").style.display = "none";
+ }).catch(fail);
+ };
+ document.body.appendChild(script);
+ }
+ fetch(location.href.split("#")[0], { cache: "reload" })
+ .then(function (r) { return r.ok ? r.text() : ""; })
+ .then(useCurrentPage)
+ .catch(function () {})
+ .then(start);
</script>
</body>
</html>
diff --git a/unity/ProjectSettings/ProjectSettings.asset b/unity/ProjectSettings/ProjectSettings.asset
index 52c337cfe..26f9e829a 100644
--- a/unity/ProjectSettings/ProjectSettings.asset
+++ b/unity/ProjectSettings/ProjectSettings.asset
@@ -803,7 +803,7 @@ PlayerSettings:
spritePackerPolicy:
webGLMemorySize: 32
webGLExceptionSupport: 1
- webGLNameFilesAsHashes: 0
+ webGLNameFilesAsHashes: 1
webGLShowDiagnostics: 0
webGLDataCaching: 1
webGLDebugSymbols: 0