refactor(douyu): 完成阶段5旧链路清理

This commit is contained in:
yml
2026-11-22 21:40:53 +08:00
parent 94de1d167b
commit 5393b668e0
20 changed files with 155 additions and 559 deletions
+2 -2
View File
@@ -212,10 +212,10 @@ ACCOUNT_COMMODITY_STABLE_TTL_SECONDS=21600
ACCOUNT_COMMODITY_LIMITED_TTL_SECONDS=86400 ACCOUNT_COMMODITY_LIMITED_TTL_SECONDS=86400
ACCOUNT_COMMODITY_NO_STOCK_TTL_SECONDS=900 ACCOUNT_COMMODITY_NO_STOCK_TTL_SECONDS=900
ACCOUNT_COMMODITY_UNKNOWN_TTL_SECONDS=300 ACCOUNT_COMMODITY_UNKNOWN_TTL_SECONDS=300
# legacy=旧实时扫号 / hybrid=本地能力索引(默认,零外部请求)/ capability=同 hybrid
PLATFORM_FULFILLMENT_MATCH_MODE=hybrid
# 单轮本地选号批量;本地选号不再逐账号请求官网 # 单轮本地选号批量;本地选号不再逐账号请求官网
PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH=20 PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH=20
# 单次从本地能力索引读取的候选账号上限
PLATFORM_FULFILLMENT_CAPABILITY_CANDIDATE_LIMIT=20
# 能力池缺失时,每次最多向独立账号同步槽补入多少个账号 # 能力池缺失时,每次最多向独立账号同步槽补入多少个账号
PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT=20 PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT=20
# 扫码超时任务保留账号多久;超过后释放未绑定账号,避免历史任务永久占号。 # 扫码超时任务保留账号多久;超过后释放未绑定账号,避免历史任务永久占号。
@@ -11,8 +11,7 @@
更新时间:2026-11-21 更新时间:2026-11-21
阶段 0-4 已全部完成;阶段 5 尚未启动。若把阶段 5 的旧逻辑清理也计入, 阶段 0-5 已全部完成,整体实施进度 **100%**。
整体实施进度约 **85%**。
| 阶段 | 完成度 | 已落地 | 主要缺口 | | 阶段 | 完成度 | 已落地 | 主要缺口 |
| --- | ---: | --- | --- | | --- | ---: | --- | --- |
@@ -21,7 +20,7 @@
| 阶段 2:账号与 CK | 100% | CK 周期字段、invalid 分流、登录流水、日/小时/分类/单账号预算、login_relogin 队列真实消费与退避回队、预算配置 API、库存与近期成功率驱动的预算建议 | 无 | | 阶段 2:账号与 CK | 100% | CK 周期字段、invalid 分流、登录流水、日/小时/分类/单账号预算、login_relogin 队列真实消费与退避回队、预算配置 API、库存与近期成功率驱动的预算建议 | 无 |
| 阶段 3:商品与供给 | 100% | 全量商品能力、限时窗口、原始响应、供给库存和目标缺口、定向补货入队、供给目标配置 API 与管理 UI、默认目标、统一平台状态快照、供给看板、阈值告警、7 天查询/登录/CK 趋势 | 无 | | 阶段 3:商品与供给 | 100% | 全量商品能力、限时窗口、原始响应、供给库存和目标缺口、定向补货入队、供给目标配置 API 与管理 UI、默认目标、统一平台状态快照、供给看板、阈值告警、7 天查询/登录/CK 趋势 | 无 |
| 阶段 4:安全恢复自动化 | 100% | account_sync_queue 与供给补货作业默认小批量开启,自动重登消费工作队列,硬失败率熔断,登录预算在线配置且熔断阈值实时生效,按 7 天成功率自动扩缩批次,长期低成功率告警,登录预算建议与人工一键应用 | 代码已完成;生产灰度效果继续观察 | | 阶段 4:安全恢复自动化 | 100% | account_sync_queue 与供给补货作业默认小批量开启,自动重登消费工作队列,硬失败率熔断,登录预算在线配置且熔断阈值实时生效,按 7 天成功率自动扩缩批次,长期低成功率告警,登录预算建议与人工一键应用 | 代码已完成;生产灰度效果继续观察 |
| 阶段 5:清理旧逻辑 | 20% | 履约补货不再直接发官网请求 | 旧资料刷新、旁路查询和旧候选兜底仍需逐步下线 | | 阶段 5:清理旧逻辑 | 100% | 删除 legacy 实时选号、旧资料全量刷新、`query_limited_goods`/`refresh_goods` 任务入口和 Runner 分支;一键查询统一返回限兑信息;自动作业共享账号准入过滤;登录入口统一受预算约束 | 无 |
## 为什么重构 ## 为什么重构
@@ -607,14 +606,15 @@ Runner 启动前必须有预算 token;没有 token 时留在工作队列。
### 阶段 5:清理旧逻辑 ### 阶段 5:清理旧逻辑
删除或降级: 已完成:
- Runner 内重复查询后写库 - `account_overview_refresh` 全量定时刷新已删除,迁移 `0117` 停用生产旧配置;
- 弱投影的 `query_limited_goods` - Runner 查询一次后直接同步账号能力,不再重复查询后补写;
- 只写全局快照的 `refresh_goods` - `query_limited_goods`、`refresh_goods` 已从任务类型、前端入口和 Runner 删除;
- 作业各自拼接候选条件 - 限兑数量与商品明细并入 `query_account_overview`,历史旧任务仍由清理作业回收;
- 自动选号 20 个账号实时扫描兜底 - 自动选号只读本地能力索引,`legacy` 模式和 20 个账号实时扫描兜底已删除;
- 绕过登录配额的自动入口 - CK 巡检、自动重登共享 `automation_account_filter` 账号准入;
- 人工登录、账号检测重登和自动重登统一经过 `LoginBatchRunner` 登录预算预占。
## 可观测性 ## 可观测性
@@ -699,6 +699,7 @@ Runner 启动前必须有预算 token;没有 token 时留在工作队列。
| 2026-11-21 | 阶段 4:增加基于库存、积压和近期成功率的登录预算建议及人工一键应用 | | 2026-11-21 | 阶段 4:增加基于库存、积压和近期成功率的登录预算建议及人工一键应用 |
| 2026-11-21 | 阶段 1:一键查询接入本地快照复用,商品过期改为后台同步,避免重复官网查询 | | 2026-11-21 | 阶段 1:一键查询接入本地快照复用,商品过期改为后台同步,避免重复官网查询 |
| 2026-11-21 | 阶段 0-4 完成:全部账号查询域接入本地优先策略、独立同步工作项和兑换记录统一投影;阶段 5 暂不启动 | | 2026-11-21 | 阶段 0-4 完成:全部账号查询域接入本地优先策略、独立同步工作项和兑换记录统一投影;阶段 5 暂不启动 |
| 2026-11-22 | 阶段 5 完成:删除 legacy 实时选号、旧商品任务入口和全量资料刷新,统一自动账号准入与登录预算入口 |
| 2026-11-22 | 履约租约改为状态化策略:默认无限,预售/人工独立配置,完成或取消后才设置释放时间 | | 2026-11-22 | 履约租约改为状态化策略:默认无限,预售/人工独立配置,完成或取消后才设置释放时间 |
| 2026-11-22 | 按生产并发、CK 流失和历史领取峰值提高全局供给目标,并安全升级旧默认组合 | | 2026-11-22 | 按生产并发、CK 流失和历史领取峰值提高全局供给目标,并安全升级旧默认组合 |
| 2026-11-22 | 抽取统一账号准入过滤;外部协作推荐改为纯本地能力池,兑换记录统一走本地同步投影 | | 2026-11-22 | 抽取统一账号准入过滤;外部协作推荐改为纯本地能力池,兑换记录统一走本地同步投影 |
@@ -416,7 +416,7 @@ AND 不违反内部兑换冷却
3. 将新鲜度与可查询性分开; 3. 将新鲜度与可查询性分开;
4. 建立官网同步运行记录; 4. 建立官网同步运行记录;
5. 统一账号商品能力查询口径; 5. 统一账号商品能力查询口径;
6. 自动选号移除无限实时扫描兜底; 6. 自动选号移除无限实时扫描兜底;阶段 5 已同时删除 legacy 实时选号代码;
7. 选号 API 增加任务级幂等、请求合并和前端 loading; 7. 选号 API 增加任务级幂等、请求合并和前端 loading;
8. 外部官网检测迁移到独立 Worker,不长期占用 API 数据库连接。 8. 外部官网检测迁移到独立 Worker,不长期占用 API 数据库连接。
+5 -4
View File
@@ -37,7 +37,7 @@
页面、外部单协作、直播账号履约和任务执行器只能调用该模块,不得直接调用 页面、外部单协作、直播账号履约和任务执行器只能调用该模块,不得直接调用
`DouyuActivityClient` 的只读查询方法。商品映射弹窗使用实时活动商品接口, `DouyuActivityClient` 的只读查询方法。商品映射弹窗使用实时活动商品接口,
不再依赖本地是否执行过 `refresh_goods`。 不再依赖已淘汰的 `refresh_goods` 任务。
腾讯游戏绑定状态只有一个业务入口: 腾讯游戏绑定状态只有一个业务入口:
`web/backend/services/account_binding.py`。原始接口字段由 `web/backend/services/account_binding.py`。原始接口字段由
@@ -57,17 +57,18 @@
2026-11-22 起,默认选号是**纯本地数据库操作**: 2026-11-22 起,默认选号是**纯本地数据库操作**:
- `hybrid` / `capability` 只读取新鲜 `account_commodity_states` 和账号主表, - 选号只读取新鲜 `account_commodity_states` 和账号主表,
不再在分配热路径串行请求斗鱼官网; 不再在分配热路径串行请求斗鱼官网;
- 一个账号的 `storehome` 商品列表会一次写入全部商品能力,不需要逐商品查询; - 一个账号的 `storehome` 商品列表会一次写入全部商品能力,不需要逐商品查询;
- 分配阶段只做账号硬过滤、候选排序和数据库租约抢占,通常应在毫秒级完成; - 分配阶段只做账号硬过滤、候选排序和数据库租约抢占,通常应在毫秒级完成;
- 绑定二维码阶段会校验 CK/角色,兑换前“刷新兑换资格”仍会实时访问官网, - 绑定二维码阶段会校验 CK/角色,兑换前“刷新兑换资格”仍会实时访问官网,
因此本地选号只负责快速占号,不替代最终业务校验; 因此本地选号只负责快速占号,不替代最终业务校验;
- `legacy` 保留旧实时扫号逻辑,仅用于故障回滚和对比,不再是生产默认路径。 - 阶段 5 已删除 `legacy` 实时扫号和 20 个账号兜底代码,环境变量也不能再切回旧路径。
能力索引与调度规则: 能力索引与调度规则:
- 一键查询或资料刷新把官方 `storehome` 商品状态写入 `account_commodity_states`; - `query_account_overview` 一键查询把官方 `storehome` 商品状态写入
`account_commodity_states`,并直接在结果中返回限兑数量;
- `storehome` 一次返回账号可见的全部商品,逐商品写状态,但每个账号只需一次列表请求; - `storehome` 一次返回账号可见的全部商品,逐商品写状态,但每个账号只需一次列表请求;
- 同时保存 `timeLimited`、`specTimes` 和起止时间,未开始/已结束与账号限兑分别处理; - 同时保存 `timeLimited`、`specTimes` 和起止时间,未开始/已结束与账号限兑分别处理;
- 账号兑换资格和活动窗口默认缓存 6 小时,库存仅作展示并默认缓存 15 分钟; - 账号兑换资格和活动窗口默认缓存 6 小时,库存仅作展示并默认缓存 15 分钟;
+16
View File
@@ -411,6 +411,8 @@ class TestOverviewAggregation:
assert seen == ["ELITE-M"], "商城商品必须用精英宝典的 manualID 拉" assert seen == ["ELITE-M"], "商城商品必须用精英宝典的 manualID 拉"
assert "esports" in r["errors"] # 电竞那一项照常报未配置 assert "esports" in r["errors"] # 电竞那一项照常报未配置
assert r["limited_goods_total"] == 2 assert r["limited_goods_total"] == 2
assert r["limited_count"] == 1
assert len(r["limited_goods"]) == 1
# 高价值三态照样落库(官方 status 说了算) # 高价值三态照样落库(官方 status 说了算)
self.session.commit() self.session.commit()
self.session.refresh(self.account) self.session.refresh(self.account)
@@ -547,6 +549,8 @@ class TestOverviewAggregation:
assert result["goods_source"] == "local_fresh_projection" assert result["goods_source"] == "local_fresh_projection"
assert result["pending_domains"] == [] assert result["pending_domains"] == []
assert result["limited_goods_total"] == 1 assert result["limited_goods_total"] == 1
assert result["limited_count"] == 0
assert result["limited_goods"] == []
assert self.session.query(AccountWorkItem).count() == 0 assert self.session.query(AccountWorkItem).count() == 0
def test_stale_esports_and_exchange_records_use_local_projection_and_queue(self): def test_stale_esports_and_exchange_records_use_local_projection_and_queue(self):
@@ -613,6 +617,18 @@ class TestOverviewTaskTypeWiring:
for scope in ("elite", "esports", "peace"): for scope in ("elite", "esports", "peace"):
assert "query_account_overview" in DOUYU_HANDBOOK_TASK_TYPES[scope] assert "query_account_overview" in DOUYU_HANDBOOK_TASK_TYPES[scope]
def test_obsolete_goods_tasks_are_not_supported(self):
from web.backend.services.douyu_service import (
DOUYU_HANDBOOK_TASK_TYPES,
SUPPORTED_DOUYU_TASK_TYPES,
)
assert "refresh_goods" not in SUPPORTED_DOUYU_TASK_TYPES
assert "query_limited_goods" not in SUPPORTED_DOUYU_TASK_TYPES
for scope in ("elite", "esports", "peace"):
assert "refresh_goods" not in DOUYU_HANDBOOK_TASK_TYPES[scope]
assert "query_limited_goods" not in DOUYU_HANDBOOK_TASK_TYPES[scope]
def test_handler_is_dispatched(self): def test_handler_is_dispatched(self):
from web.backend.services.douyu_runner import DouyuBatchRunner from web.backend.services.douyu_runner import DouyuBatchRunner
+1 -1
View File
@@ -133,7 +133,7 @@ def _seed_tasks(db):
batch_id="batch-main", batch_id="batch-main",
account_id=support_account.id, account_id=support_account.id,
account_assigned_to=support.id, account_assigned_to=support.id,
task_type="query_limited_goods", task_type="query_gold_balance",
handbook_scope="legacy", handbook_scope="legacy",
status="success", status="success",
created_by=support.id, created_by=support.id,
+4 -1
View File
@@ -244,5 +244,8 @@ class TestClassification(_Base):
"""噪声名单里的类型必须都是真实存在的任务类型(防拼写错误导致永不生效)。""" """噪声名单里的类型必须都是真实存在的任务类型(防拼写错误导致永不生效)。"""
from web.backend.services.douyu_service import SUPPORTED_DOUYU_TASK_TYPES from web.backend.services.douyu_service import SUPPORTED_DOUYU_TASK_TYPES
unknown = set(retention.NOISE_TASK_TYPES) - set(SUPPORTED_DOUYU_TASK_TYPES) known = set(SUPPORTED_DOUYU_TASK_TYPES) | set(
retention.RETIRED_NOISE_TASK_TYPES
)
unknown = set(retention.NOISE_TASK_TYPES) - known
assert not unknown, f"噪声名单里有不存在的任务类型:{unknown}" assert not unknown, f"噪声名单里有不存在的任务类型:{unknown}"
+25
View File
@@ -0,0 +1,25 @@
"""阶段 5:所有登录入口必须继续经过统一预算执行器。"""
from __future__ import annotations
import inspect
from pathlib import Path
from web.backend.services import login_service
ROOT = Path(__file__).resolve().parents[1]
def test_login_runner_reserves_quota_before_attempt() -> None:
source = inspect.getsource(login_service.LoginBatchRunner.run)
assert "reserve_login_attempt(" in source
def test_known_login_entrypoints_construct_login_runner() -> None:
for relative in (
"web/backend/routers/login.py",
"web/backend/routers/cookies.py",
"web/backend/services/automation/jobs/ck_relogin.py",
):
source = (ROOT / relative).read_text(encoding="utf-8")
assert "LoginBatchRunner(" in source, relative
+8 -60
View File
@@ -5,7 +5,6 @@ from __future__ import annotations
import asyncio import asyncio
import threading import threading
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from unittest.mock import patch
import pytest import pytest
from fastapi import HTTPException from fastapi import HTTPException
@@ -36,7 +35,6 @@ from web.backend.services.account_sync_runner import WORK_STOREHOME_SYNC
from web.backend.services.automation.jobs import ( from web.backend.services.automation.jobs import (
platform_fulfillment_lease_reaper as reaper, platform_fulfillment_lease_reaper as reaper,
) )
from web.backend.services.douyu_account_state import DouyuLiveAccountState
from web.backend.services.platform_fulfillment import account_selector, service from web.backend.services.platform_fulfillment import account_selector, service
NOW = datetime.now(UTC).replace(microsecond=0) NOW = datetime.now(UTC).replace(microsecond=0)
@@ -64,31 +62,9 @@ class _Base:
) )
) )
self.session.commit() self.session.commit()
self.refresh_patch = patch.object(
service,
"refresh_douyu_account_state",
side_effect=self._live_state,
)
self.refresh_mock = self.refresh_patch.start()
def teardown_method(self): def teardown_method(self):
self.refresh_patch.stop()
self.session.close() self.session.close()
@staticmethod
def _live_state(_db, account, **_kwargs):
return DouyuLiveAccountState(
account_id=account.id,
account_name=account.username,
checked_at=NOW,
ck_verdict="valid",
ck_message="有效",
elite_opened=True,
points=account.points or 2000,
limited_ids=frozenset(),
role_change_available_at=account.role_change_available_at,
)
def account( def account(
self, self,
name: str, name: str,
@@ -1084,9 +1060,8 @@ class TestAccountSelection(_Base):
assert detail["task"]["account"] is None assert detail["task"]["account"] is None
assert task.next_allocate_at is not None assert task.next_allocate_at is not None
assert old_retry_at is None or task.next_allocate_at >= old_retry_at assert old_retry_at is None or task.next_allocate_at >= old_retry_at
self.refresh_mock.assert_not_called()
def test_capability_match_uses_local_index_without_live_probe(self, monkeypatch): def test_capability_match_uses_local_index_without_live_probe(self):
account = self.account("capability-fast", capability=False) account = self.account("capability-fast", capability=False)
task = self.task() task = self.task()
self.session.add( self.session.add(
@@ -1106,8 +1081,6 @@ class TestAccountSelection(_Base):
) )
) )
self.session.commit() self.session.commit()
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "capability")
detail = service.allocate_task( detail = service.allocate_task(
self.session, self.session,
task_id=task.id, task_id=task.id,
@@ -1116,20 +1089,14 @@ class TestAccountSelection(_Base):
assert detail["task"]["account"]["id"] == account.id assert detail["task"]["account"]["id"] == account.id
assert detail["task"]["executionStatus"] == "allocated" assert detail["task"]["executionStatus"] == "allocated"
self.refresh_mock.assert_not_called()
def test_allocation_reports_role_cooldown_without_fast_retry_loop( def test_allocation_reports_role_cooldown_without_fast_retry_loop(self):
self,
monkeypatch,
):
self.account( self.account(
"capability-role-cooldown", "capability-role-cooldown",
points=2000, points=2000,
role_available_at=NOW + timedelta(days=2), role_available_at=NOW + timedelta(days=2),
) )
task = self.task() task = self.task()
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "capability")
detail = service.allocate_task( detail = service.allocate_task(
self.session, self.session,
task_id=task.id, task_id=task.id,
@@ -1151,13 +1118,9 @@ class TestAccountSelection(_Base):
assert event.detail_json["availabilityCounts"]["account:eligible"] == 1 assert event.detail_json["availabilityCounts"]["account:eligible"] == 1
assert event.detail_json["availabilityCounts"]["account:roleCooldown"] == 1 assert event.detail_json["availabilityCounts"]["account:roleCooldown"] == 1
def test_hybrid_without_capability_does_not_fall_back_to_live_scan( def test_missing_capability_does_not_fall_back_to_live_scan(self):
self,
monkeypatch,
):
self.account("live-fallback", capability=False) self.account("live-fallback", capability=False)
task = self.task() task = self.task()
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid")
detail = service.allocate_task( detail = service.allocate_task(
self.session, self.session,
@@ -1168,28 +1131,13 @@ class TestAccountSelection(_Base):
assert detail["task"]["account"] is None assert detail["task"]["account"] is None
assert detail["task"]["executionStatus"] == "ready" assert detail["task"]["executionStatus"] == "ready"
assert detail["task"]["issueCode"] == "capability_cache_miss" assert detail["task"]["issueCode"] == "capability_cache_miss"
self.refresh_mock.assert_not_called()
work_item = self.session.query(AccountWorkItem).one() work_item = self.session.query(AccountWorkItem).one()
assert work_item.work_type == WORK_STOREHOME_SYNC assert work_item.work_type == WORK_STOREHOME_SYNC
assert work_item.priority == 20 assert work_item.priority == 20
def test_legacy_mode_keeps_live_scan_fallback(self, monkeypatch): def test_legacy_mode_env_cannot_enable_live_scan(self, monkeypatch):
monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "legacy") monkeypatch.setenv("PLATFORM_FULFILLMENT_MATCH_MODE", "legacy")
account = Account( self.account("forced-local-selection", capability=False)
username="live-refresh-account",
password="p",
email="live@example.com",
email_password="ep",
status="imported",
ck_check_status="",
cookie="PHPSESSID=live",
elite_opened=None,
points=None,
gold_balance=100,
auto_managed=True,
)
self.session.add(account)
self.session.commit()
task = self.task() task = self.task()
detail = service.allocate_task( detail = service.allocate_task(
@@ -1198,9 +1146,9 @@ class TestAccountSelection(_Base):
current=self.admin, current=self.admin,
) )
assert detail["task"]["account"]["id"] == account.id assert detail["task"]["account"] is None
assert detail["task"]["executionStatus"] == "allocated" assert detail["task"]["executionStatus"] == "ready"
self.refresh_mock.assert_called() assert detail["task"]["issueCode"] == "capability_cache_miss"
def test_live_candidates_include_support_accounts_and_prefer_valid_cache(self): def test_live_candidates_include_support_accounts_and_prefer_valid_cache(self):
support = User( support = User(
+35 -1
View File
@@ -4,13 +4,14 @@ from __future__ import annotations
from datetime import datetime, timedelta from datetime import datetime, timedelta
from sqlalchemy import and_, or_, select from sqlalchemy import and_, func, or_, select
from ..models import ( from ..models import (
Account, Account,
AccountCommodityState, AccountCommodityState,
AccountLease, AccountLease,
DouyuExternalOrder, DouyuExternalOrder,
LoginTask,
User, User,
) )
from .account_capability_service import ( from .account_capability_service import (
@@ -31,6 +32,7 @@ ACTIVE_COLLAB_STATUSES: tuple[str, ...] = (
) )
POOL_OWNER_ROLES: tuple[str, ...] = ("super_admin", "operation", "support") POOL_OWNER_ROLES: tuple[str, ...] = ("super_admin", "operation", "support")
CK_FRESH_SECONDS = 24 * 60 * 60 CK_FRESH_SECONDS = 24 * 60 * 60
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = ("pending", "running")
def pool_owner_ids(): def pool_owner_ids():
@@ -44,6 +46,26 @@ def cookie_present_filter():
return and_(Account.cookie.isnot(None), Account.cookie != "") return and_(Account.cookie.isnot(None), Account.cookie != "")
def cookie_holding_filter():
"""账号当前是否持有 CK。"""
return cookie_present_filter()
def cookie_operable_filter():
"""持有 CK,且该账号没有在途登录/检测尝试。"""
in_flight = (
select(LoginTask.id)
.where(LoginTask.account_id == Account.id)
.where(
func.coalesce(LoginTask.attempt_status, "").in_(
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
)
)
.exists()
)
return and_(cookie_holding_filter(), ~in_flight)
def valid_ck_filter(*, checked_since: datetime | None = None): def valid_ck_filter(*, checked_since: datetime | None = None):
filters = [Account.ck_check_status == "valid"] filters = [Account.ck_check_status == "valid"]
if checked_since is not None: if checked_since is not None:
@@ -63,6 +85,14 @@ def automatable_account_filter():
) )
def automation_account_filter(*, cookie_operable: bool = True):
"""所有自动账号作业共用的账号生命周期准入。"""
return and_(
cookie_operable_filter() if cookie_operable else cookie_holding_filter(),
automatable_account_filter(),
)
def assigned_to_pool_filter(): def assigned_to_pool_filter():
return or_( return or_(
Account.assigned_to.is_(None), Account.assigned_to.is_(None),
@@ -124,11 +154,15 @@ def fresh_eligible_state_filter(
__all__ = [ __all__ = [
"ACTIVE_COLLAB_STATUSES", "ACTIVE_COLLAB_STATUSES",
"CK_FRESH_SECONDS", "CK_FRESH_SECONDS",
"LOGIN_ATTEMPT_IN_FLIGHT_STATUSES",
"POOL_OWNER_ROLES", "POOL_OWNER_ROLES",
"active_collab_order_exists", "active_collab_order_exists",
"active_lease_exists", "active_lease_exists",
"assigned_to_pool_filter", "assigned_to_pool_filter",
"automatable_account_filter", "automatable_account_filter",
"automation_account_filter",
"cookie_holding_filter",
"cookie_operable_filter",
"cookie_present_filter", "cookie_present_filter",
"fresh_ck_cutoff", "fresh_ck_cutoff",
"fresh_eligible_state_filter", "fresh_eligible_state_filter",
@@ -17,8 +17,9 @@ from sqlalchemy import and_, case, func, or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ....models import Account, AutomationJob from ....models import Account, AutomationJob
from ...account_lifecycle import MANUAL_STATES, WORK_LOGIN_RELOGIN from ...account_lifecycle import WORK_LOGIN_RELOGIN
from ...account_protection_service import load_protection_snapshot from ...account_protection_service import load_protection_snapshot
from ...account_query_filters import automation_account_filter
from ...account_value import ( from ...account_value import (
HIGH_VALUE_TIER_MAX, HIGH_VALUE_TIER_MAX,
high_value_recheck_seconds, high_value_recheck_seconds,
@@ -35,7 +36,6 @@ from ...douyu_account_probe import (
persist_probe_result, persist_probe_result,
probe_session, probe_session,
) )
from ...douyu_service import cookie_holding_filter, cookie_operable_filter
from ...task_runtime import TaskLane, submit from ...task_runtime import TaskLane, submit
JOB_KEY = "ck_health" JOB_KEY = "ck_health"
@@ -101,13 +101,11 @@ def _candidates_query(db: Session, job: AutomationJob, now: datetime):
query = ( query = (
db.query(Account) db.query(Account)
.filter(cookie_operable_filter()) .filter(automation_account_filter())
.filter(Account.auto_managed.is_(True))
# invalid 已进入自动重登队列,manual 已停止自动处理;普通 CK 探针 # invalid 已进入自动重登队列,manual 已停止自动处理;普通 CK 探针
# 再扫它们只会重复消耗官方请求,并掩盖真正需要发现的新失效。 # 再扫它们只会重复消耗官方请求,并掩盖真正需要发现的新失效。
.filter(Account.ck_check_status.notin_(("invalid", "manual"))) .filter(Account.ck_check_status.notin_(("invalid", "manual")))
# 生命周期状态机:停用/归档的账号不参与任何自动化(见 account_lifecycle)。 # 生命周期状态机:停用/归档的账号不参与任何自动化(见 account_lifecycle)。
.filter(Account.status.notin_(MANUAL_STATES))
.filter(due_filter) .filter(due_filter)
) )
if protected_ids: if protected_ids:
@@ -181,7 +179,7 @@ def run_ck_health(db: Session, job: AutomationJob) -> dict[str, Any]:
if not accounts: if not accounts:
earliest_checked = ( earliest_checked = (
db.query(func.min(Account.ck_checked_at)) db.query(func.min(Account.ck_checked_at))
.filter(cookie_holding_filter()) .filter(automation_account_filter(cookie_operable=False))
.scalar() .scalar()
) )
msg = "全库暂无到期待检账号" msg = "全库暂无到期待检账号"
@@ -35,7 +35,6 @@ from ....models import ProxyConfig as ProxyConfigModel
from ...account_events_service import EVENT_RELOGIN_FAILED, emit from ...account_events_service import EVENT_RELOGIN_FAILED, emit
from ...account_lifecycle import ( from ...account_lifecycle import (
MANUAL_KINDS, MANUAL_KINDS,
MANUAL_STATES,
WORK_LOGIN_RELOGIN, WORK_LOGIN_RELOGIN,
on_login_success, on_login_success,
sync_status, sync_status,
@@ -44,6 +43,7 @@ from ...account_protection_service import (
ProtectionSnapshot, ProtectionSnapshot,
load_protection_snapshot, load_protection_snapshot,
) )
from ...account_query_filters import automation_account_filter
from ...account_value import value_tier_expr from ...account_value import value_tier_expr
from ...account_work_queue import ( from ...account_work_queue import (
claim_account_work, claim_account_work,
@@ -51,7 +51,6 @@ from ...account_work_queue import (
fail_account_work_type, fail_account_work_type,
reschedule_account_work_type, reschedule_account_work_type,
) )
from ...douyu_service import cookie_holding_filter, cookie_operable_filter
from ...login_failure import classify_failure from ...login_failure import classify_failure
from ...login_service import LoginBatchRunner, get_relogin_limits from ...login_service import LoginBatchRunner, get_relogin_limits
@@ -121,10 +120,8 @@ def build_select_query(
query = ( query = (
db.query(Account) db.query(Account)
.filter(Account.ck_check_status == "invalid") .filter(Account.ck_check_status == "invalid")
.filter(cookie_operable_filter()) .filter(automation_account_filter())
.filter(Account.auto_managed.is_(True))
# 停用/归档的账号一律不碰(生命周期状态机,见 account_lifecycle)。 # 停用/归档的账号一律不碰(生命周期状态机,见 account_lifecycle)。
.filter(Account.status.notin_(MANUAL_STATES))
.filter(Account.relogin_attempts < max_attempts) .filter(Account.relogin_attempts < max_attempts)
.filter( .filter(
or_( or_(
@@ -248,10 +245,8 @@ def count_pending_relogin(db: Session, *, max_attempts: int = 2) -> int:
query = ( query = (
db.query(func.count(Account.id)) db.query(func.count(Account.id))
.filter(Account.ck_check_status == "invalid") .filter(Account.ck_check_status == "invalid")
.filter(cookie_holding_filter()) .filter(automation_account_filter(cookie_operable=False))
.filter(Account.auto_managed.is_(True))
# 停用/归档不计入积压(它们不会被自动处理,显示出来只会误导) # 停用/归档不计入积压(它们不会被自动处理,显示出来只会误导)
.filter(Account.status.notin_(MANUAL_STATES))
.filter(Account.relogin_attempts < max_attempts) .filter(Account.relogin_attempts < max_attempts)
.filter( .filter(
func.coalesce(Account.relogin_failure_kind, "").notin_( func.coalesce(Account.relogin_failure_kind, "").notin_(
@@ -52,16 +52,21 @@ from ....models import AutomationJob
JOB_KEY = "douyu_tasks_retention" JOB_KEY = "douyu_tasks_retention"
#: 只读、看一眼就走,且前端**不**拿它派生账号状态 → 短保留。 #: 已淘汰但仍可能有历史行的任务类型。保留在清理名单中,
#: 体量最大的就在这一类(`query_limited_goods` / `query_change_bind_time`)。 #: 避免下线入口后旧日志永久占用空间。
NOISE_TASK_TYPES: tuple[str, ...] = ( RETIRED_NOISE_TASK_TYPES: tuple[str, ...] = (
"query_limited_goods", "query_limited_goods",
"refresh_goods",
)
#: 只读、看一眼就走,且前端**不**拿它派生账号状态 → 短保留。
NOISE_TASK_TYPES: tuple[str, ...] = (
*RETIRED_NOISE_TASK_TYPES,
"query_change_bind_time", "query_change_bind_time",
"query_gold_balance", "query_gold_balance",
"query_xpd_balance", "query_xpd_balance",
"query_xpd_fragments", "query_xpd_fragments",
"query_points", "query_points",
"refresh_goods",
"refresh_esports_goods", "refresh_esports_goods",
"refresh_xpd_goods", "refresh_xpd_goods",
"prefetch_csrf_token", "prefetch_csrf_token",
-2
View File
@@ -179,7 +179,6 @@ class DouyuBatchRunner(
update_account_profile_from_cookie(account, cookie) update_account_profile_from_cookie(account, cookie)
handler = { handler = {
"refresh_goods": self._execute_refresh_goods,
"refresh_esports_goods": self._execute_refresh_esports_goods, "refresh_esports_goods": self._execute_refresh_esports_goods,
"get_bind_qr": self._execute_get_bind_qr, "get_bind_qr": self._execute_get_bind_qr,
"confirm_bind": self._execute_confirm_bind, "confirm_bind": self._execute_confirm_bind,
@@ -202,7 +201,6 @@ class DouyuBatchRunner(
"exchange_esports_goods": self._execute_exchange_esports_goods, "exchange_esports_goods": self._execute_exchange_esports_goods,
"query_game_name": self._execute_query_game_name, "query_game_name": self._execute_query_game_name,
"query_change_bind_time": self._execute_query_change_bind_time, "query_change_bind_time": self._execute_query_change_bind_time,
"query_limited_goods": self._execute_query_limited_goods,
"query_account_overview": self._execute_query_account_overview, "query_account_overview": self._execute_query_account_overview,
"query_gold_balance": self._execute_query_gold_balance, "query_gold_balance": self._execute_query_gold_balance,
"query_exchange_records": self._execute_query_exchange_records, "query_exchange_records": self._execute_query_exchange_records,
@@ -13,18 +13,13 @@ from core.douyu import DouyuActivityClient, DouyuActivityError
from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask from ..models import Account, DouyuEsportsGoodsSnapshot, DouyuGoodsSnapshot, DouyuTask
from .account_exchange_sync_service import sync_exchange_records from .account_exchange_sync_service import sync_exchange_records
from .account_sync_service import sync_storehome_snapshot
from .business_events import record_exchange from .business_events import record_exchange
from .douyu_activity_query import ( from .douyu_activity_query import (
query_activity_goods, query_activity_goods,
query_activity_goods_result,
query_csrf, query_csrf,
query_elite_user_info, query_elite_user_info,
query_esports_goods_result, query_esports_goods_result,
query_limited_goods_result,
) )
from .douyu_goods_service import upsert_goods_snapshot
from .douyu_read_gateway import storehome_snapshot_from_result
from .high_value_service import ( from .high_value_service import (
DEFAULT_HIGH_VALUE_GOODS, DEFAULT_HIGH_VALUE_GOODS,
HIGH_VALUE_STATUS_OWNED, HIGH_VALUE_STATUS_OWNED,
@@ -78,48 +73,6 @@ class GoodsMixin:
def _push_log(self, level: str, message: str) -> None: ... def _push_log(self, level: str, message: str) -> None: ...
def _mark_task(self, *args: Any, **kwargs: Any) -> None: ... def _mark_task(self, *args: Any, **kwargs: Any) -> None: ...
def _execute_refresh_goods(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
client = self._client(cookie)
result = query_activity_goods_result(
client,
manual_id=str(config["manual_id"]),
rid=str(config["rid"]),
)
goods = [
dict(item)
for item in result.get("goods") or []
if isinstance(item, dict)
]
snapshot = storehome_snapshot_from_result(
result,
manual_id=str(config["manual_id"]),
rid=str(config["rid"]),
)
upsert_goods_snapshot(db, goods, commit=False)
sync_storehome_snapshot(
db,
account,
snapshot,
source="douyu_task.refresh_goods",
task_id=task.id,
)
high_value_goods = extract_high_value_goods(goods, DEFAULT_HIGH_VALUE_GOODS, [])
apply_high_value_goods(account, high_value_goods)
account.updated_at = datetime.now(UTC)
self._mark_task(
db,
task,
"success",
f"已刷新商品 {len(goods)} 个",
{
"goods_count": len(goods),
"goods": goods,
"high_value_goods": high_value_goods,
},
)
def _refresh_high_value_after_exchange( def _refresh_high_value_after_exchange(
self, self,
client: DouyuActivityClient, client: DouyuActivityClient,
@@ -736,52 +689,6 @@ class GoodsMixin:
) )
self._mark_task(db, task, "success", message, result) self._mark_task(db, task, "success", message, result)
def _execute_query_limited_goods(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
):
client = self._client(cookie)
result = query_limited_goods_result(
client, manual_id=str(config["manual_id"]), rid=str(config["rid"])
)
limited = result["limited_goods"]
snapshot = storehome_snapshot_from_result(
result,
manual_id=str(config["manual_id"]),
rid=str(config["rid"]),
)
goods = list(snapshot.items)
sync_storehome_snapshot(
db,
account,
snapshot,
source="douyu_task.query_limited_goods",
task_id=task.id,
)
high_value_goods = extract_high_value_goods(goods, DEFAULT_HIGH_VALUE_GOODS, [])
apply_high_value_goods(account, high_value_goods)
names = [
str(item.get("commodityName") or "")
for item in limited
if item.get("commodityName")
]
message = (
"无受限商品(均可兑换)"
if not names
else f"已达上限 {len(names)} 个: {', '.join(names[:5])}"
)
account.updated_at = datetime.now(UTC)
self._mark_task(
db,
task,
"success",
message,
{
"limited_count": len(limited),
"limited_goods": limited,
"high_value_goods": high_value_goods,
},
)
def _execute_query_exchange_records( def _execute_query_exchange_records(
self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict self, db: Session, task: DouyuTask, account: Account, cookie: str, config: dict
): ):
@@ -695,7 +695,7 @@ class OverviewMixin:
# ---- 精英宝典商城商品列表(高价值套装的**唯一**判据来源)---- # ---- 精英宝典商城商品列表(高价值套装的**唯一**判据来源)----
# #
# ⚠️ 必须用**精英宝典**的 manual_id(与 `refresh_goods` 任务一致), # ⚠️ 必须用**精英宝典**的 manual_id(与其他商城能力快照一致),
# 而且**不能**寄生在上面的「电竞手册」分支里:那是两个无关的活动。 # 而且**不能**寄生在上面的「电竞手册」分支里:那是两个无关的活动。
# 之前商品列表被写在电竞手册的 else 分支内 —— 于是一旦没配 # 之前商品列表被写在电竞手册的 else 分支内 —— 于是一旦没配
# `esports_manual_id`,商城商品就永远拉不到,高价值三态就永远 # `esports_manual_id`,商城商品就永远拉不到,高价值三态就永远
@@ -785,6 +785,14 @@ class OverviewMixin:
errors["limited_goods"] = _err(exc) errors["limited_goods"] = _err(exc)
# 商品列表带有账号级 status;兑换记录只作历史展示,不参与准入判定。 # 商品列表带有账号级 status;兑换记录只作历史展示,不参与准入判定。
pending_goods = goods_items pending_goods = goods_items
limited_goods = [
item
for item in goods_items
if str(item.get("status") if item.get("status") is not None else "")
== "1"
]
overview["limited_count"] = len(limited_goods)
overview["limited_goods"] = limited_goods
# ---- 角色绑定状态(三个作用域都查)---- # ---- 角色绑定状态(三个作用域都查)----
# #
+8 -47
View File
@@ -7,14 +7,19 @@ import uuid
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from loguru import logger from loguru import logger
from sqlalchemy import and_, func, or_, select from sqlalchemy import and_, func, or_
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from core.douyu.cookie_utils import cookie_value from core.douyu.cookie_utils import cookie_value
from ..models import Account, DouyuConfig, DouyuTask, LoginTask from ..models import Account, DouyuConfig, DouyuTask
from . import account_query_filters as account_filters
from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk from .account_events_service import CATEGORY_ACTIVITY, EVENT_TASK_STARTED, emit_bulk
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = account_filters.LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
cookie_holding_filter = account_filters.cookie_holding_filter
cookie_operable_filter = account_filters.cookie_operable_filter
SUPPORTED_DOUYU_TASK_TYPES = { SUPPORTED_DOUYU_TASK_TYPES = {
"get_bind_qr": "获取绑定二维码", "get_bind_qr": "获取绑定二维码",
"confirm_bind": "确认绑定", "confirm_bind": "确认绑定",
@@ -38,11 +43,9 @@ SUPPORTED_DOUYU_TASK_TYPES = {
"exchange_goods": "兑换商品", "exchange_goods": "兑换商品",
"query_game_name": "一键获取游戏名", "query_game_name": "一键获取游戏名",
"query_change_bind_time": "一键查询换绑时间", "query_change_bind_time": "一键查询换绑时间",
"query_limited_goods": "一键查询限兑商品",
# 跨域聚合查询:鱼翅/积分/精英/电竞/小店/兑换记录/高价值套装是否已拥有 # 跨域聚合查询:鱼翅/积分/精英/电竞/小店/兑换记录/高价值套装是否已拥有
"query_account_overview": "一键查询账号信息", "query_account_overview": "一键查询账号信息",
"query_gold_balance": "一键查询鱼翅余额", "query_gold_balance": "一键查询鱼翅余额",
"refresh_goods": "刷新商品列表",
"query_exchange_records": "一键查询兑换记录", "query_exchange_records": "一键查询兑换记录",
"prefetch_csrf_token": "一键获取兑换 CSRF Token", "prefetch_csrf_token": "一键获取兑换 CSRF Token",
"get_xpd_bind_qr": "生成小店绑定二维码", "get_xpd_bind_qr": "生成小店绑定二维码",
@@ -73,9 +76,7 @@ DOUYU_HANDBOOK_TASK_TYPES = {
"exchange_goods", "exchange_goods",
"query_game_name", "query_game_name",
"query_change_bind_time", "query_change_bind_time",
"query_limited_goods",
"query_gold_balance", "query_gold_balance",
"refresh_goods",
"query_exchange_records", "query_exchange_records",
"prefetch_csrf_token", "prefetch_csrf_token",
"query_account_overview", "query_account_overview",
@@ -89,7 +90,6 @@ DOUYU_HANDBOOK_TASK_TYPES = {
"query_esports_points", "query_esports_points",
"query_gold_balance", "query_gold_balance",
"query_change_bind_time", "query_change_bind_time",
"query_limited_goods",
"refresh_esports_goods", "refresh_esports_goods",
"exchange_esports_goods", "exchange_esports_goods",
"create_gold_qr", "create_gold_qr",
@@ -235,45 +235,6 @@ def ensure_douyu_config(db: Session) -> DouyuConfig:
return config return config
# 登录/重登尝试的在途状态:判断只看 attempt_*,与账号持有的 CK 无关。
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES = ("pending", "running")
def cookie_holding_filter():
"""判定**账号**当前是否持有 CK。
CK 是账号级凭证(2026-10-04 起从 `login_tasks.cookie` 迁到 `accounts.cookie`)。
判定只看账号自己,不再看任何登录记录的状态 —— 这正是解耦的目的:
删历史、批次排队、重登失败都不该让账号凭空「没有 CK」。
"""
return and_(
Account.cookie.isnot(None),
Account.cookie != "",
)
def cookie_operable_filter():
"""判定**账号**能否基于现有 CK 再做检测或重登。
在途排除仍然要查 `login_tasks`:「正被批次处理」是**某次尝试**的属性,
CK 才是账号的属性。所以这里是「账号有 CK」+「该账号没有在途尝试」。
走 `login_tasks(account_id, attempt_status)` 索引(迁移 0042 新增),
否则每轮选行都要回表。
"""
in_flight = (
select(LoginTask.id)
.where(LoginTask.account_id == Account.id)
.where(
func.coalesce(LoginTask.attempt_status, "").in_(
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
)
)
.exists()
)
return and_(cookie_holding_filter(), ~in_flight)
def latest_cookie(db: Session, account_id: int) -> str: def latest_cookie(db: Session, account_id: int) -> str:
"""读取账号当前 CK。""" """读取账号当前 CK。"""
account = db.query(Account.cookie).filter(Account.id == account_id).first() account = db.query(Account.cookie).filter(Account.id == account_id).first()
@@ -394,7 +355,7 @@ def create_douyu_planned_tasks(
_ensure_active_task_budget(db, len(accounts)) _ensure_active_task_budget(db, len(accounts))
_lock_payment_accounts(db, accounts, task_type) _lock_payment_accounts(db, accounts, task_type)
if ( if (
task_type in {"refresh_goods", "refresh_esports_goods", "refresh_xpd_goods"} task_type in {"refresh_esports_goods", "refresh_xpd_goods"}
and accounts and accounts
): ):
# 商品快照是全局数据,一个可用 CK 足够;没有 CK 时前端无法选账号创建任务。 # 商品快照是全局数据,一个可用 CK 足够;没有 CK 时前端无法选账号创建任务。
@@ -10,7 +10,6 @@ from threading import Lock
from typing import Any from typing import Any
from fastapi import HTTPException from fastapi import HTTPException
from loguru import logger
from sqlalchemy import func, or_, select from sqlalchemy import func, or_, select
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
@@ -74,11 +73,10 @@ from ..douyu_account_probe import (
persist_probe_result, persist_probe_result,
probe_account, probe_account,
) )
from ..douyu_account_state import DouyuLiveAccountState, refresh_douyu_account_state from ..douyu_account_state import DouyuLiveAccountState
from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches from ..douyu_batch_launcher import start_douyu_batch, stop_douyu_batches
from ..douyu_service import ( from ..douyu_service import (
SUPPORTED_DOUYU_TASK_TYPES, SUPPORTED_DOUYU_TASK_TYPES,
douyu_config_value,
ensure_douyu_config, ensure_douyu_config,
) )
from ..external_order_source import ( from ..external_order_source import (
@@ -91,12 +89,9 @@ from . import classification
from .account_selector import ( from .account_selector import (
AccountCandidate, AccountCandidate,
CapabilityCandidate, CapabilityCandidate,
capability_candidate_accounts,
capability_candidate_rows, capability_candidate_rows,
capability_refresh_candidate_accounts, capability_refresh_candidate_accounts,
has_recent_exchange,
lease_account, lease_account,
live_candidate_accounts,
release_lease, release_lease,
) )
from .order_site_notifier import enqueue_order_site_binding_state from .order_site_notifier import enqueue_order_site_binding_state
@@ -117,7 +112,7 @@ BINDING_QR_TTL_SECONDS = int(
os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "1260") os.getenv("PLATFORM_BINDING_QR_TTL_SECONDS", "1260")
) )
AUTO_SYNC_INTERVAL_SECONDS = 900.0 AUTO_SYNC_INTERVAL_SECONDS = 900.0
DEFAULT_LIVE_CANDIDATE_LIMIT = 20 DEFAULT_CAPABILITY_CANDIDATE_LIMIT = 20
LOCAL_STOCK_RETRY_SECONDS = 5 * 60 LOCAL_STOCK_RETRY_SECONDS = 5 * 60
LOCAL_CACHE_MISS_RETRY_SECONDS = 2 * 60 LOCAL_CACHE_MISS_RETRY_SECONDS = 2 * 60
LOCAL_LEASE_CONFLICT_RETRY_SECONDS = 5 LOCAL_LEASE_CONFLICT_RETRY_SECONDS = 5
@@ -138,11 +133,6 @@ def binding_failed_lease_ttl_minutes() -> int:
return max(1, value) return max(1, value)
def _matching_mode() -> str:
mode = os.getenv("PLATFORM_FULFILLMENT_MATCH_MODE", "hybrid").strip().lower()
return mode if mode in {"legacy", "hybrid", "capability"} else "hybrid"
def _exchange_gate( def _exchange_gate(
state: DouyuLiveAccountState, state: DouyuLiveAccountState,
commodity_id: str, commodity_id: str,
@@ -2600,7 +2590,6 @@ def _allocate_task_from_capability(
*, *,
task: PlatformFulfillmentTask, task: PlatformFulfillmentTask,
current: User, current: User,
mode: str,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""只用本地能力索引选号;外部资格查询留给独立同步队列。""" """只用本地能力索引选号;外部资格查询留给独立同步队列。"""
moment = _now() moment = _now()
@@ -2608,12 +2597,12 @@ def _allocate_task_from_capability(
try: try:
candidate_limit = int( candidate_limit = int(
os.getenv( os.getenv(
"PLATFORM_FULFILLMENT_LIVE_CANDIDATE_LIMIT", "PLATFORM_FULFILLMENT_CAPABILITY_CANDIDATE_LIMIT",
str(DEFAULT_LIVE_CANDIDATE_LIMIT), str(DEFAULT_CAPABILITY_CANDIDATE_LIMIT),
) )
) )
except ValueError: except ValueError:
candidate_limit = DEFAULT_LIVE_CANDIDATE_LIMIT candidate_limit = DEFAULT_CAPABILITY_CANDIDATE_LIMIT
candidate_limit = max(1, min(candidate_limit, 100)) candidate_limit = max(1, min(candidate_limit, 100))
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale" is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
capability_candidates = capability_candidate_rows( capability_candidates = capability_candidate_rows(
@@ -2770,7 +2759,7 @@ def _allocate_task_from_capability(
"account_allocation_failed", "account_allocation_failed",
detail={ detail={
"candidateCount": len(capability_candidates), "candidateCount": len(capability_candidates),
"matchingMode": mode, "matchingMode": "capability",
"strategy": "local_capability", "strategy": "local_capability",
"capabilityCandidates": len(capability_candidates), "capabilityCandidates": len(capability_candidates),
"availabilityCounts": availability_counts, "availabilityCounts": availability_counts,
@@ -2874,304 +2863,17 @@ def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]
raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号")
if not task.commodity_id or not task.required_points: if not task.commodity_id or not task.required_points:
raise HTTPException(status_code=409, detail="请先完成商品映射") raise HTTPException(status_code=409, detail="请先完成商品映射")
required_points = int(task.required_points)
if task.account_id and task.lease_id: if task.account_id and task.lease_id:
lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first()
if lease and lease.status == "active": if lease and lease.status == "active":
return get_task_detail(db, task.id) return get_task_detail(db, task.id)
# 阶段 5:生产选号只允许读取本地能力索引。官网查询由
mode = _matching_mode() # account_sync_queue/商品能力补货完成,绑码与兑换前各自实时复核。
if mode in {"hybrid", "capability"}: return _allocate_task_from_capability(
# 2026-11-22:分配热路径只读本地能力索引。官网资格刷新已经由独立
# account_sync_queue 执行;绑码和兑换前仍有各自的实时校验,不应让
# 一次选号串行探测 20 个账号并阻塞其他订单。
return _allocate_task_from_capability(
db,
task=task,
current=current,
mode=mode,
)
config = ensure_douyu_config(db)
lease_duration_minutes = _lease_duration_minutes(db)
manual_id = str(douyu_config_value("manual_id", config.manual_id))
rid = str(douyu_config_value("rid", config.rid))
act_alias = str(douyu_config_value("bind_act_alias", config.bind_act_alias))
try:
candidate_limit = int(
os.getenv(
"PLATFORM_FULFILLMENT_LIVE_CANDIDATE_LIMIT",
str(DEFAULT_LIVE_CANDIDATE_LIMIT),
)
)
except ValueError:
candidate_limit = DEFAULT_LIVE_CANDIDATE_LIMIT
candidate_limit = max(1, min(candidate_limit, 100))
is_presale = classification.normalize_sale_mode(task.sale_mode) == "presale"
capability_candidates = (
capability_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
scope=task.scope or SCOPE_ELITE,
allow_not_open=is_presale,
)
if mode in {"hybrid", "capability"}
else []
)
capability_first = bool(capability_candidates)
candidates = capability_candidates
if not candidates and mode != "capability":
# hybrid 模式下能力索引为空或全部过期时,保留旧逻辑兜底。
candidates = live_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
)
diagnostics: list[dict[str, Any]] = []
qualified: list[tuple[Account, DouyuLiveAccountState]] = []
selected: AccountCandidate | None = None
selected_state: DouyuLiveAccountState | None = None
lease = None
def inspect_candidate(
account: Account,
*,
source: str,
) -> tuple[Account, DouyuLiveAccountState] | None:
live_state = refresh_douyu_account_state(
db,
account,
manual_id=manual_id,
rid=rid,
act_alias=act_alias,
)
limited = task.commodity_id in live_state.limited_ids
recent_exchange = has_recent_exchange(
db,
account_id=int(account.id),
commodity_id=task.commodity_id,
)
reasons = live_state.blocking_reasons(
commodity_id=task.commodity_id,
allow_not_open=is_presale,
)
if recent_exchange:
reasons.append("365 天内已有该商品兑换事件")
if live_state.ck_verdict == "valid" and not live_state.error:
try:
availability = live_state.commodity_availability.get(
task.commodity_id
)
blocking_reason = live_state.commodity_blocking_reasons.get(
task.commodity_id,
"",
)
if limited:
availability = AVAILABILITY_LIMITED
blocking_reason = "该账号已达此商品兑换上限"
elif live_state.commodity_availability and availability is None:
availability = AVAILABILITY_NOT_OFFERED
blocking_reason = "官方商品列表本次未返回该商品,可能已下架"
elif availability is None:
availability = AVAILABILITY_AVAILABLE
record_account_commodity_state(
db,
account,
commodity_id=task.commodity_id,
availability=availability,
blocking_reason=blocking_reason,
raw_status="1" if limited else "0",
observed_at=live_state.checked_at,
source="live_check",
scope=task.scope or SCOPE_ELITE,
)
except Exception as exc: # noqa: BLE001 - 派生索引不能阻止本次选号
logger.warning(
"写入选号商品能力失败 account_id={} commodity_id={}: {}",
account.id,
task.commodity_id,
exc,
)
if reasons:
diagnostics.append(
{
"accountId": int(account.id),
"accountName": live_state.account_name,
"ck": live_state.ck_verdict,
"eliteOpened": live_state.elite_opened,
"points": live_state.points,
"reasons": reasons,
"source": source,
}
)
return None
return account, live_state
def inspect_batch(
batch: list[Account],
*,
source: str,
) -> None:
# 能力索引已按成本排序,首个确认通过即可;旧兜底最多比较 3 个。
for account in batch:
inspected = inspect_candidate(account, source=source)
if inspected is None:
continue
qualified.append(inspected)
if source == "capability" or len(qualified) >= 3:
return
if capability_candidates:
inspect_batch(capability_candidates, source="capability")
elif mode != "capability":
inspect_batch(candidates, source="live")
if not qualified and capability_first and mode == "hybrid":
checked_ids = {int(account.id) for account in capability_candidates}
fallback_candidates = [
account
for account in live_candidate_accounts(
db,
limit=candidate_limit,
required_points=required_points,
commodity_id=task.commodity_id,
)
if int(account.id) not in checked_ids
]
candidates = [*candidates, *fallback_candidates]
inspect_batch(fallback_candidates, source="live_fallback")
# 积分和宝典开通不淘汰账号,只影响后续处理成本。优先选已经可直接兑换的账号,
# 其次是只需充值、只需开通、两者都需要的账号。
qualified.sort(
key=lambda item: (
item[1].readiness_rank(required_points=required_points),
int(item[1].points or 0),
int(item[0].id),
)
)
for account, live_state in qualified:
candidate = AccountCandidate(
account_id=int(account.id),
username=str(account.username or ""),
nickname=str(account.nickname or ""),
points=int(live_state.points or 0),
gold_balance=account.gold_balance,
points_expire_at=account.points_expire_at,
role_change_available_at=live_state.role_change_available_at,
)
lease = lease_account(
db,
candidate=candidate,
holder_user_id=current.id,
task_id=task.id,
commodity_id=task.commodity_id,
ttl_minutes=lease_duration_minutes,
)
if lease is not None:
selected = candidate
selected_state = live_state
break
diagnostics.append(
{
"accountId": int(account.id),
"accountName": live_state.account_name,
"ck": live_state.ck_verdict,
"eliteOpened": live_state.elite_opened,
"points": live_state.points,
"reasons": ["账号刚被其他任务占用"],
"source": "capability" if capability_first else "live",
}
)
if selected is None or selected_state is None or lease is None:
task.execution_status = "ready"
task.next_allocate_at = _now() + timedelta(seconds=45)
task.issue_code = "no_eligible_account"
if not candidates:
task.last_error = (
"商品能力池暂无可用账号"
if mode == "capability"
else "没有带 CK、允许自动管理且未停用的斗鱼账号"
)
else:
summary = ";".join(
f"{item['accountName']}: {', '.join(item['reasons'][:3])}"
for item in diagnostics[:5]
)
task.last_error = (
f"已实时检测 {len(diagnostics)} 个账号,当前没有可用账号"
+ (f"。{summary}" if summary else "")
)[:500]
task.updated_at = _now()
_append_event(
db,
task.id,
"account_allocation_failed",
detail={
"candidateCount": len(candidates),
"matchingMode": mode,
"capabilityCandidates": len(capability_candidates),
"diagnostics": diagnostics,
},
)
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
task.account_id = selected.account_id
task.lease_id = lease.id
task.operator_id = current.id
task.execution_status = "allocated"
task.next_allocate_at = None
task.binding_status = "not_started"
soft_reasons = selected_state.soft_requirement_reasons(
required_points=required_points
)
gate_status, gate_issue, gate_message = _exchange_gate(
selected_state,
task.commodity_id,
allow_not_open=is_presale,
)
if gate_status:
task.exchange_status = gate_status
task.issue_code = gate_issue
task.last_error = gate_message
elif selected_state.elite_opened is not True:
task.exchange_status = "not_opened"
task.issue_code = "elite_not_opened"
task.last_error = "账号尚未开通精英宝典,可开通后继续"
elif selected_state.points is None or selected_state.points < required_points:
task.exchange_status = "points_short"
task.issue_code = "points_short"
task.last_error = "账号积分不足,可充值后继续"
else:
task.exchange_status = "eligible"
task.issue_code = ""
task.last_error = ""
task.updated_at = _now()
_apply_task_lease_policy(db, task, lease=lease)
_append_event(
db, db,
task.id, task=task,
"account_allocated", current=current,
actor_type="user",
actor_id=current.id,
detail={
"accountId": selected.account_id,
"accountName": selected.display_name,
"points": selected.points,
"eliteOpened": selected_state.elite_opened,
"softReasons": soft_reasons,
"exchangeStatus": task.exchange_status,
},
) )
_emit_order_site_binding_state(db, task.id)
db.commit()
return get_task_detail(db, task.id)
def release_task_account( def release_task_account(
@@ -414,10 +414,10 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
return map; return map;
}, [isEsportsHandbook, tasks]); }, [isEsportsHandbook, tasks]);
const latestLimitedGoodsTaskByAccount = useMemo(() => { const latestOverviewTaskByAccount = useMemo(() => {
const map = new Map<number, DouyuTaskItem>(); const map = new Map<number, DouyuTaskItem>();
for (const task of tasks) { for (const task of tasks) {
if (task.task_type !== 'query_limited_goods') continue; if (task.task_type !== 'query_account_overview') continue;
if (!['success', 'failed', 'error'].includes(task.status)) continue; if (!['success', 'failed', 'error'].includes(task.status)) continue;
const previous = map.get(task.account_id); const previous = map.get(task.account_id);
if (!previous || task.id > previous.id) map.set(task.account_id, task); if (!previous || task.id > previous.id) map.set(task.account_id, task);
@@ -1786,7 +1786,7 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
{ {
title: '限制兑换', dataIndex: 'exchange_balance', width: 160, ellipsis: true, title: '限制兑换', dataIndex: 'exchange_balance', width: 160, ellipsis: true,
render: (_, record) => { render: (_, record) => {
const latestLimitedTask = latestLimitedGoodsTaskByAccount.get(record.id); const latestLimitedTask = latestOverviewTaskByAccount.get(record.id);
const text = limitedGoodsTaskText(latestLimitedTask); const text = limitedGoodsTaskText(latestLimitedTask);
if (!text) return <Text type="secondary">未查</Text>; if (!text) return <Text type="secondary">未查</Text>;
if (latestLimitedTask?.status !== 'success') { if (latestLimitedTask?.status !== 'success') {
@@ -2479,7 +2479,6 @@ export default function DouyuTasksPage({ handbook }: { handbook: HandbookKind })
style={{ width: '100%' }} style={{ width: '100%' }}
/> />
<div style={actionGridStyle}> <div style={actionGridStyle}>
{renderActionButton('refresh_goods')}
{renderActionButton('lock_goods')} {renderActionButton('lock_goods')}
{renderActionButton('exchange_goods', 'primary')} {renderActionButton('exchange_goods', 'primary')}
</div> </div>
@@ -45,7 +45,6 @@ export const ELITE_QUICK_ACTIONS = [
{ key: 'query_points', icon: <SearchOutlined /> }, { key: 'query_points', icon: <SearchOutlined /> },
{ key: 'query_game_name', icon: <SearchOutlined /> }, { key: 'query_game_name', icon: <SearchOutlined /> },
{ key: 'query_change_bind_time', icon: <FieldTimeOutlined /> }, { key: 'query_change_bind_time', icon: <FieldTimeOutlined /> },
{ key: 'query_limited_goods', icon: <SearchOutlined /> },
{ key: 'query_gold_balance', icon: <SearchOutlined /> }, { key: 'query_gold_balance', icon: <SearchOutlined /> },
{ key: 'lock_goods', icon: <ShoppingOutlined /> }, { key: 'lock_goods', icon: <ShoppingOutlined /> },
{ key: 'exchange_goods', icon: <ShoppingOutlined /> }, { key: 'exchange_goods', icon: <ShoppingOutlined /> },
@@ -59,7 +58,6 @@ export const ESPORTS_QUICK_ACTIONS = [
{ key: 'create_esports_qr', icon: <CreditCardOutlined /> }, { key: 'create_esports_qr', icon: <CreditCardOutlined /> },
{ key: 'query_esports_points', icon: <SearchOutlined /> }, { key: 'query_esports_points', icon: <SearchOutlined /> },
{ key: 'query_change_bind_time', icon: <FieldTimeOutlined /> }, { key: 'query_change_bind_time', icon: <FieldTimeOutlined /> },
{ key: 'query_limited_goods', icon: <SearchOutlined /> },
{ key: 'query_gold_balance', icon: <SearchOutlined /> }, { key: 'query_gold_balance', icon: <SearchOutlined /> },
{ key: 'refresh_esports_goods', icon: <ReloadOutlined /> }, { key: 'refresh_esports_goods', icon: <ReloadOutlined /> },
{ key: 'exchange_esports_goods', icon: <ShoppingOutlined /> }, { key: 'exchange_esports_goods', icon: <ShoppingOutlined /> },
@@ -93,9 +91,7 @@ export const ELITE_TASK_TYPES = new Set([
'exchange_goods', 'exchange_goods',
'query_game_name', 'query_game_name',
'query_change_bind_time', 'query_change_bind_time',
'query_limited_goods',
'query_gold_balance', 'query_gold_balance',
'refresh_goods',
'query_exchange_records', 'query_exchange_records',
'prefetch_csrf_token', 'prefetch_csrf_token',
'query_account_overview', 'query_account_overview',
@@ -109,7 +105,6 @@ export const ESPORTS_TASK_TYPES = new Set([
'query_esports_points', 'query_esports_points',
'query_gold_balance', 'query_gold_balance',
'query_change_bind_time', 'query_change_bind_time',
'query_limited_goods',
'refresh_esports_goods', 'refresh_esports_goods',
'exchange_esports_goods', 'exchange_esports_goods',
'create_gold_qr', 'create_gold_qr',