refactor(fudai): 抽 _handle_in_fudai_detail 步骤1 第二次打开分支 (2216 → 2079)

新增 handle_second_open_branch helper:
- 取 _last_fudai_detail_tuple;缺失/无效则重新读取(兜底)
- 有效缓存:从 countdown_tuple 提取 future_ts/原始秒数 + 设到 self
- 调 attend_choujiang:成功清标志 / 失败累加计数 / 异常 fall through

顺手修了一个 latent bug:first-open 抽出后 caller 还在用 step3_start /
skip / skip_reason 这些已不在作用域里的变量。改成从 self._last_fudai_detail_tuple
重新取 detail,去掉无意义的 step3_elapsed 日志,step4 的 skip 参数
直接传 (False, "") —— skip 已在 first-open 内部处理完。

净减 146 行嵌套样板。新增 6 个 second-open 单元测试覆盖:
- 缓存缺失重读 + fall through
- 短 tuple 触发重读
- attend 成功清标志清失败计数
- attend 失败累加计数
- attend 异常 fall through
- 缓存有效时正确设置 _current_fudai_future_ts

至此 _handle_in_fudai_detail 总长 506 → 215 行(-58%),
douyin_fudai.py 累计 4121 → 2079(-2042 行 / -50%)。

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 22:18:33 +08:00
1 parent ca953cb4ba
commit 61cdf7b445
3 files changed
+276 -146

No files matched your search

