feat: 实时通道改 SSE、服务器换 uvicorn+zttp、节奏改 40 分钟一天,并重建测试与优化热路径

三件事凑成一次不兼容变更: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)。
This commit is contained in:
snowy-yang committed 2026-09-19 12:55:45 +08:00
1 parent 47dd818360
commit f8e093c98f
36 files changed
+6865 -2204

No files matched your search

+212 -146
View File
@@ -51,7 +51,6 @@ class FarmEngine:
)
self._log_seq = 0
self._last_sleep = 0.0
self.paused = False
# 由 Scheduler 维护:下一次自动推进的绝对时间戳(无调度器时为 None)
self.next_tick_at: float | None = None
@@ -106,6 +105,44 @@ class FarmEngine:
return None
return round(max(0.0, self.next_tick_at - time.time()), 1)
def brief_source(self) -> dict[str, Any]:
"""精简状态(动作回执、排行榜、`status`)要用的字段。
刻意**不走** :meth:`snapshot`:那些场景只要十几个标量,而完整快照会把
每块地、每只牲畜都序列化成 dict,再被调用方整批丢掉。实测每个请求因此
白花 ~60µs;排行榜更夸张——N 个牧场就是 N 次全量序列化。
这里的键是 ``farm.server.app.BRIEF_KEYS`` 的超集:加字段时两边一起改。
"""
with self._lock:
state = self.state
# net_worth 是这里最贵的一项(要遍历地块与牲畜),算一次给两处用
worth = state.net_worth
return {
"day": state.day,
"gold": state.gold,
"level": state.level,
"exp": state.exp,
"exp_needed": state.exp_needed,
"ap": state.ap,
"max_ap": state.max_ap,
"feed": state.feed,
"plot_count": len(state.plots),
"max_plots": state.max_plots,
"next_plot_price": state.next_plot_price,
"animal_count": len(state.animals),
"max_animals": config.MAX_ANIMALS,
"net_worth": round(worth, 2),
"goal_index": config.goal_index(worth),
"seconds_to_tick": self.seconds_to_tick,
"paused": self.paused,
"tick_seconds": self.tick_seconds,
# 待办清单是特意为 AI 准备的:直接读模型对象,不再过一遍序列化
"ripe_plots": [p.index + 1 for p in state.plots if p.is_ripe],
"hungry_animals": [a.aid for a in state.animals if not a.fed],
"collectable_animals": [a.aid for a in state.animals if a.pending > 0],
}
def market_price(self, key: str) -> float:
with self._lock:
return round(self.state.market.get(key, 0.0), 2)
@@ -127,7 +164,7 @@ class FarmEngine:
"price": price,
"exp": info["exp"],
"level_req": info["level_req"],
"locked": self.state.level < info["level_req"],
"locked": self._is_locked(info),
"profit": round(gross - info["seed_cost"], 2),
"profit_per_day": round((gross - info["seed_cost"]) / days, 2),
}
@@ -147,7 +184,7 @@ class FarmEngine:
"feed_per_day": info["feed_per_day"],
"exp": info["exp"],
"level_req": info["level_req"],
"locked": self.state.level < info["level_req"],
"locked": self._is_locked(info),
"profit_per_day": round((price - feed_cost) / max(1, info["cycle"]), 2),
}
)
@@ -166,109 +203,151 @@ class FarmEngine:
``cost``(金币/行动点开销)、``reason``(为什么值得做)。
"""
with self._lock:
actions: list[dict[str, Any]] = []
state = self.state
# ---- 收获 / 浇水 / 播种
for plot in state.plots:
if plot.crop is None:
for key, info in config.CROPS.items():
if state.level < info["level_req"]:
continue
if state.gold < info["seed_cost"] or state.ap < config.AP_COST["plant"]:
continue
actions.append(
{
"action": "plant",
"params": {"plot": plot.index + 1, "crop": key},
"cost": {"gold": info["seed_cost"], "ap": config.AP_COST["plant"]},
"reason": f"{plot.index + 1} 号地空闲,可种{info['name']}",
}
)
elif plot.is_ripe:
actions.append(
{
"action": "harvest",
"params": {"plot": plot.index + 1},
"cost": {"gold": 0, "ap": config.AP_COST["harvest"]},
"reason": (
f"{plot.index + 1} 号地的{config.CROPS[plot.crop]['name']}已成熟"
),
}
)
elif plot.moisture == 0 and state.ap >= config.AP_COST["water"]:
actions.append(
{
"action": "water",
"params": {"plot": plot.index + 1},
"cost": {"gold": 0, "ap": config.AP_COST["water"]},
"reason": f"{plot.index + 1} 号地缺水,作物已停止生长",
}
)
# ---- 动物
for animal in state.animals:
if animal.pending > 0:
actions.append(
{
"action": "collect",
"params": {"animal_id": animal.aid},
"cost": {"gold": 0, "ap": config.AP_COST["collect"]},
"reason": f"{animal.name}有 {animal.pending} 份{animal.product}待收取",
}
)
elif not animal.fed:
need = animal.info["feed_per_day"]
cost = 0 if state.feed >= need else need * config.FEED_EMERGENCY_PRICE
if state.gold >= cost and state.ap >= config.AP_COST["feed"]:
actions.append(
{
"action": "feed",
"params": {"animal_id": animal.aid},
"cost": {"gold": cost, "ap": config.AP_COST["feed"]},
"reason": f"{animal.name}(#{animal.aid})今天还没喂食",
}
)
# ---- 投资类
price = state.next_plot_price
if price > 0 and state.gold >= price:
actions.append(
{
"action": "buy_plot",
"params": {},
"cost": {"gold": price, "ap": config.AP_COST["buy_plot"]},
"reason": f"可花 {price} 金币开垦第 {len(state.plots) + 1} 块地",
}
)
if state.feed < 5 and state.gold >= config.FEED_UNIT_PRICE * config.FEED_BULK:
actions.append(
{
"action": "buy_feed",
"params": {"quantity": config.FEED_BULK},
"cost": {
"gold": config.FEED_UNIT_PRICE * config.FEED_BULK,
"ap": config.AP_COST["buy_feed"],
},
"reason": "饲料库存偏低,建议补货",
}
)
for key, info in config.ANIMALS.items():
if state.level < info["level_req"]:
continue
if len(state.animals) >= config.MAX_ANIMALS or state.gold < info["cost"]:
continue
actions.append(
{
"action": "buy_animal",
"params": {"kind": key},
"cost": {"gold": info["cost"], "ap": config.AP_COST["buy_animal"]},
"reason": f"可购买{info['name']}({info['cost']} 金币)",
}
)
actions: list[dict[str, Any]] = []
actions.extend(self._plot_actions(state))
actions.extend(self._animal_actions(state))
actions.extend(self._investment_actions(state))
return actions
# ---- available_actions 的三个分区;拆开是为了各自能独立阅读/测试
def _plot_actions(self, state: GameState) -> list[dict[str, Any]]:
"""每块地当前能做的事:播种 / 收获 / 浇水。"""
# 能种什么只取决于等级、金币和行动点,与**具体是哪块地**无关,
# 所以整趟只筛一次,不要放进地块循环里做 O(地块 × 作物) 次判断。
plant_ap = config.AP_COST["plant"]
plantable = [
(key, info)
for key, info in config.CROPS.items()
if not self._is_locked(info)
and state.gold >= info["seed_cost"]
and state.ap >= plant_ap
]
actions: list[dict[str, Any]] = []
for plot in state.plots:
position = plot.index + 1
if plot.crop is None:
for key, info in plantable:
actions.append(
{
"action": "plant",
"params": {"plot": position, "crop": key},
"cost": {"gold": info["seed_cost"], "ap": plant_ap},
"reason": f"{position} 号地空闲,可种{info['name']}",
}
)
elif plot.is_ripe:
actions.append(
{
"action": "harvest",
"params": {"plot": position},
"cost": {"gold": 0, "ap": config.AP_COST["harvest"]},
"reason": f"{position} 号地的{config.CROPS[plot.crop]['name']}已成熟",
}
)
elif plot.moisture == 0 and state.ap >= config.AP_COST["water"]:
actions.append(
{
"action": "water",
"params": {"plot": position},
"cost": {"gold": 0, "ap": config.AP_COST["water"]},
"reason": f"{position} 号地缺水,作物已停止生长",
}
)
return actions
def _animal_actions(self, state: GameState) -> list[dict[str, Any]]:
"""每只牲畜当前能做的事:收取产出 / 喂食。"""
actions: list[dict[str, Any]] = []
for animal in state.animals:
if animal.pending > 0:
actions.append(
{
"action": "collect",
"params": {"animal_id": animal.aid},
"cost": {"gold": 0, "ap": config.AP_COST["collect"]},
"reason": f"{animal.name}有 {animal.pending} 份{animal.product}待收取",
}
)
elif not animal.fed:
need = animal.info["feed_per_day"]
cost = 0 if state.feed >= need else need * config.FEED_EMERGENCY_PRICE
if state.gold >= cost and state.ap >= config.AP_COST["feed"]:
actions.append(
{
"action": "feed",
"params": {"animal_id": animal.aid},
"cost": {"gold": cost, "ap": config.AP_COST["feed"]},
"reason": f"{animal.name}(#{animal.aid})今天还没喂食",
}
)
return actions
def _investment_actions(self, state: GameState) -> list[dict[str, Any]]:
"""与具体地块/牲畜无关的长期投入:开垦土地、补饲料、买牲畜。"""
actions: list[dict[str, Any]] = []
price = state.next_plot_price
if price > 0 and state.gold >= price:
actions.append(
{
"action": "buy_plot",
"params": {},
"cost": {"gold": price, "ap": config.AP_COST["buy_plot"]},
"reason": f"可花 {price} 金币开垦第 {len(state.plots) + 1} 块地",
}
)
bulk_cost = config.FEED_UNIT_PRICE * config.FEED_BULK
if state.feed < 5 and state.gold >= bulk_cost:
actions.append(
{
"action": "buy_feed",
"params": {"quantity": config.FEED_BULK},
"cost": {"gold": bulk_cost, "ap": config.AP_COST["buy_feed"]},
"reason": "饲料库存偏低,建议补货",
}
)
for key, info in config.ANIMALS.items():
if self._is_locked(info):
continue
if len(state.animals) >= config.MAX_ANIMALS or state.gold < info["cost"]:
continue
actions.append(
{
"action": "buy_animal",
"params": {"kind": key},
"cost": {"gold": info["cost"], "ap": config.AP_COST["buy_animal"]},
"reason": f"可购买{info['name']}({info['cost']} 金币)",
}
)
return actions
# ================================================================ 内部工具
def _is_locked(self, info: dict[str, Any]) -> bool:
"""这件作物/牲畜在当前等级是否还没解锁。
"等级门槛"这一条规则原本在 catalog / available_actions / plant /
buy_animal / _gain_exp 里各写了一遍,改文案或改判定就得追五处。
现在只在这里定义,别处一律调它。
"""
return self.state.level < info["level_req"]
def _require_level(self, info: dict[str, Any]) -> None:
"""等级不够就抛 locked。播种与买牲畜都要过这一关。"""
if self._is_locked(info):
raise GameError(
"locked",
f"{info['name']}需要 Lv.{info['level_req']},当前 Lv.{self.state.level}",
)
def _newly_unlocked(self, level: int) -> list[str]:
"""正好在 level 这一级解锁的作物与牲畜名字(先作物后牲畜)。"""
return [
info["name"]
for table in (config.CROPS, config.ANIMALS)
for info in table.values()
if info["level_req"] == level
]
def _get_plot(self, plot_no: Any) -> Plot:
"""把 1-based 的地块编号转成 Plot,越界即报错。"""
try:
@@ -299,7 +378,7 @@ class FarmEngine:
raise GameError(
"no_ap",
f"行动点不足:{action} 需要 {cost} 点,当前只剩 {self.state.ap} 点。"
f"按 N 休息或等待下一天。",
f"等一天的时间自然走完就会恢复。",
)
if cost:
self.state.ap -= cost
@@ -333,15 +412,7 @@ class FarmEngine:
self.state.level += 1
bonus = config.level_up_bonus(self.state.level)
self.state.gold += bonus
unlocked = [
info["name"]
for info in config.CROPS.values()
if info["level_req"] == self.state.level
] + [
info["name"]
for info in config.ANIMALS.values()
if info["level_req"] == self.state.level
]
unlocked = self._newly_unlocked(self.state.level)
text = f"升级到 Lv.{self.state.level}!奖励 {bonus} 金币"
if unlocked:
text += f",解锁:{'、'.join(unlocked)}"
@@ -362,11 +433,7 @@ class FarmEngine:
f"未知作物 {crop!r},可选:{'、'.join(config.CROPS)}",
)
info = config.CROPS[crop]
if self.state.level < info["level_req"]:
raise GameError(
"locked",
f"{info['name']}需要 Lv.{info['level_req']},当前 Lv.{self.state.level}",
)
self._require_level(info)
plot = self._get_plot(plot_no)
if plot.crop is not None:
raise GameError(
@@ -451,11 +518,7 @@ class FarmEngine:
f"未知动物 {kind!r},可选:{'、'.join(config.ANIMALS)}",
)
info = config.ANIMALS[kind]
if self.state.level < info["level_req"]:
raise GameError(
"locked",
f"{info['name']}需要 Lv.{info['level_req']},当前 Lv.{self.state.level}",
)
self._require_level(info)
if len(self.state.animals) >= config.MAX_ANIMALS:
raise GameError("pasture_full", f"牧场已满(上限 {config.MAX_ANIMALS} 只)")
@@ -587,17 +650,6 @@ class FarmEngine:
"next_plot_price": self.state.next_plot_price,
}
def sleep(self) -> dict[str, Any]:
"""手动推进一天,带冷却避免刷时间。"""
with self._lock:
elapsed = time.time() - self._last_sleep
if elapsed < config.SLEEP_COOLDOWN:
wait = config.SLEEP_COOLDOWN - elapsed
raise GameError("cooldown", f"刚休息过,请等待 {wait:.1f} 秒", status=429)
self._last_sleep = time.time()
events = self.advance_day(reason="休息")
return {"ok": True, "message": f"进入第 {self.state.day} 天", "events": events}
def pause(self, paused: bool | None = None) -> dict[str, Any]:
with self._lock:
self.paused = bool(paused) if paused is not None else not self.paused
@@ -610,7 +662,6 @@ class FarmEngine:
tick = self.tick_seconds
self.state = GameState()
self._log_seq = 0
self._last_sleep = 0.0
self.paused = False
if keep_tick:
self.tick_seconds = tick
@@ -709,8 +760,30 @@ class FarmEngine:
)
def tick_decision(
paused: bool, next_tick_at: float | None, tick_seconds: float, now: float
) -> tuple[bool, float]:
"""根据当前时刻决定"是否该推进一天",并给出新的调度时间点。
这是 :class:`Scheduler`(单机)与 :class:`farm.server.session.FarmClock`
(服务器)共用的唯一 tick 决策,两处不再各写一遍:
* 暂停中 → 顺延,保证恢复后仍有完整的一个 tick;
* 没有调度点(从未启动/被清空)→ 从现在起重新计时;
* 到点 → 推进,并把下一次调度设为 now + tick_seconds;
* 未到点 → 维持原调度时间。
返回 ``(should_advance, next_tick_at)``。
"""
if paused or next_tick_at is None:
return False, now + tick_seconds
if now >= next_tick_at:
return True, now + tick_seconds
return False, next_tick_at
class Scheduler:
"""自动推进游戏时间的后台线程。"""
"""自动推进游戏时间的后台线程(单机模式;服务器版见 farm.server.session.FarmClock)。"""
def __init__(self, engine: FarmEngine, enabled: bool = True) -> None:
self.engine = engine
@@ -732,16 +805,9 @@ class Scheduler:
def _run(self) -> None:
while not self._stop.wait(0.2):
engine = self.engine
if engine.paused:
# 暂停时顺延,保证恢复后仍有完整的一个 tick
engine.next_tick_at = time.time() + engine.tick_seconds
continue
deadline = engine.next_tick_at
if deadline is None:
deadline = time.time() + engine.tick_seconds
if time.time() >= deadline:
advance, engine.next_tick_at = tick_decision(
engine.paused, engine.next_tick_at, engine.tick_seconds, time.time()
)
if advance:
with contextlib.suppress(Exception):
engine.advance_day(reason="时间流逝")
engine.next_tick_at = time.time() + engine.tick_seconds
else:
engine.next_tick_at = deadline