commit dd2935366ed11f54a91cc27e191a2c2800fc5297 Author: rong Date: Fri Oct 23 10:09:06 2026 +0800 feat: 游戏中心——1818 单端口统一入口,进程按需拉起 + 空闲释放 - 一个端口按路径分发:/cnchess /cngo /cs 进程型,/alonelyroad /myword 静态目录 - 进程型首次访问以动态端口拉起子进程,就绪探测后转发;空闲 600s 且无 WS 连接才回收 - WebSocket 走原始 TCP 隧道(握手转发 + 101 透传 + 双向对拷,任一方向 EOF 即拆连) - 文本响应就地重写根绝对路径(href/src/fetch/url(/ 与 location.host}/ws),游戏源码零改动 - 入口页只显示状态与进入入口,不提供管理按钮;网关/运维接口为 /api/* - 配置 games.json 磁盘优先、内嵌兜底,改完刷新即生效 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..77c6b6b --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +/target/ +/run/logs/ +.DS_Store +*.log +.workbuddy/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..031b7fa --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,545 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-task", + "pin-project-lite", + "slab", +] + +[[package]] +name = "game-center" +version = "1.0.0" +dependencies = [ + "axum", + "http-body-util", + "hyper", + "hyper-util", + "serde", + "serde_json", + "tokio", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "libc", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-core", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..d74f53b --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "game-center" +version = "1.0.0" +edition = "2021" +description = "游戏中心:1818 单端口、按路径分发、按需拉起 / 空闲释放的统一代理" +license = "MIT" + +[[bin]] +name = "game-center" +path = "src/main.rs" + +[dependencies] +axum = "0.8" +tokio = { version = "1", features = [ + "rt-multi-thread", + "macros", + "net", + "time", + "sync", + "io-util", + "fs", + "process", + "signal", +] } +serde = { version = "1", features = ["derive"] } +serde_json = "1" +http-body-util = "0.1" +hyper = { version = "1", features = ["client", "http1", "server"] } +hyper-util = { version = "0.1", features = ["client-legacy", "http1", "tokio"] } + +[profile.release] +lto = "thin" +codegen-units = 1 +strip = true diff --git a/README.md b/README.md new file mode 100644 index 0000000..4a53f82 --- /dev/null +++ b/README.md @@ -0,0 +1,187 @@ +# 游戏中心 · Game Center + +把 `../` 下的所有游戏收进**一个端口(1818)**,按路径区分: + +``` +http://localhost:1818/ 入口页(只显示状态,点卡片即进入) +http://localhost:1818/cnchess/ 中国象棋 ← 进程型,冷启动 / 空闲释放 +http://localhost:1818/cngo/ 围棋 ← 进程型 +http://localhost:1818/cs/ 枪火对决 ← 进程型 +http://localhost:1818/alonelyroad/ 沙漠狂飙 ← 静态目录 +http://localhost:1818/myword/ 我的世界 ← 静态目录 +``` + +没有「常驻服务」的概念:**没人用就释放,有访问再拉起**。中心自己只是一个很小的 Rust +反代进程(约 1.5MB),内存占用基本就是几个游戏的进程本身。 + +入口页只做两件事:**显示每个游戏的状态**(运行中 / 休眠 / 异常,运行多久、还剩多久回收)、 +**点一下进入**。没有停止、刷新、管理按钮——拉起和释放全按访问行为自动发生, +运维要手动干预就走下面的 API(curl 即可)。 + +## 跑起来 + +```bash +bash scripts/build-games.sh # 第一次:把 cnchess / cngo / cs 编成 release 二进制 +bash run.sh # 起中心,前台跑在 1818 +``` + +打开 ,点任意卡片即可。手机 / 平板同一 Wi-Fi 用终端打印的局域网地址。 + +- 首次点击某个进程型游戏,中心现场 spawn 它(约 1 秒内可服务),页面会短暂「启动中」。 +- 关掉页面、10 分钟没人访问 → 进程被回收(默认 600s,`GC_IDLE_SECS` 可改)。 +- 再看一次 → 重新拉起。棋局这类内存态会丢,这是「不用就释放」的必然代价。 + +## 生命周期 + +``` + 请求 /cnchess/* + │ + ▼ + ┌───────────────┐ 没有进程 + │ ensure() ├──────────────► spawn(bin, PORT=随机空闲端口, HOST=127.0.0.1) + └───────┬───────┘ │ + │ 已有进程 │ 轮询 TCP connect 直到可连(上限 12s) + ▼ ▼ + 转发 / 隧道 ◄──────────────── 就绪(打 starts+1) + │ + │ last_hit = now,inflight+1 + ▼ + 响应返回(inflight-1) + + 每 5s 一次 tick: + 进程已退出? → 清状态(下次访问自动重拉) + inflight > 0 或 ws > 0 → 跳过(正在用 / 对局中,绝不回收) + now - last_hit ≥ idle → SIGKILL + wait,打 releases+1 +``` + +几个刻意的选择: + +- **动态端口**。每个进程绑 `127.0.0.1:随机`,不是写死 3000/3100。这样中心重启、旧进程残留、 + 同时开多个实例都不会撞端口,也不对外暴露第二个入口。 +- **有 WebSocket 就永不回收**。象棋 / 围棋 / 枪火的对局、等待房间全靠 WS 保活;如果只看 + 「最后一次 HTTP 请求」,等人 10 分钟就把棋局杀了。所以回收条件是 + `inflight == 0 && ws_conns == 0 && 空闲够久`。代价是「页面开着但人走了」会一直占着, + 这是对局类游戏的正确取舍。 +- **请求作用域计数**。`Lease` 在进入代理时 `inflight+1`、Drop 时 `-1`,慢请求不会被回收器 + 从中间掐断。 +- **中心退出即清场**。Ctrl-C / SIGTERM / SIGHUP 都注册了退出处理,先把所有子进程 release 掉再走, + 不留孤儿。万一被 `kill -9`:`pkill -f 'game/(cnchess|cngo|cs)/target/release'` 收一遍尾巴。 + +## 代理怎么做的 + +**HTTP**:hyper 1 的 client(`hyper::client::conn::http1`)连后端,转发方法/头/体,丢掉 +hop-by-hop 头,`Host` 改写成 `127.0.0.1:`,`Accept-Encoding: identity`(要拿到明文才能重写)。 +响应整体收进内存(都是几十 KB 的页面/JS),按 content-type 决定要不要重写。 + +**WebSocket**:不解析帧,走**原始 TCP 隧道**。把客户端的握手请求按原样(除 Host)写给后端, +读到后端 101 后,把 101 的头原样回给浏览器,随后 `copy_bidirectional` 双向对拷字节流。 +好处是帧格式、子协议、二进制/文本全都不用管;后端提前吐出的字节(`leftover`)也会先补发给客户端。 + +**路径前缀的补偿**。游戏前端里写死的是根绝对路径,挂到 `/cnchess/` 下会全部打偏,所以在文本 +响应(html/css/js)里就地重写: + +| 原文 | 重写为 | 出现在 | +| --- | --- | --- | +| `href="/` `src="/` `action="/` | `…="/cnchess/…` | 三个 Rust 游戏的 index.html | +| `fetch("/` | `fetch("/cnchess/…` | cs 取 `/level.json` | +| `location.host}/` | `location.host}/cnchess/` | 三个游戏的 `${proto}//${location.host}/ws` | +| `url(/` | `url(/cnchess/…` | CSS 里的绝对资源 | + +另外 `/cnchess`(少个斜杠)会 301 到 `/cnchess/`,否则页面里的相对路径会解析到根。 +要加新的重写规则,在 `games.json` 里给该游戏写 `rewrites: [["from", "to"]]`,`to` 里可用 +`{prefix}`。 + +## 配置:games.json + +改完刷新页面即可(中心优先读磁盘上的这份,读不到才用编译进二进制的内嵌版本),**不用重编译**。 + +```jsonc +{ + "port": 1818, + "idle_secs": 600, + "games": [ + { + "id": "cnchess", // 唯一 id,也是 /api 里的名字 + "name": "中国象棋", + "tagline": "两台设备联机对弈,服务端权威判棋", + "icon": "象", // 卡片左上角的字 + "accent": "#e2523f", // 卡片主色 + "stack": "Rust · axum", + "meta": ["2 人 · 观战", "WebSocket"], + "kind": "process", // process | static + "route": "cnchess", // 路由前缀,缺省取 id + "cwd": "../cnchess", // 相对 center/ 的工作目录 + "bin": "target/release/cnchess" + }, + { + "id": "alonelyroad", + "name": "沙漠狂飙", + "kind": "static", + "dir": "../AlonelyRoad", // 静态资源目录 + "entry": "AlonelyRoad.html" // 目录根请求的入口文件(缺省 index.html) + } + ] +} +``` + +环境变量:`GC_PORT`(覆盖端口)、`GC_IDLE_SECS`(覆盖回收时间)、`GC_HOME`(配置与资源根目录)、 +`GC_HOST`(监听地址,默认 `0.0.0.0`)。 + +## API + +入口页只用 `GET /api/games`,其余几个是给运维手工/脚本用的(页面上没有按钮暴露它们): + +| 方法 | 路径 | 说明 | +| --- | --- | --- | +| GET | `/api/games` | 全部游戏快照:state / port / 运行时长 / 剩余回收时间 / WS 数 / 拉起与释放次数 | +| POST | `/api/games/{id}/wake` | 显式拉起(入口页点卡片时先调它,失败能给出原因) | +| POST | `/api/games/{id}/stop` | 立即释放(运维用) | +| POST | `/api/stop-all` | 一键释放全部(运维用) | +| GET | `/health` | `{"ok":true,"engine":"rust","mode":"lazy-proxy","running":N,...}` | + +`state` 取值:`running`(进程在跑)、`asleep`(休眠,下次访问拉起)、`static`(静态托管,无进程)、 +`error`(拉起失败,`error` 字段带原因)。 + +## 日志 + +每个进程型的 stdout/stderr 追加到 `run/logs/.log`(已 gitignore)。启动失败时页面会提示路径。 + +## 构建缓存布局(遵循 dev-cache-layout) + +- `target/`、`run/logs/` 都在项目目录里,**不**挪到 `~/Library/Caches` 再软链回来; +- 依赖走全局 cargo 缓存实体 `~/.cache/cargo/registry`(`~/.cargo/registry` 是软链),本中心不另建 store; +- 冷启动提速已经在 `~/.cargo/config.toml` 里配好(USTC 镜像 + sccache + `jobs = 3`),这里不重复配置; +- 想强制走 sccache:`cargo cold`(= `build --config profile.dev.incremental=false`)。 + +## 加一个游戏 + +1. 进程型:把项目放在 `../`,能 `cargo build --release` 出单文件、认 `PORT`/`HOST` 环境变量、 + 起在根路径 `/`(这三条都满足就直接能用); +2. 静态型:放一个目录 + 入口 html,用相对路径引资源; +3. 在 `games.json` 里加一条,刷新启动器。 + +如果新游戏的前端用的是别的根路径写法(比如 `import('/x.js')`、`new URL('/y')`), +在它的 `rewrites` 里补规则,别去改游戏源码。 + +## 排错 + +| 现象 | 原因 / 处理 | +| --- | --- | +| 卡片显示「未构建」 | 跑 `bash scripts/build-games.sh` | +| 点击后 502,页面说「启动即退出」 | 看 `run/logs/.log`;多半是二进制缺动态库或端口被占 | +| 页面出来了但白屏 / 资源 404 | 该游戏前端有未被重写的根绝对路径,打开 DevTools 看缺哪个,补 `rewrites` | +| WS 连不上(状态一直「未连接」) | 浏览器 Network 里看 `/xxx/ws` 是否 101;若不是,看中心 stdout 的 `代理失败` 日志 | +| 对局 10 分钟后人还在却断了 | 不该发生(有 WS 就不回收);若真发生,检查是不是 WS 已经断开而页面没重连 | +| 改了游戏前端不生效 | 三个游戏对静态资源都发 `no-cache`,硬刷新即可;若改的是 `public/` 而二进制内嵌了旧版,需重新 build 游戏 | + +## 已实测(2026-10-22) + +| 项 | 结果 | +| --- | --- | +| 5 条路径 GET | `/` `/cnchess/` `/cngo/` `/cs/` `/alonelyroad/` `/myword/` 全 200,未知路径 404 | +| 路径重写 | `href/src` 补前缀、 cs 的 `fetch("/level.json")` → `/cs/level.json`、三个游戏的 `${location.host}/ws` → `//ws` | +| WebSocket | 象棋 / 围棋 / 枪火 三条 `/ws` 均 101 并完成真实业务消息(建房拿到房号、CS 拿到 welcome + 关卡) | +| 并发冷启动 | 10 个并发请求打 `/cs/` → `starts=1`、全部 200 | +| 空闲回收 | 门槛调成 6s:拉起到 `running`,空闲后变 `asleep` 且 `releases=1`,再访问 `starts=2` | +| WS 保活 | 持连 15s(远超 idle)始终 `running`;断开后 ~5s 内回收 | +| 拉起失败 | 指向不存在的二进制 → 502 页面写明缺失路径 + 构建命令,`state=error` | diff --git a/build.rs b/build.rs new file mode 100644 index 0000000..d4b7155 --- /dev/null +++ b/build.rs @@ -0,0 +1,62 @@ +//! 把 public/ 整个目录编译进二进制,同时运行期优先读磁盘(改页面不用重编译)。 +//! 跟 cnchess / cngo / cs 里的 build.rs 是同一套做法。 + +use std::fmt::Write as _; +use std::path::{Path, PathBuf}; +use std::{env, fs}; + +fn mime_of(name: &str) -> &'static str { + match name.rsplit('.').next().unwrap_or("").to_ascii_lowercase().as_str() { + "html" | "htm" => "text/html; charset=utf-8", + "js" | "mjs" => "text/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "json" | "webmanifest" => "application/json; charset=utf-8", + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "svg" => "image/svg+xml", + "ico" => "image/x-icon", + "woff2" => "font/woff2", + "webp" => "image/webp", + _ => "application/octet-stream", + } +} + +fn walk(dir: &Path, out: &mut Vec) { + let Ok(rd) = fs::read_dir(dir) else { return }; + for entry in rd.flatten() { + let p = entry.path(); + if p.is_dir() { + walk(&p, out); + } else { + out.push(p); + } + } +} + +fn main() { + let manifest = PathBuf::from(env::var("CARGO_MANIFEST_DIR").unwrap()); + let public = manifest.join("public"); + println!("cargo:rerun-if-changed=public"); + println!("cargo:rerun-if-changed=games.json"); + + let mut files = Vec::new(); + walk(&public, &mut files); + files.sort(); + + let mut src = String::from("// 由 build.rs 生成,勿手改\npub static ASSETS: &[(&str, &str, &[u8])] = &[\n"); + for f in &files { + let rel = f.strip_prefix(&public).unwrap().to_string_lossy().replace('\\', "/"); + let key = format!("/{rel}"); + let mime = mime_of(&rel); + writeln!( + src, + " ({key:?}, {mime:?}, include_bytes!({:?})),", + f.to_string_lossy() + ) + .unwrap(); + } + src.push_str("];\n"); + + let out = PathBuf::from(env::var("OUT_DIR").unwrap()).join("assets_gen.rs"); + fs::write(out, src).unwrap(); +} diff --git a/games.json b/games.json new file mode 100644 index 0000000..3e0f6c8 --- /dev/null +++ b/games.json @@ -0,0 +1,66 @@ +{ + "port": 1818, + "idle_secs": 600, + "games": [ + { + "id": "cnchess", + "name": "中国象棋", + "tagline": "两台设备联机对弈,服务端权威判棋", + "icon": "象", + "accent": "#e2523f", + "stack": "Rust · axum", + "meta": ["2 人 · 观战", "WebSocket", "内置语音"], + "kind": "process", + "cwd": "../cnchess", + "bin": "target/release/cnchess" + }, + { + "id": "cngo", + "name": "围棋", + "tagline": "落子圈地,联机对局、观战与棋谱", + "icon": "围", + "accent": "#4aa8ff", + "stack": "Rust · axum", + "meta": ["2 人 · 观战", "WebSocket", "贴目规则"], + "kind": "process", + "cwd": "../cngo", + "bin": "target/release/cngo" + }, + { + "id": "cs", + "name": "枪火对决", + "tagline": "第一人称 1v1 对枪,60Hz 物理模拟", + "icon": "枪", + "accent": "#f5a623", + "stack": "Rust · WebGL", + "meta": ["1v1 对战", "WebSocket", "30Hz 快照"], + "kind": "process", + "cwd": "../cs", + "bin": "target/release/cs" + }, + { + "id": "alonelyroad", + "name": "沙漠狂飙", + "tagline": "单机越野冲刺,纯 Canvas 手写渲染", + "icon": "飙", + "accent": "#ffb84d", + "stack": "单页 · Canvas", + "meta": ["单人", "键盘 / 触屏", "零依赖"], + "kind": "static", + "dir": "../AlonelyRoad", + "entry": "AlonelyRoad.html" + }, + { + "id": "myword", + "name": "我的世界", + "tagline": "体素沙盒:挖矿、合成、生存,夜里僵尸会来", + "icon": "世", + "accent": "#55c98a", + "stack": "单页 · Three.js", + "meta": ["单人", "合成 / 生存", "CDN 依赖"], + "kind": "static", + "dir": "../MyWord", + "entry": "index.html" + } + ] +} diff --git a/public/app.js b/public/app.js new file mode 100644 index 0000000..080a289 --- /dev/null +++ b/public/app.js @@ -0,0 +1,217 @@ +/* 游戏中心入口:拉状态 → 渲染卡片 → 点击唤醒后跳转。 + 这里只负责「显示 + 进入」,不做进程管理(拉起/释放由中心自己按访问和空闲决定)。 */ + +const cards = new Map(); +let toastTimer = null; + +const $ = (sel) => document.querySelector(sel); + +/* ----------------------------- 工具 ----------------------------- */ + +function fmtDur(sec) { + sec = Math.max(0, Math.floor(sec || 0)); + if (sec < 60) return `${sec}s`; + const m = Math.floor(sec / 60); + const s = sec % 60; + if (m < 60) return s ? `${m}m${String(s).padStart(2, "0")}s` : `${m}m`; + const h = Math.floor(m / 60); + return `${h}h${String(m % 60).padStart(2, "0")}m`; +} + +function fmtIdle(sec) { + if (sec >= 60 && sec % 60 === 0) return `${sec / 60} 分钟`; + if (sec >= 60) return `${Math.round(sec / 60)} 分钟`; + return `${sec} 秒`; +} + +function toast(msg, isErr) { + const el = $("#toast"); + el.textContent = msg; + el.classList.toggle("err", !!isErr); + el.classList.add("show"); + clearTimeout(toastTimer); + toastTimer = setTimeout(() => el.classList.remove("show"), isErr ? 5200 : 2200); +} + +async function api(path, opts) { + const res = await fetch(path, { + cache: "no-store", + headers: { "content-type": "application/json" }, + ...opts, + }); + let data = null; + try { + data = await res.json(); + } catch (_) { + /* 非 JSON,交给调用方按状态码处理 */ + } + return { res, data }; +} + +/* ----------------------------- 渲染 ----------------------------- */ + +function buildCard(g) { + const el = document.createElement("article"); + el.className = "card"; + el.dataset.id = g.id; + el.style.setProperty("--accent", g.accent || "#4a8dff"); + el.innerHTML = ` +
+ + — +
+

+

+
    +
    + — + 进入 → +
    `; + + el.querySelector(".glyph").textContent = g.icon || g.name.slice(0, 1); + el.querySelector('[data-role="name"]').textContent = g.name; + el.querySelector('[data-role="tag"]').textContent = g.tagline || ""; + + const meta = el.querySelector('[data-role="meta"]'); + const chips = [...(g.meta || [])]; + if (g.stack) chips.push(g.stack); + for (const c of chips) { + const li = document.createElement("li"); + li.textContent = c; + meta.appendChild(li); + } + + el.addEventListener("click", (ev) => { + ev.preventDefault(); + if (el.classList.contains("loading")) return; + enterGame(g.id, el); + }); + + return el; +} + +function paint(el, g) { + const pill = el.querySelector('[data-role="pill"]'); + const stat = el.querySelector('[data-role="stat"]'); + + let cls = "asleep"; + let label = "休眠"; + let statText = ""; + + if (g.state === "static") { + if (!g.ready) { + cls = "error"; + label = "缺目录"; + statText = "目录不存在 · 检查 games.json 里的 dir"; + } else { + cls = "static"; + label = "静态"; + statText = "直接托管 · 不占进程"; + } + } else if (g.state === "running") { + cls = "running"; + label = "运行中"; + const ws = g.ws_conns > 0 ? ` · 联机中×${g.ws_conns}` : ""; + const rel = g.release_in_secs != null ? ` · ${fmtDur(g.release_in_secs)}后释放` : ""; + statText = `已运行 ${fmtDur(g.uptime_secs)}${ws}${rel}`; + } else if (g.state === "error") { + cls = "error"; + label = "异常"; + statText = g.error || "拉起失败"; + } else if (!g.ready) { + cls = "error"; + label = "未构建"; + statText = "二进制缺失"; + } else { + cls = "asleep"; + label = "休眠"; + statText = "点击即拉起"; + } + + if (el.dataset.state === "starting") { + cls = "starting"; + label = "启动中"; + statText = "正在拉起进程…"; + } + + pill.className = `pill ${cls}`; + pill.textContent = label; + stat.textContent = statText; + stat.title = statText; +} + +function applyState(data) { + const list = data.games || []; + const seen = new Set(); + + for (const g of list) { + seen.add(g.id); + let el = cards.get(g.id); + if (!el) { + el = buildCard(g); + cards.set(g.id, el); + $("#cards").appendChild(el); + } + paint(el, g); + } + + // 清单里被删掉的游戏,卡片也撤掉 + for (const [id, el] of cards) { + if (!seen.has(id)) { + el.remove(); + cards.delete(id); + } + } + + const running = list.filter((g) => g.state === "running").length; + $("#runningCount").textContent = running; + $("#totalCount").textContent = list.length; + $("#runtimeDot").classList.toggle("on", running > 0); + + const idle = data.idle_secs || 0; + $("#idleLabel").textContent = fmtIdle(idle); + $("#idleLabel2").textContent = fmtIdle(idle); + $("#portLabel").textContent = `:${data.port || 1818}`; +} + +async function refresh() { + try { + const { res, data } = await api("/api/games"); + if (!res.ok || !data || !data.ok) throw new Error(`状态接口 ${res.status}`); + applyState(data); + } catch (e) { + $("#runtimeDot").classList.remove("on"); + toast(`拿不到游戏状态:${e.message}`, true); + } +} + +/* ----------------------------- 进入 ----------------------------- */ + +async function enterGame(id, el) { + el.classList.add("loading"); + el.dataset.state = "starting"; + paint(el, { state: "asleep", ready: true }); + try { + const { res, data } = await api(`/api/games/${id}/wake`, { method: "POST" }); + if (!res.ok || !data || !data.ok) { + throw new Error((data && data.error) || `HTTP ${res.status}`); + } + location.href = data.path; + } catch (e) { + el.classList.remove("loading"); + delete el.dataset.state; + toast(`没能拉起:${String(e.message).split("\n")[0]}`, true); + refresh(); + } +} + +/* ----------------------------- 启动 ----------------------------- */ + +refresh(); +setInterval(() => { + if (!document.hidden) refresh(); +}, 2000); + +document.addEventListener("visibilitychange", () => { + if (!document.hidden) refresh(); +}); diff --git a/public/index.html b/public/index.html new file mode 100644 index 0000000..f0ce07c --- /dev/null +++ b/public/index.html @@ -0,0 +1,56 @@ + + + + + + + 游戏中心 · Game Center + + + + + + +
    +
    + +
    +

    游戏中心

    +

    GAME CENTER · :1818

    +
    +
    + +
    +
    + + + 运行中 0/0 + · 空闲 10 分钟后自动释放 + +
    +
    +
    + +
    +
    + +
    +

    + 一个端口,按路径区分。 + 每个游戏挂在独立前缀下;进程型游戏首个访客触发冷启动,没人访问且没有 WebSocket + 连接超过 10 分钟就自动释放,下次访问再拉起。 +

    +

    + 静态游戏(纯前端单页)由中心直接托管,不占进程,也就没有冷启动。状态每 2 秒自动刷新。 +

    +
    +
    + +
    + + + + diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..ab10128 --- /dev/null +++ b/public/style.css @@ -0,0 +1,506 @@ +:root { + --bg: #070b12; + --panel: rgba(15, 23, 37, 0.78); + --panel-2: rgba(11, 17, 28, 0.9); + --line: rgba(120, 165, 255, 0.14); + --line-strong: rgba(120, 165, 255, 0.3); + --text: #dde8fb; + --muted: #7d8ca8; + --muted-2: #5a6780; + --blue: #4a8dff; + --green: #46d39a; + --amber: #f0b429; + --red: #ff6b6b; + --mono: ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace; +} + +* { + box-sizing: border-box; +} + +html, +body { + margin: 0; + min-height: 100%; +} + +body { + background: var(--bg); + color: var(--text); + font-family: -apple-system, BlinkMacSystemFont, "PingFang SC", "Microsoft YaHei", + "Helvetica Neue", Arial, sans-serif; + font-size: 14px; + line-height: 1.6; + -webkit-font-smoothing: antialiased; + overflow-x: hidden; +} + +/* 背景:深蓝径向光 + 细网格 */ +.bg { + position: fixed; + inset: 0; + z-index: 0; + pointer-events: none; + background: + radial-gradient(900px 520px at 12% -8%, rgba(74, 141, 255, 0.16), transparent 70%), + radial-gradient(760px 460px at 92% 6%, rgba(70, 211, 154, 0.09), transparent 72%), + radial-gradient(680px 420px at 50% 108%, rgba(74, 141, 255, 0.08), transparent 70%); +} + +.bg::after { + content: ""; + position: absolute; + inset: 0; + background-image: + linear-gradient(rgba(120, 165, 255, 0.045) 1px, transparent 1px), + linear-gradient(90deg, rgba(120, 165, 255, 0.045) 1px, transparent 1px); + background-size: 64px 64px; + mask-image: radial-gradient(circle at 50% 30%, #000 0%, transparent 78%); + -webkit-mask-image: radial-gradient(circle at 50% 30%, #000 0%, transparent 78%); +} + +.topbar, +main { + position: relative; + z-index: 1; +} + +/* ------------------------------- 顶栏 ------------------------------- */ + +.topbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 20px; + flex-wrap: wrap; + padding: 26px clamp(18px, 5vw, 56px) 18px; + border-bottom: 1px solid var(--line); + backdrop-filter: blur(6px); +} + +.brand { + display: flex; + align-items: center; + gap: 14px; +} + +.logo { + width: 42px; + height: 42px; + border-radius: 13px; + border: 1px solid rgba(74, 141, 255, 0.45); + background: linear-gradient(150deg, rgba(74, 141, 255, 0.22), rgba(74, 141, 255, 0.04)); + display: grid; + place-items: center; + box-shadow: 0 0 24px rgba(74, 141, 255, 0.18) inset; +} + +.logo i { + width: 16px; + height: 16px; + border-radius: 50%; + border: 2px solid var(--blue); + box-shadow: 0 0 12px rgba(74, 141, 255, 0.7); + position: relative; +} + +.logo i::after { + content: ""; + position: absolute; + inset: 4px; + border-radius: 50%; + background: #9cc2ff; +} + +.brand-text h1 { + margin: 0; + font-size: 19px; + letter-spacing: 0.5px; + font-weight: 650; +} + +.brand-text p { + margin: 0; + font-family: var(--mono); + font-size: 11px; + letter-spacing: 1.4px; + color: var(--muted-2); + text-transform: uppercase; +} + +.topbar-right { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; +} + +.runtime { + display: flex; + align-items: center; + gap: 9px; + padding: 8px 14px; + border: 1px solid var(--line); + border-radius: 999px; + background: var(--panel-2); + font-size: 12.5px; + color: var(--muted); +} + +.runtime b { + color: var(--text); + font-family: var(--mono); + font-weight: 600; +} + +.runtime em { + font-style: normal; + color: var(--muted-2); + margin: 0 2px; +} + +.runtime-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: var(--muted-2); + box-shadow: 0 0 0 0 rgba(70, 211, 154, 0.5); +} + +.runtime-dot.on { + background: var(--green); + animation: breathe 2.2s infinite; +} + +@keyframes breathe { + 0% { + box-shadow: 0 0 0 0 rgba(70, 211, 154, 0.45); + } + 70% { + box-shadow: 0 0 0 7px rgba(70, 211, 154, 0); + } + 100% { + box-shadow: 0 0 0 0 rgba(70, 211, 154, 0); + } +} + +/* ------------------------------- 卡片区 ------------------------------- */ + +main { + padding: 30px clamp(18px, 5vw, 56px) 48px; + max-width: 1320px; + margin: 0 auto; +} + +.cards { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(306px, 1fr)); + gap: 18px; +} + +.card { + --accent: var(--blue); + position: relative; + display: flex; + flex-direction: column; + gap: 12px; + padding: 20px 20px 16px; + border-radius: 18px; + border: 1px solid var(--line); + background: linear-gradient(160deg, rgba(20, 30, 48, 0.9), rgba(10, 15, 25, 0.92)); + overflow: hidden; + cursor: pointer; + transition: transform 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease; + color: inherit; + text-decoration: none; +} + +.card::before { + content: ""; + position: absolute; + inset: -40% -20% auto -20%; + height: 220px; + background: radial-gradient( + circle at 30% 0%, + color-mix(in srgb, var(--accent) 26%, transparent), + transparent 68% + ); + opacity: 0.55; + transition: opacity 0.18s ease; + pointer-events: none; +} + +.card:hover { + transform: translateY(-3px); + border-color: color-mix(in srgb, var(--accent) 45%, transparent); + box-shadow: 0 18px 40px -22px color-mix(in srgb, var(--accent) 60%, transparent), + 0 0 0 1px color-mix(in srgb, var(--accent) 18%, transparent) inset; +} + +.card:hover::before { + opacity: 0.9; +} + +.card.loading { + cursor: progress; +} + +.card.loading::after { + content: ""; + position: absolute; + inset: 0; + background: linear-gradient( + 100deg, + transparent 20%, + color-mix(in srgb, var(--accent) 14%, transparent) 50%, + transparent 80% + ); + animation: sweep 1.1s linear infinite; +} + +@keyframes sweep { + from { + transform: translateX(-60%); + } + to { + transform: translateX(60%); + } +} + +.card-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 12px; + position: relative; +} + +.glyph { + width: 50px; + height: 50px; + border-radius: 14px; + display: grid; + place-items: center; + font-size: 22px; + font-weight: 700; + letter-spacing: 0; + color: color-mix(in srgb, var(--accent) 88%, white); + border: 1px solid color-mix(in srgb, var(--accent) 42%, transparent); + background: color-mix(in srgb, var(--accent) 16%, rgba(9, 14, 23, 0.9)); + box-shadow: 0 0 22px -8px color-mix(in srgb, var(--accent) 70%, transparent) inset; +} + +.pill { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border-radius: 999px; + font-size: 11.5px; + font-family: var(--mono); + letter-spacing: 0.3px; + border: 1px solid var(--line); + color: var(--muted); + background: rgba(9, 14, 23, 0.72); + white-space: nowrap; +} + +.pill::before { + content: ""; + width: 6px; + height: 6px; + border-radius: 50%; + background: currentColor; +} + +.pill.running { + color: var(--green); + border-color: rgba(70, 211, 154, 0.35); + background: rgba(70, 211, 154, 0.08); +} + +.pill.asleep { + color: var(--muted-2); +} + +.pill.static { + color: #8fb6ff; + border-color: rgba(120, 165, 255, 0.28); + background: rgba(74, 141, 255, 0.08); +} + +.pill.error { + color: var(--red); + border-color: rgba(255, 107, 107, 0.35); + background: rgba(255, 107, 107, 0.08); +} + +.pill.starting { + color: var(--amber); + border-color: rgba(240, 180, 41, 0.35); + background: rgba(240, 180, 41, 0.08); +} + +.pill.starting::before { + animation: blink 0.9s infinite; +} + +@keyframes blink { + 50% { + opacity: 0.25; + } +} + +.card h2 { + margin: 2px 0 0; + font-size: 17px; + font-weight: 650; + letter-spacing: 0.3px; + position: relative; +} + +.tag { + margin: -8px 0 0; + font-size: 12.5px; + color: var(--muted); + min-height: 40px; + position: relative; +} + +.meta { + list-style: none; + display: flex; + flex-wrap: wrap; + gap: 6px; + margin: 0; + padding: 0; + position: relative; +} + +.meta li { + font-size: 11px; + color: var(--muted); + padding: 3px 9px; + border-radius: 7px; + background: rgba(120, 165, 255, 0.07); + border: 1px solid rgba(120, 165, 255, 0.1); + white-space: nowrap; +} + +.card-foot { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-top: 4px; + padding-top: 12px; + border-top: 1px dashed rgba(120, 165, 255, 0.12); + position: relative; +} + +.stat { + font-family: var(--mono); + font-size: 11.5px; + color: var(--muted-2); + letter-spacing: 0.2px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.stat b { + color: var(--muted); + font-weight: 500; +} + +.go { + font-size: 12px; + font-weight: 600; + padding: 5px 12px; + border-radius: 9px; + color: color-mix(in srgb, var(--accent) 92%, white); + border: 1px solid color-mix(in srgb, var(--accent) 45%, transparent); + background: color-mix(in srgb, var(--accent) 14%, transparent); + white-space: nowrap; + flex: 0 0 auto; + transition: all 0.16s; +} + +.card:hover .go { + background: color-mix(in srgb, var(--accent) 26%, transparent); +} + +/* ------------------------------- 页脚 ------------------------------- */ + +.page-foot { + margin-top: 34px; + padding: 18px 20px; + border: 1px solid var(--line); + border-radius: 14px; + background: var(--panel); + color: var(--muted); + font-size: 12.5px; +} + +.page-foot p { + margin: 0; +} + +.page-foot b { + color: var(--text); + font-weight: 600; +} + +.page-foot .tiny { + margin-top: 6px; + color: var(--muted-2); + font-size: 11.5px; +} + +/* ------------------------------- toast ------------------------------- */ + +.toast { + position: fixed; + left: 50%; + bottom: 32px; + transform: translate(-50%, 16px); + padding: 10px 18px; + border-radius: 11px; + border: 1px solid var(--line-strong); + background: rgba(16, 24, 38, 0.96); + color: var(--text); + font-size: 13px; + box-shadow: 0 16px 40px -18px rgba(0, 0, 0, 0.9); + opacity: 0; + pointer-events: none; + transition: opacity 0.2s, transform 0.2s; + z-index: 20; + max-width: min(560px, 88vw); +} + +.toast.show { + opacity: 1; + transform: translate(-50%, 0); +} + +.toast.err { + border-color: rgba(255, 107, 107, 0.45); + color: #ffd2d2; +} + +@media (max-width: 620px) { + .topbar { + padding-top: 18px; + } + .runtime { + order: 3; + width: 100%; + justify-content: center; + } + .cards { + grid-template-columns: 1fr; + } + .tag { + min-height: 0; + } +} diff --git a/run.sh b/run.sh new file mode 100755 index 0000000..bddcc6f --- /dev/null +++ b/run.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +# 启动游戏中心:没有二进制就先编,然后前台跑在 1818。 +set -euo pipefail + +here="$(cd "$(dirname "$0")" && pwd)" +bin="$here/target/release/game-center" + +if [ ! -x "$bin" ]; then + echo "==> 首次运行,先编译 game-center" + ( cd "$here" && cargo build --release ) +fi + +exec "$bin" "$@" diff --git a/scripts/build-games.sh b/scripts/build-games.sh new file mode 100755 index 0000000..749362f --- /dev/null +++ b/scripts/build-games.sh @@ -0,0 +1,27 @@ +#!/usr/bin/env bash +# 把三个「进程型」游戏编成 release 单文件二进制。 +# 游戏中心只在第一次访问时才拉起它们,所以先得有这么三个可执行文件。 +set -euo pipefail + +here="$(cd "$(dirname "$0")/.." && pwd)" + +for g in cnchess cngo cs; do + dir="$here/../$g" + if [ ! -d "$dir" ]; then + echo "!! 找不到 $dir,跳过" + continue + fi + echo "==> 构建 $g($(basename "$dir"))" + ( cd "$dir" && cargo build --release ) +done + +echo +echo "完成。二进制:" +for g in cnchess cngo cs; do + bin="$here/../$g/target/release/$g" + if [ -x "$bin" ]; then + printf ' %-10s %s\n' "$g" "$(du -h "$bin" | cut -f1)" + else + printf ' %-10s 缺失\n' "$g" + fi +done diff --git a/src/assets.rs b/src/assets.rs new file mode 100644 index 0000000..7370344 --- /dev/null +++ b/src/assets.rs @@ -0,0 +1,37 @@ +//! 启动器页面资源:磁盘优先 → 编译期内嵌兜底(跟 cnchess 一样的做法) + +use std::path::Path; + +include!(concat!(env!("OUT_DIR"), "/assets_gen.rs")); + +pub fn mime_of(key: &str) -> &'static str { + match key.rsplit('.').next().unwrap_or("").to_ascii_lowercase().as_str() { + "html" | "htm" => "text/html; charset=utf-8", + "js" | "mjs" => "text/javascript; charset=utf-8", + "css" => "text/css; charset=utf-8", + "json" | "webmanifest" => "application/json; charset=utf-8", + "png" => "image/png", + "jpg" | "jpeg" => "image/jpeg", + "svg" => "image/svg+xml", + "ico" => "image/x-icon", + "woff2" => "font/woff2", + "webp" => "image/webp", + _ => "application/octet-stream", + } +} + +/// 按 key(形如 `/style.css`)取资源,磁盘上的 public/ 优先 +pub fn lookup(base: &Path, key: &str) -> Option<(String, Vec)> { + let rel = key.trim_start_matches('/'); + if rel.contains("..") { + return None; + } + let p = base.join("public").join(rel); + if let Ok(bytes) = std::fs::read(&p) { + return Some((mime_of(rel).to_string(), bytes)); + } + ASSETS + .iter() + .find(|(k, _, _)| *k == key) + .map(|(_, m, b)| (m.to_string(), b.to_vec())) +} diff --git a/src/config.rs b/src/config.rs new file mode 100644 index 0000000..32b67c8 --- /dev/null +++ b/src/config.rs @@ -0,0 +1,108 @@ +//! 游戏清单:优先读磁盘上的 games.json(改完刷新即可,不用重编译), +//! 读不到就用编译时内嵌的同一份。 + +use std::path::Path; + +use serde::Deserialize; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)] +#[serde(rename_all = "lowercase")] +pub enum Kind { + /// 独立后端进程:按需拉起、空闲释放 + Process, + /// 纯静态目录:由中心直接托管,没有进程可释放 + Static, +} + +#[derive(Debug, Clone, Deserialize)] +pub struct GameDef { + pub id: String, + pub name: String, + #[serde(default)] + pub tagline: String, + #[serde(default)] + pub icon: String, + #[serde(default)] + pub accent: String, + #[serde(default)] + pub stack: String, + #[serde(default)] + pub meta: Vec, + #[serde(default = "default_kind")] + pub kind: Kind, + /// 路由前缀,缺省取 id + #[serde(default)] + pub route: Option, + /// 进程型:相对 center/ 的工作目录与二进制 + #[serde(default)] + pub cwd: String, + #[serde(default)] + pub bin: String, + /// 静态型:相对 center/ 的资源目录与入口文件 + #[serde(default)] + pub dir: String, + #[serde(default)] + pub entry: Option, + /// 额外的文本重写规则(from, to),to 里可用 {prefix} + #[serde(default)] + pub rewrites: Vec<(String, String)>, +} + +impl GameDef { + pub fn route(&self) -> String { + self.route.clone().unwrap_or_else(|| self.id.clone()) + } + + /// 静态型的入口文件 + pub fn entry_name(&self) -> &str { + self.entry.as_deref().unwrap_or("index.html") + } +} + +#[derive(Debug, Clone, Deserialize)] +pub struct Config { + #[serde(default = "default_port")] + pub port: u16, + #[serde(default = "default_idle")] + pub idle_secs: u64, + #[serde(default)] + pub games: Vec, +} + +fn default_port() -> u16 { + 1818 +} + +fn default_idle() -> u64 { + 600 +} + +fn default_kind() -> Kind { + Kind::Process +} + +const EMBEDDED: &str = include_str!("../games.json"); + +pub fn load(base: &Path) -> Config { + let path = base.join("games.json"); + let raw = std::fs::read_to_string(&path).unwrap_or_else(|_| EMBEDDED.to_string()); + let mut cfg: Config = match serde_json::from_str(&raw) { + Ok(c) => c, + Err(e) => { + eprintln!("[gc] games.json 解析失败({e}),改用内嵌清单"); + serde_json::from_str(EMBEDDED).expect("内嵌清单必须合法") + } + }; + + // 环境变量兜底,方便临时改端口 / 回收时间 + if let Some(p) = std::env::var("GC_PORT").ok().and_then(|v| v.parse().ok()) { + cfg.port = p; + } + if let Some(v) = std::env::var("GC_IDLE_SECS").ok().and_then(|v| v.parse().ok()) { + cfg.idle_secs = v; + } + if cfg.games.is_empty() { + cfg = serde_json::from_str(EMBEDDED).expect("内嵌清单必须合法"); + } + cfg +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..9b16663 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,315 @@ +//! 游戏中心:单端口(默认 1818)+ 按路径分发 + 按需拉起 / 空闲释放。 +//! +//! ```text +//! / 启动器页面 +//! /cnchess/ 中国象棋 ← 进程型:冷启动 / 空闲回收 +//! /cngo/ 围棋 ← 进程型 +//! /cs/ 枪火对决 ← 进程型 +//! /alonelyroad/ 沙漠狂飙 ← 静态目录 +//! /myword/ 我的世界 ← 静态目录 +//! /api/games 状态快照 /api/games/{id}/wake|stop /health +//! ``` + +mod assets; +mod config; +mod proxy; +mod registry; + +use std::net::SocketAddr; +use std::path::PathBuf; +use std::sync::Arc; +use std::time::Duration; + +use axum::extract::{Path as UrlPath, State}; +use axum::http::{header, StatusCode}; +use axum::response::{IntoResponse, Response}; +use axum::routing::{any, get, post}; +use axum::Router; +use serde_json::{json, Value}; + +use registry::{now_secs, Runtime}; + +pub struct AppState { + pub base: PathBuf, + pub logs: PathBuf, + pub port: u16, + pub idle_secs: u64, + pub boot: u64, + pub games: Vec>, +} + +impl AppState { + pub fn find(&self, seg: &str) -> Option> { + self.games + .iter() + .find(|g| g.route() == seg) + .map(Arc::clone) + } + + pub fn find_by_id(&self, id: &str) -> Option> { + self.games.iter().find(|g| g.def.id == id).map(Arc::clone) + } +} + +fn json_resp(status: StatusCode, v: Value) -> Response { + ( + status, + [(header::CONTENT_TYPE, "application/json; charset=utf-8")], + v.to_string(), + ) + .into_response() +} + +#[tokio::main] +async fn main() { + let base = std::env::var("GC_HOME") + .map(PathBuf::from) + .unwrap_or_else(|_| PathBuf::from(env!("CARGO_MANIFEST_DIR"))); + let cfg = config::load(&base); + + let games: Vec> = cfg + .games + .iter() + .cloned() + .map(|d| Arc::new(Runtime::new(d))) + .collect(); + + let state = Arc::new(AppState { + logs: base.join("run/logs"), + base: base.clone(), + port: cfg.port, + idle_secs: cfg.idle_secs, + boot: now_secs(), + games: games.clone(), + }); + + // 后台回收器:每 5s 扫一遍,空闲够久就杀进程 + { + let games = games.clone(); + let idle = Duration::from_secs(cfg.idle_secs); + tokio::spawn(async move { + let mut tick = tokio::time::interval(Duration::from_secs(5)); + tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Delay); + loop { + tick.tick().await; + for g in &games { + g.tick(idle).await; + } + } + }); + } + + let host = std::env::var("GC_HOST").unwrap_or_else(|_| "0.0.0.0".to_string()); + let addr: SocketAddr = match format!("{host}:{}", cfg.port).parse() { + Ok(a) => a, + Err(_) => { + eprintln!("地址不合法:{host}:{}", cfg.port); + std::process::exit(1); + } + }; + + let app = router(state.clone()); + let listener = match tokio::net::TcpListener::bind(addr).await { + Ok(l) => l, + Err(e) => { + eprintln!("端口 {} 起不来:{e}", cfg.port); + std::process::exit(1); + } + }; + + banner(&state, cfg.port); + + let shutdown = { + let games = games.clone(); + async move { + wait_shutdown().await; + eprintln!("\n[gc] 收到退出信号,释放所有游戏进程"); + for g in &games { + g.release("中心退出").await; + } + } + }; + + if let Err(e) = axum::serve(listener, app) + .with_graceful_shutdown(shutdown) + .await + { + eprintln!("服务异常退出:{e}"); + std::process::exit(1); + } +} + +fn router(state: Arc) -> Router { + Router::new() + .route("/api/games", get(api_games)) + .route("/api/games/{id}/wake", post(api_wake)) + .route("/api/games/{id}/stop", post(api_stop)) + .route("/api/stop-all", post(api_stop_all)) + .route("/health", get(health)) + .fallback(any(proxy::dispatch)) + .with_state(state) +} + +/* ------------------------------- API ------------------------------- */ + +async fn api_games(State(state): State>) -> Response { + let mut list = Vec::with_capacity(state.games.len()); + for g in &state.games { + list.push(g.status(&state.base, state.idle_secs).await); + } + let running = list.iter().filter(|s| s.state == "running").count(); + json_resp( + StatusCode::OK, + json!({ + "ok": true, + "port": state.port, + "idle_secs": state.idle_secs, + "uptime_secs": now_secs().saturating_sub(state.boot), + "running": running, + "total": list.len(), + "games": list, + }), + ) +} + +async fn api_wake(State(state): State>, UrlPath(id): UrlPath) -> Response { + let Some(rt) = state.find_by_id(&id) else { + return json_resp( + StatusCode::NOT_FOUND, + json!({"ok": false, "error": format!("没有这个游戏:{id}")}), + ); + }; + if rt.is_static() { + return json_resp( + StatusCode::OK, + json!({"ok": true, "state": "static", "path": format!("/{}/", rt.route())}), + ); + } + match rt.ensure(&state.base, &state.logs).await { + Ok(port) => json_resp( + StatusCode::OK, + json!({"ok": true, "state": "running", "port": port, + "path": format!("/{}/", rt.route())}), + ), + Err(e) => json_resp(StatusCode::BAD_GATEWAY, json!({"ok": false, "error": e})), + } +} + +async fn api_stop(State(state): State>, UrlPath(id): UrlPath) -> Response { + let Some(rt) = state.find_by_id(&id) else { + return json_resp( + StatusCode::NOT_FOUND, + json!({"ok": false, "error": format!("没有这个游戏:{id}")}), + ); + }; + rt.release("手动释放").await; + json_resp(StatusCode::OK, json!({"ok": true})) +} + +async fn api_stop_all(State(state): State>) -> Response { + let mut n = 0; + for g in &state.games { + g.release("一键释放").await; + n += 1; + } + json_resp(StatusCode::OK, json!({"ok": true, "released": n})) +} + +async fn health(State(state): State>) -> Response { + let mut running = 0; + for g in &state.games { + if g.status(&state.base, state.idle_secs).await.state == "running" { + running += 1; + } + } + json_resp( + StatusCode::OK, + json!({ + "ok": true, + "engine": "rust", + "mode": "lazy-proxy", + "port": state.port, + "uptime_secs": now_secs().saturating_sub(state.boot), + "games": state.games.len(), + "running": running, + "idle_secs": state.idle_secs, + }), + ) +} + +/* ------------------------------- 启动横幅 ------------------------------- */ + +/// Ctrl-C / SIGTERM / SIGHUP 都当作退出信号:三种情况都要先把子进程清掉, +/// 否则中心没了、游戏还在后台占内存。 +async fn wait_shutdown() { + #[cfg(unix)] + { + use tokio::signal::unix::{signal, SignalKind}; + let mut term = match signal(SignalKind::terminate()) { + Ok(s) => s, + Err(_) => { + let _ = tokio::signal::ctrl_c().await; + return; + } + }; + let mut hup = match signal(SignalKind::hangup()) { + Ok(s) => s, + Err(_) => { + let _ = tokio::signal::ctrl_c().await; + return; + } + }; + tokio::select! { + _ = tokio::signal::ctrl_c() => {} + _ = term.recv() => {} + _ = hup.recv() => {} + } + } + #[cfg(not(unix))] + { + let _ = tokio::signal::ctrl_c().await; + } +} + +fn banner(state: &AppState, port: u16) { + println!(); + println!(" 游戏中心 已启动"); + println!(" 统一端口 {port}(按路径分发,进程按需拉起 / 空闲回收)"); + println!(" 空闲回收 {}s 无请求且无 WebSocket 连接才释放", state.idle_secs); + println!(" 本机访问 http://localhost:{port}"); + for ip in lan_addrs() { + println!(" 同一局域网 http://{ip}:{port}"); + } + println!(); + for g in &state.games { + let kind = if g.is_static() { "静态" } else { "进程" }; + let bin = if g.is_static() { + format!("{}/{}", g.def.dir, g.def.entry_name()) + } else { + format!("{}/{}", g.def.cwd, g.def.bin) + }; + let mark = if g.ready_on_disk(&state.base) { "" } else { " ⚠ 未构建" }; + println!( + " /{:<12} {:<10} {:<4} {}{}", + g.route(), + g.def.name, + kind, + bin, + mark + ); + } + println!(); +} + +/// 本机 IPv4(打印局域网地址用),跟三个游戏里同一套做法,不引第三方依赖 +fn lan_addrs() -> Vec { + let mut out = Vec::new(); + if let Ok(sock) = std::net::UdpSocket::bind("0.0.0.0:0") { + if sock.connect("8.8.8.8:80").is_ok() { + if let Ok(addr) = sock.local_addr() { + out.push(addr.ip().to_string()); + } + } + } + out +} diff --git a/src/proxy.rs b/src/proxy.rs new file mode 100644 index 0000000..89687a0 --- /dev/null +++ b/src/proxy.rs @@ -0,0 +1,474 @@ +//! 统一代理:一个端口(默认 1818),按路径前缀分发到各个游戏。 +//! +//! - `/cnchess/...` → 拉起 `cnchess` 进程(动态端口)并把前缀剥掉转发; +//! - `/alonelyroad/` → 静态目录直接托管,没有进程; +//! - WebSocket 用**原始 TCP 隧道**:只在握手阶段改请求行和 Host, +//! 拿到 101 之后双向字节流直接对拷,游戏里的帧格式完全不用关心。 +//! +//! 路径前缀带来的两个副作用在这里统一补偿: +//! 1. 游戏前端写死的根绝对路径(`/style.css`、`/js/...`、`/ws`、`fetch("/level.json")`) +//! 在文本响应里就地重写成带前缀的版本; +//! 2. `/cnchess` 少写斜杠时 301 到 `/cnchess/`,否则页面里的相对路径会解析到根。 + +use std::net::SocketAddr; +use std::sync::Arc; + +use axum::body::Body; +use axum::extract::State; +use axum::http::{ + header, HeaderMap, HeaderName, HeaderValue, Request, StatusCode, +}; +use axum::response::{IntoResponse, Response}; +use http_body_util::BodyExt; +use hyper_util::rt::TokioIo; +use tokio::io::{AsyncReadExt, AsyncWriteExt}; +use tokio::net::TcpStream; + +use crate::assets; +use crate::registry::{Runtime, WsGuard}; +use crate::AppState; + +const MAX_HEAD: usize = 64 * 1024; + +/* ------------------------------- 分发 ------------------------------- */ + +pub async fn dispatch(State(state): State>, req: Request) -> Response { + let path = req.uri().path().to_string(); + + if path == "/" { + return launcher(&state); + } + + let trimmed = path.trim_start_matches('/'); + let (seg, rest) = match trimmed.split_once('/') { + Some((s, r)) => (s, format!("/{r}")), + None => (trimmed, String::new()), + }; + + let Some(rt) = state.find(seg) else { + // 不是游戏前缀,再看看是不是启动器自己的静态资源 + if let Some((mime, bytes)) = assets::lookup(&state.base, &path) { + return with_no_cache(([(header::CONTENT_TYPE, mime)], bytes).into_response()); + } + return not_found(&path); + }; + + // `/cnchess` → `/cnchess/`,避免相对路径解析跑偏 + if rest.is_empty() { + let q = req + .uri() + .query() + .map(|q| format!("?{q}")) + .unwrap_or_default(); + return Response::builder() + .status(StatusCode::MOVED_PERMANENTLY) + .header(header::LOCATION, format!("{path}/{q}")) + .body(Body::empty()) + .unwrap(); + } + + if rt.is_static() { + return serve_static(&state, &rt, &rest).await; + } + + let target = { + let q = req + .uri() + .query() + .map(|q| format!("?{q}")) + .unwrap_or_default(); + format!("{rest}{q}") + }; + + let _lease = rt.lease(); + let port = match rt.ensure(&state.base, &state.logs).await { + Ok(p) => p, + Err(e) => return boot_error(&rt, &e), + }; + let addr = SocketAddr::from(([127, 0, 0, 1], port)); + + if is_ws(&req) { + tunnel(rt.clone(), addr, target, req).await + } else { + forward(&state, &rt, addr, port, target, req).await + } +} + +/* ------------------------------- 启动器 ------------------------------- */ + +fn launcher(state: &AppState) -> Response { + match assets::lookup(&state.base, "/index.html") { + Some((mime, body)) => with_no_cache( + Response::builder() + .header(header::CONTENT_TYPE, mime) + .body(Body::from(body)) + .unwrap(), + ), + None => ( + StatusCode::INTERNAL_SERVER_ERROR, + "启动器页面丢了:public/index.html", + ) + .into_response(), + } +} + +fn with_no_cache(mut resp: Response) -> Response { + resp.headers_mut().insert( + header::CACHE_CONTROL, + HeaderValue::from_static("no-cache, must-revalidate"), + ); + resp +} + +fn not_found(path: &str) -> Response { + let html = format!( + r#" +404 · 游戏中心 +
    +

    404

    没有这个游戏路径:{path}

    +← 回到游戏中心
    "# + ); + with_no_cache( + Response::builder() + .status(StatusCode::NOT_FOUND) + .header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .body(Body::from(html)) + .unwrap(), + ) +} + +fn boot_error(rt: &Runtime, err: &str) -> Response { + let name = &rt.def.name; + let detail = err.replace('&', "&").replace('<', "<"); + let html = format!( + r#" +拉起失败 · {name} +
    +

    {name} 没能拉起来

    {detail}
    +

    ← 回到游戏中心

    "# + ); + with_no_cache( + Response::builder() + .status(StatusCode::BAD_GATEWAY) + .header(header::CONTENT_TYPE, "text/html; charset=utf-8") + .body(Body::from(html)) + .unwrap(), + ) +} + +/* ------------------------------- 静态游戏 ------------------------------- */ + +async fn serve_static(state: &AppState, rt: &Arc, rest: &str) -> Response { + let dir = state.base.join(&rt.def.dir); + let rel = rest.trim_start_matches('/'); + let rel = if rel.is_empty() { rt.def.entry_name() } else { rel }; + + if rel.split('/').any(|c| c == "..") { + return not_found(rest); + } + + let mut path = dir.join(rel); + if path.is_dir() { + path = path.join(rt.def.entry_name()); + } + + match tokio::fs::read(&path).await { + Ok(bytes) => { + let mime = assets::mime_of(rel); + with_no_cache( + Response::builder() + .header(header::CONTENT_TYPE, mime) + .body(Body::from(bytes)) + .unwrap(), + ) + } + Err(_) => not_found(rest), + } +} + +/* ------------------------------- HTTP 反代 ------------------------------- */ + +fn hop_by_hop(name: &str) -> bool { + matches!( + name.to_ascii_lowercase().as_str(), + "connection" + | "keep-alive" + | "proxy-authenticate" + | "proxy-authorization" + | "proxy-connection" + | "te" + | "trailer" + | "transfer-encoding" + | "upgrade" + | "host" + | "content-length" + | "accept-encoding" + ) +} + +async fn forward( + _state: &AppState, + rt: &Arc, + addr: SocketAddr, + port: u16, + target: String, + req: Request, +) -> Response { + let method = req.method().clone(); + let mut headers = HeaderMap::new(); + for (k, v) in req.headers() { + if hop_by_hop(k.as_str()) { + continue; + } + headers.insert(k.clone(), v.clone()); + } + headers.insert( + header::HOST, + HeaderValue::from_str(&format!("127.0.0.1:{port}")).unwrap(), + ); + headers.insert(header::ACCEPT_ENCODING, HeaderValue::from_static("identity")); + + let io = match TcpStream::connect(addr).await { + Ok(io) => io, + Err(e) => return upstream_error(rt, &format!("连不上后端 {addr}:{e}")), + }; + let (mut sender, conn) = match hyper::client::conn::http1::handshake(TokioIo::new(io)).await { + Ok(v) => v, + Err(e) => return upstream_error(rt, &format!("后端握手失败:{e}")), + }; + tokio::spawn(async move { + let _ = conn.await; + }); + + let mut out = Request::builder() + .method(method) + .uri(target.clone()) + .body(req.into_body()) + .unwrap(); + *out.headers_mut() = headers; + + let res = match sender.send_request(out).await { + Ok(r) => r, + Err(e) => return upstream_error(rt, &format!("后端没有响应:{e}")), + }; + + let status = res.status(); + let mut res_headers = res.headers().clone(); + let bytes = match res.into_body().collect().await { + Ok(c) => c.to_bytes(), + Err(e) => return upstream_error(rt, &format!("读后端响应体失败:{e}")), + }; + + let body = if is_textual(&res_headers) { + rewrite_text(rt, &bytes).into() + } else { + bytes + }; + + res_headers.remove(header::CONTENT_LENGTH); + res_headers.remove(header::CONTENT_ENCODING); + res_headers.remove(header::TRANSFER_ENCODING); + res_headers.remove(header::CONNECTION); + res_headers.insert( + header::CACHE_CONTROL, + HeaderValue::from_static("no-cache, must-revalidate"), + ); + + let mut resp = Response::new(Body::from(body)); + *resp.status_mut() = status; + *resp.headers_mut() = res_headers; + resp +} + +fn upstream_error(rt: &Runtime, msg: &str) -> Response { + eprintln!("[gc] {} 代理失败:{msg}", rt.def.id); + ( + StatusCode::BAD_GATEWAY, + [(header::CONTENT_TYPE, "application/json; charset=utf-8")], + format!( + r#"{{"ok":false,"game":"{}","error":"{}"}}"#, + rt.def.id, + msg.replace('"', "'") + ), + ) + .into_response() +} + +/* ------------------------------- 文本重写 ------------------------------- */ + +fn is_textual(headers: &HeaderMap) -> bool { + let Some(ct) = headers + .get(header::CONTENT_TYPE) + .and_then(|v| v.to_str().ok()) + else { + return false; + }; + let ct = ct.to_ascii_lowercase(); + ct.starts_with("text/html") + || ct.starts_with("text/css") + || ct.contains("javascript") + || ct.starts_with("text/plain") +} + +/// 把游戏里写死的根路径补上 `//` 前缀 +fn rewrite_text(rt: &Runtime, body: &[u8]) -> Vec { + let prefix = format!("/{}/", rt.route()); + let mut s = String::from_utf8_lossy(body).into_owned(); + + // WS / API 地址:三个游戏都是 `${proto}//${location.host}/ws` + s = s.replace("location.host}/", &format!("location.host}}{prefix}")); + + // HTML / CSS / JS 里的根绝对路径 + let pairs = [ + ("href=\"/", format!("href=\"{prefix}")), + ("src=\"/", format!("src=\"{prefix}")), + ("action=\"/", format!("action=\"{prefix}")), + ("fetch(\"/", format!("fetch(\"{prefix}")), + ("url(/", format!("url({prefix}")), + ]; + for (from, to) in pairs { + s = s.replace(from, &to); + } + + // 每个游戏自己补的规则(from → to,to 里可用 {prefix}) + for (from, to) in &rt.def.rewrites { + if from.is_empty() { + continue; + } + s = s.replace(from, &to.replace("{prefix}", &prefix)); + } + + s.into_bytes() +} + +/* ------------------------------- WebSocket ------------------------------- */ + +fn is_ws(req: &Request) -> bool { + req.headers() + .get(header::UPGRADE) + .and_then(|v| v.to_str().ok()) + .map(|v| v.to_ascii_lowercase().contains("websocket")) + .unwrap_or(false) +} + +async fn tunnel(rt: Arc, addr: SocketAddr, target: String, req: Request) -> Response { + // 先把请求头抄下来(upgrade 句柄要吃掉整个 Request) + let mut head = format!("GET {target} HTTP/1.1\r\n"); + for (k, v) in req.headers() { + let name = k.as_str().to_ascii_lowercase(); + if matches!( + name.as_str(), + "host" | "proxy-connection" | "keep-alive" | "te" | "trailer" | "transfer-encoding" + ) { + continue; + } + let Ok(val) = v.to_str() else { continue }; + head.push_str(&format!("{}: {}\r\n", k.as_str(), val)); + } + head.push_str(&format!("Host: 127.0.0.1:{}\r\n\r\n", addr.port())); + + let on_upgrade = hyper::upgrade::on(req); + + let mut tcp = match TcpStream::connect(addr).await { + Ok(t) => t, + Err(e) => return upstream_error(&rt, &format!("连不上后端 {addr}:{e}")), + }; + if let Err(e) = tcp.write_all(head.as_bytes()).await { + return upstream_error(&rt, &format!("握手写入失败:{e}")); + } + + // 读后端响应头(101 之前不会有 body) + let mut buf: Vec = Vec::with_capacity(1024); + let mut tmp = [0u8; 2048]; + let split = loop { + if let Some(idx) = find_head_end(&buf) { + break idx; + } + if buf.len() > MAX_HEAD { + return upstream_error(&rt, "后端响应头过大"); + } + match tcp.read(&mut tmp).await { + Ok(0) => return upstream_error(&rt, "后端在握手阶段就断开了"), + Ok(n) => buf.extend_from_slice(&tmp[..n]), + Err(e) => return upstream_error(&rt, &format!("读握手响应失败:{e}")), + } + }; + + let (head_bytes, leftover) = buf.split_at(split); + let head_str = String::from_utf8_lossy(head_bytes).into_owned(); + let leftover = leftover.to_vec(); + + let first_line = head_str.lines().next().unwrap_or(""); + if !first_line.contains(" 101") { + return upstream_error(&rt, &format!("后端拒绝升级:{first_line}")); + } + + let mut resp = Response::new(Body::empty()); + *resp.status_mut() = StatusCode::SWITCHING_PROTOCOLS; + for line in head_str.lines().skip(1) { + let Some((k, v)) = line.split_once(':') else { + continue; + }; + let (Ok(name), Ok(val)) = ( + HeaderName::from_bytes(k.trim().as_bytes()), + HeaderValue::from_str(v.trim()), + ) else { + continue; + }; + if name == header::CONTENT_LENGTH { + continue; + } + resp.headers_mut().append(name, val); + } + + let guard = WsGuard::new(rt.clone()); + tokio::spawn(async move { + let _guard = guard; // 连接活多久,回收器就绕道多久 + let Ok(upgraded) = on_upgrade.await else { + return; + }; + let mut client = TokioIo::new(upgraded); + if !leftover.is_empty() && client.write_all(&leftover).await.is_err() { + return; + } + + // 任一方向 EOF 就整体拆连接:copy_bidirectional 会等两边都结束, + // 遇到「客户端浏览器关了、后端还挂着 WS」时计数迟迟不归零, + // 这里要的是立刻归还 ws_conns。 + let (mut cr, mut cw) = tokio::io::split(client); + let (mut br, mut bw) = tcp.into_split(); + let c2b = tokio::io::copy(&mut cr, &mut bw); + let b2c = tokio::io::copy(&mut br, &mut cw); + tokio::pin!(c2b, b2c); + tokio::select! { + _ = &mut c2b => {} + _ = &mut b2c => {} + } + }); + + resp +} + +fn find_head_end(buf: &[u8]) -> Option { + buf.windows(4).position(|w| w == b"\r\n\r\n").map(|i| i + 4) +} diff --git a/src/registry.rs b/src/registry.rs new file mode 100644 index 0000000..cb832bd --- /dev/null +++ b/src/registry.rs @@ -0,0 +1,380 @@ +//! 进程生命周期:按需拉起、就绪探测、空闲释放、崩溃复位。 +//! +//! 规则(对应「没有使用就释放,有访问再拉起」): +//! - 请求进来先 `ensure()`:没进程就以**动态端口**拉一个,等它开始 listen 再转发; +//! - 每个进程记着 `last_hit`;回收器每 5s 扫一遍,满足 +//! `inflight == 0 && ws_conns == 0 && 空闲 ≥ GC_IDLE_SECS` 才杀; +//! - 有 WebSocket 连着就**绝不回收**(对局中、等待对手都靠这条保命), +//! 局面清空 / 浏览器关页面后 WS 断开,再开始计空闲。 +//! - 进程自己退出(panic / 被手动 kill)也会被扫到,下一次访问自动重拉。 + +use std::path::{Path, PathBuf}; +use std::process::Stdio; +use std::sync::atomic::{AtomicU32, AtomicU64, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; + +use serde::Serialize; +use tokio::net::TcpStream; +use tokio::process::{Child, Command}; +use tokio::sync::Mutex; + +use crate::config::{GameDef, Kind}; + +pub fn now_secs() -> u64 { + SystemTime::now() + .duration_since(UNIX_EPOCH) + .map(|d| d.as_secs()) + .unwrap_or(0) +} + +pub struct Runtime { + pub def: GameDef, + inner: Mutex, + /// 正在处理的 HTTP 请求数(含握手阶段的 WS) + inflight: AtomicU32, + /// 活着的 WebSocket 连接数 + ws_conns: AtomicU32, + last_hit: AtomicU64, + hits: AtomicU64, + starts: AtomicU64, + releases: AtomicU64, +} + +struct Inner { + child: Option, + port: Option, + started_at: Option, + error: Option, +} + +impl Inner { + fn new() -> Self { + Self { + child: None, + port: None, + started_at: None, + error: None, + } + } + + fn reset(&mut self) { + self.child = None; + self.port = None; + self.started_at = None; + } +} + +impl Runtime { + pub fn new(def: GameDef) -> Self { + Self { + def, + inner: Mutex::new(Inner::new()), + inflight: AtomicU32::new(0), + ws_conns: AtomicU32::new(0), + last_hit: AtomicU64::new(now_secs()), + hits: AtomicU64::new(0), + starts: AtomicU64::new(0), + releases: AtomicU64::new(0), + } + } + + pub fn is_static(&self) -> bool { + self.def.kind == Kind::Static + } + + pub fn route(&self) -> String { + self.def.route() + } + + /// 进入请求作用域:计数 +1,Drop 时 -1,保证回收器不会在请求中途下手 + pub fn lease(self: &Arc) -> Lease { + self.inflight.fetch_add(1, Ordering::SeqCst); + Lease { + rt: Arc::clone(self), + } + } + + pub fn hit(&self) { + self.last_hit.store(now_secs(), Ordering::Relaxed); + self.hits.fetch_add(1, Ordering::Relaxed); + } + + fn bin_path(&self, base: &Path) -> PathBuf { + base.join(&self.def.cwd).join(&self.def.bin) + } + + /// 静态型目录 / 进程型二进制是否就位(UI 用来提示「未构建」) + pub fn ready_on_disk(&self, base: &Path) -> bool { + if self.is_static() { + let dir = base.join(&self.def.dir); + dir.is_dir() + } else { + self.bin_path(base).is_file() + } + } + + /// 确保进程在跑,返回它的内部端口 + pub async fn ensure(&self, base: &Path, logs: &Path) -> Result { + self.hit(); + let mut inner = self.inner.lock().await; + + if let Some(port) = inner.port { + let alive = match inner.child.as_mut() { + Some(ch) => matches!(ch.try_wait(), Ok(None)), + None => false, + }; + if alive { + inner.error = None; + return Ok(port); + } + // 进程自己没了:清状态,走下面重拉 + inner.reset(); + } + + let bin = self.bin_path(base); + if !bin.is_file() { + let msg = format!( + "{} 还没构建:{}\n先跑 bash scripts/build-games.sh", + self.def.name, + bin.display() + ); + inner.error = Some(msg.clone()); + return Err(msg); + } + + let port = free_port()?; + if let Err(e) = std::fs::create_dir_all(logs) { + eprintln!("[gc] 建日志目录失败:{e}"); + } + let log_path = logs.join(format!("{}.log", self.def.id)); + let stdout = std::fs::OpenOptions::new() + .create(true) + .append(true) + .open(&log_path) + .map_err(|e| format!("日志文件打不开:{e}"))?; + let stderr = stdout.try_clone().map_err(|e| format!("日志文件复制失败:{e}"))?; + + let cwd = base.join(&self.def.cwd); + let mut cmd = Command::new(&bin); + cmd.current_dir(&cwd) + .env("PORT", port.to_string()) + .env("HOST", "127.0.0.1") + .stdin(Stdio::null()) + .stdout(Stdio::from(stdout)) + .stderr(Stdio::from(stderr)); + + let mut child = cmd + .spawn() + .map_err(|e| format!("拉起 {} 失败:{e}", self.def.name))?; + + // 等端口真的能连上(axum 是先 bind 再 serve,连上即代表可服务) + let deadline = Instant::now() + Duration::from_secs(12); + loop { + if let Ok(Some(status)) = child.try_wait() { + let msg = format!( + "{} 启动即退出({status}),看日志:{}", + self.def.name, + log_path.display() + ); + inner.error = Some(msg.clone()); + return Err(msg); + } + if TcpStream::connect(("127.0.0.1", port)).await.is_ok() { + break; + } + if Instant::now() >= deadline { + let _ = child.start_kill(); + let msg = format!("{} 启动超时(12s)", self.def.name); + inner.error = Some(msg.clone()); + return Err(msg); + } + tokio::time::sleep(Duration::from_millis(40)).await; + } + + inner.child = Some(child); + inner.port = Some(port); + inner.started_at = Some(Instant::now()); + inner.error = None; + self.starts.fetch_add(1, Ordering::Relaxed); + eprintln!("[gc] 拉起 {}(:{})", self.def.id, port); + Ok(port) + } + + /// 立即释放(手动停止 / 退出时) + pub async fn release(&self, why: &str) { + if self.is_static() { + return; + } + let mut inner = self.inner.lock().await; + let had = inner.child.is_some(); + if let Some(mut ch) = inner.child.take() { + let _ = ch.start_kill(); + let _ = tokio::time::timeout(Duration::from_secs(2), ch.wait()).await; + } + inner.reset(); + if had { + self.releases.fetch_add(1, Ordering::Relaxed); + eprintln!("[gc] 释放 {}({why})", self.def.id); + } + } + + /// 回收器每次 tick 调它:进程挂了复位,空闲够久就释放 + pub async fn tick(&self, idle: Duration) { + if self.is_static() { + return; + } + let mut inner = self.inner.lock().await; + if inner.port.is_none() && inner.child.is_none() { + return; + } + + let exited = match inner.child.as_mut() { + Some(ch) => !matches!(ch.try_wait(), Ok(None)), + None => true, + }; + if exited { + if inner.child.is_some() { + eprintln!("[gc] {} 进程已退出,状态复位", self.def.id); + } + inner.reset(); + return; + } + + // 有活连接 / 有请求在飞,一律不动 + if self.ws_conns.load(Ordering::SeqCst) > 0 || self.inflight.load(Ordering::SeqCst) > 0 { + return; + } + + let idle_for = now_secs().saturating_sub(self.last_hit.load(Ordering::Relaxed)); + if idle_for < idle.as_secs() { + return; + } + + if let Some(mut ch) = inner.child.take() { + let _ = ch.start_kill(); + let _ = tokio::time::timeout(Duration::from_secs(2), ch.wait()).await; + } + inner.reset(); + self.releases.fetch_add(1, Ordering::Relaxed); + eprintln!( + "[gc] 回收 {}(空闲 {}s ≥ {}s)", + self.def.id, + idle_for, + idle.as_secs() + ); + } + + pub async fn status(&self, base: &Path, idle_secs: u64) -> GameStatus { + let inner = self.inner.lock().await; + let now = now_secs(); + let running = inner.port.is_some(); + let idle_for = now.saturating_sub(self.last_hit.load(Ordering::Relaxed)); + let ws = self.ws_conns.load(Ordering::SeqCst); + + let state = if self.is_static() { + "static" + } else if running { + "running" + } else if inner.error.is_some() { + "error" + } else { + "asleep" + }; + + GameStatus { + id: self.def.id.clone(), + name: self.def.name.clone(), + tagline: self.def.tagline.clone(), + icon: self.def.icon.clone(), + accent: self.def.accent.clone(), + stack: self.def.stack.clone(), + meta: self.def.meta.clone(), + path: format!("/{}/", self.route()), + kind: if self.is_static() { "static" } else { "process" }, + state, + ready: self.ready_on_disk(base), + port: inner.port, + uptime_secs: inner.started_at.map(|t| t.elapsed().as_secs()).unwrap_or(0), + idle_secs: if running { idle_for } else { 0 }, + // 还有多久被回收;有 WS 连着就是 None(不会回收) + release_in_secs: if running && ws == 0 && idle_secs > 0 { + Some(idle_secs.saturating_sub(idle_for)) + } else { + None + }, + ws_conns: ws, + inflight: self.inflight.load(Ordering::SeqCst), + hits: self.hits.load(Ordering::Relaxed), + starts: self.starts.load(Ordering::Relaxed), + releases: self.releases.load(Ordering::Relaxed), + error: inner.error.clone(), + entry: Some(format!("/{}/", self.route())), + } + } +} + +#[derive(Debug, Serialize)] +pub struct GameStatus { + pub id: String, + pub name: String, + pub tagline: String, + pub icon: String, + pub accent: String, + pub stack: String, + pub meta: Vec, + pub path: String, + pub entry: Option, + pub kind: &'static str, + /// static | running | asleep | error + pub state: &'static str, + /// 磁盘上是否就位(进程型=二进制存在,静态型=目录存在) + pub ready: bool, + pub port: Option, + pub uptime_secs: u64, + pub idle_secs: u64, + pub release_in_secs: Option, + pub ws_conns: u32, + pub inflight: u32, + pub hits: u64, + pub starts: u64, + pub releases: u64, + pub error: Option, +} + +/// 请求作用域守卫 +pub struct Lease { + rt: Arc, +} + +impl Drop for Lease { + fn drop(&mut self) { + self.rt.inflight.fetch_sub(1, Ordering::SeqCst); + } +} + +/// WebSocket 连接守卫:连接期间禁止回收 +pub struct WsGuard { + pub rt: Arc, +} + +impl WsGuard { + pub fn new(rt: Arc) -> Self { + rt.ws_conns.fetch_add(1, Ordering::SeqCst); + Self { rt } + } +} + +impl Drop for WsGuard { + fn drop(&mut self) { + self.rt.ws_conns.fetch_sub(1, Ordering::SeqCst); + } +} + +fn free_port() -> Result { + let l = std::net::TcpListener::bind("127.0.0.1:0") + .map_err(|e| format!("找不到空闲端口:{e}"))?; + let port = l.local_addr().map_err(|e| e.to_string())?.port(); + drop(l); + Ok(port) +}