From 7f7943a1e81caa2687c66a763cced39bbabbdd30 Mon Sep 17 00:00:00 2001 From: yml Date: Sat, 21 Nov 2026 17:35:34 +0800 Subject: [PATCH] =?UTF-8?q?fix(platform-fulfillment):=20=E9=87=8A=E6=94=BE?= =?UTF-8?q?=E7=A9=BA=E9=97=B2=E8=BF=9E=E6=8E=A5=E5=B9=B6=E5=90=88=E5=B9=B6?= =?UTF-8?q?=E9=80=89=E5=8F=B7=E8=AF=B7=E6=B1=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 5 +- dev.sh | 6 +- docker-compose.yml | 3 + docs/README.md | 1 + docs/直播账号履约工作台.md | 3 + docs/设计-账号全生命周期.md | 3 + docs/设计-账号能力中心与统一选号.md | 425 ++++++++++++++++++ tests/test_platform_fulfillment.py | 16 + ...est_platform_fulfillment_auto_allocator.py | 21 + web/backend/database.py | 58 ++- web/backend/main.py | 3 +- web/backend/routers/platform_fulfillment.py | 10 +- .../platform_fulfillment/auto_allocator.py | 144 +++--- .../services/platform_fulfillment/service.py | 29 ++ web/frontend/src/api/platformFulfillment.ts | 3 +- web/frontend/src/api/types.ts | 4 + .../src/pages/PlatformFulfillmentPage.tsx | 30 +- 17 files changed, 690 insertions(+), 74 deletions(-) create mode 100644 docs/设计-账号能力中心与统一选号.md diff --git a/.env.example b/.env.example index fec7502..1c27484 100644 --- a/.env.example +++ b/.env.example @@ -71,7 +71,10 @@ DEV_DB_PORT=3307 # DB_USER=douyu_login # DB_PASSWORD= -# 数据库连接池配置(仅 MySQL 生效) +# 数据库连接策略(仅 MySQL 生效) +# null=每次 Session 关闭即断开物理连接;queue=复用连接池。 +DB_POOL_MODE=null +WORKER_DB_POOL_MODE=null DB_POOL_SIZE=20 DB_MAX_OVERFLOW=20 WORKER_DB_POOL_SIZE=12 diff --git a/dev.sh b/dev.sh index fc93399..924bf27 100755 --- a/dev.sh +++ b/dev.sh @@ -56,6 +56,7 @@ DB_PORT="$DEV_DB_PORT" DB_NAME="${DB_NAME:-$MYSQL_DATABASE}" DB_USER="${DB_USER:-$MYSQL_USER}" DB_PASSWORD="${DB_PASSWORD:-${MYSQL_PASSWORD:-}}" +DB_POOL_MODE="${DB_POOL_MODE:-queue}" DB_POOL_SIZE="${DB_POOL_SIZE:-20}" DB_MAX_OVERFLOW="${DB_MAX_OVERFLOW:-20}" DB_POOL_TIMEOUT="${DB_POOL_TIMEOUT:-30}" @@ -63,6 +64,7 @@ DB_POOL_RECYCLE="${DB_POOL_RECYCLE:-1800}" WORKER_DB_POOL_SIZE="${WORKER_DB_POOL_SIZE:-12}" WORKER_DB_MAX_OVERFLOW="${WORKER_DB_MAX_OVERFLOW:-4}" WORKER_DB_POOL_TIMEOUT="${WORKER_DB_POOL_TIMEOUT:-30}" +WORKER_DB_POOL_MODE="${WORKER_DB_POOL_MODE:-$DB_POOL_MODE}" YYB_WORKER_PORT="${YYB_WORKER_PORT:-8810}" DEV_YYB_WORKER_URL="${DEV_YYB_WORKER_URL:-http://127.0.0.1:${YYB_WORKER_PORT}}" YYB_WORKER_DATA_DIR="${YYB_WORKER_DATA_DIR:-$ROOT_DIR/data/yyb-worker-dev}" @@ -358,8 +360,8 @@ echo "" ( export DB_HOST DB_PORT DB_NAME DB_USER DB_PASSWORD - export DB_POOL_SIZE DB_MAX_OVERFLOW DB_POOL_TIMEOUT DB_POOL_RECYCLE - export WORKER_DB_POOL_SIZE WORKER_DB_MAX_OVERFLOW WORKER_DB_POOL_TIMEOUT + export DB_POOL_MODE DB_POOL_SIZE DB_MAX_OVERFLOW DB_POOL_TIMEOUT DB_POOL_RECYCLE + export WORKER_DB_POOL_MODE WORKER_DB_POOL_SIZE WORKER_DB_MAX_OVERFLOW WORKER_DB_POOL_TIMEOUT export YYB_WORKER_KEY LOG_LEVEL LOG_DIR export YYB_WORKER_URL="$DEV_YYB_WORKER_URL" uv run python -m uvicorn web.backend.main:app \ diff --git a/docker-compose.yml b/docker-compose.yml index 9816f46..f534532 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -36,11 +36,14 @@ services: - DB_NAME=${MYSQL_DATABASE:-douyu_login} - DB_USER=${MYSQL_USER:-douyu_login} - DB_PASSWORD=${MYSQL_PASSWORD:?请在 .env 中设置 MYSQL_PASSWORD} + # null=Session.close 立即断开物理连接;queue=保留连接池复用。 + - DB_POOL_MODE=${DB_POOL_MODE:-null} - DB_POOL_SIZE=${DB_POOL_SIZE:-20} - DB_MAX_OVERFLOW=${DB_MAX_OVERFLOW:-20} - DB_POOL_TIMEOUT=${DB_POOL_TIMEOUT:-30} - DB_POOL_RECYCLE=${DB_POOL_RECYCLE:-1800} - DB_LOCK_WAIT_TIMEOUT=${DB_LOCK_WAIT_TIMEOUT:-10} + - WORKER_DB_POOL_MODE=${WORKER_DB_POOL_MODE:-null} - WORKER_DB_POOL_SIZE=${WORKER_DB_POOL_SIZE:-12} - WORKER_DB_MAX_OVERFLOW=${WORKER_DB_MAX_OVERFLOW:-4} - WORKER_DB_POOL_TIMEOUT=${WORKER_DB_POOL_TIMEOUT:-30} diff --git a/docs/README.md b/docs/README.md index 5564ce1..26d21f7 100644 --- a/docs/README.md +++ b/docs/README.md @@ -9,6 +9,7 @@ - [自动化与资料收集](自动化与资料收集.md):账号巡检、CK 自动重登、资料刷新、订单读取、文件存储的运行规则。 - [账号全生命周期](设计-账号全生命周期.md):斗鱼账号状态、CK、事件流和自动化边界。 +- [账号能力中心与统一选号](设计-账号能力中心与统一选号.md):官网事实同步、账号商品能力、兑换账本和履约选号的统一数据模型。 - [微博账号池、分配与个人工作台](微博/微博账号池与个人工作台-2026-11-08.md):微博 CK、账号归属、客服可见范围、分配管理和个人工作台。 - [虎牙外部 CK 协作台账](设计-虎牙外部CK协作台账.md):外部订单、CK、业务状态、核账、归档和权限规则。 - [虎牙 Cookie 路线状态](虎牙/HUYA_COOKIE路线状态.md):当前 Cookie 字段来源、已完成链路和已知边界。 diff --git a/docs/直播账号履约工作台.md b/docs/直播账号履约工作台.md index 23de8b1..9603de1 100644 --- a/docs/直播账号履约工作台.md +++ b/docs/直播账号履约工作台.md @@ -2,6 +2,9 @@ 更新时间:2026-11-20 +账号能力同步、官网事实覆盖和统一候选账号查询的设计见 +[账号能力中心与统一选号](设计-账号能力中心与统一选号.md)。 + ## 目标 消费 `order_site` 事务 Outbox 推送的人工渠道订单项快照,由系统选择内部斗鱼账号, diff --git a/docs/设计-账号全生命周期.md b/docs/设计-账号全生命周期.md index 36f6d32..1e6949c 100644 --- a/docs/设计-账号全生命周期.md +++ b/docs/设计-账号全生命周期.md @@ -198,6 +198,9 @@ CK 本体和健康结果都在账号上: ## 代码入口 +账号商品能力、官网同步和履约选号的跨模块设计见 +[账号能力中心与统一选号](设计-账号能力中心与统一选号.md)。 + - `web/backend/models.py`:`Account`、`AccountEvent` - `web/backend/services/account_lifecycle.py`:状态推导与唯一写入口 - `web/backend/services/account_events_service.py`:事件写入与幂等 diff --git a/docs/设计-账号能力中心与统一选号.md b/docs/设计-账号能力中心与统一选号.md new file mode 100644 index 0000000..7f5c9ca --- /dev/null +++ b/docs/设计-账号能力中心与统一选号.md @@ -0,0 +1,425 @@ +# 账号能力中心与统一选号设计 + +更新时间:2026-11-21 + +状态:设计基线,后续代码按本文分阶段落地 + +## 目标 + +把账号管理、账号全生命周期、一键查询和直播账号履约选号统一到同一份本地账号数据上: + +1. 斗鱼官网是外部账号事实的唯一权威来源; +2. 本地数据库保存当前投影、查询时间、历史事实和内部业务占用; +3. 查询官网后,以官网结果更新本地当前投影; +4. 账号管理筛选和自动选号直接查询本地数据库; +5. 只有最终候选账号在分配前做一次官网实时确认; +6. 官网查询失败时保留上一次有效结论,不把“没查到”写成“不可兑换”。 + +本文不把所有内部业务数据交给官网覆盖。租约、订单、协作单、归属和内部 +365 天规则仍然以本地数据库为准。 + +## 现有基础 + +当前项目已经具备这套模型的主要组件: + +- `accounts`:账号当前状态、CK、积分、宝典、角色和生命周期; +- `account_events`:不可变事件账本,记录兑换、充值、积分、开通、换绑和登录变化; +- `account_commodity_states`:账号 × 商品的当前兑换能力投影; +- `douyu_goods_snapshot`:斗鱼商品目录快照; +- `douyu_runner_overview`:官网一键查询和投影写入链; +- `platform_fulfillment.account_selector`:履约候选筛选和租约; +- `account_lifecycle`:账号生命周期状态的唯一推导和写入入口。 + +不需要另建一套账号系统。重点是补齐同步覆盖、明确数据语义,并让账号管理和自动选号 +共享同一个数据库查询服务。 + +## 当前主要缺口 + +1. 商品能力覆盖不完整。有效 CK 账号和商品能力投影没有一一对应,一键查询过的账号 + 也可能没有写入商品状态。 +2. 能力刷新作业从已有的 `account_commodity_states` 出发,无法主动发现从未建立商品 + 状态的新账号。 +3. `valid_until` 同时承担“当前是否新鲜”和“是否还能查询”的职责,过期数据容易被 + 当成不存在。 +4. 自动选号在能力索引没有严格候选时回退到实时扫描,并且只检查有限的低积分账号, + 容易反复撞到同一批已限兑账号。 +5. 账号管理、自动选号、履约详情各自组装筛选条件,口径不完全一致。 +6. 官网当前结论与内部业务资格没有明确拆开,页面上容易把“官网可兑换”和“当前可分配” + 混为一谈。 +7. 每次同步的覆盖范围、成功时间、失败原因和官方原始版本没有统一台账。 + +## 2026-11-21 生产只读基线 + +以下数据用于说明改造规模,不代表固定业务量: + +- 账号总数:约 31,150; +- CK 有效账号:4,848; +- 已做账号一键查询:17,068; +- 已有商品能力状态的账号:2,804; +- 有效 CK 账号中已有商品能力状态:2,775; +- 有效 CK 且已一键查询、但没有商品状态:1,073; +- 商品能力状态行数:75,527; +- 当前商品数量:60; +- 已覆盖账号平均每个只有约 26.9 个商品记录。 + +按 60 个商品计算,4,848 个有效账号的完整矩阵约 29 万行;即使覆盖全部 3 万账号, +理论规模约 187 万行。规模可控,但必须分批、幂等和限速同步。 + +## 数据分层 + +### 账号当前状态 + +`accounts` 回答“账号整体是什么状态”: + +- CK 是否可用; +- 生命周期状态; +- 积分、鱼翅和精英宝典开通状态; +- 角色绑定、换绑冷却; +- 自动管理和归属; +- 最近一次账号资料查询时间。 + +账号生命周期写入继续遵守 `account_lifecycle` 的唯一写入口约束。 + +### 商品目录 + +商品目录回答“斗鱼当前有哪些商品、何时开放、需要多少积分、是否有库存”: + +- `platform`、`scope`、`commodity_id`; +- 商品名称、所需积分和平台状态; +- `timeLimited`、`startTime/endTime`、`specTimes`; +- 库存、开放状态和目录观察时间。 + +商品目录是跨账号共享数据,不能在每个账号记录中重复保存商品名称和开放计划。 + +`douyu_goods_snapshot` 可以继续作为目录表来源,但应明确一个商品只有一条当前目录投影, +历史变化通过事件或同步记录保留。 + +### 账号商品能力 + +`account_commodity_states` 回答“这个账号对这个商品的官网结论是什么”: + +- `availability`:`available / limited / no_stock / not_open / expired / + not_offered / unknown`; +- `raw_status`:官网原始账号级状态; +- `observed_at`:最近一次观察时间; +- `valid_until`:当前结论的匹配有效期; +- `next_check_at`:下次建议检查时间; +- `available_from / available_until / schedule_json`:限时窗口; +- `last_exchange_at / exchange_count_365d`:从事件账本派生的兑换摘要。 + +这张表保存的是当前投影,不是只用于 15 分钟缓存的临时数据。过期记录仍然可以被账号 +管理查询和展示,只是不能直接作为自动分配依据。 + +### 事件账本 + +`account_events` 继续保存不可变事实: + +- 本地实际兑换成功:`source=douyu_task`; +- 官网兑换记录补录:`source=official_sync`; +- 积分、鱼翅、开通、换绑、CK 和生命周期变化; +- 必要的商品能力状态转变。 + +兑换历史不另建重复台账。`account_events` 已经能够回答“兑换过什么、何时兑换、消耗多少 +积分、来源是什么”。 + +官网记录可以通过 `source_ref` 幂等去重。后续应优先使用官网记录 ID;没有记录 ID 时, +再使用账号、作用域、商品、时间、数量和原始记录哈希组合,避免同一秒多次兑换被合并。 + +### 同步运行与脏数据队列 + +建议后续补充两类基础设施: + +1. `account_sync_runs`:记录一次官网同步的账号、平台、作用域、同步类型、开始/结束时间、 + 成功/失败状态、写入数量、错误摘要和官方数据哈希。 +2. 账号同步脏队列或等价字段:记录 `dirty_reason`、`next_sync_at`、`last_success_at`、 + `last_error`,用于登录成功、CK 恢复、兑换后核对、充值后刷新和订单需求触发。 + +没有同步台账时,只能知道“字段现在是什么”,无法可靠回答“什么时候查过、为什么没更新、 +同一份官网数据是否已经处理过”。 + +## 三种“能换”必须分开 + +### 官网可兑换 + +`official_available` 只由斗鱼官网判断: + +- 官方账号级 `status=0`; +- 商品开放窗口有效; +- 官方库存和开放状态允许兑换; +- 没有明确限兑、无库存、未开放或已结束。 + +### 资源已就绪 + +`resource_ready` 表示账号自身资源是否足够: + +- 精英宝典已开通; +- 积分达到订单要求; +- 角色状态满足后续兑换流程。 + +积分不足和未开通宝典是否阻止分配,由具体履约策略决定。当前直播履约把它们作为软条件, +允许先绑定角色,再充值或开通。 + +### 可分配 + +`allocatable` 表示账号现在能否分配给订单: + +- 官网可兑换; +- 账号生命周期可用且允许自动管理; +- CK 检测新鲜; +- 没有有效租约; +- 没有活动外部协作单; +- 角色换绑冷却已结束; +- 归属符合账号池规则; +- 不违反内部 365 天不可重复使用规则; +- 满足当前订单的必要资源策略。 + +官网可兑换但已有租约时,账号必须在账号管理里显示为“官网可兑换,当前任务占用”, +不能因为官网结果而释放或覆盖本地租约。 + +## 事实源与冲突处理 + +| 数据 | 当前事实源 | 本地处理 | +| --- | --- | --- | +| 商品是否限兑 | 官网 | 官网结果覆盖当前能力投影 | +| 商品开放时间、库存 | 官网 | 更新商品目录和账号商品状态 | +| 积分、鱼翅、宝典状态 | 官网 | 官网结果覆盖账号当前字段 | +| 官方兑换记录 | 官网 | 幂等补入 `account_events`,不删除历史 | +| 官网查询时间、失败原因 | 本地 | 写入同步运行记录 | +| CK、登录和重登过程 | 本地 | 由账号生命周期管理 | +| 租约、履约任务、协作单 | 本地 | 本地业务事实优先 | +| 账号归属和维护责任 | 本地 | 官网无权覆盖 | +| 内部 365 天规则 | 本地业务政策 | 独立于官网可兑换状态 | + +冲突处理规则: + +1. 官网明确返回新的当前状态时,更新本地当前投影; +2. 官网未返回、接口失败或结果不完整时,保留上一次有效结论; +3. 官网说“可兑换”,不能删除本地有效租约或其他内部占用; +4. 官网说“限兑”,应立即从自动选号候选中移除; +5. 本地有兑换事件但官网暂时没有记录时,保留本地事实并标记待核对; +6. 官网记录晚到后只补事实,不回滚已经完成的内部流程。 + +## 统一候选查询 + +账号管理和自动选号应调用同一个候选查询服务,输入至少包括: + +- 平台和作用域; +- 商品 ID; +- 是否只允许自动管理; +- 是否允许过期能力复核; +- 是否要求积分足够或宝典已开通; +- 归属和客服范围; +- 是否包含已被租约或协作单占用的账号; +- 排序和分页。 + +基础候选条件: + +```text +accounts.status 可用 +AND accounts.auto_managed = 1 +AND accounts.ck_check_status = 'valid' +AND CK 检测时间不早于 Cookie 更新时间 +AND account_commodity_states.availability = 'available' +AND 商品时间窗口允许兑换 +AND NOT EXISTS 有效账号租约 +AND NOT EXISTS 活动外部协作单 +AND 角色换绑冷却已结束 +AND 归属符合账号池规则 +AND 不违反内部兑换冷却 +``` + +排序建议: + +1. 新鲜 `available`; +2. 过期但曾经 `available`,允许官网复核; +3. 从未查询或 `unknown`; +4. 已知 `limited / no_stock / not_open / expired` 默认不进入候选。 + +候选结果必须同时返回阻塞诊断,例如: + +- 官网限兑; +- 无库存; +- 未开放; +- CK 失效; +- 角色换绑冷却; +- 有效租约; +- 活动协作单; +- 归属不符合; +- 365 天内兑换过; +- 数据过期。 + +## 自动选号流程 + +1. 订单完成商品映射,得到 `commodity_id`; +2. 查询本地统一候选服务,不直接发起大量官网请求; +3. 优先选择新鲜 `available` 候选; +4. 没有新鲜候选时,触发对应账号的官网能力刷新; +5. 对排序最靠前的少量账号做官网实时确认; +6. 用官网结果更新 `account_commodity_states`; +7. 官网确认仍可用后,依赖数据库唯一约束领取租约; +8. 分配成功后立即开始绑定流程; +9. 官网确认和本地状态不一致时记录诊断,并继续下一个候选。 + +禁止继续采用“只取前 20 个低积分账号逐个实时检查,全部失败后等待重试”的兜底方式。 +已知限兑账号不应反复消耗外部请求,未知账号必须有分批补全机制。 + +### 并发与连接边界 + +自动选号和人工重试必须满足以下约束: + +1. 同一个履约任务同一时间最多只有一个选号请求,重复点击应合并或返回“选号中”; +2. 前端按钮在请求完成前必须进入 loading/disabled 状态; +3. 候选数据库查询使用短事务,查询完成立即释放连接; +4. 外部账号检测属于长耗时 I/O,不得在整个检测期间一直持有一个 FastAPI 请求事务和 + 数据库连接; +5. 实时官网确认由独立 Worker 任务槽执行,请求只创建或唤醒任务,不同步占满 API + 连接池; +6. 自动选号和人工重试共享同一把任务级互斥锁,不能因为两个入口并行而重复扫描; +7. 数据库连接池大小只是保护阈值,不能通过盲目扩大连接池掩盖请求风暴。 + +2026-11-21 生产只读检查发现,同一个“人工重试选号”请求在约 0.6 秒内重复进入 +14 次。每次请求都会执行多账号实时检查,随后应用连接池达到 `20 + 20` 上限并持续 +30 秒等待连接,健康检查因 5 秒超时转为 unhealthy。因此请求合并、Worker 隔离和 +任务级互斥属于 P0,不是后续体验优化。 + +处理约定: + +- 生产 `docker-compose.yml` 默认使用 `DB_POOL_MODE=null` 和 + `WORKER_DB_POOL_MODE=null`,Session 关闭即断开物理连接; +- 本地开发可显式改为 `queue`,保留连接池复用和更低连接建立开销; +- 应用退出时必须调用统一的 `dispose_engines()`,确保 queue 模式也不会残留连接; +- 人工选号接口只做短数据库校验并写入后台队列,不再同步执行官网账号检测。 + +## 同步策略 + +### 触发时机 + +- 账号首次导入完成后; +- 登录或自动重登成功后; +- CK 从失效恢复为有效后; +- 有 pending 履约订单且对应商品能力过期时; +- 本地兑换成功后立即定向标脏并核对; +- 充值、赠送精英令或开通宝典后; +- 人工点击“立即同步”; +- 周期巡检到期时。 + +### 同步内容 + +一次斗鱼完整商品列表请求应更新该账号的全部商品能力,不按商品逐个请求。同步还应根据 +配置和需要更新: + +- CK 和活动登录态; +- 积分、鱼翅; +- 精英宝典开通和到期; +- 角色绑定与换绑冷却; +- 三个作用域的官方兑换记录; +- 高价值商品准入。 + +### 新鲜度 + +新鲜度按业务需求分级,不能所有字段统一使用一个 TTL: + +- 有 pending 履约订单的商品:短周期刷新并优先调度; +- 无 pending 订单:慢速周期刷新; +- 兑换后:立即标脏; +- CK 失效:立即作废所有 `available` 结论; +- 网络错误:保留旧状态,指数退避重试。 + +过期不等于不可查询。账号管理始终展示最后一次结论和过期状态,自动选号只把过期状态作为 +“需要复核”,而不是直接删除。 + +## 兑换账本 + +兑换事实继续写入 `account_events`: + +- 实际兑换成功时立即写本地事件; +- 同时更新对应商品能力为 `limited`; +- 后续官网核对成功时补写 `official_sync` 事件; +- 官网查询失败或记录暂未出现时,不删除本地事件; +- 同一官网记录重复查询只保留一条; +- 列表和详情优先展示官方记录,同时保留本地执行来源。 + +兑换记录应支持: + +- 按账号查询; +- 按商品反查; +- 按时间范围查询; +- 查看官方记录 ID; +- 查看本地执行时间与官网确认时间; +- 查看待核对、已核对和官网迟到状态。 + +## 账号管理页面 + +账号管理应成为账号能力中心的统一入口: + +- 按商品筛选 `available / limited / not_open / unknown`; +- 按商品和兑换时间筛选历史兑换; +- 显示最后官网确认时间和数据是否过期; +- 显示积分、宝典、换绑冷却和 CK 新鲜度; +- 显示当前租约和外部协作单占用; +- 区分“官网可兑换”“资源已就绪”“当前可分配”; +- 支持单账号立即同步; +- 支持针对 pending 商品批量补全能力。 + +账号详情中的商品能力矩阵和兑换时间线应直接读取本文定义的本地投影与事件账本。 + +## 代码边界 + +- 官网请求继续收口在 `douyu_activity_query.py` 和现有 Runner; +- 官网结果写当前投影必须经过统一的 capability service; +- 兑换等业务事实继续经过 `account_events_service` / `business_events`; +- 生命周期状态继续只允许通过 `account_lifecycle` 写入; +- 自动选号和账号管理必须共享同一个候选查询服务; +- 页面和履约服务不得各自实现一套能力判定。 + +相关入口: + +- `web/backend/models.py` +- `web/backend/services/account_capability_service.py` +- `web/backend/services/account_events_service.py` +- `web/backend/services/business_events.py` +- `web/backend/services/douyu_runner_overview.py` +- `web/backend/services/platform_fulfillment/account_selector.py` +- `web/backend/services/platform_fulfillment/service.py` +- `web/backend/services/automation/jobs/account_capability_refresh.py` + +## 分阶段落地 + +### P0:数据正确 + +1. 补齐有效账号的商品能力矩阵; +2. 修复能力刷新只处理已有商品状态账号的问题; +3. 将新鲜度与可查询性分开; +4. 建立官网同步运行记录; +5. 统一账号商品能力查询口径; +6. 自动选号移除无限实时扫描兜底; +7. 选号 API 增加任务级幂等、请求合并和前端 loading; +8. 外部官网检测迁移到独立 Worker,不长期占用 API 数据库连接。 + +### P1:业务统一 + +1. 账号管理和自动选号共享统一候选服务; +2. 增加商品维度筛选和能力诊断; +3. 兑换后自动标脏并核对; +4. 充值、开通、赠送后触发定向刷新; +5. 增加真正的指定账号人工分配能力。 + +### P2:运营增强 + +1. 商品能力覆盖率、新鲜度和同步失败率监控; +2. 候选成本排序和账号使用均衡; +3. 官网记录冲突队列; +4. 账号价值、维护成本和使用效率分析。 + +## 验收标准 + +1. 任意有效账号都能在本地查询到 60 个商品的最后已知状态或“未查询”; +2. 数据过期仍然可查,但不会直接参与自动分配; +3. 自动选号不再依赖固定的前 20 个低积分账号; +4. 已知限兑账号不会反复消耗实时查询请求; +5. 官网确认结果在一次事务中更新本地投影; +6. 官网失败不覆盖上一次有效结论; +7. 每笔兑换都能查询本地执行来源和官网补录记录; +8. 账号管理和自动选号对同一账号、同一商品给出相同资格结论; +9. 有效租约和协作单永远不会被官网“可兑换”结果覆盖; +10. 生产高峰期不再因为选号扫描产生大量重复外部请求和慢查询。 diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index 3358e1d..15956b8 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -1042,6 +1042,22 @@ class TestSnapshotSync(_Base): class TestAccountSelection(_Base): + def test_manual_allocation_request_only_marks_task_due(self): + task = self.task() + old_retry_at = task.next_allocate_at + + detail = service.prepare_manual_allocation( + self.session, + task_id=task.id, + current=self.admin, + ) + + self.session.refresh(task) + assert detail["task"]["account"] is None + assert task.next_allocate_at is not None + assert old_retry_at is None or task.next_allocate_at >= old_retry_at + self.refresh_mock.assert_not_called() + def test_capability_match_checks_only_selected_candidate(self, monkeypatch): account = self.account("capability-fast") task = self.task() diff --git a/tests/test_platform_fulfillment_auto_allocator.py b/tests/test_platform_fulfillment_auto_allocator.py index 9066aec..a03518e 100644 --- a/tests/test_platform_fulfillment_auto_allocator.py +++ b/tests/test_platform_fulfillment_auto_allocator.py @@ -13,6 +13,26 @@ from web.backend.models import ( from web.backend.services.platform_fulfillment import auto_allocator +def test_queue_task_allocation_deduplicates_pending_and_running_tasks(): + with auto_allocator._pending_lock: + auto_allocator._pending_task_ids.clear() + auto_allocator._running_task_ids.clear() + try: + assert auto_allocator.queue_task_allocation(3565) is True + assert auto_allocator.queue_task_allocation(3565) is False + + with auto_allocator._pending_lock: + auto_allocator._pending_task_ids.discard(3565) + auto_allocator._running_task_ids.add(3565) + + assert auto_allocator.queue_task_allocation(3565) is False + finally: + with auto_allocator._pending_lock: + auto_allocator._pending_task_ids.clear() + auto_allocator._running_task_ids.clear() + auto_allocator._wake_event.clear() + + def test_auto_allocator_only_scans_ready_unassigned_tasks(db): actor = User(username="auto-alloc-actor", password_hash="h", role="super_admin") db.add( @@ -81,6 +101,7 @@ def test_auto_allocator_only_scans_ready_unassigned_tasks(db): assert calls == [ready.id] assert result == {"checked": 1, "allocated": 1, "failed": 0} + assert not auto_allocator._running_task_ids def test_auto_allocator_schedules_retry_only_after_failed_allocation(db): diff --git a/web/backend/database.py b/web/backend/database.py index a88da22..a2853a9 100644 --- a/web/backend/database.py +++ b/web/backend/database.py @@ -7,6 +7,7 @@ from urllib.parse import quote_plus from sqlalchemy import DateTime, create_engine, event from sqlalchemy.orm import declarative_base, sessionmaker +from sqlalchemy.pool import NullPool from sqlalchemy.types import TypeDecorator PROJECT_ROOT = Path(__file__).resolve().parents[2] @@ -21,6 +22,11 @@ def _env_int(name: str, default: int) -> int: return value if value > 0 else default +def _pool_mode(name: str, default: str = "queue") -> str: + mode = os.getenv(name, default).strip().lower() + return mode if mode in {"queue", "null"} else default + + def _get_database_url() -> str: """优先使用完整连接串,否则按 DB_* 环境变量构造 MySQL 连接。""" database_url = os.getenv("DATABASE_URL", "").strip() @@ -61,13 +67,16 @@ engine_options = { "echo": False, } if not DATABASE_URL.startswith("sqlite"): - engine_options.update( - pool_pre_ping=True, - pool_size=_env_int("DB_POOL_SIZE", 20), - max_overflow=_env_int("DB_MAX_OVERFLOW", 20), - pool_timeout=_env_int("DB_POOL_TIMEOUT", 30), - pool_recycle=_env_int("DB_POOL_RECYCLE", 1800), - ) + if _pool_mode("DB_POOL_MODE") == "null": + engine_options["poolclass"] = NullPool + else: + engine_options["pool_pre_ping"] = True + engine_options.update( + pool_size=_env_int("DB_POOL_SIZE", 20), + max_overflow=_env_int("DB_MAX_OVERFLOW", 20), + pool_timeout=_env_int("DB_POOL_TIMEOUT", 30), + pool_recycle=_env_int("DB_POOL_RECYCLE", 1800), + ) engine = create_engine(DATABASE_URL, **engine_options) @@ -76,13 +85,22 @@ worker_engine_options = { "echo": False, } if not DATABASE_URL.startswith("sqlite"): - worker_engine_options.update( - pool_pre_ping=True, - pool_size=_env_int("WORKER_DB_POOL_SIZE", 12), - max_overflow=_env_int("WORKER_DB_MAX_OVERFLOW", 4), - pool_timeout=_env_int("WORKER_DB_POOL_TIMEOUT", 30), - pool_recycle=_env_int("DB_POOL_RECYCLE", 1800), - ) + if ( + _pool_mode( + "WORKER_DB_POOL_MODE", + _pool_mode("DB_POOL_MODE"), + ) + == "null" + ): + worker_engine_options["poolclass"] = NullPool + else: + worker_engine_options["pool_pre_ping"] = True + worker_engine_options.update( + pool_size=_env_int("WORKER_DB_POOL_SIZE", 12), + max_overflow=_env_int("WORKER_DB_MAX_OVERFLOW", 4), + pool_timeout=_env_int("WORKER_DB_POOL_TIMEOUT", 30), + pool_recycle=_env_int("DB_POOL_RECYCLE", 1800), + ) worker_engine = create_engine(DATABASE_URL, **worker_engine_options) @@ -140,6 +158,18 @@ WorkerSessionLocal = sessionmaker( Base = declarative_base() +def dispose_engines() -> None: + """关闭应用中所有持久连接。 + + `NullPool` 模式下通常没有空闲连接可关闭;保留这个统一出口是为了: + - queue 模式进程退出时主动释放 Sleep 连接; + - uvicorn reload / 测试重建应用时避免旧 engine 残留; + - 任务线程停止后再统一收口,顺序可预测。 + """ + engine.dispose() + worker_engine.dispose() + + class UTCDateTime(TypeDecorator): """时间列统一走这里:**库里存 naive UTC,Python 侧永远是 tz-aware UTC**。 diff --git a/web/backend/main.py b/web/backend/main.py index 3ce1c8d..2f1f56f 100644 --- a/web/backend/main.py +++ b/web/backend/main.py @@ -57,7 +57,7 @@ async def lifespan(app: FastAPI): # 进程重启后内存批次丢失,清理历史 pending/running,避免前端被假活跃批次锁死。 from loguru import logger - from .database import SessionLocal + from .database import SessionLocal, dispose_engines from .services.douyu_service import cleanup_orphan_douyu_tasks from .services.huya_service import cleanup_orphan_huya_tasks from .services.login_service import ( @@ -138,6 +138,7 @@ async def lifespan(app: FastAPI): stop_integration_outbox_worker() stop_scheduler() shutdown_task_runtime(wait=False) + dispose_engines() app = FastAPI( diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index eb3aa8e..625fc40 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -352,15 +352,21 @@ def allocate_task( db: Session = Depends(get_db), current: User = Depends(require_permission("platform_fulfillment:use")), ) -> dict[str, Any]: - result = service.allocate_task(db, task_id=task_id, current=current) + result = service.prepare_manual_allocation(db, task_id=task_id, current=current) record_audit( db, current, action="platform_fulfillment:allocate", target=f"platform_fulfillment_task:{task_id}", - detail={"accountId": result.get("task", {}).get("account", {})}, + detail={"requested": True}, ) db.commit() + from ..services.platform_fulfillment.auto_allocator import queue_task_allocation + + result["allocationQueued"] = ( + result.get("task", {}).get("executionStatus") == "ready" + and queue_task_allocation(task_id) + ) return result diff --git a/web/backend/services/platform_fulfillment/auto_allocator.py b/web/backend/services/platform_fulfillment/auto_allocator.py index 334ee6f..3a4daef 100644 --- a/web/backend/services/platform_fulfillment/auto_allocator.py +++ b/web/backend/services/platform_fulfillment/auto_allocator.py @@ -27,6 +27,7 @@ _thread: threading.Thread | None = None _lock = threading.Lock() _pending_lock = threading.Lock() _pending_task_ids: set[int] = set() +_running_task_ids: set[int] = set() _wake_event = threading.Event() @@ -39,14 +40,33 @@ def _env_int(name: str, default: int, minimum: int, maximum: int) -> int: def wake_auto_allocator(task_ids: Iterable[int] | None = None) -> None: - """立即唤醒选号 worker;传入任务 ID 时优先处理这些新任务。""" + """立即唤醒选号 worker;同一任务在排队或执行中时不会重复入队。""" normalized = {int(task_id) for task_id in (task_ids or []) if int(task_id) > 0} if normalized: with _pending_lock: - _pending_task_ids.update(normalized) + for task_id in normalized: + if task_id not in _running_task_ids: + _pending_task_ids.add(task_id) _wake_event.set() +def queue_task_allocation(task_id: int) -> bool: + """把一次人工选号请求合并到后台 worker。 + + 返回值只表示本次调用是否新增了队列项。重复点击、已经在执行以及已经排队的 + 请求都返回 False,调用方不应把它当成失败。 + """ + normalized = int(task_id) + if normalized <= 0: + return False + with _pending_lock: + if normalized in _running_task_ids or normalized in _pending_task_ids: + return False + _pending_task_ids.add(normalized) + _wake_event.set() + return True + + def _take_pending_task_ids(limit: int) -> list[int]: with _pending_lock: selected = sorted(_pending_task_ids)[:limit] @@ -55,6 +75,19 @@ def _take_pending_task_ids(limit: int) -> list[int]: return selected +def _claim_running_task_ids(task_ids: Iterable[int]) -> list[int]: + normalized = [int(task_id) for task_id in task_ids] + with _pending_lock: + _running_task_ids.update(normalized) + _pending_task_ids.difference_update(normalized) + return normalized + + +def _release_running_task_ids(task_ids: Iterable[int]) -> None: + with _pending_lock: + _running_task_ids.difference_update(int(task_id) for task_id in task_ids) + + def _has_pending_task_ids() -> bool: with _pending_lock: return bool(_pending_task_ids) @@ -127,37 +160,50 @@ def run_auto_allocation_once( if not candidates: return {"checked": 0, "allocated": 0, "failed": 0} - actor = service._integration_actor(db) - allocated = 0 - failed = 0 - for task in candidates: - candidate_task_id = int(task.id) - try: - detail: dict[str, Any] = service.allocate_task( - db, - task_id=candidate_task_id, - current=actor, - ) - if detail.get("task", {}).get("account"): - allocated += 1 - allocated_task = db.get(PlatformFulfillmentTask, candidate_task_id) - if allocated_task is not None: - allocated_task.next_allocate_at = None - db.commit() - try: - service.start_binding_sync( - db, - task_id=candidate_task_id, - current=actor, - ) - except Exception as exc: # noqa: BLE001 - allocation remains valid - db.rollback() - logger.warning( - "直播账号履约自动开始绑定失败 task_id={}: {}", - candidate_task_id, - exc, - ) - else: + candidate_task_ids = _claim_running_task_ids( + int(task.id) for task in candidates + ) + try: + actor = service._integration_actor(db) + allocated = 0 + failed = 0 + for task in candidates: + candidate_task_id = int(task.id) + try: + detail: dict[str, Any] = service.allocate_task( + db, + task_id=candidate_task_id, + current=actor, + ) + if detail.get("task", {}).get("account"): + allocated += 1 + allocated_task = db.get(PlatformFulfillmentTask, candidate_task_id) + if allocated_task is not None: + allocated_task.next_allocate_at = None + db.commit() + try: + service.start_binding_sync( + db, + task_id=candidate_task_id, + current=actor, + ) + except Exception as exc: # noqa: BLE001 - allocation remains valid + db.rollback() + logger.warning( + "直播账号履约自动开始绑定失败 task_id={}: {}", + candidate_task_id, + exc, + ) + else: + failed += 1 + _schedule_retry( + db, + task_id=candidate_task_id, + moment=moment, + retry_seconds=retry_seconds, + ) + except Exception as exc: # noqa: BLE001 - 单个任务异常不能中断整批 + db.rollback() failed += 1 _schedule_retry( db, @@ -165,25 +211,18 @@ def run_auto_allocation_once( moment=moment, retry_seconds=retry_seconds, ) - except Exception as exc: # noqa: BLE001 - 单个任务异常不能中断整批 - db.rollback() - failed += 1 - _schedule_retry( - db, - task_id=candidate_task_id, - moment=moment, - retry_seconds=retry_seconds, - ) - logger.warning( - "直播账号履约自动选号失败 task_id={}: {}", - candidate_task_id, - exc, - ) - return { - "checked": len(candidates), - "allocated": allocated, - "failed": failed, - } + logger.warning( + "直播账号履约自动选号失败 task_id={}: {}", + candidate_task_id, + exc, + ) + return { + "checked": len(candidates), + "allocated": allocated, + "failed": failed, + } + finally: + _release_running_task_ids(candidate_task_ids) def start_allocated_bindings_once( @@ -282,6 +321,7 @@ def start_platform_fulfillment_auto_allocator() -> bool: _wake_event.clear() with _pending_lock: _pending_task_ids.clear() + _running_task_ids.clear() _thread = threading.Thread( target=_run, name="platform-fulfillment-auto-allocator", diff --git a/web/backend/services/platform_fulfillment/service.py b/web/backend/services/platform_fulfillment/service.py index 8ffd1a8..012e2a6 100644 --- a/web/backend/services/platform_fulfillment/service.py +++ b/web/backend/services/platform_fulfillment/service.py @@ -2045,6 +2045,34 @@ def upsert_mapping( return update_mapping(db, mapping_id=row.id, **values) +def prepare_manual_allocation( + db: Session, + *, + task_id: int, + current: User, +) -> dict[str, Any]: + """在短请求内完成人工选号校验,并把任务标记为立即可领取。 + + 真正的官网账号检测由后台 auto allocator 执行。这样 API 请求不会在多次外部 + HTTP 调用期间一直持有数据库事务,也不会因为重复点击占满连接池。 + """ + task = _load_task(db, task_id) + if task.execution_status in {"completed", "cancelled"}: + raise HTTPException(status_code=409, detail="已结束任务不能重新分配账号") + if not task.commodity_id or not task.required_points: + raise HTTPException(status_code=409, detail="请先完成商品映射") + if task.account_id and task.lease_id: + lease = db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() + if lease and lease.status == "active": + return get_task_detail(db, task.id) + if task.execution_status != "ready": + raise HTTPException(status_code=409, detail="只有待分配任务可以重新选号") + task.next_allocate_at = _now() + task.updated_at = _now() + db.flush() + return get_task_detail(db, task.id) + + def allocate_task(db: Session, *, task_id: int, current: User) -> dict[str, Any]: task = _load_task(db, task_id) if task.execution_status in {"completed", "cancelled"}: @@ -3310,6 +3338,7 @@ __all__ = [ "list_tasks", "mapping_impact", "mark_manual_required", + "prepare_manual_allocation", "reconcile_binding_state_outbox", "record_douyu_operation_result", "record_douyu_operation_started", diff --git a/web/frontend/src/api/platformFulfillment.ts b/web/frontend/src/api/platformFulfillment.ts index 07324dd..9e58c2f 100644 --- a/web/frontend/src/api/platformFulfillment.ts +++ b/web/frontend/src/api/platformFulfillment.ts @@ -1,5 +1,6 @@ import api from './client'; import type { + PlatformFulfillmentAllocationResult, PlatformFulfillmentDetail, PlatformFulfillmentCollabSyncResult, PlatformFulfillmentListResponse, @@ -105,7 +106,7 @@ export const platformFulfillmentApi = { groups: Array<{ executionStatus: string; saleMode: string; count: number }>; }>(`/platform-fulfillment/mappings/${mappingId}/impact`), allocate: (taskId: number) => - api.post( + api.post( `/platform-fulfillment/tasks/${taskId}/allocate`, ), startBinding: (taskId: number) => diff --git a/web/frontend/src/api/types.ts b/web/frontend/src/api/types.ts index ebaf853..55d634d 100644 --- a/web/frontend/src/api/types.ts +++ b/web/frontend/src/api/types.ts @@ -2278,6 +2278,10 @@ export interface PlatformFulfillmentDetail { events: PlatformFulfillmentEvent[]; } +export interface PlatformFulfillmentAllocationResult extends PlatformFulfillmentDetail { + allocationQueued: boolean; +} + export interface PlatformFulfillmentMapping { id: number; targetPlatform: string; diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index dd1b2eb..6e59f81 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -348,6 +348,7 @@ export default function PlatformFulfillmentPage() { const [syncing, setSyncing] = useState(false); const [collabSyncing, setCollabSyncing] = useState(false); const [rowCollabSyncingId, setRowCollabSyncingId] = useState(null); + const [allocatingTaskId, setAllocatingTaskId] = useState(null); const [restoreTarget, setRestoreTarget] = useState(null); const [restoreReason, setRestoreReason] = useState(''); const [restoring, setRestoring] = useState(false); @@ -603,6 +604,26 @@ export default function PlatformFulfillmentPage() { } }; + const requestAllocation = async (task: PlatformFulfillmentTask) => { + if (allocatingTaskId !== null) return; + setAllocatingTaskId(task.id); + try { + const result = await platformFulfillmentApi.allocate(task.id); + setDetail(result); + setSelectedId(result.task.id); + await loadTasks(); + if (result.allocationQueued) { + message.info('选号请求已提交,后台完成后会自动刷新'); + } else { + message.info('该任务已在选号队列中或已经分配,请稍候刷新'); + } + } catch (error) { + message.error(getErrorMessage(error)); + } finally { + setAllocatingTaskId(null); + } + }; + const resetBinding = (task: PlatformFulfillmentTask) => { Modal.confirm({ title: '重置角色资料和绑定记录?', @@ -1156,7 +1177,14 @@ export default function PlatformFulfillmentPage() { ) : null} {task.executionStatus === 'ready' ? ( - ) : null}