三件事凑成一次不兼容变更:WebSocket 通道、Hypercorn 服务器、「手动推进一天」都消失了。 实时通道:WebSocket -> SSE - hub 改为 SSE 订阅池,GET /api/stream 单向推送 welcome/state/day/notice/bye, 250ms 节流 + 15s 心跳注释;写操作一律走 HTTP POST /api/actions,不再有 WS 回执。 - 停机三处一起修才干净:close_all() 发 bye + timeout_graceful_shutdown 兜底 + 客户端 stop() 直接 shutdown 底层 socket(光 close() 会等读线程的锁,最长卡到下次心跳)。 - 网页版改 EventSource + fetch;tools/ws_demo.py 换成 tools/sse_demo.py。 服务器:Hypercorn -> uvicorn + zttp 的 HTTP/2 - 同一端口同时说 HTTP/1.1 与 HTTP/2。uvicorn 0.53 不再内置 h2,必须装 zttp 并显式 http="zttp",否则 Config.load() 直接 raise。 - 信号接管改成子类覆盖 Server.handle_exit(0.53 没有 install_signal_handlers 可覆盖), 不调 super()、不写 _captured_signals,退出时不重放信号;第二次信号强制退出。 - 入口启动前用 daemon.port_busy() 自检端口:Windows 上 SO_REUSEADDR 会让第二个实例 「绑上」已监听端口并抢走新连接,所以判断「能不能连上」而不是「能不能 bind」。 - 修掉 clear_pid_file 的 Windows 真 bug:文件还开着就 os.remove 会失败且被 except OSError 吞掉,导致每次正常退出都留 stale pid 文件。 节奏:一天 15 秒 -> 40 分钟,并整体移除「休息」 - DEFAULT_TICK_SECONDS=2400,MAX_TICK_SECONDS 放宽到 86400(旧上限会把 40 分钟夹回去)。 - engine.sleep / SLEEP_COOLDOWN / /api/sleep / TUI 的 [N]休息 / 网页版按钮全部删掉, 时间只能自然流动;机器人改为 wait_for_next_day(timeout),CLI 加 bot --wait。 - 时长显示统一走 models.format_duration(),不再出现 2399.6s 这种写法。 键盘:修复方向键/空格/Tab/ESC 全部静默失效 - keys.py 的具名键统一小写并成为唯一来源,tui.py 一律引用 keys.XXX 而不手写字符串 (历史 bug 就是 Windows 侧产大写 UP、TUI 里写小写 up,字母键正常所以很难发现)。 - 顺带修 POSIX 路径一次 os.read 只取首字节、其余按键静默丢弃的老毛病。 测试:重建 500 项 - test_engine 110 / test_actions 35 / test_server 131(skip 35) / test_tui_keys 75 / test_bot 36 / test_client 113。未安装的第三方依赖用 skipUnless 自动跳过,其余照跑, 所以是全绿而不是靠跳过伪装。 - 被测试逼出两处真隐患并修掉:RemoteFarm._normalize() 必须「先补 scheme 再削尾斜杠」 (顺序反了畸形端点会溜到系统代理、报一个和真实原因无关的 502);StateView 空视图要 预置 plots/animals,否则连不上服务器时读 state.plots 直接 AttributeError。 优化:先量后改,依据与前后数字都在 tools/bench.py - 新增 engine.brief_source():brief/summary/动作回执只要十几个标量,不再为它们序列化 整局;to_dict 里 net_worth 只算一次。brief -76%、summary -77%、leaderboard(32) -78%、 GET /api/world -31%、POST /api/actions?full=1 -16%。 - 拆掉三个巨型函数:create_app 475->32 行(_Services + _register_*)、 build_parser 与 available_actions 分组、__main__.main 160->7 行。 - 消除重复:等级门槛 5 处 -> _is_locked/_require_level/_newly_unlocked;hub 的 broadcast/broadcast_all/close_all -> _push_many;daemon.probe/world -> _get_json; main.py 的 _add_endpoint_args/_leaderboard_lines。 - tools/bench.py 作为长期性能守卫(含调用计数器),谁把轻量路径改回 snapshot() 会立刻报警。 门禁:ruff format/check 全绿、pyright 0 错误、500 项测试 OK(skip 35)。
148 lines
5.7 KiB
Python
148 lines
5.7 KiB
Python
#!/usr/bin/env python3
|
||
"""SSE 通道演示脚本:证明"服务器主动推、客户端用 HTTP 发"这一对方向都通。
|
||
|
||
它同时是一个"外部客户端"的样板——完全不知道游戏内部结构,只知道协议:
|
||
|
||
连上 /api/stream → 收 welcome(含状态)→ 用 HTTP 发一个动作 → 收 state 推送
|
||
|
||
只用标准库(urllib 流式读长连接),所以任何有 Python 的环境都能跑。
|
||
|
||
用法:
|
||
python tools/sse_demo.py --url http://127.0.0.1:8765 --farm demo --seconds 8
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import json
|
||
import os
|
||
import sys
|
||
import time
|
||
import urllib.parse
|
||
import urllib.request
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||
|
||
from farm import net
|
||
|
||
|
||
def stream_url(endpoint: str, farm: str, token: str | None) -> str:
|
||
base = endpoint if "://" in endpoint else "http://" + endpoint
|
||
query = {"farm": farm, "name": "sse-demo"}
|
||
if token:
|
||
query["token"] = token
|
||
return f"{base.rstrip('/')}/api/stream?{urllib.parse.urlencode(query)}"
|
||
|
||
|
||
def action_url(endpoint: str, farm: str, token: str | None) -> str:
|
||
base = endpoint if "://" in endpoint else "http://" + endpoint
|
||
query = {"farm": farm}
|
||
if token:
|
||
query["token"] = token
|
||
return f"{base.rstrip('/')}/api/actions?{urllib.parse.urlencode(query)}"
|
||
|
||
|
||
def post_action(url: str, action: str, params: dict | None = None) -> dict:
|
||
"""用普通 HTTP POST 提交动作——上行不占用实时通道。"""
|
||
body = json.dumps({"action": action, "params": params or {}}).encode("utf-8")
|
||
request = urllib.request.Request(
|
||
url, data=body, method="POST", headers={"Content-Type": "application/json"}
|
||
)
|
||
with net.open_url(request, timeout=8.0) as response:
|
||
return json.loads(response.read().decode("utf-8"))
|
||
|
||
|
||
def run(endpoint: str, farm: str, token: str | None, seconds: float) -> int:
|
||
url = stream_url(endpoint, farm, token)
|
||
print(f"连接 {url}")
|
||
request = urllib.request.Request(url, headers={"Accept": "text/event-stream"})
|
||
|
||
counts: dict[str, int] = {}
|
||
acted = False
|
||
deadline = time.time() + seconds
|
||
|
||
# 读超时必须比服务器心跳(15 秒)宽裕,否则空闲时会被自己的超时打断
|
||
with net.open_url(request, timeout=45.0) as response:
|
||
while True:
|
||
try:
|
||
raw_line = response.readline()
|
||
except (TimeoutError, OSError) as exc:
|
||
print(f"(读超时:{exc})")
|
||
break
|
||
if not raw_line:
|
||
print("(服务器关闭了长连接)")
|
||
break
|
||
line = raw_line.decode("utf-8", errors="replace").strip()
|
||
if not line or line.startswith(":"):
|
||
continue
|
||
if not line.startswith("data:"):
|
||
continue
|
||
message = json.loads(line[len("data:") :].strip())
|
||
kind = message.get("type", "?")
|
||
counts[kind] = counts.get(kind, 0) + 1
|
||
|
||
if kind == "welcome":
|
||
state = message.get("state", {})
|
||
print(
|
||
f"← welcome:牧场 {message.get('farm')} · 第 {state.get('day')} 天 · "
|
||
f"金币 {state.get('gold')} · 候选动作 {len(message.get('actions', []))} 个"
|
||
)
|
||
# welcome 里就带着当前合法动作,挑第一个执行,
|
||
# 验证"两条通道改的是同一个引擎"
|
||
candidates = message.get("actions") or []
|
||
if candidates:
|
||
pick = candidates[0]
|
||
reply = post_action(
|
||
action_url(endpoint, farm, token),
|
||
pick["action"],
|
||
pick.get("params") or {},
|
||
)
|
||
acted = True
|
||
print(
|
||
f"→ POST /api/actions {pick['action']} "
|
||
f"{pick.get('params') or {}}:{reply.get('message')}"
|
||
)
|
||
elif kind == "state":
|
||
snapshot = message.get("state", {})
|
||
print(
|
||
f"← state(seq={message.get('seq')}):第 {snapshot.get('day')} 天 · "
|
||
f"金币 {snapshot.get('gold')} · 行动点 {snapshot.get('ap')} · "
|
||
f"在线 {message.get('online')}"
|
||
)
|
||
if acted:
|
||
# 收到了动作触发的推送,两条路都验证完了
|
||
break
|
||
elif kind == "day":
|
||
print(f"← day:进入第 {message.get('day')} 天,事件 {message.get('events')}")
|
||
elif kind == "notice":
|
||
print(f"← notice:{message.get('text')}")
|
||
else:
|
||
print(f"← {kind}")
|
||
|
||
if time.time() >= deadline:
|
||
break
|
||
|
||
print(f"\n消息统计:{counts}")
|
||
if counts.get("welcome", 0) < 1:
|
||
print("✗ 没有收到 welcome,SSE 长连接可能没建立")
|
||
return 1
|
||
if counts.get("state", 0) < 1:
|
||
print("✗ 动作之后没有收到 state 推送(引擎与推送线程之间可能断了)")
|
||
return 1
|
||
print("✓ SSE 通道正常:状态会主动下行,动作经由 HTTP 上行")
|
||
return 0
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description="SSE 通道演示")
|
||
parser.add_argument("--url", default="http://127.0.0.1:8765")
|
||
parser.add_argument("--farm", default="sse-demo")
|
||
parser.add_argument("--token", default=None)
|
||
parser.add_argument("--seconds", type=float, default=8.0)
|
||
args = parser.parse_args()
|
||
return run(args.url, args.farm, args.token, args.seconds)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|