diff --git a/CHANGELOG.md b/CHANGELOG.md index c6be46fe..996a8691 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,14 @@ +## 0.2.6-dev — 未发布 + +### 开服流量 +- 静音或把背景音乐音量调到 0 时不再下载背景音乐,重新打开声音后才下载当前该放的曲子(关音乐的玩家每局少下约 7–14 MB)。 +- 1 KB 以上的 WebSocket 消息用 permessage-deflate 压缩,一局单人对局的服务器消息实测从 173 KB 降到 60 KB。 +- 素材地址带内容哈希:浏览器把图片、模型和音频缓存一年,服务器更新、重新解压或 Docker 重建后只重新下载内容变了的文件;哈希存在 `.cache/asset-hashes.json`,`SP_ASSET_INDEX=0` 可关闭。 +- 支持 brotli 压缩(浏览器只在 HTTPS 页面和 localhost 上使用),`.skel` 和数据文件比 gzip 再小约四分之一。 +- 本地提取的「玩法说明」教程图另存无损 WebP(25.6 MB → 17.4 MB),看说明时只预载下一页。 +- 流量统计:`/healthz?traffic=1` 显示服务器发出的各类流量;「问题反馈」的诊断信息增加本页下载量。 +- 部署指南:固定访问地址、反代开 HTTP/2、Cloudflare 缓存规则。 + ## 0.2.5 — 2026-10-12 ### 新功能 diff --git a/README.md b/README.md index c76e48ec..99e1a649 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ # 卫戍协议:盟约 · Stronghold Protocol: Alliance +> **开发版(dev 分支):不稳定,请勿用于公开服务器**。当前为 0.2.6-dev,尚未发布;稳定版请使用 Releases 中的 0.2.5。 + 《明日方舟》季节性自走棋塔防玩法「卫戍协议:盟约」的**非官方同人复刻**:浏览器即开即玩,单人或 1–4 人联机合作。 -![version](https://img.shields.io/badge/version-0.2.5-2ea44f) +![version](https://img.shields.io/badge/version-0.2.6--dev-2ea44f) ![license](https://img.shields.io/badge/code%20license-GPL--3.0--or--later-blue) ![node](https://img.shields.io/badge/node-22%20%7C%2024-339933) @@ -37,7 +39,7 @@ English summary: [below](#english). - **独立模拟**(单人)与**同盟模拟**(1–4 人**合作**,没有 PvP;空位可以加 AI 队友)。 - 服务器是一个 Node.js 程序,**战斗在各玩家的浏览器里模拟**(和官方一样),服务器只管经济与回合,一台低功耗小主机就能开服。 -- 当前版本 0.2.5:3D 棋盘按战场显示官方场景,新增「官方伤害数字」选项,首领每局随机配对,固定赠品和已展示的干员牌不再被库存阻断,并修复了 0.2.4 发布后玩家和 GitHub 上反馈的问题,详见 [CHANGELOG.md](CHANGELOG.md)。仍有少数规则按推断实现,与官方不一致的地方欢迎在 Issue 里反馈。 +- 当前开发版 0.2.6-dev(未发布):减轻开服电脑的流量——静音时不下载背景音乐、WebSocket 消息压缩、素材地址带内容哈希长期缓存、brotli 压缩。最近发布版 0.2.5:3D 棋盘按战场显示官方场景,新增「官方伤害数字」选项,首领每局随机配对,固定赠品和已展示的干员牌不再被库存阻断,并修复了 0.2.4 发布后玩家和 GitHub 上反馈的问题,详见 [CHANGELOG.md](CHANGELOG.md)。仍有少数规则按推断实现,与官方不一致的地方欢迎在 Issue 里反馈。 ## 功能一览 @@ -120,6 +122,7 @@ npm start # 启动服务器:http://localhost:3000 | `DEBUG` | 空 | 设为任意值输出详细日志 | | `SP_NO_BROWSER` | 空 | 设为 `1` 时启动脚本不自动打开浏览器 | | `SP_BOT_EMOTES` | 空 | AI 队友的对局表情回应(战斗、整备、合成、联防、收礼时即刻的 `m.emote` 广播);设为 `0` 时整体关闭 | +| `SP_ASSET_INDEX` | 空 | 素材地址带内容哈希、浏览器长期缓存(0.2.6 起默认开启,哈希存在 `.cache/asset-hashes.json`);设为 `0` 时关闭,素材清单原样下发 | 设置方式:macOS / Linux `PORT=8080 npm start`;PowerShell `$env:PORT=8080; npm start`;cmd `set "PORT=8080" && npm start`。健康检查:`GET /healthz`。 diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 50efc4c6..a491d1a4 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -77,7 +77,7 @@ so old imports keep working: `public/js/ui/gameLogic.js` (`public/js/ui/gameLogi | path | what | |---|---| | `server/index.js` | the process entry (`npm start`); `startServer()` wires `server/http/` | -| `server/http/` | `config.js` (environment), `websocket.js` (sessions, `/ws`), `static.js` (the mounts), `media.js`, `files.js` (MIME, gzip, ETag, ranges), `buildTag.js`, `routes.js` (`/healthz`), `common.js`, `boot.js` (a pending update package first, banner, shutdown) | +| `server/http/` | `config.js` (environment), `websocket.js` (sessions, `/ws`, permessage-deflate), `static.js` (the mounts, the `~` asset routes), `media.js`, `files.js` (MIME, brotli / gzip, ETag, ranges), `buildTag.js`, `routes.js` (`/healthz`), `traffic.js` (bytes sent by category and on the WebSocket, `/healthz?traffic=1`), `assetIndex.js` (the content hashes of `public/assets/` and `public/fonts/`, cached in `.cache/asset-hashes.json`), `assetViews.js` (the served `/data/assets.json` and `/data/local-assets.json`: every art URL with its hash segment; ASSETS.md), `common.js`, `boot.js` (a pending update package first, banner, shutdown) | | `server/net.js` | sessions and reconnect tokens, rate limits, message validation | | `server/lobby.js` | rooms, seats, AI seats, spectators; starts a `Match` | | `server/data.js` | loads `data/*.json` once (frozen) | @@ -131,7 +131,8 @@ data/*.json ──────────┬─▶ server/data.js ──── ├─▶ public/js/data.js ──────────▶ the UI └─▶ public/js/battle/runner.js ─▶ the browser's battles (setSimData) data/i18n/en.json ──────▶ public/js/data.js ──────────▶ the English game texts -public/assets/ ─────────▶ public/js/render/, public/js/audio.js (URLs listed in data/assets.json) +public/assets/ ─────────▶ public/js/render/, public/js/audio.js (URLs listed in data/assets.json, + served with content-hash segments: server/http/assetViews.js) ``` - **Game data.** `tools/build-data.mjs` downloads the official zh_CN tables into `.cache/gamedata/` (or reads them diff --git a/docs/ASSETS.md b/docs/ASSETS.md index 3145f9d9..d553e524 100644 --- a/docs/ASSETS.md +++ b/docs/ASSETS.md @@ -211,11 +211,11 @@ The `stem` of a Spine model is the upstream file name. Two examples: `char_107_l - **Fonts:** OTF/TTF files are converted to WOFF2 by a built-in encoder (`tools/assets/woff2.mjs`: Brotli with null transforms). - Its output was verified lossless against Google's reference `woff2` decoder. - `fonts.css` lists WOFF2 first and falls back to the original file. -- Images stay PNG. WebP conversion is not done: it would need a native dependency. The local-client board textures are the exception: `tools/local-extract/extract.py` (Python, where Pillow is already a dependency) writes WebP copies of the 12 textures the 3D board downloads (`WEBP`: colour maps lossy at quality 95 with the alpha and the RGB under transparent texels kept, normal and data maps lossless) and `data/local-assets.json` lists the copies; the PNGs stay beside them for `tools/crop-board-atlas.mjs`. `extract.py --webp` adds the copies to an existing extraction without the client. +- Images stay PNG. WebP conversion is not done: it would need a native dependency. The local-client board textures are the exception: `tools/local-extract/extract.py` (Python, where Pillow is already a dependency) writes WebP copies of the 12 textures the 3D board downloads (`WEBP`: colour maps lossy at quality 95 with the alpha and the RGB under transparent texels kept, normal and data maps lossless) and `data/local-assets.json` lists the copies; the PNGs stay beside them for `tools/crop-board-atlas.mjs`. The 19 local 玩法说明 pages get a WebP copy too (`GUIDE_WEBP_MODE`, lossless: 25.6 MB → 17.4 MB on the CN client's pages; lossy quality 90 would be 4.2 MB and waits for the maintainer's side-by-side look), listed in place of the PNG, which stays beside it; the mirror copies under `ui/guide/` stay PNG. `extract.py --webp` adds the copies to an existing extraction without the client. ## Manifest schema (`data/assets.json`) -All paths are URL paths relative to the site root, for example `/assets/char/avatar/char_002_amiya.png`. **Only entries whose files exist on disk are emitted.** When a key is missing, the client should use its fallback (research 07 §5.6). +All paths are URL paths relative to the site root, for example `/assets/char/avatar/char_002_amiya.png` — in the committed file; a server hands them out with a content-hash segment ("The committed manifest and the served manifests" below). **Only entries whose files exist on disk are emitted.** When a key is missing, the client should use its fallback (research 07 §5.6). ```js { @@ -470,6 +470,39 @@ Other renderer rules from research 07 §5.4–5.5: - **Missing unit SFX:** use `audio.sfx.battle.enemyHit` or a WebAudio blip (research 07 §6.4). - **Bond icons:** if the real glyph ever fails, the stored file is the nation camp logo. +## The committed manifest and the served manifests + +`data/assets.json` in git (and as `tools/fetch-assets.mjs` writes it) and `data/local-assets.json` (as +`tools/local-extract` writes it) hold plain URLs. Since 0.2.6 (host bandwidth, layer 1) the server hands out a view of +each (`server/http/assetIndex.js`, `server/http/assetViews.js`): + +- Shortly after the start (1 s) the server hashes every file under `public/assets/` and `public/fonts/` in the + background: SHA-256, the first 16 hex digits. The hashes are kept in `.cache/asset-hashes.json` by path + size + + mtime, so a restart only stats the files and reads none of the unchanged ones (12,691 files / 724 MB on the + maintainer's machine: 1.3 s for the first build, 0.25 s after that). A file whose size or mtime changed is hashed + again; a re-extraction, `setup --force` or a Docker rebuild then costs the players only the files whose bytes changed. +- `GET /data/assets.json` and `GET /data/local-assets.json` answer with every art URL carrying its file's hash as the + first segment: `/assets/char/avatar/char_003_kalts.png` → `/assets/~398f32e2ff78d9e6/char/avatar/char_003_kalts.png`, + `/fonts/~/…`. Audio keeps its `/assets/~/audio/….mp3` form; `public/js/media.js` asks for it as + `/media/~/…` (the download-manager route, `shared/media.js`). +- A Spine model's skeleton, atlas and pages carry one hash, the model's (SHA-256 of the files' hashes): pixi-spine finds + the atlas by the skeleton's name and the pages next to the atlas, so the URLs share a folder. In `data/assets.json` + every `{ skel, atlas, textures }` object is a model; in `data/local-assets.json` every `spine/…` group (the files a + `spineLocal` record names). +- The server strips the segment and serves the file at the plain path. When the segment names the file's current bytes + (its own hash, or its model's) the answer is `Cache-Control: public, max-age=31536000, immutable`; any other segment — + a page loaded before an update, a URL derived from another file's — gets the current file with `no-cache`, so an old + page keeps working. The ETag of every indexed file is its content hash (`"398f32e2ff78d9e6"`, plus `-br` / `-gz` when + compressed), on the plain URL too. +- A path segment, never `?v=`: `assets.js validSpine` matches `/\.skel$/`, `audio.js SKILL_MODE_FILE` the `.mp3` ending, + pixi-spine takes the atlas name from the skeleton's basename and resolves the pages against the atlas's folder — a + query string survives none of that. +- A URL the index has no hash for (the file is missing, or not hashed yet) stays plain; plain URLs work as before + (`public, max-age=86400`, revalidated after a day). +- Until the index is ready, with `SP_ASSET_INDEX=0`, or on a static host without this server, the manifests go out as + committed. The views are rebuilt in memory when a manifest or the hashes change; neither file is ever written by the + server, and the `hash` field is the committed one. The index lives in `.cache/` only and is never packaged. + ## Verification `node --test test/assets.test.js` covers the pure helpers: the resolver, the atlas normalizer, the format sniffers, WOFF2, audio banks, the plan id sets, the downloader against a fake network, and the self-heal of corrupt skeletons. diff --git a/docs/DEPLOY.md b/docs/DEPLOY.md index 9f1973c9..91fe4737 100644 --- a/docs/DEPLOY.md +++ b/docs/DEPLOY.md @@ -9,7 +9,7 @@ |---|---| | 服务器 CPU | 战斗在各玩家浏览器里模拟(DESIGN §14),服务器只负责回合、经济和校验:**每个房间每个作战回合约 1 ms CPU**。AI 队友 / 掉线玩家的战场由服务器模拟:作战开始时 3 个 AI 战场在开发机上约 0.2–0.5 s CPU,小主机上可能要几秒(分成 8 ms 小片执行,不会卡住其他房间)。`SP_VERIFY=all` 会复算每个真人战场,CPU 明显增加,小主机建议保持 `off` 或 `sample`。 | | 服务器内存 | 空闲约 100 MB,每个进行中的对局再增加几 MB。 | -| 网络 | 4 人对局中服务器每回合下行约 0.25 MB(DESIGN §14 实测)。首次进入游戏时浏览器要从主机下载所需的图片 / Spine 模型 / 音频(按需加载,之后走浏览器缓存),公网隧道带宽小时第一次会慢一些。 | +| 网络 | 4 人对局中服务器每回合下行约 0.25 MB(DESIGN §14 实测;0.2.6 起 1 KB 以上的 WebSocket 消息用 permessage-deflate 压缩,实测一局单人对局的服务器消息从 173 KB 降到 60 KB,约为原来的三分之一)。首次进入游戏时浏览器要从主机下载所需的图片 / Spine 模型 / 音频(按需加载,之后走浏览器缓存),公网隧道带宽小时第一次会慢一些。0.2.6 起服务器启动后在后台给素材算内容哈希(第一次约 1–20 秒,看机器和硬盘;之后只检查大小和修改时间),下发的素材清单里每个地址带上哈希:浏览器把图片、模型和音频缓存一年,服务器更新、重新解压或 Docker 重建之后,玩家只重新下载内容真的变了的文件。哈希存在 `.cache/asset-hashes.json`,删掉会重新计算;目录不可写(例如只读的容器)时只在内存里算。 | | 磁盘 | 素材约 550 MB(`public/assets`,含中文约 65 MB、日文约 85 MB 两套干员语音)+ 依赖约 125 MB(`node_modules`;整合包只带运行依赖,约 65 MB);可选的本地提取约 40 MB(`.venv-extract`)+ 70 MB 贴图(见第 6 节)。完整包解压后约 710 MB。 | | 玩家设备 | 支持 WebGL 的现代浏览器(Chrome / Edge / Firefox / Safari 最新版),电脑或手机平板(横屏)。老旧设备可在设置里调低画质或访问 `/?board=2d`。 | @@ -170,6 +170,8 @@ cloudflared tunnel --url http://localhost:3000 把输出的 `https://xxxx.trycloudflare.com` 发给朋友。页面是 https 时客户端自动改用 `wss://`,不需要任何配置;服务器会通过隧道转发的 `CF-Connecting-IP` 识别真实来源(`TRUST_PROXY=auto`)。临时隧道每次启动地址都不同,且没有可用性保证;需要固定地址请使用 Cloudflare 账号 + 自己域名的「命名隧道」。 +**固定访问地址能省很多流量**:浏览器的缓存、设置、统计和断线令牌都按地址(域名或 IP + 端口)分开保存。地址一换,对玩家来说就是一个新网站:每个人进游戏都要把图片、模型和音频重新下载一遍(第一局约 20–50 MB),设置和本机统计也看不到了。临时隧道每次重启都换域名,所以固定朋友圈子长期开服时,建议用命名隧道、Tailscale(2.1)或固定的公网 IP / 局域网 IP(1.3),让大家一直用同一个地址。 + ### 2.3 路由器端口转发 仅当你有**公网 IPv4**(很多宽带是运营商级 NAT,没有公网 IP,此时请用 2.1 / 2.2): @@ -219,7 +221,11 @@ server { } ``` -**HTTP/2**:客户端由数百个小脚本模块组成(0.2.0 起进入对局时约 340 个),隔着公网时建议让代理以 HTTP/2 提供页面:所有模块走同一条连接,远距离玩家首次进入对局明显更快。Caddy 默认就是 HTTP/2;Nginx 见上面的 `http2`。服务器本身只说 HTTP/1.1,局域网或本机游玩不受影响。 +**HTTP/2**:客户端由数百个小脚本模块组成(0.2.0 起进入对局时约 340 个),隔着公网时建议让代理以 HTTP/2 提供页面:所有模块走同一条连接,远距离玩家首次进入对局明显更快。Caddy 默认就是 HTTP/2;Nginx 见上面的 `http2`。服务器本身只说 HTTP/1.1,局域网或本机游玩不受影响。HTTP/2 省的是往返等待,不减少字节数。 + +**压缩**:服务器自己压缩脚本、样式、数据和 Spine 的 `.skel` / `.atlas`:浏览器支持 brotli 时用 brotli(0.2.6 起,质量 5,比 gzip 快且更小:实测 `.skel` 小约 27%、游戏数据 JSON 小约 26%、前端库小约 14%、脚本小约 5%),否则用 gzip;图片和音频本来就是压缩格式,原样发送。浏览器只在 HTTPS 页面(以及 `localhost`)上声明支持 brotli,所以通过代理或隧道的 https 地址访问时用 brotli,局域网里的 `http://192.168.x.x:3000` 这类地址用 gzip。代理不需要另开压缩(Caddy 的 `encode`、Nginx 的 `gzip` 遇到已经压缩的响应会跳过)。 + +**Cloudflare 缓存**(命名隧道或自己的域名经过 Cloudflare 时):Cloudflare 默认只缓存常见扩展名,`.skel`、`.atlas` 和没有扩展名的音频地址 `/media/…` 都不在其中,每个请求都会回到开服的电脑。在 Cloudflare 控制台的「缓存规则」里加一条:主机名是你的游戏域名、且 URI 路径以 `/assets/`、`/fonts/` 或 `/media/` 开头时「符合缓存条件」,边缘 TTL 选「使用源站的 Cache-Control」。0.2.6 起素材清单里的地址带内容哈希(`/assets/~<哈希>/…`),服务器给这类地址一年的 `immutable`,换了内容的文件会换地址,所以长期缓存是安全的;`/data/`、页面和脚本不要加进规则(它们要随服务器更新)。注意:边缘公开缓存官方素材会增加被投诉的风险,大量媒体文件也要留意 Cloudflare 的服务条款;只给自己人玩时不加这条规则也可以。 https / wss 说明:页面通过 https 打开时客户端自动连接 `wss://同一域名/ws`;http 时用 `ws://`。服务器本身只提供 http,证书由代理 / 隧道负责。代理与服务器在同一台机器或内网时,`TRUST_PROXY=auto` 会信任它的 `X-Forwarded-For` / `X-Real-IP`;代理在公网另一台机器上时设 `TRUST_PROXY=1`(同时确保游戏端口只对代理开放)。 @@ -289,6 +295,8 @@ services: | 表情显示成默认图标、「玩法说明」只有文字要点 | 素材没下载完整:重新运行 `node tools/setup.mjs`(表情和教程图随其他素材一起从公开镜像下载,不需要客户端);缺失明细在 `.cache/assets-report.json` | | 本地提取失败 | 游戏照常运行,只是第 6 节表格里的几样换成替代样式。确认客户端已下载全部资源;Python 版本太新导致依赖安装失败时,安装 Python 3.12 后删除 `.venv-extract` 再运行 `node tools/setup.mjs --local` | | 3D 棋盘没出现 | 需要本地提取的棋盘贴图(`node tools/doctor.mjs` 会显示「3D 棋盘可用」),以及支持 WebGL2 的浏览器。没有客户端的服务器可以从同一版本的整合包复制本地素材(第 6 节) | +| 素材地址里的 `~` 加一串字母数字 | `/assets/~<哈希>/…` 是 0.2.6 起的带版本地址(见第 0 节「网络」),浏览器可以长期缓存,属于正常现象。怀疑它导致问题时,可以用 `SP_ASSET_INDEX=0` 启动服务器临时关闭(清单改回普通地址),并请在 issue 里说明 | +| 想知道开服电脑上传了多少流量 | 浏览器打开 `http://localhost:3000/healthz?traffic=1`(换成你的端口):`traffic.http` 是服务器启动以来各类内容(`assets` 图片和模型、`audio` 音频、`code` 页面和脚本、`data` 游戏数据和素材清单)发出的字节数和请求数(压缩后的实际字节,`notModified` 是只回了「没变」的 304),`traffic.ws` 是 WebSocket 的线上字节(`wireOut` / `wireIn`,压缩后)和压缩前的消息字节(`payloadOut` / `payloadIn`)。数字只在内存里,重启后从 0 开始。玩家那边:设置 →「问题反馈」复制的诊断里有一行 `traffic:`,是这个页面从打开起下载的字节数(`cached` 是浏览器缓存直接给的,不占流量;`external` 是其他网站,例如 Google 字体) | | 断线 | 同盟模拟 10 分钟内、独立模拟 24 小时内(`config.constants.singleReconnectTime`)用同一浏览器重新打开页面,自动回到原座位。同盟掉线期间按原阵容自动作战、到时自动准备(不会代为购买;想让 AI 代打请用「离开模拟 → 暂离(AI 托管)」);独立模拟不计时,等你回来 | ## 6. 本地客户端素材(可选) @@ -315,6 +323,8 @@ services: **3D 棋盘贴图的下载量**:每位玩家进入对局时都要从开服的电脑下载 3D 棋盘的 12 张贴图。提取时会给这 12 张各写一份 WebP(颜色贴图有损、质量 95,法线和数据贴图无损),清单里列的是 WebP,同名 PNG 留在旁边给裁切工具和 setup 用。这部分下载量从约 6.7 MB 降到约 2 MB,网速慢的远程联机最明显。只有 PNG 的本地素材(例如在这一改动之前提取的)可以用提取时的 Python 环境运行 `tools/local-extract/extract.py --webp` 就地补上,只需要 Pillow,不需要客户端。 +**「玩法说明」教程图的下载量**(0.2.6 起):本地提取的 19 页教程图每页 1.2–1.5 MB,玩家每翻一页都要从开服的电脑下载。提取时同样给每页写一份无损 WebP,清单列 WebP,PNG 留在旁边;19 页合计从约 25.6 MB 降到约 17.4 MB,画面完全不变。看说明时只预载下一页(以前前后两页都预载)。已经提取过的同样用 `tools/local-extract/extract.py --webp` 补上。 + ## 7. 打包发布(维护者) Releases 的 zip(完整包、精简包,0.2.1 起还有更新包)由 `tools/package.mjs` 生成,在**源码仓库**里运行(整合包里没有这个工具): diff --git a/docs/DESIGN.md b/docs/DESIGN.md index 5bb042d2..245ce678 100644 --- a/docs/DESIGN.md +++ b/docs/DESIGN.md @@ -4,7 +4,7 @@ This is the **single source of truth** for every implementer. Research lives in Language: player-facing text is **Simplified Chinese** by default, with an English switch since 0.2.0 (§25.2, docs/I18N.md: UI strings through `t('中文')`, game texts from the official Chinese data or the official EN client's). Code, comments and identifiers are English. -Versions: the first public release was **0.1.0** (2026-10-02, the state of §0–§20.15); the releases after it add the player feedback and GitHub reports — 0.1.1 §21, 0.1.2 §22, 0.1.3 §23, 0.1.4 §24 — and **0.2.0** (2026-10-07; `CHANGELOG.md`) the maintainability refactor, two languages, 补位, 自选编队 and their fidelity work — §25 — **0.2.1** (2026-10-07) the 联防 battlefield restored, full potential and the GitHub fixes after it — §26 — and **0.2.2** (2026-10-09) per-operator 潜能 / 练度, Japanese voices, the statistics page, 失衡, whole-frame attack timing and the GitHub fixes after 0.2.1 — §27. **0.2.3** (2026-10-10; `package.json`, `shared/constants.js APP_VERSION`) 克莱门莎 and new modules, community fixes, text size, per-operator voices, installation, the opening reroll and local match recovery — §28. **0.2.4** (2026-10-11) the official shared card pool and item stock, Raid revival and #475, and the community fixes after 0.2.3 — §29. **0.2.5** (2026-10-12) fixed gifts and already displayed operator offers under the shared stock, random boss pairing, the official battlefield scenes on the 3D board (optional local art: the full bundle includes them when extracted, a missing scene keeps the metal board; §15, §30.21), the official damage-number option, the 驭械术师 / hit-tile / bot ports and the community fixes after 0.2.4 — §30, the state described by this document; its rules supersede the corresponding 0.2.4 ones. The labels v1 / v2 / v2.1–v2.5.2 in §0, §14–§20 and in the BALANCE / SIM comparisons name the design generations and the private playtest builds that came before it; they are kept as history. +Versions: the first public release was **0.1.0** (2026-10-02, the state of §0–§20.15); the releases after it add the player feedback and GitHub reports — 0.1.1 §21, 0.1.2 §22, 0.1.3 §23, 0.1.4 §24 — and **0.2.0** (2026-10-07; `CHANGELOG.md`) the maintainability refactor, two languages, 补位, 自选编队 and their fidelity work — §25 — **0.2.1** (2026-10-07) the 联防 battlefield restored, full potential and the GitHub fixes after it — §26 — and **0.2.2** (2026-10-09) per-operator 潜能 / 练度, Japanese voices, the statistics page, 失衡, whole-frame attack timing and the GitHub fixes after 0.2.1 — §27. **0.2.3** (2026-10-10; `package.json`, `shared/constants.js APP_VERSION`) 克莱门莎 and new modules, community fixes, text size, per-operator voices, installation, the opening reroll and local match recovery — §28. **0.2.4** (2026-10-11) the official shared card pool and item stock, Raid revival and #475, and the community fixes after 0.2.3 — §29. **0.2.5** (2026-10-12) fixed gifts and already displayed operator offers under the shared stock, random boss pairing, the official battlefield scenes on the 3D board (optional local art: the full bundle includes them when extracted, a missing scene keeps the metal board; §15, §30.21), the official damage-number option, the 驭械术师 / hit-tile / bot ports and the community fixes after 0.2.4 — §30; its rules supersede the corresponding 0.2.4 ones. **0.2.6-dev** adds the host-bandwidth layers 0 and 1 (no BGM download while the music is silent, WebSocket compression, content-hashed asset URLs with long caching, brotli) — §31, the current development state described by this document. The labels v1 / v2 / v2.1–v2.5.2 in §0, §14–§20 and in the BALANCE / SIM comparisons name the design generations and the private playtest builds that came before it; they are kept as history. --- @@ -37,3 +37,4 @@ normative lines it rewrote). | §28 | [history/0.2.3.md](history/0.2.3.md) | 0.2.3 — after the 0.2.2 release (2026-10-10) | | §29 | [history/0.2.4.md](history/0.2.4.md) | 0.2.4 — after the 0.2.3 release (2026-10-11) | | §30 | [history/0.2.5.md](history/0.2.5.md) | 0.2.5 — after the 0.2.4 release (2026-10-12) | +| §31 | [history/0.2.6.md](history/0.2.6.md) | 0.2.6-dev — after the 0.2.5 release | diff --git a/docs/PLAYING.md b/docs/PLAYING.md index da9b8753..f25892df 100644 --- a/docs/PLAYING.md +++ b/docs/PLAYING.md @@ -184,7 +184,7 @@ 标题画面页脚的「项目仓库」在新标签页打开本项目的 [GitHub 仓库](https://github.com/sganggs/Stronghold-Protocol)。 -遇到报错、卡住或结果不对时,打开「设置」→「问题反馈」,点「复制诊断信息」,再到 [GitHub issue](https://github.com/sganggs/Stronghold-Protocol/issues) 里描述发生了什么并粘贴进去。诊断信息包括游戏版本、浏览器和设备、当前所在的阶段与回合,以及打开页面以来记录到的错误(最多保留最近 40 条)。战斗中复制时,默认附上这场战斗的数据,开发者可以用它重现这场战斗;不想附上可以关掉「附上本场战斗」。诊断信息只在你的浏览器里生成,不会自动上传;你和其他玩家的名字、房间号会被替换成 ``、``、`` 这样的占位符。剪贴板不可用时(部分 App 内置浏览器),内容会显示在下方的文本框里,手动全选复制即可。 +遇到报错、卡住或结果不对时,打开「设置」→「问题反馈」,点「复制诊断信息」,再到 [GitHub issue](https://github.com/sganggs/Stronghold-Protocol/issues) 里描述发生了什么并粘贴进去。诊断信息包括游戏版本、浏览器和设备、当前所在的阶段与回合、打开页面以来按类别统计的下载量(图片和模型、音频、代码、数据),以及打开页面以来记录到的错误(最多保留最近 40 条)。战斗中复制时,默认附上这场战斗的数据,开发者可以用它重现这场战斗;不想附上可以关掉「附上本场战斗」。诊断信息只在你的浏览器里生成,不会自动上传;你和其他玩家的名字、房间号会被替换成 ``、``、`` 这样的占位符。剪贴板不可用时(部分 App 内置浏览器),内容会显示在下方的文本框里,手动全选复制即可。 ## 13. 统计(本机) diff --git a/docs/design/client.md b/docs/design/client.md index b0b94b44..b0f14202 100644 --- a/docs/design/client.md +++ b/docs/design/client.md @@ -40,6 +40,8 @@ view.resize() ; view.destroy() `createFieldView(host, { …, signal })` takes an `AbortSignal` (0.2.2, GitHub PR #302 by @siruimei07): an abort during the build — the Pixi load, the manifest, the fonts, the board art and the 3D board waits — destroys what the attempt made (the canvas, the ticker, the listeners, the observers) and rejects, a failure while it is built releases the same partial resources, and `view.destroy()` is idempotent. `ui/fieldHost.js mountFieldView(host, { signal })` aborts that signal when the engine fails, times out (12 s) or the owner unmounts, disposes a view a factory returns after that, and never clears the other children of `host` — the simplified view and a newer mount share it. +Asset URLs (0.2.6, host bandwidth layer 1): the client takes every art, model and audio URL from `data/assets.json` and `data/local-assets.json` and builds none itself, so the content-hash segment the server puts in front (`/assets/~/…`, docs/ASSETS.md "The committed manifest and the served manifests") needs nothing on this side: `validSpine` still sees `.skel`, pixi-spine finds the atlas and its pages under the same segment (a model shares one hash), audio is fetched as `/media/~/…`. The two URLs the client derives from another file's — the 3D board's `tiles.json` beside the atlas and the token death sound beside `charDie` — are served `no-cache` (the board) or drop the segment (`shared/assetPaths.js unhashedUrl`, the sound). + Visuals: oblique perspective board (tilted ~30°, trapezoid tiles), raised highland blocks with side faces, road/floor/forbidden styles per research 07 §7, pulsing red gates, blue objective, dashed hand pads. Units: Spine (Front/Back rule, feet anchored — flying units hover `FLY_HOVER` 1.3 tiles up, the client's 0.35 in character space, research 12, §25.13.5 — an enemy flyer from the road whatever tile it crosses (GitHub #277) —, shadow sprite on the ground), elite gold outline glow, tier chip, HP bar (green ally / red enemy), SP bar (skill ready glow; while an ammo skill runs it is the magazine instead — a yellow cell per round, emptying from the right, `b.snap ammo`, and the skill draws no standing aura, UnitInfo `ammoSkill`), 斩业星熊's 我执 pool as a red bar over her drained HP bar (`b.snap neg`), 伺夜's 狼群 count as a row of diamonds under the bars, the lit ones the 狼影 left (`b.snap wolves`; 0.2.2, GitHub PR #303 / #378 / #383), status icons, the element gauge row under the bars — icon + white bar of the remaining 元素值, element-coloured refill during a 爆发冷却 (§18.3, §20.8); enemies drawn × their official prefab factor (enemies.json `modelScale`, §20.4); an enemy's mode — the `form` of a sim fx (`shared/protocol.js fxForm`), or UnitInfo `form` for a view built later through `render/app/info.js renderInfo` — switches clip sets (`render/units.js FORMS`: 掠海漂移体 crawl, 暴鸰 bombed, 转译基底's forms, the 逐火 embers, the leaders' 重生, 守墓石像, the 孤岛风云 prisoners' warning and 解放; closing clips timed from the fx `dur`), a one-off cast (`PROJ[kind].once`) plays once, and a local-only model's web alias is tinted (`ALIAS_TINT`: 灼热 / 炽焰源石虫, §21.14); damage numbers (phys orange-white, arts purple, true white, heal green); projectiles drawn per kind, hit sparks and melee slashes, skill activation bursts and auras (§17.3); death fade for enemies, summons and devices — a knocked-out operator stays on its tile in its held Die pose under a redeploy ring (§18.3); leak flash at the objective. Fallback when Spine missing/failed: avatar in a rarity-coloured diamond with bob/lunge tweens — a failed or timed-out model is loaded again (bounded), and a view re-resolves its model and avatar when the asset manifest arrives late or the tab is shown again (§21.27). 60 fps target with ≤ 120 units (a crowd draws its Spine units through the cached atlas, `render/impostor.js`, each refreshed every k-th frame: the refresh turns follow this frame's update order — `ctx.impostorSlot()`, a counter reset at the start of every frame — so a frame refreshes ⌊n/k⌋ or ⌈n/k⌉ of n units instead of whatever random per-unit phases gave, and a unit not refreshed for 2k frames is refreshed regardless; GitHub PR #334 by @Cloudnyco, issue #327 step 1 — its step 2, a time budget by priority, is not done; a model whose pose cannot change — `SpineActor.poseHeld()`: a knocked-out operator in the held end of its Die clip, a frozen model — is neither re-posed nor redrawn, only its clock runs, until a new clip, a revive, a wind-up, a form's closing clip, a clipping switch or a zoom past the impostor's rescale threshold; the redeploy rings draw one shared rasterised label per number, `render/textures.js downLabel`, the same pixels as a Text of their own). Picking (which unit a press / hover / dropped item is on) and the drag target follow one rule, `render/pick.js` — the tile under the pointer (§18.1); the Spine store never hands out a skeleton whose unload is in flight (§17.1). --- @@ -62,7 +64,7 @@ its board-space position and facing, including on a mirrored boss half. They can from this preview. The inspection affordance does not make the preview a combat unit; the battle sim still creates the selected variant at battle start (§30.22). -Audio: autochess BGM per phase, UI SFX (buy/sell/refresh/level/merge/ready/timer), per-unit attack/hit SFX (throttled; an impact plays for a hostile attack's phys / arts / true damage only, never an operator's skill-mode file for a normal attack, ≤ 2 copies of one battle sound — §18.4; a skill cue that reaches the client before its unit — the sim emits a deploy-tick cast ahead of the unit's `['spawn']` — is held and sounds once when the unit is tracked, `AudioManager.pendingSkill`, GitHub PR #292 by @LimitlessHPPK; entering a field late hands the sound the buffered `spawn` tuples only, `screens/game/early.js audioEarly`, so no old death, deploy or cast replays), boss music in R14/15. +Audio: autochess BGM per phase, UI SFX (buy/sell/refresh/level/merge/ready/timer), per-unit attack/hit SFX (throttled; an impact plays for a hostile attack's phys / arts / true damage only, never an operator's skill-mode file for a normal attack, ≤ 2 copies of one battle sound — §18.4; a skill cue that reaches the client before its unit — the sim emits a deploy-tick cast ahead of the unit's `['spawn']` — is held and sounds once when the unit is tracked, `AudioManager.pendingSkill`, GitHub PR #292 by @LimitlessHPPK; entering a field late hands the sound the buffered `spawn` tuples only, `screens/game/early.js audioEarly`, so no old death, deploy or cast replays), boss music in R14/15. While the music is silent — muted, or the BGM volume at 0 — no BGM is downloaded: the track the screen wants is remembered, a different one still playing stops, and the wanted track is fetched once the music is audible again (`AudioManager.bgmSilent`; about 14 MB a match for a player who turned the music off). --- @@ -73,7 +75,7 @@ Audio: autochess BGM per phase, UI SFX (buy/sell/refresh/level/merge/ready/timer - `scene//` and `scene/tex/` — the official scene of a battlefield (§15 "Official battlefield scenes", DESIGN §30.21): `scene.json` (materials, key light, chunk records), `scene.bin` (the meshes in board space), the lightmap pages `lm`, and the materials' albedo textures shared by the scenes. Read from the scene bundles `scenes/activities//level_/…`, which the client carries only while the season runs: `extract.py --only scene` takes them from the client or from `--scenes ` / `.cache/official-scenes/*` (`tools/local-extract/fetch_scenes.py` downloads them from the official CDN's in-season version). The 0.2.5 full release zip includes the extracted files when the maintainer extracted them before packaging; a lite zip and a source install may fetch and extract them (`node tools/setup.mjs --scenes`). The repository never stores the bundles or the extracted files. - `ui/{common,battle,outer}/*` — every sprite of the three official autochess UI bundles (tier chips I–VI, bond disc rings, frames, banners, HUD pieces, badges, backgrounds, mode art). - `emoticon//.png` — the 36 official battle emotes, 6 themes (`shared/constants.js → EMOTE_THEMES / EMOTES`, `emoteArtPath`; data/emotes.json); also downloaded from the mirror (§22.5). -- `guide/autochess_{home,shop,handbook}_N.png` — the 19 official tutorial pages; stored squashed to 1024² — **display at 16:9** (the mirror copies too, §22.5). +- `guide/autochess_{home,shop,handbook}_N.png` — the 19 official tutorial pages; stored squashed to 1024² — **display at 16:9** (the mirror copies too, §22.5). `extract.py` writes a lossless WebP copy beside each page and the manifest lists the copy (`GUIDE_WEBP_MODE`; 25.6 MB → 17.4 MB); the viewer preloads only the next page (`ui/guide.js guidePreloadUrl`), not the previous one too. - `projectiles/*` — battle projectile sprites. - `spine/enemy//` — enemy models no web dump carries (灼热 / 炽焰源石虫, `extract.py ENEMY_SPINES`): manifest `enemies[id].spineLocal` (metadata from the committed `tools/assets/local-enemy-spines.json`); drawn instead of the tinted web alias when every file is listed (§21.14). - `spine/token//` — token (summon) models no web dump carries (40: most 自选 summons, 凯瑟琳's 爬行号·防护单元, 凛御银灰's 风雪之眼; `extract.py TOKEN_SPINES`, the Front renderer's skeleton of each battle token prefab): manifest `tokens[id].spineLocal` (metadata from the committed `tools/assets/local-token-spines.json`); drawn instead of the avatar diamond when every file is listed (docs/ASSETS.md "Token models from the local client"). diff --git a/docs/design/network.md b/docs/design/network.md index 377ee918..98bff74b 100644 --- a/docs/design/network.md +++ b/docs/design/network.md @@ -4,7 +4,7 @@ Part of [DESIGN.md](../DESIGN.md) (the index; section numbers are global). ## 8. Network protocol (shared/protocol.js is normative) -Transport: one WebSocket per tab at `/ws`, JSON text frames `{ t: '', ...payload }`. Client requests may carry `rid` (request id); the server's direct reply echoes `rid` (`ok` or `error`). Server pushes have no `rid`. Max frame 64 KB inbound; rate limit 40 msgs/s per connection (excess dropped with `error RATE`). +Transport: one WebSocket per tab at `/ws`, JSON text frames `{ t: '', ...payload }`. Client requests may carry `rid` (request id); the server's direct reply echoes `rid` (`ok` or `error`). Server pushes have no `rid`. Max frame 64 KB inbound (a compressed frame counts its inflated size); rate limit 40 msgs/s per connection (excess dropped with `error RATE`). Frames from 1 KB up are compressed with permessage-deflate (RFC 7692; `server/http/websocket.js WS_DEFLATE`: no server context takeover, a 2 KB server window, zlib memLevel 7 — about 72 KB of zlib state per connection); smaller frames go out plain, and a client that offers no compression, or caps the server window below 2 KB, gets plain frames. A measured solo session (rounds 3–5, `/healthz?traffic=1`): 173 KB of server frames → 60 KB on the wire. ### 8.1 Session & lobby C→S: `hello {name, token?, version}` · `room.create {mode:'solo'|'coop', difficulty}` · `room.join {code}` · `room.leave` · `room.ready {ready}` · `room.setDifficulty {difficulty}` (host) · `room.setAiPicksLast {on}` (host, co-op, before the match — `ROOM_STARTED` during it, `BAD_TARGET` in a solo room; un-readies the other humans like a difficulty change; the match takes it as `opts.aiPicksLast`: humans draft before AI seats, off by default, no extra random draw) · `room.addBot` / `room.removeBot {seat}` (host) · `room.kick {seat, playerId}` (host, before the match: another human leaves the room and gets `room.closed {reason:'kicked'}`; may join again; `playerId` = the player the host confirmed, a seat that changed hands meanwhile → `BAD_TARGET`) · `room.start` (host) · `room.loadout {entries, ops?}` (§16: any time in the lobby / room and during INFO_CHECK, then `WRONG_PHASE`; heavy rate-limit bucket; the match exposes it as `m.private.loadout`; `ops` — 0.2.2 — the per-operator 潜能 / 练度 `{ [charId]: { potential?: 1–6, cultivate?: 0–3 } }` of the 干员调配 roster and the 自选 owned pool, ≤ 256, checked strictly with the entries, `m.private.ops`; absent = none set: every operator 潜能 6, 精英2 Lv.60) · `room.ownership {notOwned}` (0.2.0 补位, the 干员持有 tab: the base chess ids marked as not owned — ≤ 160 ids, kept leniently: anything but a droppable NORMAL chess is dropped; stored on the session and the seat, a match takes the seat's list when it starts and never changes it — during a match `ROOM_STARTED` 'stored for the next match'; heavy bucket; the match exposes it as `m.private.standIns`) · `room.diy {picks}` (0.2.0 自选编队: `{ [slotBaseId]: { charId, skillIndex?, uniEquipId? } | null }` for the four DIY slots — ≤ 8 entries, kept leniently: shared/protocol.js `checkDiyPicks` drops an illegal pick (an operator without a kit, another tier's prototype, a prototype off its locked skill, a module of another game mode (集成战略 / 生息演算), an owned operator's second slot, the same operator twice in a tier, an unknown slot), only malformed picks are `BAD_MSG`; stored on the session and the seat like the not-owned list, a match takes the seat's picks when it starts — during a match `ROOM_STARTED` 'stored for the next match'; heavy bucket; the match exposes them as `m.private.diy`) · `ping {c}` diff --git a/docs/design/overview.md b/docs/design/overview.md index 875b7e69..0d2756ac 100644 --- a/docs/design/overview.md +++ b/docs/design/overview.md @@ -42,12 +42,18 @@ server/ index.js process entry: startServer() wires server/http/ (plain node:http + ws); boots when run directly http/ config.js ROOT, served dirs, env (PORT, HOST, TRUST_PROXY, DEBUG), options handed to net.js / lobby.js - websocket.js session wiring (SessionRegistry → Lobby → Network), WebSocket upgrade at /ws (64 KB frames) - static.js mounts / → public, /data/, /shared/, /sim/ (.js only), the /data.js browser stand-in, path guards + websocket.js session wiring (SessionRegistry → Lobby → Network), WebSocket upgrade at /ws (64 KB frames, + permessage-deflate from 1 KB) + static.js mounts / → public, /data/, /shared/, /sim/ (.js only), the /data.js browser stand-in, path guards, + the ~ segment of /assets/ /fonts/ /media/ URLs stripped (immutable when it names the file) media.js /media/… extension-less audio → public/assets/audio - files.js one file → response: MIME, gzip (.skel/.atlas/.json/.js/.css …), ETag / 304, cache policy, ranges + files.js one file → response: MIME, brotli q5 / gzip (.skel/.atlas/.json/.js/.css …), ETag (content hash when known) / 304, + cache policy, ranges; serveBuffer for the served manifests buildTag.js build tag of the served browser runtime (/healthz build, public/js/ui/buildGuard.js) - routes.js request listener: 414 / 400 / 405 guards, GET /healthz, then static files + routes.js request listener: 414 / 400 / 405 guards, GET /healthz (?traffic=1: the counters), then static files + traffic.js traffic counters: HTTP body bytes by category (assets / audio / code / data), WebSocket wire / payload + assetIndex.js content hashes (SHA-256, 16 hex) of public/assets + public/fonts, background build, .cache/asset-hashes.json + assetViews.js the served /data/assets.json + /data/local-assets.json: art URLs as /assets/~/… (immutable when it matches) common.js security headers, URL split, error page, JSON replies, bare 400 for unparseable requests boot.js boot banner (Local / LAN / tunnel URLs), port-in-use hint, graceful SIGINT / SIGTERM net.js session registry, send helpers, per-connection rate limit, message validation (uses shared/protocol.js) diff --git a/docs/history/0.2.6.md b/docs/history/0.2.6.md new file mode 100644 index 00000000..03f44202 --- /dev/null +++ b/docs/history/0.2.6.md @@ -0,0 +1,95 @@ +# DESIGN §31 — 0.2.6-dev + +Part of [DESIGN.md](../DESIGN.md). Development after the 0.2.5 release. + +## 31. Host bandwidth, layers 0 and 1 + +Unreleased. The maintainer's decision of 2026-10-12 on the bandwidth study (its measurements: a new player's first match costs the +host about 52 MB, audio ≈ 40 % of it; returning players re-download after a re-extraction, a `setup --force`, a Docker +rebuild or a changed tunnel address): do layer 0 (small fixes) and layer 1 (content-hashed URLs, long caching, brotli) +first. Later layers (WebP / Opus variants, an asset-only service worker, a desktop client mode, importing an asset pack in +the browser) are agreed and not part of this note. Nothing here touches the battle sim, the protocol messages or the +committed data. + +### 31.1 Layer 0 — small fixes + +- **No BGM while the music is silent.** Muted, or the BGM volume at 0, `AudioManager.playBgm` only remembers the wanted + track (a different one still playing stops); `setVolumes` fetches and starts it once the music is audible again. SFX + and voices were already gated. Normative line: design/client.md Audio. +- **WebSocket permessage-deflate** (`server/http/websocket.js WS_DEFLATE`): frames from 1 KB, no server context + takeover, a 2 KB server window, zlib memLevel 7 (about 72 KB of zlib state per connection). [ASSUMED] the parameters + come from measured solo sessions (the server counters: 173 KB of frames → 60 KB on the wire; replaying 216 captured + frames, windows above 2 KB gained nothing); co-op messages are the same kinds. A client that offers a narrower server + window than 2 KB, which ws would refuse with a 400, connects uncompressed instead (`narrowDeflateOffer`). Normative + line: design/network.md §8 Transport. +- **玩法说明 pages as WebP.** `tools/local-extract/extract.py` writes a WebP copy beside each of the 19 local pages and + the manifest lists it (`GUIDE_WEBP_MODE`); the guide preloads only the next page instead of both neighbours. The + copies are lossless (25.6 MB → 17.4 MB on the CN client's pages). Lossy quality 90 would make them 4.2 MB; per the + decision that tutorial pages may go lossy only after a side-by-side comparison, that switch (one constant, then + `extract.py --webp`) is left to the maintainer. Normative lines: design/client.md §13, ASSETS.md Post-processing. +- **Traffic counters.** `GET /healthz?traffic=1` adds `traffic` (HTTP body bytes and requests by category — assets, + audio, code, data, other — and 304s; WebSocket wire bytes after compression and payload bytes before it) and + `assetHashes` (the index state). The 问题反馈 diagnostics gain a `traffic:` line: the page's Resource Timing + `transferSize` by the same categories (`shared/assetPaths.js trafficCategory`), other sites apart. Nothing is stored + or uploaded. +- **DEPLOY.md**: a stable address keeps every player's cache, settings and reconnect token (a quick tunnel's new domain + is a new site to the browser); HTTP/2 through the proxy saves round trips, not bytes; browsers offer brotli on HTTPS + pages and localhost only; a Cloudflare cache rule for `/assets/`, `/fonts/`, `/media/` (with the risk note). + +### 31.2 Layer 1 — content-hashed URLs, long caching, brotli + +- **Content-hash index** (`server/http/assetIndex.js`): 1 s after the start, SHA-256 (16 hex) of every file under + `public/assets/` and `public/fonts/` (dot names skipped, linked folders followed once), computed off the main thread, + cached in `.cache/asset-hashes.json` by path + size + mtime (12,691 files / 724 MB here: 1.3 s the first time, 0.25 s + after). A file whose size or mtime differs from its record is never vouched for; serving it asks for a rescan (at most + one per 10 s). [ASSUMED] the 1 s delay and the 10 s rescan gap. A name that differs from a file's only in case finds + that file (the manifest's `/assets/module/wah-y.png` is `WAH-Y.png` on this machine). `SP_ASSET_INDEX=0` turns it off. +- **Served manifests** (`server/http/assetViews.js`): `/data/assets.json` and `/data/local-assets.json` go out with every + art URL carrying its file's hash as the first segment (`/assets/~/…`, `/fonts/~/…`; audio stays + `/assets/~/audio/….mp3`). A Spine model — a `{ skel, atlas, textures }` object of data/assets.json, a `spine/…` + group of data/local-assets.json — carries one hash for all its files, since pixi-spine finds the atlas and the pages + next to the skeleton. `no-cache` with the view's own ETag; rebuilt in memory when a manifest or the hashes change; the + committed files are never written. Until the index is ready, without it, or on a static host: the files as committed. +- **The `~hash` routes**: `static.js` strips the segment for `/assets/`, `/fonts/` and `/media/`; a hash that names the + file's current bytes (its own or its model's) answers `public, max-age=31536000, immutable`, any other the current + file with `no-cache` (an old page keeps working). Every indexed file's ETag is its content hash, on plain URLs too. + Path segments, never `?v=`: `validSpine`'s `/\.skel$/`, `SKILL_MODE_FILE`'s `.mp3`, pixi-spine's basename and folder + resolution all need the URL to end in the file name. +- **Media**: `public/js/media.js` turns `/assets/~/audio/x.mp3` into `/media/~/x`; `server/http/media.js` + resolves it like `/media/x`. The token death sound derived next to `charDie` drops `charDie`'s hash (`unhashedUrl`). +- **Brotli** (`server/http/files.js`): quality 5 on the fly with the same memory cache (one entry per file and + encoding), for clients that name `br` at least as high as gzip; gzip for the rest (`*` alone never picks brotli + [ASSUMED]); `-br` / `-gz` ETag suffixes. Measured against gzip-6 on this repository: `.skel` −27 %, `data/*.json` + −26 %, vendor −14 %, `public/js` and `server/sim` −5 %, `.atlas` −7 %. + +### 31.3 Measured sample session + +Measured sample session (headless Chrome, a fresh profile, `test/e2e/fastServer.mjs` solo match from round 3 to the +result after round 5, host bytes only, response headers included; the shop and the enemies vary between runs): + +| session | code | data | assets | audio | WebSocket (server → client) | host total | +|---|---:|---:|---:|---:|---:|---:| +| before, music on | 3.16 MB | 0.67 MB | 9.0–9.7 MB | 7.9 MB | 163–179 KB (no compression) | 20.8–21.4 MB | +| after, music on | 2.95 MB | 0.62 MB | 9.5 MB | 8.0 MB | 60 KB on the wire (173 KB payload) | 21.1 MB | +| before, muted | 3.16 MB | 0.67 MB | 9.6 MB | 7.3 MB (BGM) | 165 KB | 20.7 MB | +| after, muted | 2.95 MB | 0.62 MB | 9.5 MB | 0 | 57 KB on the wire | 13.1 MB | + +A first visit with music on saves little (brotli on code and data, the WebSocket); a muted player saves the BGM. The +caching gains are for returning players: within a day both versions answer from the browser cache, but after that the +old version revalidated every asset of the session (≈ 340 requests here) and re-downloaded everything whose mtime had +changed, while a hashed URL is never asked for again until its bytes change. + +### 31.4 Open items and tests + +Open: `/fonts/fonts.css` (linked by index.html) and the woff2 files it names keep plain URLs (content ETags only); the +optional versioned vendor URLs (layer 1.5) are not done; lossy tutorial pages wait for the comparison. + +Tests: `test/ui/audio.test.js` (BGM gating; hashed audio through `/media/~hash/`), `test/ws-compression.test.js`, +`test/local-extract.test.js` (guide WebP), `test/ui/localArt.test.js` (next-page preload), `test/traffic.test.js`, +`test/asset-paths.test.js`, `test/diag.test.js` (traffic line), `test/asset-index.test.js` (index, views, `~hash` +routes), `test/lobby.test.js` (brotli negotiation, streamed brotli, content ETags), `test/media-url.test.js`, +`test/content/tokens_summons.test.js`; the browser suites `test/render/browser.test.js` (Spine through hashed URLs, +`RENDER_E2E=1`), `test/ui/bond-audio.e2e.test.js` (`SP_E2E=1`, the cue through `/media/~hash/`) and +`test/ui/real.e2e.test.js` (`SP_REAL_E2E=1`: the co-op run loads Spine, audio and art through hashed URLs). The e2e +servers wait for the asset index before the first page (`test/e2e/client.mjs startRealServer`, the in-process ones in +their `before`), so the browser suites see the URLs a player sees. Golden: unchanged. diff --git a/package-lock.json b/package-lock.json index fd397922..3224750d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "stronghold-protocol-alliance", - "version": "0.2.5", + "version": "0.2.6-dev", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "stronghold-protocol-alliance", - "version": "0.2.5", + "version": "0.2.6-dev", "hasInstallScript": true, "license": "GPL-3.0-or-later", "dependencies": { diff --git a/package.json b/package.json index 56058776..1720a507 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stronghold-protocol-alliance", - "version": "0.2.5", + "version": "0.2.6-dev", "private": true, "description": "明日方舟「卫戍协议:盟约」非官方同人联机网页复刻(1–4 人合作,Node.js 服务器 + 浏览器客户端)", "license": "GPL-3.0-or-later", diff --git a/public/js/audio.js b/public/js/audio.js index 53cb8686..6feeaa7b 100644 --- a/public/js/audio.js +++ b/public/js/audio.js @@ -13,7 +13,9 @@ // never block or warn; everything requested before that is remembered (BGM) or dropped (SFX). // - Channels: master → { bgm, sfx, voice } gains; volumes from settings (0..1) + mute. Tab hidden ⇒ suspend. // - BGM: `intro` then `loop` (1 s crossfade); switching tracks fades out/in (0.8 s). The same loop URL -// keeps playing across phases (prep and combat share a track). +// keeps playing across phases (prep and combat share a track). While the music is silent — muted, or the BGM volume +// at 0 — no track is downloaded (≈ 14 MB a match): the wanted one is remembered, another one playing stops, and the +// track the screen wants then starts once the music is audible again (`setVolumes`; host bandwidth, layer 0). // - 开战 BGM: `bgm.combatAlts` are the mode's own battle tracks (塞壬唱片 骑士之日 / 无畏者). The track is fixed per // round, not drawn: 无畏者 through rounds 1–7 and 骑士之日 from round 8 on (`combatTrackFor`, the official // schedule), so every client of a match hears the same one, a fight never switches track halfway through and the @@ -68,6 +70,7 @@ import { sanitizeVoiceOverrides, voiceLangFor } from './voicePrefs.js'; import { PHASE } from '../../shared/constants.js'; import { mediaUrl } from './media.js'; +import { unhashedUrl } from '../../shared/assetPaths.js'; const MAX_VOICES = 8; const UNIT_COOLDOWN_MS = 160; @@ -191,11 +194,14 @@ export function unitSoundClass(info) { return 'char'; } -/** URL of the generic token death sound (b_char_tokendead): sfx.battle.tokenDie, else next to charDie. */ +/** + * URL of the generic token death sound (b_char_tokendead): sfx.battle.tokenDie, else next to charDie — without charDie's + * content-hash segment, which names charDie's bytes, not this file's (the plain URL is cached for a day). + */ function tokenDieUrl(manifest) { const b = manifest?.audio?.sfx?.battle; if (typeof b?.tokenDie === 'string') return b.tokenDie; - return typeof b?.charDie === 'string' && /b_char_dead\.mp3$/.test(b.charDie) ? b.charDie.replace(/b_char_dead\.mp3$/, 'b_char_tokendead.mp3') : null; + return typeof b?.charDie === 'string' && /b_char_dead\.mp3$/.test(b.charDie) ? unhashedUrl(b.charDie).replace(/b_char_dead\.mp3$/, 'b_char_tokendead.mp3') : null; } /** @@ -662,6 +668,7 @@ export class AudioManager { */ setVolumes(v) { const n = (x, d) => (Number.isFinite(x) ? Math.max(0, Math.min(1, x)) : d); + const wasSilent = this.bgmSilent; this.volumes = { bgm: n(v?.bgm, this.volumes.bgm), sfx: n(v?.sfx, this.volumes.sfx), @@ -670,8 +677,13 @@ export class AudioManager { }; this._applyVolumes(); if (this.volumes.muted || this.volumes.sfx <= 0) this.stopBondCue(); + // the music became audible again: download and start the track the screen wants now (none was fetched meanwhile) + if (wasSilent && !this.bgmSilent && this.ctx && this.wantBgm) { const k = this.wantBgm; this.wantBgm = null; this.playBgm(k); } } + /** Is the music silent — muted, or the BGM volume at 0? Then no BGM is downloaded (playBgm). */ + get bgmSilent() { return this.volumes.muted || this.volumes.bgm <= 0; } + /** * The voice dub (settings 语音语言): 'jp' plays `audio.voiceJp`, anything else `audio.voice` (中文, the default). The * line on air finishes in its own dub; the next one follows the setting. @@ -766,12 +778,23 @@ export class AudioManager { // ---- BGM ------------------------------------------------------------------------------------------------ /** - * Switch BGM (null stops). Same loop URL ⇒ no restart. + * Switch BGM (null stops). Same loop URL ⇒ no restart. Before the first gesture, or while the music is silent + * (`bgmSilent`), the key is only remembered (`wantBgm`) and nothing is downloaded; a different track that is still + * playing stops. `_unlock` / `setVolumes` start the remembered track once it can be heard. * @param {string|null} key see bgmKeyFor */ playBgm(key) { try { if (!this.ctx) { this.wantBgm = key; return; } + if (this.bgmSilent) { + this.wantBgm = key; + const silentTrack = resolveBgm(this.getManifest(), key); + if (this.bgm && silentTrack && this.bgm.loopUrl === silentTrack.loop) { this.bgm.key = key; return; } + ++this.bgmToken; // a start still waiting for its download stays silent too + this._fadeOutBgm(); + return; + } + this.wantBgm = null; const track = resolveBgm(this.getManifest(), key); if (this.bgm && track && this.bgm.loopUrl === track.loop) { this.bgm.key = key; return; } if (!track && !this.bgm) return; diff --git a/public/js/diag.js b/public/js/diag.js index 959ae1e2..4132fca7 100644 --- a/public/js/diag.js +++ b/public/js/diag.js @@ -5,19 +5,23 @@ // the room code and the reconnect token replaced and the page's host cut from every URL. A secret is a whole token in // the prose and an exact string value in the attached battle JSON, so a name never rewrites a longer id. The battle // on screen can be attached as its BattleSpec (the b.start a browser receives: player ids, no names), which the dev -// tools replay. +// tools replay. The report's `traffic:` line sums what this page downloaded (Resource Timing `transferSize`: bytes +// on the wire, 0 for a response from the browser cache) by the categories of shared/assetPaths.js trafficCategory, +// other sites apart as `external` (host bandwidth, layer 0; the server's own counters: /healthz?traffic=1). // // recordError(source, err, detail?) source: 'error' (uncaught) | 'rejection' (unhandled promise) | 'sim' (a content // error the battle isolated) | 'runner' (the local battle runner) | 'request' // (a failed request or error push the player was shown) // errorLog() / errorCount() / clearErrorLog() // setBattleSource(fn) the battle runner registers how to read the battle on screen +// installTrafficMeter() / recordResourceEntry(entry) / trafficSummary() / clearTraffic() the page's download totals // buildDiagnostics(input) the report text (pure: the state, the environment and the battle are passed in) // diagnosticsText({ state, settings, attachBattle }) the report of this page (this browser, the battle on screen) // // Report keys are English on purpose: the text is read by developers and searched in issues, whatever the UI language. import { APP_VERSION } from '../../shared/constants.js'; +import { TRAFFIC_CATEGORIES, trafficCategory } from '../../shared/assetPaths.js'; export const LOG_MAX = 40; export const STACK_LINES = 6; @@ -87,6 +91,78 @@ export const errorLog = () => log.map((e) => ({ ...e })); export const errorCount = () => total; export function clearErrorLog() { log.length = 0; total = 0; dropped = 0; } +// ---- traffic: what this page downloaded --------------------------------------------------------------------- + +/** @type {Map} category → totals */ +const traffic = new Map(); +let trafficMeter = null; + +/** + * Add one Resource Timing entry (a PerformanceResourceTiming, or the page's own navigation entry) to the totals: bytes + * on the wire (`transferSize`; headers included, 0 when the browser cache answered — counted as `cached`). A same-origin + * URL counts under trafficCategory(path), another site's under `external`; data: / blob: URLs are not downloads. + * @param {{ name?: string, transferSize?: number, decodedBodySize?: number }} entry + * @param {string} [origin] the page's origin + */ +export function recordResourceEntry(entry, origin = globalThis.location?.origin) { + if (!entry || typeof entry.name !== 'string') return; + let u; + try { u = new URL(entry.name, origin || 'http://localhost'); } catch { return; } + if (u.protocol !== 'http:' && u.protocol !== 'https:') return; + const cat = origin && u.origin !== origin ? 'external' : trafficCategory(u.pathname); + let t = traffic.get(cat); + if (!t) traffic.set(cat, (t = { requests: 0, bytes: 0, cached: 0 })); + const bytes = Number(entry.transferSize) || 0; + t.requests++; + t.bytes += bytes; + if (bytes === 0 && (Number(entry.decodedBodySize) || 0) > 0) t.cached++; +} + +/** + * Start summing this page's downloads (main.js at boot): the entries already in the Resource Timing buffer, then + * every new one (a PerformanceObserver also gets the entries a full buffer drops). False where unsupported. + * @param {any} [win] + */ +export function installTrafficMeter(win = globalThis) { + if (trafficMeter) return true; + const PO = win?.PerformanceObserver; + if (typeof PO !== 'function') return false; + try { + const origin = win.location?.origin; + for (const e of win.performance?.getEntriesByType?.('navigation') || []) recordResourceEntry(e, origin); + trafficMeter = new PO((list) => { for (const e of list.getEntries()) recordResourceEntry(e, origin); }); + trafficMeter.observe({ type: 'resource', buffered: true }); + return true; + } catch { + trafficMeter = null; + return false; + } +} + +/** The totals so far: `{ [category]: { requests, bytes, cached } }` in report order, plus `total`. */ +export function trafficSummary() { + const out = {}; + const total = { requests: 0, bytes: 0, cached: 0 }; + for (const cat of [...TRAFFIC_CATEGORIES, 'external']) { + const t = traffic.get(cat); + if (!t) continue; + out[cat] = { ...t }; + if (cat !== 'external') { total.requests += t.requests; total.bytes += t.bytes; total.cached += t.cached; } + } + out.total = total; + return out; +} +export function clearTraffic() { traffic.clear(); } + +const sizeOf = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(1)} MB` : n >= 1e3 ? `${Math.round(n / 1e3)} KB` : `${n} B`); +/** `assets 9.7 MB (254, 41 cached) | … | host total 21.4 MB (869)` — the report's traffic line; null when nothing was recorded. */ +export function trafficLine(summary) { + if (!summary || !summary.total || !(summary.total.requests > 0)) return null; + const parts = Object.entries(summary).filter(([k]) => k !== 'total') + .map(([k, t]) => `${k} ${sizeOf(t.bytes)} (${t.requests}${t.cached ? `, ${t.cached} cached` : ''})`); + return `${parts.join(' | ')} | host total ${sizeOf(summary.total.bytes)} (${summary.total.requests})`; +} + let battleSource = null; /** @param {() => ({ battleId: string, fieldId?: string, kind?: string, spec: object, time?: number }|null)} fn */ export function setBattleSource(fn) { battleSource = typeof fn === 'function' ? fn : null; } @@ -177,10 +253,10 @@ const join = (...parts) => parts.filter((p) => p != null && p !== '' && p !== fa * error log newest first) and, with `battle`, a ```json block of its spec. Secrets of `state` are whole tokens in the * prose and exact string values in the JSON. * @param {{ state: any, env?: any, settings?: any, battle?: any, entries?: any[], dropped?: number, total?: number, - * now?: number, pageStart?: number, version?: string }} input + * now?: number, pageStart?: number, version?: string, traffic?: ReturnType | null }} input */ export function buildDiagnostics(input) { - const { state = {}, env = {}, settings = null, battle = null } = input; + const { state = {}, env = {}, settings = null, battle = null, traffic: trafficTotals = null } = input; const entries = input.entries ?? errorLog(); const now = input.now ?? Date.now(); const lines = []; @@ -208,6 +284,8 @@ export function buildDiagnostics(input) { if (settings) { lines.push(`settings: ${join(`quality ${settings.quality}`, settings.damageNumbers ? 'damage numbers' : null, settings.officialDamageNumbers ? 'official damage numbers' : null, settings.muted ? 'muted' : null)}`); } + const tl = trafficLine(trafficTotals); + if (tl) lines.push(`traffic: ${tl}`); const shown = entries.slice().reverse(); const tot = input.total ?? total; const drop = input.dropped ?? dropped; @@ -265,5 +343,5 @@ export function browserEnv() { * @param {{ state: any, settings?: any, attachBattle?: boolean }} opts */ export function diagnosticsText({ state, settings = null, attachBattle = false }) { - return buildDiagnostics({ state, settings, env: browserEnv(), battle: attachBattle ? currentBattle() : null }); + return buildDiagnostics({ state, settings, env: browserEnv(), battle: attachBattle ? currentBattle() : null, traffic: trafficSummary() }); } diff --git a/public/js/main.js b/public/js/main.js index f40b6545..52782875 100644 --- a/public/js/main.js +++ b/public/js/main.js @@ -55,7 +55,7 @@ import { installLoadoutSync, installOwnershipSync, installDiySync } from './ui/l import { startBuildGuard } from './ui/buildGuard.js'; import { initLang, useLang, tickerText } from './ui/lang.js'; import { t, N_, translateWire } from '../../shared/i18n.js'; -import { recordError } from './diag.js'; +import { recordError, installTrafficMeter } from './diag.js'; const RESTORE_GRACE_MS = 1500; const JOIN_DELAY_MS = 350; @@ -346,6 +346,8 @@ function installGlobalErrorHandlers() { async function boot() { installGlobalErrorHandlers(); + // what this page downloads, by category, for the 问题反馈 report's traffic line (diag.js; nothing is sent anywhere) + installTrafficMeter(); // touch / hover / fullscreen classes, zoom-gesture blocking, rotation re-layout (ui/device.js, css/devices.css) installDeviceSupport(); // A page restored from the back/forward cache has a dead socket and a stale token choice: start over. diff --git a/public/js/media.js b/public/js/media.js index 1d716ac1..3bd8110b 100644 --- a/public/js/media.js +++ b/public/js/media.js @@ -11,10 +11,14 @@ // // `server/http/media.js` resolves /media/… back to the real file under public/assets/audio and still answers with // `Content-Type: audio/mpeg` + range support; Web Audio sniffs the container, so the URL is all the same to it. +// A served manifest's content-hashed URL keeps its segment (shared/assetPaths.js; host bandwidth, layer 1): +// +// /assets/~0123456789abcdef/audio/bgm/act1.mp3 → /media/~0123456789abcdef/bgm/act1 // A host that does not implement /media/ keeps working: `audio.js` falls back to the original URL whenever the // /media/ response is unusable (a 404, or a 200 that is not audio at all — some static hosts answer a missing // path with the SPA's index.html). import { MEDIA_PREFIX, AUDIO_EXTS } from '../../shared/media.js'; +import { splitHashedPath } from '../../shared/assetPaths.js'; const AUDIO_PATH = /^\/assets\/audio\/(.+)$/i; @@ -36,7 +40,8 @@ export function mediaUrl(url, origin = globalThis.location?.origin) { // Cross-origin (or absolute while the page origin is unknown) stays untouched: that host serves its own media. const absolute = /^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('//'); if (origin ? u.origin !== origin : absolute) return url; - const m = AUDIO_PATH.exec(u.pathname); + const { hash, path: plain } = splitHashedPath(u.pathname); + const m = AUDIO_PATH.exec(plain); if (!m) return url; let rest = m[1]; const ext = AUDIO_EXTS.find((e) => rest.toLowerCase().endsWith(e)); @@ -44,5 +49,5 @@ export function mediaUrl(url, origin = globalThis.location?.origin) { rest = rest.slice(0, -ext.length); const segments = rest.split('/'); if (!rest || segments.some((s) => !s || s === '.' || s === '..' || s.startsWith('.'))) return url; - return `${MEDIA_PREFIX}${rest}${u.search}`; + return `${MEDIA_PREFIX}${hash ? `~${hash}/` : ''}${rest}${u.search}`; } diff --git a/public/js/ui/guide.js b/public/js/ui/guide.js index 907abd0e..46cb9626 100644 --- a/public/js/ui/guide.js +++ b/public/js/ui/guide.js @@ -3,7 +3,8 @@ // downloads from the public mirror (data/assets.json → ui['guide/']; GitHub issue #42) — data.js artUrls; a page // whose picture fails to load tries its next URL. The pages are stored squashed to 1024² (both copies) and are // displayed stretched back to 16:9. Three chapters (基础规则 / 调度手册 / 进阶图鉴), ‹ › buttons, ←/→ (A/D) keys, page -// dots, thumbnails; Esc or the backdrop closes. Adjacent pages are preloaded. +// dots, thumbnails; Esc or the backdrop closes. Only the next page is preloaded (a page is 0.9–1.5 MB; the one before +// has usually just been seen, so preloading it too doubled the download — host bandwidth, layer 0). // With no page listed the viewer shows the official loading-screen tips (config.tips) instead, and so does a page none // of whose copies loads (`guideStage`: data/assets.json lists the downloaded pages but the files are not on disk — a // `git pull` and restart without setup, an older asset folder, a failed download the shrink guard kept); the chapter @@ -66,6 +67,19 @@ export function guideStage(page, failed) { return src ? { kind: 'image', src } : { kind: 'tips' }; } +/** + * The one page the viewer preloads while page `i` is shown: the next one (wrapping around), its first URL that has not + * failed — null without pages. The previous page is not preloaded (see the header). + * @param {Array<{ urls?: string[] }>} pages guidePages() + * @param {number} i + * @param {Set} [failed] + */ +export function guidePreloadUrl(pages, i, failed) { + const n = Array.isArray(pages) ? pages.length : 0; + if (!n || n < 2) return null; + return nextArtUrl(pages[(((i + 1) % n) + n) % n]?.urls, failed); +} + /** Open/closed + current page. */ export const guideStore = createStore({ open: false, page: 0 }); @@ -136,8 +150,7 @@ export function GuideHost() { useEffect(() => { if (!open || !n) return; - preload(nextArtUrl(pages[(i + 1) % n]?.urls, failed)); - preload(nextArtUrl(pages[(i + n - 1) % n]?.urls, failed)); + preload(guidePreloadUrl(pages, i, failed)); }, [open, i, n, failed]); if (!open) return null; diff --git a/server/http/assetIndex.js b/server/http/assetIndex.js new file mode 100644 index 00000000..d2a497d6 --- /dev/null +++ b/server/http/assetIndex.js @@ -0,0 +1,352 @@ +// server/http/assetIndex.js — the content hashes of the served art (host bandwidth, layer 1; docs/ASSETS.md "The served +// manifests"): +// +// * built in the background shortly after the start (ASSET_INDEX_DELAY_MS): every file under public/assets/ and +// public/fonts/ (dot names skipped like the static server does, linked folders followed once), the first 16 hex +// digits of the SHA-256 of its bytes (WebCrypto, off the main thread); +// * remembered in .cache/asset-hashes.json by path + size + mtime: a restart only stats the files and reads none of +// the unchanged ones again; a file whose size or mtime changed is hashed again (a re-extraction, `setup --force`, +// a Docker rebuild then costs the players only the files whose bytes changed); +// * never trusted beyond what it checked: `hashOf(rel, stat)` answers only while the file still has the size and +// mtime it was hashed with, else null — the caller then serves the plain way (1-day cache, size-mtime ETag) and +// the miss asks for a rescan (at most one every RESCAN_GAP_MS); +// * models: lists of files that share one URL hash — a Spine skeleton, its atlas and its pages (pixi-spine finds the +// atlas next to the skeleton and the pages next to the atlas, so all their URLs carry the same segment). A model's +// hash is the SHA-256 of its members' hashes; assetViews.js hands the lists over (`setModels`), read from the +// manifests. `urlHashOk` accepts a file's own hash or the hash of a model it belongs to. +// +// Rel paths are POSIX and relative to public/ ('assets/char/avatar/x.png', 'fonts/bender-regular.woff2'). A rel that +// differs from a file's name only in case finds that file when no other name matches it that way (Windows and macOS +// serve `wah-y.png` from `WAH-Y.png`; on Linux the request is a 404 anyway). + +import fs from 'node:fs'; +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import { createHash, webcrypto } from 'node:crypto'; +import { ASSET_HASH_HEX } from '../../shared/assetPaths.js'; +import { noopLog } from './config.js'; +import { IMMUTABLE_CACHE } from './files.js'; + +/** Folders of public/ whose files are hashed. */ +export const ASSET_INDEX_ROOTS = Object.freeze(['assets', 'fonts']); +/** The first build waits this long after the start (a server that is only started and stopped again — tests — reads nothing). */ +export const ASSET_INDEX_DELAY_MS = 1000; +/** Shortest time between two rescans a stale or unknown file asks for. */ +export const RESCAN_GAP_MS = 10_000; +/** Version of .cache/asset-hashes.json. */ +export const HASH_CACHE_VERSION = 1; +const STAT_CONCURRENCY = 64; +const HASH_CONCURRENCY = 4; + +const hex = (bytes) => Buffer.from(bytes).toString('hex').slice(0, ASSET_HASH_HEX); + +/** First ASSET_HASH_HEX hex digits of the SHA-256 of `data` (synchronous; model hashes, manifests, tests). */ +export function hash16(data) { + return createHash('sha256').update(data).digest('hex').slice(0, ASSET_HASH_HEX); +} + +/** The same for a file's bytes, computed off the main thread (WebCrypto runs in libuv's thread pool). */ +async function digest16(buf) { + return hex(await webcrypto.subtle.digest('SHA-256', buf)); +} + +/** Run `fn` over `items` with at most `n` at a time; stops early when `stop()` says so. */ +async function eachLimit(items, n, fn, stop) { + let i = 0; + const worker = async () => { + while (i < items.length && !stop()) { + const item = items[i++]; + await fn(item); + } + }; + await Promise.all(Array.from({ length: Math.min(n, items.length) }, worker)); +} + +/** + * The asset index of one server. + * @param {{ publicDir: string, roots?: readonly string[], cacheFile?: string | null, log?: object, delayMs?: number, + * rescanGapMs?: number, now?: () => number }} opts + * cacheFile: where the hashes persist (null: in memory only — a test's temporary public/) + */ +export function createAssetIndex({ publicDir, roots = ASSET_INDEX_ROOTS, cacheFile = null, log = noopLog, delayMs = ASSET_INDEX_DELAY_MS, + rescanGapMs = RESCAN_GAP_MS, now = Date.now }) { + const base = path.resolve(publicDir); + /** @type {Map} */ + let records = new Map(); + /** @type {Map} lower-case rel → the rel (null: two names differ only in case) */ + let lower = new Map(); + /** @type {string[][]} */ + let modelLists = []; + /** @type {Map>} rel → hashes of the models it belongs to */ + let modelOf = new Map(); + let generation = 0; + let ready = false; + let closed = false; + let building = null; // the build in flight (a promise) + let again = false; // another build was asked for while one ran + let startTimer = null; + let rescanTimer = null; + let lastBuildAt = -Infinity; + let readyResolve; + const readyPromise = new Promise((r) => { readyResolve = r; }); + const listeners = new Set(); + const last = { files: 0, bytes: 0, hashed: 0, reused: 0, ms: 0, at: null, error: null }; + + /** The cache file's records ({} when absent, unreadable or another version). */ + function loadCache() { + if (!cacheFile) return new Map(); + try { + const doc = JSON.parse(fs.readFileSync(cacheFile, 'utf8')); + if (!doc || doc.version !== HASH_CACHE_VERSION || typeof doc.files !== 'object' || !doc.files) return new Map(); + const out = new Map(); + for (const [rel, v] of Object.entries(doc.files)) { + if (Array.isArray(v) && Number.isFinite(v[0]) && Number.isFinite(v[1]) && typeof v[2] === 'string' && v[2].length === ASSET_HASH_HEX) { + out.set(rel, { size: v[0], mtimeMs: v[1], hash: v[2] }); + } + } + return out; + } catch { + return new Map(); + } + } + + /** Write the records (temp file + rename: a concurrent reader never sees half a file). Failures only log. */ + async function saveCache(map) { + if (!cacheFile) return; + const files = {}; + for (const [rel, r] of [...map].sort((a, b) => (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0))) files[rel] = [r.size, r.mtimeMs, r.hash]; + const tmp = `${cacheFile}.${process.pid}.tmp`; + try { + await fsp.mkdir(path.dirname(cacheFile), { recursive: true }); + await fsp.writeFile(tmp, JSON.stringify({ version: HASH_CACHE_VERSION, algo: 'sha256/16', files })); + await fsp.rename(tmp, cacheFile); + } catch (e) { + log.debug?.('[assets] hash cache not saved', e?.code || e?.message); + fsp.rm(tmp, { force: true }).catch(() => {}); + } + } + + /** Every file under the roots: [rel, abs] (dot names skipped, a folder reached twice — a link loop — walked once). */ + async function listFiles() { + const out = []; + const seen = new Set(); + const walk = async (abs, rel) => { + let real; + try { real = await fsp.realpath(abs); } catch { return; } + if (seen.has(real)) return; + seen.add(real); + let ents; + try { ents = await fsp.readdir(abs, { withFileTypes: true }); } catch { return; } + for (const d of ents) { + if (closed) return; + if (d.name.startsWith('.')) continue; + const childAbs = path.join(abs, d.name); + const childRel = `${rel}/${d.name}`; + if (d.isDirectory()) await walk(childAbs, childRel); + else if (d.isFile()) out.push([childRel, childAbs]); + else if (d.isSymbolicLink()) { + const st = await fsp.stat(childAbs).catch(() => null); + if (st?.isDirectory()) await walk(childAbs, childRel); + else if (st?.isFile()) out.push([childRel, childAbs]); + } + } + }; + for (const root of roots) await walk(path.join(base, root), root); + return out; + } + + /** Model hashes from the current records (a model with a member the index does not know has none). */ + function computeModels() { + const next = new Map(); + for (const list of modelLists) { + const h = modelHashOf(list); + if (!h) continue; + for (const rel of list) { + const c = canonical(rel); + let set = next.get(c); + if (!set) next.set(c, (set = new Set())); + set.add(h); + } + } + modelOf = next; + } + + /** The indexed name of `rel`: itself, or the one file whose name differs from it only in case (else null). */ + function canonical(rel) { + if (typeof rel !== 'string') return null; + if (records.has(rel)) return rel; + return lower.get(rel.toLowerCase()) || null; + } + + function recordOf(rel) { + const c = canonical(rel); + return c ? records.get(c) : null; + } + + function modelHashOf(list) { + if (!Array.isArray(list) || !list.length) return null; + const parts = []; + for (const rel of list) { + const r = recordOf(rel); + if (!r) return null; + parts.push(r.hash); + } + return hash16(parts.join('\n')); + } + + /** One build; true when the records changed (a new generation). */ + async function build() { + const t0 = now(); + const known = records.size ? records : loadCache(); + const next = new Map(); + let hashed = 0; + let reused = 0; + let bytes = 0; + const files = await listFiles(); + const toHash = []; + await eachLimit(files, STAT_CONCURRENCY, async ([rel, abs]) => { + const st = await fsp.stat(abs).catch(() => null); + if (!st || !st.isFile()) return; + bytes += st.size; + const k = known.get(rel); + if (k && k.size === st.size && k.mtimeMs === st.mtimeMs) { next.set(rel, k); reused++; } else toHash.push([rel, abs, st]); + }, () => closed); + await eachLimit(toHash, HASH_CONCURRENCY, async ([rel, abs, st]) => { + try { + const buf = await fsp.readFile(abs); + const after = await fsp.stat(abs); + // changed while it was read: hashed again by the next build + if (after.size !== st.size || after.mtimeMs !== st.mtimeMs || buf.length !== st.size) return; + next.set(rel, { size: st.size, mtimeMs: st.mtimeMs, hash: await digest16(buf) }); + hashed++; + } catch { /* vanished or unreadable: not in the index */ } + }, () => closed); + if (closed) return false; + // commit: records, model hashes and the generation change together (one synchronous step) + let changed = next.size !== records.size; + if (!changed) for (const [rel, r] of next) { const o = records.get(rel); if (!o || o.hash !== r.hash || o.size !== r.size || o.mtimeMs !== r.mtimeMs) { changed = true; break; } } + const cacheChanged = hashed > 0 || next.size !== known.size; + records = next; + lower = new Map(); + for (const rel of next.keys()) { const k = rel.toLowerCase(); lower.set(k, lower.has(k) ? null : rel); } + if (changed) { generation++; computeModels(); } + Object.assign(last, { files: next.size, bytes, hashed, reused, ms: now() - t0, at: new Date().toISOString(), error: null }); + lastBuildAt = now(); + if (cacheChanged) await saveCache(next); + if (hashed) log.info?.(`[assets] content hashes: ${next.size} files, ${hashed} hashed, ${reused} unchanged (${Math.round(last.ms)} ms)`); + return changed; + } + + function markReady() { + if (ready) return; + ready = true; + readyResolve(); + } + + function notify() { + for (const fn of [...listeners]) { try { fn(generation); } catch (e) { log.error?.('[assets] index listener failed', e); } } + } + + /** Build now (or once more after the build in flight). */ + function refresh() { + if (closed) return Promise.resolve(); + if (building) { again = true; return building; } + building = (async () => { + try { + do { + again = false; + const changed = await build(); + if (closed) break; + markReady(); + if (changed) notify(); + } while (again && !closed); + } catch (e) { + last.error = e?.message || String(e); + log.warn?.('[assets] content hash index failed', e?.message || e); + } finally { + building = null; + if (!closed) markReady(); + } + })(); + return building; + } + + return { + /** Start the background build (after `delayMs`); returns at once. Idempotent. */ + start() { + if (closed || startTimer || building || ready) return; + if (!(delayMs > 0)) { refresh(); return; } + startTimer = setTimeout(() => { startTimer = null; refresh(); }, delayMs); + startTimer.unref?.(); + }, + refresh, + /** Resolves once the first build is done (never rejects). */ + whenReady() { return readyPromise; }, + get ready() { return ready; }, + get generation() { return generation; }, + /** Files with a hash. */ + get size() { return records.size; }, + /** + * The file's content hash while it still has the size and mtime it was hashed with (`stat` given), else null. + * Without `stat`: the hash of the last build. + * @param {string} rel @param {{ size: number, mtimeMs: number }} [stat] + */ + hashOf(rel, stat) { + const r = recordOf(rel); + if (!r) return null; + if (stat && (stat.size !== r.size || stat.mtimeMs !== r.mtimeMs)) return null; + return r.hash; + }, + /** Does `urlHash` name exactly these bytes: the file's own hash, or the hash of a model it belongs to? */ + urlHashOk(rel, stat, urlHash) { + if (typeof urlHash !== 'string') return false; + const own = this.hashOf(rel, stat); + if (!own) return false; + return own === urlHash || !!modelOf.get(canonical(rel))?.has(urlHash); + }, + /** The hash of a model (its members' hashes hashed), null while a member is unknown. */ + modelHash: (list) => modelHashOf(list), + /** Replace the model lists (assetViews.js, from the manifests). */ + setModels(lists) { + modelLists = Array.isArray(lists) ? lists.filter((l) => Array.isArray(l) && l.length) : []; + computeModels(); + }, + /** A file was served that the index does not know, or no longer matches: rescan (at most one per rescanGapMs). */ + noteMiss() { + if (closed || !ready || rescanTimer || building) return; + const wait = Math.max(0, lastBuildAt + rescanGapMs - now()); + rescanTimer = setTimeout(() => { rescanTimer = null; refresh(); }, wait); + rescanTimer.unref?.(); + }, + /** `fn(generation)` after a build changed the records; returns the unsubscribe. */ + onChange(fn) { listeners.add(fn); return () => listeners.delete(fn); }, + stats() { + return { ready, building: !!building, generation, files: records.size, models: modelLists.length, last: { ...last } }; + }, + /** Stop: timers cleared, a build in flight abandoned. */ + close() { + closed = true; + if (startTimer) { clearTimeout(startTimer); startTimer = null; } + if (rescanTimer) { clearTimeout(rescanTimer); rescanTimer = null; } + readyResolve(); // a waiter is let go; `ready` stays as it was + }, + }; +} + +/** + * The ETag source and cache policy of a file of the asset index's folders (public/assets, public/fonts), for + * serveFile: its content hash when the index has it for these bytes (a miss asks for a rescan); for a URL with a hash + * segment `immutable` when that hash names these bytes, else `no-cache`. + * @param {ReturnType | null} assetIndex + * @param {string} rel the file under public/ ('assets/…', POSIX) + * @param {import('node:fs').Stats} stat + * @param {string | null} urlHash the URL's hash segment + * @returns {{ contentHash?: string | null, cacheControl?: string }} + */ +export function hashedFileOpts(assetIndex, rel, stat, urlHash) { + if (!assetIndex) return urlHash ? { cacheControl: 'no-cache' } : {}; + const contentHash = assetIndex.hashOf(rel, stat); + if (!contentHash) assetIndex.noteMiss(rel); + if (!urlHash) return { contentHash }; + return { contentHash, cacheControl: contentHash && assetIndex.urlHashOk(rel, stat, urlHash) ? IMMUTABLE_CACHE : 'no-cache' }; +} diff --git a/server/http/assetViews.js b/server/http/assetViews.js new file mode 100644 index 00000000..e908e6d2 --- /dev/null +++ b/server/http/assetViews.js @@ -0,0 +1,185 @@ +// server/http/assetViews.js — the served manifests (host bandwidth, layer 1; docs/ASSETS.md "The served manifests"): +// data/assets.json and data/local-assets.json as this server hands them out, every art URL carrying the content hash +// of its file as its first segment (shared/assetPaths.js) — `/assets/char/avatar/x.png` → +// `/assets/~/char/avatar/x.png`, `/fonts/~/…` — so the browser keeps the file for a year and asks again +// only when the bytes change. Audio keeps the `/assets/~/audio/….mp3` form: public/js/media.js turns it into +// `/media/~/…` when it fetches it. +// +// * A Spine model's skeleton, atlas and pages carry ONE hash, that of the model (assetIndex.js models): pixi-spine +// finds the atlas by the skeleton's name and the pages next to the atlas, so their URLs share a folder. A model is +// every `{ skel, atlas, textures }` object of data/assets.json (chars' front / back, tokens, enemies) and every +// `spine/…` group of data/local-assets.json (the files a `spineLocal` record names). +// * A URL the index has no hash for (not on disk, not hashed yet) stays as it is. +// * The committed data/assets.json is never written: a view is built in memory from the file and the index, again +// when either changes (the file's size / mtime, the index's generation), and once after every index build, so the +// index knows the model lists before any page asks. +// * No index, or not ready yet: no view (`get` → null) and the files go out as they are. + +import fsp from 'node:fs/promises'; +import path from 'node:path'; +import { hashedPath } from '../../shared/assetPaths.js'; +import { hash16 } from './assetIndex.js'; +import { noopLog } from './config.js'; + +/** The manifests that have a view, by their name under data/. */ +export const VIEW_MANIFESTS = Object.freeze(['assets.json', 'local-assets.json']); + +const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v); +const ART_URL = /^\/(?:assets|fonts)\/./; + +/** URL path of a manifest → the index's rel path ('/assets/a%20b.png' → 'assets/a b.png'), or null. */ +export function relOf(url) { + if (typeof url !== 'string' || !ART_URL.test(url) || /[?#]/.test(url)) return null; + let p; + try { p = decodeURIComponent(url); } catch { return null; } + if (p.includes('\0') || p.includes('\\')) return null; + const segs = p.slice(1).split('/'); + if (segs.some((s) => s === '' || s === '.' || s === '..')) return null; + return segs.join('/'); +} + +/** Is `o` a Spine object of data/assets.json (`{ skel: '/….skel', atlas, textures? }`)? */ +const isSpine = (o) => isObj(o) && typeof o.skel === 'string' && o.skel.startsWith('/') && /\.skel$/.test(o.skel); + +/** The URLs of a Spine object: skeleton, atlas, pages (the `.png` when it lists none). */ +function spineUrls(o) { + const out = [o.skel]; + if (typeof o.atlas === 'string' && o.atlas) out.push(o.atlas); + const pages = Array.isArray(o.textures) ? o.textures.filter((u) => typeof u === 'string' && u) : []; + out.push(...(pages.length ? pages : [o.skel.replace(/\.skel$/, '.png')])); + return out; +} + +/** + * The served copy of a manifest and its model lists. `index`: hashOf(rel) / modelHash(rels) of assetIndex.js. + * @param {any} doc the parsed manifest (not changed) + * @param {'assets.json'|'local-assets.json'} name + * @param {{ hashOf: (rel: string) => string | null, modelHash: (rels: string[]) => string | null }} index + * @returns {{ doc: any, models: string[][], hashed: number, plain: number }} + */ +export function rewriteManifest(doc, name, index) { + const models = []; + let hashed = 0; + let plain = 0; + const own = (url) => { + const rel = relOf(url); + const h = rel ? index.hashOf(rel) : null; + if (h) { hashed++; return hashedPath(url, h); } + if (rel) plain++; + return url; + }; + /** All URLs of one model with the model's hash (or all left plain when a member is unknown). */ + const model = (urls) => { + const rels = urls.map(relOf); + if (rels.some((r) => !r)) return null; + models.push(rels); + const h = index.modelHash(rels); + if (!h) { plain += urls.length; return null; } + hashed += urls.length; + return h; + }; + const walk = (v) => { + if (typeof v === 'string') return ART_URL.test(v) ? own(v) : v; + if (Array.isArray(v)) return v.map(walk); + if (!isObj(v)) return v; + if (name === 'assets.json' && isSpine(v)) { + const h = model(spineUrls(v)); + const out = {}; + for (const [k, x] of Object.entries(v)) { + if (h && k === 'skel') out[k] = hashedPath(x, h); + else if (h && k === 'atlas' && typeof x === 'string') out[k] = hashedPath(x, h); + else if (h && k === 'textures' && Array.isArray(x)) out[k] = x.map((u) => (typeof u === 'string' ? hashedPath(u, h) : u)); + else out[k] = walk(x); + } + return out; + } + const out = {}; + for (const [k, x] of Object.entries(v)) out[k] = walk(x); + return out; + }; + if (name === 'local-assets.json' && isObj(doc) && isObj(doc.groups)) { + const groups = {}; + for (const [g, entries] of Object.entries(doc.groups)) { + if (g.startsWith('spine/') && isObj(entries)) { + const names = Object.keys(entries).filter((n) => isObj(entries[n]) && typeof entries[n].path === 'string').sort(); + const h = names.length ? model(names.map((n) => entries[n].path)) : null; + groups[g] = {}; + for (const [n, e] of Object.entries(entries)) { + groups[g][n] = h && isObj(e) && typeof e.path === 'string' ? { ...e, path: hashedPath(e.path, h) } : walk(e); + } + } else groups[g] = walk(entries); + } + return { doc: { ...walk({ ...doc, groups: null }), groups }, models, hashed, plain }; + } + return { doc: walk(doc), models, hashed, plain }; +} + +/** + * The views of one server. + * @param {{ dataDir: string, index: ReturnType, log?: object }} opts + */ +export function createManifestViews({ dataDir, index, log = noopLog }) { + const dir = path.resolve(dataDir); + /** @type {Map} */ + const cache = new Map(); + /** @type {Map>} */ + const pending = new Map(); + const warned = new Set(); + + const pushModels = () => index.setModels([...cache.values()].flatMap((c) => c.models)); + + /** Build (or reuse) the view of `name`; null without the file, while the index is not ready or empty, or for a broken file. */ + async function build(name) { + if (!index.ready || !index.size) return null; + const file = path.join(dir, name); + const st = await fsp.stat(file).catch(() => null); + if (!st || !st.isFile()) { + if (cache.delete(name)) pushModels(); + return null; + } + const key = `${index.generation}|${st.size}|${st.mtimeMs}`; + const hit = cache.get(name); + if (hit && hit.key === key) return hit.view; + let doc; + try { + doc = JSON.parse(await fsp.readFile(file, 'utf8')); + } catch (e) { + if (!warned.has(name)) { warned.add(name); log.warn?.(`[assets] data/${name} unreadable (${e?.message || e}); served as it is`); } + cache.set(name, { key, view: null, models: [] }); + pushModels(); + return null; + } + // one synchronous step: the view and the model lists the index checks a model's URLs against + const { doc: out, models, hashed, plain } = rewriteManifest(doc, name, index); + const body = Buffer.from(JSON.stringify(out)); + const view = { body, hash: hash16(body), hashed, plain }; + cache.set(name, { key, view, models }); + pushModels(); + return view; + } + + /** The view of `name` (one build at a time per manifest). */ + function get(name) { + if (!VIEW_MANIFESTS.includes(name)) return Promise.resolve(null); + const running = pending.get(name); + if (running) return running; + const p = build(name).catch((e) => { log.error?.('[assets] manifest view failed', e); return null; }).finally(() => pending.delete(name)); + pending.set(name, p); + return p; + } + + const rebuildAll = () => Promise.all(VIEW_MANIFESTS.map(get)); + // after every build that changed the hashes (and the first one): the views, and with them the index's model lists + index.onChange(() => { rebuildAll(); }); + index.whenReady().then(() => rebuildAll(), () => {}); + + return { + get, + rebuildAll, + stats() { + const out = {}; + for (const [name, c] of cache) out[name] = c.view ? { bytes: c.view.body.length, hashed: c.view.hashed, plain: c.view.plain } : null; + return out; + }, + }; +} diff --git a/server/http/config.js b/server/http/config.js index 3d1bd123..113c4441 100644 --- a/server/http/config.js +++ b/server/http/config.js @@ -4,6 +4,8 @@ // * TRUST_PROXY ('auto' default: honour CF-Connecting-IP / X-Real-IP / X-Forwarded-For only from loopback/private // peers such as a local cloudflared; '1' always; '0' never) → net.js trustProxy; // * DEBUG → the console logger's debug level; +// * SP_ASSET_INDEX=0 (or the `assetIndex: false` option) → no content-hash index: plain asset URLs, size-mtime ETags +// (assetIndex.js); the index of the default public/ persists in .cache/asset-hashes.json; // * the served directories (public/, data/, shared/ and the content packs' packs/ of this repository unless the // options name others), and which startServer() options are handed on to net.js Network and lobby.js Lobby. @@ -64,6 +66,25 @@ export function serveDirs(opts) { }; } +/** + * The asset index options out of the startServer() options and the environment, or null for none: `assetIndex: false` + * or SP_ASSET_INDEX=0 / off / false / no switches it off; `assetIndex: { cacheFile, delayMs }` overrides the defaults. + * The hashes persist in .cache/asset-hashes.json only for the repository's own public/ (a test's temporary folder keeps + * them in memory). + * @param {{ assetIndex?: boolean | { cacheFile?: string | null, delayMs?: number } }} opts + * @param {string} publicDir + * @returns {{ cacheFile: string | null, delayMs?: number } | null} + */ +export function assetIndexOptionsFrom(opts, publicDir) { + if (opts.assetIndex === false) return null; + const env = String(process.env.SP_ASSET_INDEX ?? '').trim().toLowerCase(); + if (opts.assetIndex == null && ['0', 'off', 'false', 'no'].includes(env)) return null; + const o = typeof opts.assetIndex === 'object' && opts.assetIndex ? opts.assetIndex : {}; + const own = path.resolve(publicDir) === path.join(ROOT, 'public'); + const cacheFile = o.cacheFile !== undefined ? o.cacheFile : (own ? path.join(ROOT, '.cache', 'asset-hashes.json') : null); + return { cacheFile, ...(Number.isFinite(o.delayMs) ? { delayMs: o.delayMs } : {}) }; +} + /** net.js Network options out of the startServer() options; `trustProxy` falls back to TRUST_PROXY. */ export function netOptionsFrom(opts) { const netOptions = {}; diff --git a/server/http/files.js b/server/http/files.js index c15de0e6..a9ed003f 100644 --- a/server/http/files.js +++ b/server/http/files.js @@ -1,9 +1,12 @@ -// server/http/files.js — one file on disk → an HTTP response (static.js and media.js decide which file): +// server/http/files.js — one file on disk (serveFile) or one body in memory (serveBuffer, the served manifests of +// assetViews.js) → an HTTP response (static.js and media.js decide which file): // MIME types incl. .mjs/.js text/javascript, .skel application/octet-stream, .atlas text/plain; -// gzip for text-like types, .skel and uncompressed fonts when the client accepts it (small files are -// compressed once and cached in memory); strong ETag + Last-Modified with 304s; Cache-Control -// (html & code/data: no-cache + revalidate; public/assets|fonts|vendor: 1 day; any `?v=` URL: immutable); -// single byte-range requests (206/416, used by