refactor(reservation): 拆出 attend_window 计算+日志辅助(1437→1375,-62 行)

process_reservation_attend_window 中两个互不依赖的子块抽到 attend_window_helpers:
- compute_dynamic_ahead:根据回退步数 + 单步延迟动态计算提前进入参与窗口秒数(纯函数)
- log_attend_window_check_details:输出锁定期 / 时间窗口诊断结构化日志

新增 13 个单元测试覆盖各种边界(零步 / 截断 / 大延迟 / 异常兜底 / 锁定期内外)。
1050 → 1063 用例全过。

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 02:08:11 +08:00
1 parent 189d24255d
commit c7c6c51d20
3 files changed
+275 -82

No files matched your search

@@ -22,6 +22,10 @@ from .helpers import (
_now_ts,
_sort_reservations_inplace,
)
from .attend_window_helpers import (
compute_dynamic_ahead,
log_attend_window_check_details,
)
def process_reservation_attend_window(
@@ -375,90 +379,24 @@ def process_reservation_attend_window(
return False
# 仅在"即将开奖窗口"(包括已过一小段时间)内才触发回退
try:
join_ahead = float(
getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100
)
except Exception:
join_ahead = 100.0
# poll_before 已在函数前部统一计算
# 动态提前量计算:考虑回退步数耗时,避免提前量太小导致回退后错过
dynamic_ahead = int(join_ahead)
est_back_times = 0
try:
target_pos = int(target.get("pos_seen") or 0)
est_back_times = max(0, int(room_pos) - target_pos)
try:
max_back = int(
getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60
)
except Exception:
max_back = 60
if max_back > 0:
est_back_times = min(est_back_times, max_back)
# 动态提前量 = max(基础提前量, 回退步数 * 延迟 + 额外缓冲)
reservation_back_swipe_delay_s_val = float(
reservation_back_swipe_delay_s or 0.6
)
dynamic_ahead = int(
max(join_ahead, est_back_times * reservation_back_swipe_delay_s_val + 18)
)
except Exception:
dynamic_ahead = int(join_ahead)
join_ahead = float(
getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100
)
dynamic_ahead, est_back_times = compute_dynamic_ahead(
analyser, target, room_pos, reservation_back_swipe_delay_s
)
# 添加详细的调试日志:记录锁定期状态和时间窗口检查结果
try:
from datetime import datetime
now_str = datetime.fromtimestamp(now_ts).strftime("%Y-%m-%d %H:%M:%S")
time_window_start_ts = ft - dynamic_ahead
time_window_start_str = (
datetime.fromtimestamp(time_window_start_ts).strftime("%Y-%m-%d %H:%M:%S")
if time_window_start_ts > 0
else "无效"
)
time_window_end_ts = ft + max(0.0, poll_before)
time_window_end_str = (
datetime.fromtimestamp(time_window_end_ts).strftime("%Y-%m-%d %H:%M:%S")
if time_window_end_ts > 0
else "无效"
)
ft_str = (
datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S")
if ft > 0
else "无效"
)
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 详细检查",
now_ts=int(now_ts),
now_str=now_str,
focus_until=int(focus_until) if focus_until > 0 else 0,
target_future_ts=int(ft),
target_future_str=ft_str,
dynamic_ahead=dynamic_ahead,
join_ahead=join_ahead,
poll_before=poll_before,
est_back_times=est_back_times,
time_window_start=int(time_window_start_ts),
time_window_start_str=time_window_start_str,
time_window_end=int(time_window_end_ts),
time_window_end_str=time_window_end_str,
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
remain_seconds_to_window=(
int(time_window_start_ts - now_ts)
if time_window_start_ts > now_ts
else 0
),
in_lock_period=bool(focus_until > 0 and now_ts < focus_until),
in_time_window=bool(now_ts >= time_window_start_ts),
passed_time_window=bool(now_ts > time_window_end_ts),
)
except Exception:
pass
log_attend_window_check_details(
analyser,
now_ts=now_ts,
focus_until=focus_until,
ft=ft,
dynamic_ahead=dynamic_ahead,
join_ahead=join_ahead,
poll_before=poll_before,
est_back_times=est_back_times,
)
# 优化锁定期检查:
# 1. 如果没有锁定期(focus_until = 0),直接允许检查时间窗口
@@ -0,0 +1,104 @@
"""attend_window 内部辅助函数。
把 process_reservation_attend_window 中纯计算 + 纯日志的子块抽出来:
- compute_dynamic_ahead:根据回退步数和延迟动态计算"提前进入参与窗口"的秒数
- log_attend_window_check_details:记录锁定期 / 时间窗口诊断的结构化日志
"""
from __future__ import annotations
from datetime import datetime
from typing import Any, Dict, Tuple
def compute_dynamic_ahead(
analyser: Any,
target: Dict[str, Any],
room_pos: int,
reservation_back_swipe_delay_s: float,
) -> Tuple[int, int]:
"""根据回退步数动态算出"参与提前量"。
返回 (dynamic_ahead, est_back_times):
- dynamic_ahead:建议提前进入参与窗口的秒数
- est_back_times:估算的回退步数(用于日志)
"""
try:
join_ahead = float(
getattr(analyser, "high_value_fudai_join_ahead_seconds", 100) or 100
)
except Exception:
join_ahead = 100.0
dynamic_ahead = int(join_ahead)
est_back_times = 0
try:
target_pos = int(target.get("pos_seen") or 0)
est_back_times = max(0, int(room_pos) - target_pos)
try:
max_back = int(
getattr(analyser, "high_value_fudai_max_swipe_back", 60) or 60
)
except Exception:
max_back = 60
if max_back > 0:
est_back_times = min(est_back_times, max_back)
delay_s = float(reservation_back_swipe_delay_s or 0.6)
dynamic_ahead = int(max(join_ahead, est_back_times * delay_s + 18))
except Exception:
dynamic_ahead = int(join_ahead)
return dynamic_ahead, est_back_times
def _ts_to_str(ts: float) -> str:
if ts <= 0:
return "无效"
try:
return datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M:%S")
except Exception:
return "无效"
def log_attend_window_check_details(
analyser: Any,
*,
now_ts: float,
focus_until: float,
ft: float,
dynamic_ahead: int,
join_ahead: float,
poll_before: float,
est_back_times: int,
) -> None:
"""记录锁定期 + 时间窗口诊断的详细日志。"""
try:
time_window_start_ts = ft - dynamic_ahead
time_window_end_ts = ft + max(0.0, poll_before)
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 详细检查",
now_ts=int(now_ts),
now_str=_ts_to_str(now_ts),
focus_until=int(focus_until) if focus_until > 0 else 0,
target_future_ts=int(ft),
target_future_str=_ts_to_str(ft),
dynamic_ahead=dynamic_ahead,
join_ahead=join_ahead,
poll_before=poll_before,
est_back_times=est_back_times,
time_window_start=int(time_window_start_ts),
time_window_start_str=_ts_to_str(time_window_start_ts),
time_window_end=int(time_window_end_ts),
time_window_end_str=_ts_to_str(time_window_end_ts),
remain_seconds_to_open=int(ft - now_ts) if ft > now_ts else 0,
remain_seconds_to_window=(
int(time_window_start_ts - now_ts)
if time_window_start_ts > now_ts
else 0
),
in_lock_period=bool(focus_until > 0 and now_ts < focus_until),
in_time_window=bool(now_ts >= time_window_start_ts),
passed_time_window=bool(now_ts > time_window_end_ts),
)
except Exception:
pass
+151
View File
@@ -0,0 +1,151 @@
"""单元测试:douyin/reservation/reservation_logic/attend_window_helpers.py"""
from __future__ import annotations
from unittest.mock import MagicMock
from douyin.reservation.reservation_logic import attend_window_helpers as h
def _make_analyser(**overrides):
a = MagicMock()
a.high_value_fudai_join_ahead_seconds = 100
a.high_value_fudai_max_swipe_back = 60
for k, v in overrides.items():
setattr(a, k, v)
return a
# ---- compute_dynamic_ahead ---- #
def test_compute_dynamic_ahead_zero_back_steps():
"""target_pos == room_pos → 不需要回退,提前量保持 join_ahead"""
a = _make_analyser()
target = {"pos_seen": 5}
da, est = h.compute_dynamic_ahead(a, target, room_pos=5, reservation_back_swipe_delay_s=0.6)
assert est == 0
assert da == 100 # join_ahead 默认值
def test_compute_dynamic_ahead_with_back_steps():
"""需要回退 50 步,每步 0.6s → 50*0.6+18 = 48s,仍小于 join_ahead=100,所以保持 100"""
a = _make_analyser()
target = {"pos_seen": 0}
da, est = h.compute_dynamic_ahead(a, target, room_pos=50, reservation_back_swipe_delay_s=0.6)
assert est == 50
assert da == 100
def test_compute_dynamic_ahead_back_steps_dominate():
"""需要回退 200 步但被 max_back=60 截断 → 60*0.6+18 = 54,仍 < 100"""
a = _make_analyser()
target = {"pos_seen": 0}
da, est = h.compute_dynamic_ahead(a, target, room_pos=200, reservation_back_swipe_delay_s=0.6)
assert est == 60 # 截断到 max_back
def test_compute_dynamic_ahead_huge_delay_dominates():
"""delay=5s 时 60*5+18=318 > join_ahead,dynamic_ahead 取大值"""
a = _make_analyser()
target = {"pos_seen": 0}
da, est = h.compute_dynamic_ahead(a, target, room_pos=60, reservation_back_swipe_delay_s=5.0)
assert est == 60
assert da == 318 # 60*5+18
def test_compute_dynamic_ahead_no_max_back_uncapped():
"""high_value_fudai_max_swipe_back=0 时,由于 `or 60` 会被兜底成 60"""
a = _make_analyser(high_value_fudai_max_swipe_back=0)
target = {"pos_seen": 0}
da, est = h.compute_dynamic_ahead(a, target, room_pos=100, reservation_back_swipe_delay_s=2.0)
assert est == 60 # 0 被 `or 60` 兜底
assert da == 138 # 60*2+18
def test_compute_dynamic_ahead_handles_bad_target_pos():
"""target.pos_seen 缺失时按 0 处理"""
a = _make_analyser()
target = {}
da, est = h.compute_dynamic_ahead(a, target, room_pos=10, reservation_back_swipe_delay_s=0.6)
assert est == 10
def test_compute_dynamic_ahead_negative_back_steps_clamped():
"""target_pos > room_pos(不正常)时 est_back_times 被钳到 0"""
a = _make_analyser()
target = {"pos_seen": 100}
da, est = h.compute_dynamic_ahead(a, target, room_pos=10, reservation_back_swipe_delay_s=0.6)
assert est == 0
def test_compute_dynamic_ahead_handles_bad_join_ahead():
"""getattr 抛错时回退到 100.0"""
a = MagicMock()
type(a).high_value_fudai_join_ahead_seconds = property(
lambda self: (_ for _ in ()).throw(RuntimeError("boom"))
)
a.high_value_fudai_max_swipe_back = 60
target = {"pos_seen": 5}
da, est = h.compute_dynamic_ahead(a, target, room_pos=5, reservation_back_swipe_delay_s=0.6)
# join_ahead 兜底为 100.0
assert da == 100
# ---- _ts_to_str ---- #
def test_ts_to_str_invalid():
assert h._ts_to_str(0) == "无效"
assert h._ts_to_str(-100) == "无效"
def test_ts_to_str_valid():
s = h._ts_to_str(1700000000) # 2023-11-14 22:13:20 UTC, 本地时区
assert len(s) == 19 # YYYY-MM-DD HH:MM:SS
# ---- log_attend_window_check_details ---- #
def test_log_attend_window_check_details_writes_one_line():
a = MagicMock()
h.log_attend_window_check_details(
a,
now_ts=1700000000,
focus_until=0,
ft=1700000100,
dynamic_ahead=100,
join_ahead=100.0,
poll_before=10.0,
est_back_times=0,
)
assert a._log_kv.call_count == 1
args, kwargs = a._log_kv.call_args
assert args[0] == "预约"
assert "process_reservation_attend_window 详细检查" in args[1]
assert kwargs["target_future_ts"] == 1700000100
assert kwargs["dynamic_ahead"] == 100
assert kwargs["in_lock_period"] is False # focus_until=0
def test_log_attend_window_check_details_in_lock_period():
a = MagicMock()
h.log_attend_window_check_details(
a,
now_ts=1700000000,
focus_until=1700000050, # > now_ts
ft=1700000100,
dynamic_ahead=100,
join_ahead=100.0,
poll_before=10.0,
est_back_times=0,
)
args, kwargs = a._log_kv.call_args
assert kwargs["in_lock_period"] is True
def test_log_attend_window_check_details_swallows_exceptions():
bad = MagicMock()
bad._log_kv.side_effect = RuntimeError("boom")
h.log_attend_window_check_details(
bad, now_ts=0, focus_until=0, ft=0, dynamic_ahead=0,
join_ahead=0.0, poll_before=0.0, est_back_times=0,
)