Files
douyi_guaji_main/douyin/reservation/reservation_logic/attend_window.py
T
CodexandClaude Opus 4.7 398133bbb0 refactor(reservation): 抽 process_reservation_attend_window 中"if ok 整段后处理"块到 process_seek_success
将 188 行的"seek 成功后整段后处理"块抽到 helper:
- 写"回退操作成功"日志
- 检查 reservation_back_verify_enabled,启用时:
  - wait_after_seek_and_verify 等待
  - 调用 validate_back_to_reservation
  - 校验失败 → handle_verify_failure_retry_via_mapping
  - 校验通过 → 写日志
- setup_lock_period_and_log_success

返回值约定:
- True:处理成功(含校验通过 OR 校验失败重试成功)
- False:校验失败且重试失败

attend_window.py: 574 → 405 行 (-169)
attend_window_helpers.py: 804 → 994 行

attend_window.py 跌破 500 行(1437 → 405,本会话累计削减 1032 行 = -72%)
process_reservation_attend_window 函数从 1218 → 376 行

验证:
- pytest 1013 passed
- compile OK

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 13:05:49 +08:00

406 lines
13 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""reservation_logic.attend_window - 进入预约窗口的处理(最大头)。
process_reservation_attend_window:当临近某条预约的开奖时间时,
抢占当前流程,回退到目标直播间,再触发详情识别与参与逻辑。
包含回退路径选择、回退校验、超时保护、失败重试等。
"""
from __future__ import annotations
import time
from typing import Any, Callable, Dict, List, Optional
from ._common import (
ReservationItem,
_RESERVATION_ERROR_UTILS_AVAILABLE,
format_reservation_context,
log_reservation_error,
safe_write_state,
)
from .helpers import (
_calculate_string_similarity,
_extract_content_core,
_normalize_room_title_for_matching,
_now_ts,
_sort_reservations_inplace,
)
def process_reservation_attend_window(
analyser: Any,
reservations: List[ReservationItem],
room_pos: int,
reservation_focus_until_ts_ref: List[float],
reservation_after_action_pending_ref: List[bool],
reservation_back_swipe_delay_s: float,
swipe_down_back_callback: Callable[[], None],
seek_reservation_room_callback: Callable[[ReservationItem], bool],
sort_reservations_callback: Callable[[], None],
write_state_callback: Callable[[], None],
) -> bool:
"""在主循环中调用:处理"是否需要回退到某个预约直播间并参与"。
返回:
bool: 若为 True,表示已经触发了回退/跳转,本轮主循环应尽快结束,
让上层逻辑继续后续处理(例如识别详情并参与)。
"""
start_time = time.time()
# 总超时兜底:避免预约分支在某些机型/状态下长时间阻塞导致主循环“看似卡死”。
try:
total_timeout_s = float(
getattr(analyser, "reservation_back_total_timeout_seconds", 20.0) or 20.0
)
except Exception:
total_timeout_s = 20.0
# 添加函数入口日志
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 函数入口",
reservations_count=len(reservations) if reservations else 0,
room_pos=room_pos,
)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(reservations=reservations),
level="WARNING",
stage="记录函数入口日志",
)
else:
pass
# 检查是否正在等待开奖且当前参与的是预约福袋,如果是则不抢占
try:
waiting_for_lottery = bool(
getattr(analyser, "_waiting_for_lottery_result", False)
)
current_attending_reservation = bool(
getattr(analyser, "_current_attending_reservation_fudai", False)
)
if waiting_for_lottery and current_attending_reservation:
try:
analyser._log_kv(
"预约",
"[预约] 正在等待预约福袋开奖,不抢占其他预约",
waiting_for_lottery=waiting_for_lottery,
current_attending_reservation=current_attending_reservation,
)
except Exception:
pass
return False
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(reservations=reservations),
level="WARNING",
stage="检查是否正在等待预约福袋开奖",
)
else:
pass
if not reservations:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:预约队列为空,跳过",
)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
{},
level="WARNING",
stage="记录队列为空日志",
)
else:
pass
return False
now_ts = _now_ts()
focus_until = float(
reservation_focus_until_ts_ref[0] if reservation_focus_until_ts_ref else 0.0
)
# 用于锁定期判断/匹配的轮询提前量(允许为 0,禁止为负数)
try:
poll_before = float(
getattr(analyser, "high_value_fudai_poll_before_seconds", 10.0) or 10.0
)
except Exception:
poll_before = 10.0
poll_before = max(0.0, poll_before)
# 按统一规则排序(防止外部遗漏 sort)
# 这里不依赖外部 sort_reservations_callback:避免回调内部潜在阻塞/死锁导致主流程卡死。
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:开始队列排序",
reservations_count=len(reservations) if reservations else 0,
)
except Exception:
pass
# 超时检查
from .attend_window_helpers import check_total_timeout
if check_total_timeout(analyser, start_time, total_timeout_s, "排序前"):
return False
try:
_sort_reservations_inplace(reservations)
except Exception as e:
if _RESERVATION_ERROR_UTILS_AVAILABLE:
log_reservation_error(
analyser,
e,
format_reservation_context(reservations=reservations),
level="WARNING",
stage="队列排序",
)
else:
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序异常(忽略)",
error=str(e),
error_type=type(e).__name__,
)
except Exception:
pass
try:
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window:队列排序完成",
earliest_future_ts=(
int(float((reservations[0].get("future_ts") or 0.0)))
if reservations
else 0
),
)
except Exception:
pass
# 锁定期内:优先处理“锁定的预约”,避免被队头其它预约打断。
# 同时,如果锁定期对应的预约已不在队列(例如刚参与成功并移除),视为“锁定失效”,清除锁定期。
if focus_until > 0 and now_ts < focus_until:
from .attend_window_helpers import process_lock_period
focus_until = process_lock_period(
analyser,
reservations,
focus_until,
now_ts,
poll_before,
reservation_focus_until_ts_ref,
)
# 超时检查
if check_total_timeout(analyser, start_time, total_timeout_s, "排序后"):
return False
# 取队头(最早需要处理的一条;若在锁定期内已将锁定目标移动到队头,则这里即为锁定目标)
target = reservations[0]
try:
ft = float(target.get("future_ts") or 0.0)
except Exception:
ft = 0.0
# 检查是否已经参与过该预约(通过 _participated_fudai_future_ts)
from .attend_window_helpers import (
handle_already_participated,
handle_invalid_future_ts,
)
if handle_already_participated(
analyser, reservations, target, ft, write_state_callback
):
return False
# 添加目标预约的详细信息日志
try:
from datetime import datetime
ft_str = (
datetime.fromtimestamp(ft).strftime("%Y-%m-%d %H:%M:%S")
if ft > 0
else "无效"
)
analyser._log_kv(
"预约",
"[预约] process_reservation_attend_window 获取目标预约",
target_future_ts=int(ft) if ft > 0 else 0,
target_future_str=ft_str,
target_value=float(target.get("prize_value_yuan", 0)),
target_pos_seen=int(target.get("pos_seen", 0)),
target_content=str(target.get("content", ""))[:50],
)
except Exception:
pass
# 没有合法 future_ts,则直接丢弃
if ft <= 0:
handle_invalid_future_ts(
analyser, reservations, target, ft, write_state_callback
)
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)
# 添加详细的调试日志:记录锁定期状态和时间窗口检查结果
from .attend_window_helpers import log_attend_window_detail_check
log_attend_window_detail_check(
analyser,
now_ts,
focus_until,
ft,
dynamic_ahead,
join_ahead,
poll_before,
est_back_times,
)
# 优化锁定期检查(详细规则见 helper docstring)
from .attend_window_helpers import handle_lock_period_same_reservation_check
lock_check_result = handle_lock_period_same_reservation_check(
analyser,
target,
ft,
now_ts,
focus_until,
room_pos,
dynamic_ahead,
poll_before,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
write_state_callback,
)
if lock_check_result is True:
return True
if lock_check_result is False:
return False
# 否则继续后续检查
# 检查是否是队列满后立即参与的情况(使用标志判断,而不是锁定期)
is_queue_full_immediate_attend = False
try:
# 检查队列满等待标志
queue_full_waiting = bool(
getattr(analyser, "queue_full_waiting_at_earliest", False) or False
)
if queue_full_waiting:
is_queue_full_immediate_attend = True
try:
analyser._log_kv(
"预约",
"[预约] 检测到队列满后立即参与模式(通过标志判断),跳过时间窗口检查,直接参与",
queue_full_waiting=queue_full_waiting,
target_future_ts=int(ft),
)
except Exception:
pass
except Exception:
pass
if not is_queue_full_immediate_attend and now_ts < ft - dynamic_ahead:
# 还没到窗口(非队列满立即参与模式)
from .attend_window_helpers import log_time_window_not_yet
log_time_window_not_yet(analyser, now_ts, ft, dynamic_ahead)
return False
if now_ts > ft + max(0.0, poll_before):
# 已明显错过开奖时间,交给统一清理逻辑
from .attend_window_helpers import log_missed_window
log_missed_window(analyser, now_ts, ft, poll_before)
cleanup_expired_reservations(analyser, reservations, write_state_callback)
return False
# 进入预约参与窗口:执行回退动作(含日志 + seek 回调 + 异常处理)
from .attend_window_helpers import execute_seek_reservation_with_logging
ok, current_room_pos, target_pos, pos_diff = execute_seek_reservation_with_logging(
analyser,
target,
reservations,
room_pos,
ft,
now_ts,
dynamic_ahead,
est_back_times,
poll_before,
seek_reservation_room_callback,
)
if ok:
from .attend_window_helpers import process_seek_success
if process_seek_success(
analyser,
target,
reservations,
ft,
now_ts,
room_pos,
poll_before,
reservation_focus_until_ts_ref,
reservation_after_action_pending_ref,
seek_reservation_room_callback,
write_state_callback,
start_time,
):
return True
return False
# 回退失败:记录日志,等待后续重试或清理
from .attend_window_helpers import log_seek_failure_and_finish
log_seek_failure_and_finish(
analyser, target, ft, now_ts, room_pos, start_time, write_state_callback
)
return False