+9 -146
View File
@@ -1875,146 +1875,10 @@ class fudai_analyse:
step1_start = time.time()
is_second_open = getattr(self, "_fudai_detail_first_read", False)
if is_second_open:
# 第二次打开:直接点击参与,不进行验证,使用第一次的倒计时
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:第二次打开,直接点击参与,跳过验证和内容识别",
)
except Exception:
pass
# 获取第一次读取的详情数据
detail = getattr(self, "_last_fudai_detail_tuple", None)
if detail is None or not isinstance(detail, tuple) or len(detail) < 6:
# 如果没有保存的详情数据,需要重新读取(兜底逻辑)
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取",
)
except Exception:
pass
detail = douyin_fudai_detail.read_fudai_detail_with_retries(
self,
fudai_x=0,
read_once_callback=douyin_fudai_detail.read_fudai_detail_once,
close_detail_callback=douyin_fudai_detail.close_fudai_detail,
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
)
# 重新读取后,更新保存的详情数据
if detail and isinstance(detail, tuple) and len(detail) >= 6:
self._last_fudai_detail_tuple = detail
# 设置当前福袋的 content(使用 cast 帮助静态分析)
detail_t: Tuple[Any, ...] = tuple(detail)
self._current_fudai_content = (
detail_t[0] if len(detail_t) > 0 else ""
)
else:
# 使用第一次保存的详情数据,设置当前福袋的倒计时信息
try:
# 从保存的 tuple 中安全读取倒计时信息,使用 cast 明确类型以帮助静态分析
detail = getattr(self, "_last_fudai_detail_tuple", None)
if (
detail is not None
and isinstance(detail, tuple)
and len(detail) >= 6
):
# 使用 cast 明确 detail 的类型,避免静态分析报 unsubscriptable
detail_t: Tuple[Any, ...] = tuple(detail)
# detail 已校验为 tuple 且长度足够,可直接索引读取倒计时信息
countdown_tuple = detail_t[5]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 3 # 现在需要至少3个元素
):
future_ts = float(countdown_tuple[1] or 0.0)
original_seconds = countdown_tuple[2] # 原始秒数
if future_ts > 0:
# 设置当前福袋的 future_ts 和 content,供 attend_choujiang 使用
self._current_fudai_future_ts = future_ts
self._current_fudai_content = (
detail_t[0] if len(detail_t) > 0 else ""
)
# 优先使用原始秒数计算剩余时间,避免时间差误差
remain_seconds = (
max(0, int(original_seconds or 0))
if original_seconds is not None
else int(future_ts - time.time())
)
self._log_kv(
"参与",
"第二次打开:使用第一次的倒计时信息",
future_ts=int(future_ts),
remain_seconds=remain_seconds,
original_seconds=(
int(original_seconds or 0)
if original_seconds is not None
else None
),
)
except Exception as e:
try:
self._log_kv(
"参与",
"第二次打开:设置倒计时信息时出错",
error=str(e),
)
except Exception:
pass
# 直接调用参与函数,不进行验证
try:
attend_result = douyin_fudai_core.attend_choujiang(self)
if attend_result:
self._log_kv(
"参与",
"第二次打开:直接点击参与成功",
result="参与成功",
)
# 参与成功,重置连续失败计数器
self._consecutive_attend_failures = 0
else:
self._log_kv(
"参与",
"第二次打开:直接点击参与失败",
result="参与失败",
)
# 参与失败,增加连续失败计数器
self._consecutive_attend_failures = (
getattr(self, "_consecutive_attend_failures", 0) + 1
)
# 清除第一次读取标志,下次打开新福袋时重新识别
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
# 清除任务数量标志
_hd_helpers._clear_task_count_flag(self)
# 步骤1结束计时
step1_elapsed = (time.time() - step1_start) * 1000
self._log_kv(
"详情处理",
"步骤1[检查是否第二次打开]-完成",
总耗时毫秒=step1_elapsed,
)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(第二次打开直接参与)",
elapsed_seconds=round(elapsed, 2),
attend_result=attend_result,
)
return
except Exception as e:
self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e))
# 异常时继续正常流程
# 第二次打开分支已抽到 handle_second_open_branch
if _hd_helpers.handle_second_open_branch(self, start_time, step1_start):
return
# 异常或兜底重读时 fall through 到正常流程
else:
# 步骤2 + 步骤3:第一次打开分支已抽到 handle_first_open_branch
if _hd_helpers.handle_first_open_branch(self, start_time):
@@ -2024,6 +1888,9 @@ class fudai_analyse:
if _hd_helpers.check_last_status_branch(self, start_time):
return
# 重新取 detail(first-open / second-open 可能已 cache 到 self._last_fudai_detail_tuple)
detail = getattr(self, "_last_fudai_detail_tuple", None)
# 如果成功读取,重置失败计数
try:
self._fudai_detail_consecutive_failures = 0
@@ -2032,7 +1899,6 @@ class fudai_analyse:
# 额外验证:使用验证函数检查数据合理性
try:
# 使用已导入的模块,避免重复导入导致作用域问题
if detail is None:
try:
self._log_kv("福袋详情", "详情数据为 None,跳过验证")
@@ -2073,13 +1939,10 @@ class fudai_analyse:
# 步骤3 末尾准备:记录参与前状态、提取 future_ts、重置 _detail_closed_by_attend
attend_before_ts = _hd_helpers.prepare_for_attend(self, detail)
# 步骤3结束计时
step3_elapsed = (time.time() - step3_start) * 1000
self._log_kv("详情处理", "步骤3[筛选检查]-完成", 总耗时毫秒=step3_elapsed)
# 步骤4:参与决策(已抽到 handle_detail_helpers.step4_make_join_decision)
# skip / skip_reason 已在 first-open 分支处理;fall-through 到此处时认为是"立即参与"
_hd_helpers.step4_make_join_decision(
self, detail, skip, skip_reason, attend_before_ts, start_time
self, detail, False, "", attend_before_ts, start_time
)
def _handle_live_room_has_or_not_fudai(self) -> None:
@@ -690,6 +690,163 @@ def _close_detail_after_attend(self: "fudai_analyse") -> None:
# handle_first_open_branch —— 步骤2 + 步骤3 完整分支
# ============================================================
def handle_second_open_branch(
self: "fudai_analyse", start_time: float, step1_start: float
) -> bool:
"""步骤1:第二次打开福袋详情,直接点击参与(跳过验证和内容识别)。
流程:
1. 取 self._last_fudai_detail_tuple
2. 缺失或无效 → 重新读取,保存到 self(兜底)后 fall through
3. 有效 → 设置 self._current_fudai_future_ts 等倒计时信息
4. 调 douyin_fudai_core.attend_choujiang
- 成功:清标志 + 步骤1结束日志 + return True
- 失败:增加连续失败计数 + 清标志 + 步骤1结束日志 + return True
- 异常:log + 继续走正常流程,return False
返回 True 表示 caller 应当 `return`;False 表示需要走后续步骤
(fall through 到 last_status / 验证 / 兜底 / step4)。
"""
import time
from typing import Any, Tuple
from douyin.fudai import douyin_fudai_core, douyin_fudai_detail
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:第二次打开,直接点击参与,跳过验证和内容识别",
)
except Exception:
pass
# 取第一次读取的详情数据
detail = getattr(self, "_last_fudai_detail_tuple", None)
if detail is None or not isinstance(detail, tuple) or len(detail) < 6:
# 没有保存的详情数据,需要重新读取(兜底逻辑)
try:
self._log_kv(
"流程",
"_handle_in_fudai_detail:未找到第一次读取的详情数据,重新读取",
)
except Exception:
pass
detail = douyin_fudai_detail.read_fudai_detail_with_retries(
self,
fudai_x=0,
read_once_callback=douyin_fudai_detail.read_fudai_detail_once,
close_detail_callback=douyin_fudai_detail.close_fudai_detail,
ensure_open_callback=douyin_fudai_detail.ensure_fudai_detail_open,
)
# 重新读取后,更新保存的详情数据
if detail and isinstance(detail, tuple) and len(detail) >= 6:
self._last_fudai_detail_tuple = detail
detail_t: Tuple[Any, ...] = tuple(detail)
self._current_fudai_content = (
detail_t[0] if len(detail_t) > 0 else ""
)
# 兜底重读后无论成功失败,都不在此 return —— 让 caller 继续走正常流程
return False
# 有效详情:设置倒计时信息
try:
if (
detail is not None
and isinstance(detail, tuple)
and len(detail) >= 6
):
detail_t = tuple(detail)
countdown_tuple = detail_t[5]
if (
isinstance(countdown_tuple, (tuple, list))
and len(countdown_tuple) >= 3
):
future_ts = float(countdown_tuple[1] or 0.0)
original_seconds = countdown_tuple[2]
if future_ts > 0:
self._current_fudai_future_ts = future_ts
self._current_fudai_content = (
detail_t[0] if len(detail_t) > 0 else ""
)
remain_seconds = (
max(0, int(original_seconds or 0))
if original_seconds is not None
else int(future_ts - time.time())
)
self._log_kv(
"参与",
"第二次打开:使用第一次的倒计时信息",
future_ts=int(future_ts),
remain_seconds=remain_seconds,
original_seconds=(
int(original_seconds or 0)
if original_seconds is not None
else None
),
)
except Exception as e:
try:
self._log_kv(
"参与",
"第二次打开:设置倒计时信息时出错",
error=str(e),
)
except Exception:
pass
# 直接调用参与函数,不进行验证
try:
attend_result = douyin_fudai_core.attend_choujiang(self)
if attend_result:
self._log_kv(
"参与",
"第二次打开:直接点击参与成功",
result="参与成功",
)
self._consecutive_attend_failures = 0
else:
self._log_kv(
"参与",
"第二次打开:直接点击参与失败",
result="参与失败",
)
self._consecutive_attend_failures = (
getattr(self, "_consecutive_attend_failures", 0) + 1
)
# 清除第一次读取标志,下次打开新福袋时重新识别
try:
self._fudai_detail_first_read = False
self._last_fudai_detail_tuple = None
except Exception:
pass
# 清除任务数量标志
_clear_task_count_flag(self)
# 步骤1结束计时
step1_elapsed = (time.time() - step1_start) * 1000
self._log_kv(
"详情处理",
"步骤1[检查是否第二次打开]-完成",
总耗时毫秒=step1_elapsed,
)
elapsed = time.time() - start_time
self._log_kv(
"流程",
"_handle_in_fudai_detail完成(第二次打开直接参与)",
elapsed_seconds=round(elapsed, 2),
attend_result=attend_result,
)
return True
except Exception as e:
self._log_kv("参与", "第二次打开:直接点击参与异常", error=str(e))
# 异常时继续正常流程
return False
def handle_first_open_branch(
self: "fudai_analyse", start_time: float
) -> bool:
+110
View File
@@ -596,3 +596,113 @@ class TestHandleFirstOpenBranch:
assert result is True
join_called.assert_called_once()
# ============================================================
# handle_second_open_branch
# ============================================================
class TestHandleSecondOpenBranch:
def _mk_for_second_open(self):
s = _mk_self()
s.device_id = "MOCK"
s.operation = MagicMock()
s.operation.delay = MagicMock(return_value=None)
s._fudai_detail_first_read = True
s._consecutive_attend_failures = 0
s._fudai_detail_task_count_from_stage = 0
return s
def test_no_cached_detail_refetches_and_returns_false(self):
"""没有缓存的 detail → 重新读取后保存,return False 让 caller 继续走正常流程。"""
import time
s = self._mk_for_second_open()
s._last_fudai_detail_tuple = None
new_detail = ("X", 0, 0, 0, 100.0, (time.time(), time.time() + 60, 60))
with patch(
"douyin.fudai.douyin_fudai_detail.read_fudai_detail_with_retries",
return_value=new_detail,
):
result = hd.handle_second_open_branch(s, 0.0, 0.0)
assert result is False
# 重读成功应保存到 self
assert s._last_fudai_detail_tuple == new_detail
assert s._current_fudai_content == "X"
def test_short_tuple_triggers_refetch(self):
"""缓存 tuple 长度 < 6 → 触发重新读取。"""
s = self._mk_for_second_open()
s._last_fudai_detail_tuple = ("a", "b") # 太短
with patch(
"douyin.fudai.douyin_fudai_detail.read_fudai_detail_with_retries",
return_value=None,
) as mock_read:
result = hd.handle_second_open_branch(s, 0.0, 0.0)
assert result is False
mock_read.assert_called_once()
def test_attend_success_returns_true_clears_failures(self):
"""attend_choujiang 成功 → 清标志 + 清失败计数 + return True。"""
import time
s = self._mk_for_second_open()
s._consecutive_attend_failures = 3
future_ts = time.time() + 60
s._last_fudai_detail_tuple = ("X", 0, 0, 0, 100.0, (time.time(), future_ts, 60))
with patch(
"douyin.fudai.douyin_fudai_core.attend_choujiang",
return_value=True,
):
result = hd.handle_second_open_branch(s, 0.0, 0.0)
assert result is True
assert s._consecutive_attend_failures == 0
# 清标志:first_read 重置、tuple 清掉
assert s._fudai_detail_first_read is False
assert s._last_fudai_detail_tuple is None
# 任务数量标志被清掉
assert s._fudai_detail_task_count_from_stage is None
def test_attend_failure_returns_true_increments_counter(self):
"""attend_choujiang 失败 → 增加连续失败计数 + return True。"""
import time
s = self._mk_for_second_open()
s._consecutive_attend_failures = 2
future_ts = time.time() + 60
s._last_fudai_detail_tuple = ("X", 0, 0, 0, 100.0, (time.time(), future_ts, 60))
with patch(
"douyin.fudai.douyin_fudai_core.attend_choujiang",
return_value=False,
):
result = hd.handle_second_open_branch(s, 0.0, 0.0)
assert result is True
assert s._consecutive_attend_failures == 3
def test_attend_exception_returns_false(self):
"""attend_choujiang 抛异常 → log + return False(fall through 到正常流程)。"""
import time
s = self._mk_for_second_open()
future_ts = time.time() + 60
s._last_fudai_detail_tuple = ("X", 0, 0, 0, 100.0, (time.time(), future_ts, 60))
with patch(
"douyin.fudai.douyin_fudai_core.attend_choujiang",
side_effect=RuntimeError("boom"),
):
result = hd.handle_second_open_branch(s, 0.0, 0.0)
assert result is False
def test_sets_current_fudai_future_ts_from_cache(self):
"""缓存 detail 有效时设置 self._current_fudai_future_ts。"""
import time
s = self._mk_for_second_open()
future_ts = time.time() + 60
s._last_fudai_detail_tuple = ("X", 0, 0, 0, 100.0, (time.time(), future_ts, 60))
with patch(
"douyin.fudai.douyin_fudai_core.attend_choujiang",
return_value=True,
):
hd.handle_second_open_branch(s, 0.0, 0.0)
assert s._current_fudai_future_ts == future_ts