Clear runtime state at fudai startup

This commit is contained in:
Your Name committed 2026-06-19 20:18:15 +08:00
1 parent d4931b6820
commit f129206df7
2 files changed
+136 -10

No files matched your search

+86 -10
View File
@@ -8,6 +8,7 @@
"""
from __future__ import annotations
import json
import os
import time
from typing import Any, Optional, Tuple
@@ -155,7 +156,7 @@ def apply_fudai_defaults(self: Any) -> None:
# 预约队列状态文件 + 清理映射表导出文件
_resolve_reservations_state_path(self)
_cleanup_old_room_pos_map_files(self)
_clear_runtime_state_files_on_start(self)
# 已记录统计的福袋跟踪
self._recorded_fudai_stats = set()
@@ -235,15 +236,90 @@ def _resolve_reservations_state_path(self: Any) -> None:
def _cleanup_old_room_pos_map_files(self: Any) -> None:
"""每次启动时删除上次运行的导出文件,避免 GUI 显示过期内容。"""
"""兼容旧入口:每次启动写入空映射表,避免 GUI 显示过期内容。"""
_write_empty_room_pos_map_state(self, reason="startup_clear")
def _clear_runtime_state_files_on_start(self: Any) -> None:
"""新运行实例启动时清空运行态预约队列和映射表状态文件。"""
try:
state_dir = os.path.dirname(self._reservations_state_path)
for filename in ("room_pos_map.json", "room_pos_map.csv", "room_pos_map.md"):
try:
p = os.path.join(state_dir, filename)
if os.path.exists(p):
os.remove(p)
except Exception:
pass
self.reservations = []
self.reservation_focus_until_ts = 0.0
self.reservation_after_action_pending = False
self.queue_full_waiting_at_earliest = False
self.reset_to_list_after_reservations = False
except Exception:
pass
try:
state_path = getattr(self, "_reservations_state_path", None)
if state_path:
from douyin.reservation.douyin_reservation import write_reservations_state
write_reservations_state(
state_path=state_path,
reservations=[],
room_pos=0,
current_room_title="",
current_room_title_raw="",
reason="startup_clear",
analyser=self,
)
except Exception as exc:
try:
self._log_kv(
"预约",
"[预约] 启动时清空预约状态文件失败",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
_write_empty_room_pos_map_state(self, reason="startup_clear")
def _write_empty_room_pos_map_state(self: Any, *, reason: str) -> None:
"""写入空的 room_pos_map 三件套,避免新一轮启动时暴露旧映射。"""
try:
state_dir = os.path.dirname(self._reservations_state_path)
os.makedirs(state_dir, exist_ok=True)
json_path = os.path.join(state_dir, "room_pos_map.json")
csv_path = os.path.join(state_dir, "room_pos_map.csv")
md_path = os.path.join(state_dir, "room_pos_map.md")
data = {
"_meta": {
"source": json_path,
"generated_ts": int(time.time()),
"run_id": getattr(self, "_run_id", ""),
"reason": str(reason or ""),
}
}
tmp_json = json_path + ".tmp"
with open(tmp_json, "w", encoding="utf-8") as f:
json.dump(data, f, ensure_ascii=False, indent=2)
f.write("\n")
os.replace(tmp_json, json_path)
tmp_csv = csv_path + ".tmp"
with open(tmp_csv, "w", encoding="utf-8", newline="") as f:
f.write("pos,title,title_raw,has_fudai,fudai_content\n")
os.replace(tmp_csv, csv_path)
tmp_md = md_path + ".tmp"
with open(tmp_md, "w", encoding="utf-8") as f:
f.write("| pos | title | title_raw | has_fudai | fudai_content |\n")
f.write("| --- | --- | --- | --- | --- |\n")
f.write("| - | 暂无映射 | - | - | - |\n")
os.replace(tmp_md, md_path)
except Exception as exc:
try:
self._log_kv(
"映射表",
"启动时清空映射表状态文件失败",
error=str(exc),
error_type=type(exc).__name__,
)
except Exception:
pass
pass
+50
View File
@@ -13,6 +13,7 @@ import os
import json
import tempfile
from types import SimpleNamespace
from unittest.mock import MagicMock
import pytest
@@ -201,6 +202,55 @@ class TestFudaiDetectionDefaults:
assert analyser.pixel_detect_shopping_redpacket_enabled is True
assert analyser.ocr_shopping_redpacket_enabled is False
def test_apply_defaults_clears_runtime_reservation_and_mapping_state(self, tmp_path, monkeypatch):
from douyin.core import path_config
from douyin.core.fudai_modules.init_helpers import apply_fudai_defaults
state_dir = tmp_path / "state"
state_dir.mkdir()
reservations_path = state_dir / "reservations.json"
reservations_path.write_text(
json.dumps(
{
"reason": "old_run",
"room_pos": 9,
"reservations": [
{
"future_ts": 9999999999.0,
"content": "old",
"pos_seen": 9,
}
],
},
ensure_ascii=False,
),
encoding="utf-8",
)
for name, content in {
"room_pos_map.json": '{"9": {"title": "old"}}',
"room_pos_map.csv": "pos,title\n9,old\n",
"room_pos_map.md": "| pos | title |\n| 9 | old |\n",
}.items():
(state_dir / name).write_text(content, encoding="utf-8")
monkeypatch.setattr(path_config, "get_reservations_path", lambda: str(reservations_path))
analyser = SimpleNamespace(
_run_id="unit_run",
_log_kv=MagicMock(return_value=None),
)
apply_fudai_defaults(analyser)
reservations = json.loads(reservations_path.read_text(encoding="utf-8"))
assert reservations["reason"] == "startup_clear"
assert reservations["reservations"] == []
room_map = json.loads((state_dir / "room_pos_map.json").read_text(encoding="utf-8"))
assert room_map.get("_meta", {}).get("reason") == "startup_clear"
assert [key for key in room_map.keys() if not str(key).startswith("_")] == []
assert (state_dir / "room_pos_map.csv").read_text(encoding="utf-8").strip() == "pos,title,title_raw,has_fudai,fudai_content"
assert "暂无映射" in (state_dir / "room_pos_map.md").read_text(encoding="utf-8")
def test_config_loader_defaults_shopping_redpacket_detection_enabled(self):
from douyin.utils.douyin_config import ConfigManager