refactor(fudai): 拆出预约队列状态文件写入(2545→2460,-85 行)

把 run_once_basic 中嵌套的 _write_state 闭包(87 行 JSON 写文件 + 节流)抽到
fudai_run_blocks.write_reservations_state_throttled。原闭包改为单行调用。

新增 3 个单元测试覆盖:1秒节流跳过 / 节流过后写入 / IO 错误吞噬。
1138 → 1141 用例全过。

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
CodexandClaude Opus 4.7 committed 2026-05-22 03:02:45 +08:00
1 parent a317b38b25
commit c6a4d5fb99
3 files changed
+142 -86

No files matched your search

+1 -86
View File
@@ -1237,92 +1237,7 @@ class fudai_analyse:
douyin_reservation_logic._sort_reservations_inplace(self.reservations) # type: ignore[attr-defined]
def _write_state() -> None:
# 将预约队列写入状态文件,供外部查看(格式与 douyin_fudai_core.py 一致)
try:
# 节流:避免高频写盘(某些环境下会造成明显卡顿甚至看似卡死)
now_ts = time.time()
last_ts = float(
getattr(self, "_reservations_state_last_write_ts", 0.0)
or 0.0
)
if (now_ts - last_ts) < 1.0:
return
self._reservations_state_last_write_ts = now_ts
import json
os.makedirs(
os.path.dirname(self._reservations_state_path),
exist_ok=True,
)
# 格式化预约队列数据(与 douyin_reservation.py 格式一致)
items = []
for r in self.reservations or []:
try:
ft = float(r.get("future_ts") or 0)
except Exception:
ft = 0.0
try:
ft_str = (
datetime.fromtimestamp(ft).strftime(
"%Y-%m-%d %H:%M:%S"
)
if ft
else ""
)
except Exception:
ft_str = str(r.get("future_str", ""))
items.append(
{
"prize_value_yuan": float(
r.get("prize_value_yuan") or 0
),
"content": str(r.get("content") or ""),
"future_ts": ft,
"future_str": ft_str,
"pos_seen": int(r.get("pos_seen") or 0),
"room_title": str(r.get("room_title", "") or ""),
"room_title_raw": str(
r.get("room_title_raw", "") or ""
),
"created_ts": float(r.get("created_ts") or 0),
}
)
# 获取当前直播间标题(用于状态文件)
current_title = str(
getattr(self, "current_room_title", "") or ""
)
current_title_raw = str(
getattr(self, "current_room_title_raw", "") or ""
)
# 写入完整的状态数据
data = {
"updated_ts": time.time(),
"reason": "process_reservation",
"room_pos": int(getattr(self, "room_pos", 0) or 0),
"current_room_title": current_title,
"current_room_title_raw": current_title_raw,
"reservations": items,
}
with open(
self._reservations_state_path, "w", encoding="utf-8"
) as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as exc:
try:
self._log_kv(
"预约",
"写入预约队列状态文件失败",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
fudai_run_blocks.write_reservations_state_throttled(self)
focus_ref = [float(self.reservation_focus_until_ts or 0.0)]
after_action_ref = [
@@ -655,6 +655,83 @@ def handle_live_closed_stage(analyser: Any, start_time: float) -> None:
)
def write_reservations_state_throttled(analyser: Any) -> None:
"""把当前预约队列写到状态文件,1 秒节流避免高频写盘。
供 run_once_basic 中作为 ``_write_state`` 回调用。本函数捕获所有异常,
仅记录到日志,不影响主流程。
"""
try:
now_ts = time.time()
last_ts = float(
getattr(analyser, "_reservations_state_last_write_ts", 0.0) or 0.0
)
if (now_ts - last_ts) < 1.0:
return
analyser._reservations_state_last_write_ts = now_ts
import json
import os
os.makedirs(
os.path.dirname(analyser._reservations_state_path),
exist_ok=True,
)
items = []
for r in analyser.reservations or []:
try:
ft = float(r.get("future_ts") or 0)
except Exception:
ft = 0.0
try:
ft_str = (
datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S")
if ft
else ""
)
except Exception:
ft_str = str(r.get("future_str", ""))
items.append(
{
"prize_value_yuan": float(r.get("prize_value_yuan") or 0),
"content": str(r.get("content") or ""),
"future_ts": ft,
"future_str": ft_str,
"pos_seen": int(r.get("pos_seen") or 0),
"room_title": str(r.get("room_title", "") or ""),
"room_title_raw": str(r.get("room_title_raw", "") or ""),
"created_ts": float(r.get("created_ts") or 0),
}
)
current_title = str(getattr(analyser, "current_room_title", "") or "")
current_title_raw = str(getattr(analyser, "current_room_title_raw", "") or "")
data = {
"updated_ts": time.time(),
"reason": "process_reservation",
"room_pos": int(getattr(analyser, "room_pos", 0) or 0),
"current_room_title": current_title,
"current_room_title_raw": current_title_raw,
"reservations": items,
}
with open(analyser._reservations_state_path, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
except Exception as exc:
try:
analyser._log_kv(
"预约",
"写入预约队列状态文件失败",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
def log_reservation_trigger_check(
analyser: Any, high_value_enabled: bool, reservations_list: Any, reservations_count: int
) -> None:
+64
View File
@@ -575,3 +575,67 @@ def test_log_trigger_check_truncates_to_first_three():
)
detail = overview_call.kwargs.get("reservations_detail", [])
assert len(detail) == 3
# ---- write_reservations_state_throttled ---- #
def test_write_state_throttled_skips_within_1s(tmp_path):
a = MagicMock()
state_path = tmp_path / "state.json"
a._reservations_state_path = str(state_path)
a._reservations_state_last_write_ts = time.time() - 0.5 # 0.5s 前刚写过
a.reservations = [{"future_ts": 100}]
fudai_run_blocks.write_reservations_state_throttled(a)
# 节流,文件不应被写
assert not state_path.exists()
def test_write_state_writes_when_throttle_passed(tmp_path):
a = MagicMock()
state_path = tmp_path / "state.json"
a._reservations_state_path = str(state_path)
a._reservations_state_last_write_ts = time.time() - 5 # 5s 前
a.reservations = [
{
"future_ts": 1700000000.0,
"prize_value_yuan": 5.0,
"content": "test",
"pos_seen": 3,
"room_title": "房间A",
"room_title_raw": "房间A原始",
"created_ts": 1699999999,
}
]
a.current_room_title = "当前"
a.current_room_title_raw = "当前原始"
a.room_pos = 5
fudai_run_blocks.write_reservations_state_throttled(a)
import json as _json
assert state_path.exists()
data = _json.loads(state_path.read_text(encoding="utf-8"))
assert data["reason"] == "process_reservation"
assert data["room_pos"] == 5
assert len(data["reservations"]) == 1
assert data["reservations"][0]["prize_value_yuan"] == 5.0
def test_write_state_swallows_io_error():
"""state_path 不可写时不应抛错"""
a = MagicMock()
# Windows: 用一个明确无效的路径(包含非法字符)
a._reservations_state_path = "Z:\\nonexistent\\path\\with\x00null\\state.json"
a._reservations_state_last_write_ts = 0.0
a.reservations = []
a.current_room_title = ""
a.current_room_title_raw = ""
a.room_pos = 0
# 不应抛错
fudai_run_blocks.write_reservations_state_throttled(a)
# 应记录失败日志
failure = [
c for c in a._log_kv.call_args_list
if len(c.args) >= 2 and "写入预约队列状态文件失败" in c.args[1]
]
assert len(failure) == 1