Compare commits
6
Commits
3d5d0f551f
...
8fc8e623b9
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8fc8e623b9 | ||
|
|
5645f19102 | ||
|
|
9143a3afa0 | ||
|
|
f8c5e896d4 | ||
|
|
60f1a8d542 | ||
|
|
65a4590291 |
@@ -122,6 +122,12 @@ services:
|
||||
command:
|
||||
- --character-set-server=utf8mb4
|
||||
- --collation-server=utf8mb4_0900_ai_ci
|
||||
# 会话时区与存储口径对齐:库里所有时间列存的都是 UTC(应用一律写
|
||||
# datetime.now(UTC),MySQL 绑定参数丢掉 tzinfo 后落库即 UTC 裸值)。
|
||||
# 若仍跟随系统 +08:00,SQL 里的 NOW()/CURDATE() 会比库里时间快 8 小时,
|
||||
# 查询静默返回空、看着像「没数据」。全库无 TIMESTAMP 列、也没有
|
||||
# CURRENT_TIMESTAMP 默认值,因此改这里不会改变任何已有数据的语义。
|
||||
- --default-time-zone=+00:00
|
||||
# 业务表已超过 300MiB;可通过 .env 调整,默认给 MySQL 512MiB 缓冲池。
|
||||
- --innodb-buffer-pool-size=${MYSQL_INNODB_BUFFER_POOL_SIZE:-512M}
|
||||
# 默认记录 1 秒以上查询,便于验证查询优化;稳定后可设 MYSQL_SLOW_QUERY_LOG=0。
|
||||
|
||||
+135
-15
@@ -215,6 +215,7 @@
|
||||
| 8 | 资料模板字段固定为 **游戏编号 + 游戏昵称 + 主页截图**;**皮肤优先由订单号自动对应**;仅当订单命中多个斗鱼商品时(「3选1」「小店自选」类,占 12.4%),才让用户在链接里**选一件** |
|
||||
| 9 | 兑换**不涉及「加好友后赠送」**,状态机不需要"等待可赠送"等待态 |
|
||||
| 10 | 订单准入**分两层**:① 订单在 order_site 里**既无履约任务、也无接单平台工单**(`route=unhandled`,即「没人管」)才进入候选;② 候选订单的商品必须**命中皮肤兑换规则**才放行。其余一律提示「该订单暂不支持,请联系客服」,客服可在后台人工放行(留审计) |
|
||||
| 11a | **重登失败按原因分型**(`relogin_failure_kind`),不是笼统「失败」:极验/凭证问题转人工,取码/中断/网络自动重试,配额满退避到次日(详见 §7.4.3) |
|
||||
| 11 | **准入白名单以斗鱼商品目录为准**:能映射到 `douyu_goods_snapshot` 的才放行;映射不到(占 C 桶皮肤订单 59.9%)直接拒绝 —— 因为斗鱼兑不出来。**不匹配就不建单**,后续按实际数据逐步放宽 |
|
||||
| 12 | **匹配优先按 SKU 精确定位**(`relSkuId` / `skuNick`),商品名文本只作兜底(§3.6)—— 接单平台已是这个做法 |
|
||||
|
||||
@@ -365,6 +366,25 @@ lookup_order(order_no) -> {
|
||||
> `tests/test_automation_ck_health.py`(22 条)。
|
||||
> 端到端已用 3 个真实账号验证:巡检结果与直接检测逐条一致,且 `cookie` / `status` / `message` / `attempt_status` 全程未变。
|
||||
|
||||
**生产上线记录(2026-10-02)**
|
||||
|
||||
按三段走完,全部通过:
|
||||
|
||||
| 段 | 动作 | 结果 |
|
||||
| --- | --- | --- |
|
||||
| ① | `AUTOMATION_ENABLED=true` + 重启 | 容器内变量生效,日志「自动化调度器已启动,tick=300s」 |
|
||||
| ② | 手动跑一轮(每轮 50 条,作业开关仍关) | `success`,50 条 / 7 秒,**斗鱼无风控反应**(无验证码、无频控、无超时) |
|
||||
| ③ | 每轮 200 条 + 打开作业开关 | 调度器自动接管:12:27:26 → 12:27:48 跑完 200 条(22 秒),`next_run_at` 按 tick 推进到 +5 分钟 |
|
||||
|
||||
**上线过程中抓到(并已修)两个只有生产才会暴露的问题**,都已在 §C.2 记档:
|
||||
|
||||
1. `NULLS FIRST` 在 SQLite 合法、**MySQL 报 1064** → 改用 `col IS NULL DESC`,并加了一条按 MySQL 方言 `compile()` 的回归测试;
|
||||
2. compose 的 `environment:` 是**显式列表**,只写 `.env` 不会传进容器 → `AUTOMATION_ENABLED` 起初根本没生效(顺带发现早先写入的 `ORDER_SITE_*` / `OSS_*` 也全都没传进去)。
|
||||
|
||||
**首轮数据结论(供客服侧预期管理)**:前几轮 100% `invalid` 属正常且正是价值所在 —— 选行是「从没检测过的优先」,而积压的 1,897 条未检测记录里大部分是 **2026-08-04 一次性批量导入、`attempt_status` 为空(从未尝试登录)**、CK 已放两个月的陈旧账号。错误信息统一是斗鱼侧的「用户未登录」,不是风控。按 200 条/5 分钟,约 5.4 小时扫完全库积压后进入稳态。
|
||||
|
||||
> **注意**:巡检会把这些陈旧账号的 `ck_check_status` 从空翻成 `invalid`,客服在「CK 检测与重登」页会突然看到大批失效账号 —— 这是预期行为,不是故障。
|
||||
|
||||
### 7.2 数据模型(迁移 1 个,P1a/P1b 共用)
|
||||
|
||||
**新表 `automation_jobs`**
|
||||
@@ -397,6 +417,16 @@ lookup_order(order_no) -> {
|
||||
如果误把作业周期设成 `interval_seconds`,就变成「200 条/6 小时 = 800 条/天」,全库 12,881 条要 16 天才能过一轮 —— 等于没巡检(P1a 实现时踩过一次,已修);
|
||||
- **排除**:`auto_managed = false`;`attempt_status in (pending, running)`(正在被批次处理);最近 10 分钟内刚检测过(防重入);
|
||||
- **动作**:调用现有 `check_douyu_cookie()`(两个只读接口,直连),写回 `ck_check_status / ck_check_result / ck_checked_at`;
|
||||
- **⚠️ 三类判定(关键防护)**:检测失败不等于 CK 失效,结果必须分三类处理,否则斗鱼接口抖动一小时就能把上千个好账号标成失效、让客服误判成「CK 大面积挂掉」:
|
||||
|
||||
| 判定 | 依据 | 处理 |
|
||||
| --- | --- | --- |
|
||||
| `valid` | 两个接口都通过 | 写 `ck_check_status='valid'` |
|
||||
| `invalid` | 斗鱼**明确**回「未登录 / 登陆异常 / 请重新登陆」 | 写 `ck_check_status='invalid'` |
|
||||
| `error` | 其余失败(`请求失败:` 超时、`响应异常`、未知结构、走异常兜底) | **不覆盖该行原结论**,只更新 `ck_check_result`(带 `verdict`)与 `ck_checked_at`,计入 `skipped` |
|
||||
|
||||
- **自动暂停**:一轮里 `error` 占比 > 30% 且条数 ≥ 20 时,作业把自己 `enabled` 置 false 并在 `message` 写明原因(`detail.paused=true`)—— 大面积「查不到」通常是接口抖动或被风控,继续跑只会污染更多账号;
|
||||
> 注意:**真实死号占比高不触发暂停**。首轮 100% `invalid` 是合法且预期的情况(选行是「从没检测过的优先」,积压的多是两个月前批量导入、从未登录的陈旧账号)。
|
||||
- **并发**:默认 5,沿用现有 `ThreadPoolExecutor` 模式;
|
||||
- **不做**:不改 CK、不建重登批次、不动 `login_tasks.status`。
|
||||
|
||||
@@ -424,16 +454,103 @@ lookup_order(order_no) -> {
|
||||
|
||||
### 7.4 P1b · 作业二:`ck_relogin`(自愈,默认关闭)
|
||||
|
||||
- **调度**:每 5 分钟 tick;取满足以下条件的账号,最多 `batch_size`(默认 20)个:
|
||||
`ck_check_status = 'invalid'` 且 `relogin_next_at <= now`(或为空)且 `relogin_attempts < max_attempts_per_day`(默认 2)且 `auto_managed = true` 且 `attempt_status` 不在途;
|
||||
- **执行**:复用 `LoginBatchRunner(mode="relogin")`,成功才替换 CK;
|
||||
> **这一节 2026-10-02 按线上实测数据重写过。** 原来的设计只有「退避 + 熔断 + 开关」,
|
||||
> 数据表明那样不够:**失败必须分型**,否则 64% 本可自动解决的失败会被当成人工活。
|
||||
|
||||
#### 7.4.1 为什么必须和 P1a 联动(数据)
|
||||
|
||||
巡检只产出「谁失效了」的清单,不兑现修复,1,000+ 个账号还是要人工逐个选集→点重登→过滑块。
|
||||
线上实测(2026-10-02):
|
||||
|
||||
| 项 | 数值 | 依据 |
|
||||
| --- | --- | --- |
|
||||
| 当前失效 | **1,356**(还在涨,巡检在排空积压) | `ck_check_status='invalid'` |
|
||||
| 其中「还没在 attempt_* 时代重试过」 | 941 | 纯新机会 |
|
||||
| 其中「最近一次重登失败过」 | 415 | 已有失败记录 |
|
||||
| 历史重登**真实成功率** | **≈78%** | 成功 1,767 ÷ (1,767 + 真实失败 508),已排除「中断/停止」这类非真失败 |
|
||||
| 预计可自动救回 | **≈1,050** | 1,356 × 78% |
|
||||
| 预计需人工 | **≈300** | 主要是极验滑块 |
|
||||
|
||||
**关键结论:失效是「会话级」而不是「凭证级」。** 斗鱼对这批账号回的是「用户未登录」,
|
||||
不是「密码错误」;而这些行**本来都是登录成功的产物**(见下)。
|
||||
|
||||
> **「持有 CK 的行 = 真实登录成功过」的依据**:`LoginTask` 全项目**只在一处创建**
|
||||
> —— `services/login_service.py`(登录成功写回 CK 处);**导入账号不建 LoginTask、
|
||||
> 不写 cookie**(已 grep 核实)。因此 `cookie` 非空且 `status='success'` 的行,
|
||||
> 只可能是某次真实登录成功留下的。那批 `attempt_status=''` 不是「从未登录」,
|
||||
> 而是「登录成功发生在 `attempt_*` 字段存在之前」(字段是迁移 `20261001_0035` 才加的)。
|
||||
|
||||
#### 7.4.2 候选筛选
|
||||
|
||||
- 每 5 分钟 tick,取满足以下条件的行,最多 `batch_size`(默认 20)个:
|
||||
`ck_check_status = 'invalid'` 且 `relogin_next_at <= now`(或为空)
|
||||
且 `relogin_attempts < max_attempts_per_day`(默认 2)
|
||||
且 `auto_managed = true` 且 `attempt_status` 不在途;
|
||||
- **不再按「有没有成功过」筛**:持 CK 的行按定义都成功过,这个条件没有区分度;
|
||||
真正有区分度的是「上一次为什么失败」(下一步的分型)。
|
||||
|
||||
#### 7.4.3 失败分型(本次新增的核心)
|
||||
|
||||
重登失败不能笼统地「再试一次」或「丢给人工」。按原因落 **`login_tasks.relogin_failure_kind`**
|
||||
(枚举字段,新增迁移;**不要靠 `attempt_message` 做字符串匹配** —— 文案一改就失效,
|
||||
且页面要按类型筛选),不同分型走不同后续:
|
||||
|
||||
| kind | 触发(线上实测条数) | 后续动作 |
|
||||
| --- | --- | --- |
|
||||
| `captcha` | 极验滑块失败(144 / 35%) | **转人工队列,不再自动重试**(反复撞只会加重风控) |
|
||||
| `email_code` | 验证码错误 / 等待超时(144 / 35%) | **自动重试**(走退避表);这批多半正是 `20261001` 修掉的取码 bug 造成的 |
|
||||
| `interrupted` | 服务重启 / 人工停止(121 / 29%) | **不是真失败** → 自动重试 |
|
||||
| `email_quota` | 「发送次数已达上限」 | 退避到**次日零点 + 随机抖动 ±30 分钟**(决策 1:只影响该账号,批次继续) |
|
||||
| `credential` | 密码错误 / 账号异常 | **转人工队列**(需核对密码或邮箱) |
|
||||
| `network` | 请求失败 / 超时 / 连接异常 | 自动重试(退避) |
|
||||
|
||||
> 64% 的线上「失败」(`email_code` + `interrupted`)其实是可自动解决的;不分型就会把它们
|
||||
> 一起推给人工,白费 265 个可救名额。
|
||||
|
||||
#### 7.4.4 退避与熔断
|
||||
|
||||
- **退避**:`relogin_attempts` 1→1h、2→3h、3→12h、4+→24h(写 `relogin_next_at`);
|
||||
- **邮箱配额(决策 1)**:命中 `EmailQuotaError` 时
|
||||
- 只把**该账号**标记为「邮件配额用尽」,`relogin_next_at` 设为次日零点 + 随机抖动(默认 ±30 分钟,避免整点齐发),`relogin_last_error` 记录原因;
|
||||
- **批次继续跑其他账号**,不全局暂停;
|
||||
- 说明:现有 `login()` 已经是这个语义(单账号返回失败、批次继续),自动化层只需额外记录退避时间,避免反复重试同一账号;
|
||||
- **系统性故障刹车(与决策 1 不冲突)**:以下情况仍会自动暂停作业并告警 ——
|
||||
代理 API 不可用 / 连续 N 轮失败率超过阈值(默认 80%)/ 单轮异常数超过阈值。这些不是单账号问题,继续跑只会浪费资源。
|
||||
- **极验即停**:同一账号连续 2 次 `captcha` → 直接转人工,不再自动重试;
|
||||
- **系统性故障刹车(与决策 1 不冲突)**:代理 API 不可用 / 单轮失败率超阈值(默认 80%)
|
||||
/ 单轮异常数超阈值 → **自动暂停作业并告警**。这些不是单账号问题,继续跑只会浪费资源。
|
||||
|
||||
#### 7.4.5 速率与风控
|
||||
|
||||
| 约束 | 实测/建议 |
|
||||
| --- | --- |
|
||||
| 邮箱配额 | **13,618 个账号对应 13,618 个独立邮箱(1:1,实测)** → 单账号配额满不影响他人,决策 1 成立;也不存在「打爆共享邮箱」的问题 |
|
||||
| IP 才是瓶颈 | 1,356 次登录 + 1,356 封验证码,短时间集中做会触发风控 → **走现有代理池 + 限速每小时 30~60 个**(约 1~2 天跑完,后台慢慢来完全可以接受) |
|
||||
| 单轮上限 | `batch_size` 默认 20(5 分钟一轮 = 上限 240/小时,实际由退避与每日上限压住) |
|
||||
|
||||
#### 7.4.6 页面呈现(对应「失败单独标记提示」)
|
||||
|
||||
`/automation` 页在作业卡片之外增加两块:
|
||||
|
||||
- **自动重登中**:有退避倒计时、下次重试时间、当前 `relogin_attempts`;
|
||||
- **待人工处理**:按 `relogin_failure_kind` 分组 ——
|
||||
- 极验失败(要人工过滑块)
|
||||
- 凭证问题(要核对密码/邮箱)
|
||||
- 多次失败(要人工查账号可用性)
|
||||
|
||||
#### 7.4.7 上线方式(三段,同 P1a 的谨慎程度)
|
||||
|
||||
1. **小规模实测** ✅ **已完成(2026-10-02),结果远好于预期**:
|
||||
|
||||
| 项 | 结果 |
|
||||
| --- | --- |
|
||||
| 样本 | **20 个** invalid,两组各 10:A「还没重试过」/ B「取码 bug 时代失败过」 |
|
||||
| 成功率 | **20 / 20 = 100%**(历史推断只有 78%) |
|
||||
| 耗时 | 2 分 13 秒(≈ 9 个/分钟) |
|
||||
| 极验滑块 | **0 次** |
|
||||
| 邮箱取码 | 全部正常 → **`20261001` 的取码修复在生产验证通过**(B 组全过,证实那 144 个「验证码失败」就是旧 bug 造成的) |
|
||||
| CK 替换 | 20 个全部换成新 CK;`ck_check_status` 由登录流程自动改回 `valid`(`login_service.py` 成功分支) |
|
||||
|
||||
**结论**:会话确实只是过期,重登几乎必定成功;可救量从估的 1,050 上调到
|
||||
**≈1,350**(1,356 × 近 100%)。失败分型仍然要做,但属少数路径(极验/配额/凭证)。
|
||||
实测 9 个/分钟且零极验,说明斗鱼当前风控容忍度比预想高,不过全量仍建议限速
|
||||
(先按每小时 100~200 个开,观察极验率再决定是否加速);
|
||||
2. **限量开作业**:按实测成功率定 `batch_size` 与日上限,先只跑一个分组;
|
||||
3. **全量**:观察若干轮,确认分型与退避符合预期后再放开。
|
||||
|
||||
### 7.5 并发与互斥
|
||||
|
||||
@@ -943,13 +1060,14 @@ pending_material(待用户补资料) ← 模板有必填字段时的
|
||||
| **P2** | 资料收集链接(公开页 + **OSS 图片直传** + 后端代理读图 + 队列 + 订单回显) | P0(订单回显)+ 运维建 OSS 桶;P0 未完成时先留手工填订单号 | 5~6 人日 |
|
||||
| **P3** | 皮肤台账(`skin_catalog` 以斗鱼商品为锚 + `skin_aliases` 映射 + 四路来源 + 365 天规则 + `/skins` 页) | P0(订单皮肤);映射分析**已完成**(见分析文档),人工只需过 60 个商品 / 76 条别名 | 4~5 人日 |
|
||||
| **P4** | 皮肤兑换工单(规则/模板 + 匹配层 + 工单/事件表 + 状态机 + 三处界面 + 前置校验作业) | P1a + P2 + P3(**不依赖 P1b**:CK 失效时先标记等人工重登,P1b 上线后自动接管) | 6~8 人日 |
|
||||
| **P1b** | CK 自愈(`ck_relogin` 自动重登:退避 + 熔断 + 开关,**默认关闭**) | P1a 观察一到两周 | 1.5~2 人日 |
|
||||
| **P1b** | CK 自愈(`ck_relogin` 自动重登:**失败分型** + 退避 + 熔断 + 开关,**默认关闭**) | P1a(检测已验证,不必再等观察期) | 2.5~3 人日 |
|
||||
|
||||
**建议顺序:P1a → P0 → P2 → P3 → P4 → P1b。**
|
||||
**建议顺序:P1a → P1b → P0 → P2 → P3 → P4。**
|
||||
|
||||
- **P1a 先上**:只做「帮你把失效 CK 找出来」,零风险、立刻省掉大批量人工点检测;观察一到两周、确认检测结果与人工判断一致后,再打开 P1b;
|
||||
- **P1a 已上线**(2026-10-02),只做「帮你把失效 CK 找出来」,零风险;
|
||||
- **P1b 提到 P1a 之后**:原计划等一到两周观察期,但线上数据已把三个前提验证完了 —— 检测结果与人工/直连逐条一致、误判路径已封(三类判定 + 自动暂停)、失效性质查清(会话过期而非凭证问题)。不联动的话,巡检每天翻出失效清单却没人兑现修复,1,356 个账号只会越积越多;
|
||||
- **P0 随时可做**:只动本系统,order_site 侧代码改动量为 0;
|
||||
- **P1b 代码可与 P1a 一起写完**,但开关默认关闭,等观察结论再开;
|
||||
- **P1b 开关仍默认关闭**,按 §7.4.7 三段上线:小规模实测 → 限量开 → 全量;
|
||||
- **P1a 上线按三段走**:
|
||||
① 打开 `AUTOMATION_ENABLED=true` 并重启(此时作业开关仍关着,调度线程空转,不会有任何检测);
|
||||
② 在 `/automation` 页点「立即跑一次」并先把「每轮条数」设 **50** —— 手动触发不受开关限制,正好用来观察斗鱼风控与失败率;
|
||||
@@ -972,7 +1090,8 @@ P0 ──┬──> P2 ────┤
|
||||
| --- | --- | --- | --- |
|
||||
| 只读查 order_site 打慢对方生产库 | 影响自动发货 | `statement_timeout=3s`、单行索引查询、2 条连接、本地缓存 | 关 `ORDER_SITE_LOOKUP_ENABLED` |
|
||||
| order_site 改表结构 | 适配层报错 | 只读 4 列且 88 个迁移零变更;SQL 集中在一个文件 | 同上(降级为手工) |
|
||||
| **巡检本身触发斗鱼风控** | 检测接口被限流/封禁,误判大面积 invalid | 巡检走**只读接口**且不并发过高;失败率超阈值自动暂停;必要时给请求加随机抖动、降 `concurrency` | 关 `ck_health` 作业(回到人工检测) |
|
||||
| **巡检把「查不到」当成「失效」** | 接口抖动/被风控时批量误标失效,客服误判 | 已做三类判定:只有斗鱼明确回「未登录」才写 invalid,其余只记 `error`、保留原结论;`error` 占比 > 30% 自动暂停作业 | 恢复接口后重新打开作业开关 |
|
||||
| 巡检本身触发斗鱼风控 | 检测接口被限流/封禁,误判大面积 invalid | 巡检走**只读接口**且不并发过高;失败率超阈值自动暂停;必要时给请求加随机抖动、降 `concurrency` | 关 `ck_health` 作业(回到人工检测) |
|
||||
| 冷启动一次性全量扫 | 短时高并发被风控 | 首轮小批量(50)观察后再放量 | 调小 `batch_size` |
|
||||
| 自动重登烧掉邮箱配额 | 该账号当天无法登录 | 单账号退避到次日 + 每日上限 + 失败率熔断 | 关 `ck_relogin` 作业 |
|
||||
| 自动重登与人工操作撞车 | 状态互相覆盖 | `attempt_status` 在途判断 + 作业锁 | 关作业 |
|
||||
@@ -1085,7 +1204,8 @@ OSS_PREFIX=collect
|
||||
| 阶段 | 迁移内容 |
|
||||
| --- | --- |
|
||||
| P0 | `external_order_cache` |
|
||||
| P1 | `automation_jobs`、`automation_runs`;`login_tasks` + `relogin_attempts`/`relogin_next_at`/`relogin_last_error`;`accounts` + `auto_managed` |
|
||||
| P1a | `automation_jobs`、`automation_runs`;`login_tasks` + `relogin_attempts`/`relogin_next_at`/`relogin_last_error`;`accounts` + `auto_managed`(revision `20261002_0037`) |
|
||||
| P1b | `login_tasks` + `relogin_failure_kind`(枚举;按落地顺序取号) |
|
||||
| P2 | `collect_links`、`collect_submissions`(截图只存 `object_key`,不存 URL/本地路径) |
|
||||
| P3 | `skin_catalog`、`skin_aliases`、`skin_douyu_items`、`account_exchange_records` |
|
||||
| P4 | `exchange_skin_rules`、`exchange_match_logs`、`exchange_orders`、`exchange_order_events`(**4 张**,映射层已取消) |
|
||||
|
||||
@@ -183,7 +183,11 @@ class TestCkHealthNeverTouchesCookie(_Base):
|
||||
def test_invalid_result_marks_invalid_but_keeps_cookie(self):
|
||||
job = self._job()
|
||||
task = self.make_task(self.make_account("acc"))
|
||||
ck_health.check_douyu_cookie = _fake_check(valid=False)
|
||||
# 必须是鉴权类失败(斗鱼说未登录)才会被标成 invalid
|
||||
ck_health.check_douyu_cookie = _fake_check(
|
||||
valid=False,
|
||||
message="鱼丸接口: 账户登陆异常,请重新登陆;等级接口: 用户未登录",
|
||||
)
|
||||
try:
|
||||
counters = ck_health.run_ck_health(self.session, job)
|
||||
finally:
|
||||
@@ -194,16 +198,23 @@ class TestCkHealthNeverTouchesCookie(_Base):
|
||||
assert task.cookie == "acf_uid=1"
|
||||
|
||||
def test_detection_exception_does_not_abort_round(self):
|
||||
"""单个账号检测抛异常不影响整轮,但也不能把它标成失效。"""
|
||||
job = self._job()
|
||||
self.make_task(self.make_account("a"))
|
||||
self.make_task(self.make_account("b"))
|
||||
first = self.make_task(self.make_account("a"), ck_check_status="valid")
|
||||
second = self.make_task(self.make_account("b"), ck_check_status="valid")
|
||||
ck_health.check_douyu_cookie = _fake_check(raises=True)
|
||||
try:
|
||||
counters = ck_health.run_ck_health(self.session, job)
|
||||
finally:
|
||||
ck_health.check_douyu_cookie = _REAL_CHECK
|
||||
assert counters["scanned"] == 2
|
||||
assert counters["invalid"] == 2
|
||||
# 查不到不等于失效:两行都保留原结论,只记录这次异常
|
||||
assert counters["invalid"] == 0
|
||||
assert counters["skipped"] == 2
|
||||
for task in (first, second):
|
||||
self.session.refresh(task)
|
||||
assert task.ck_check_status == "valid"
|
||||
assert task.ck_check_result["verdict"] == "error"
|
||||
|
||||
def _job(self):
|
||||
return AutomationJob(
|
||||
@@ -363,13 +374,15 @@ def _aware(value):
|
||||
_REAL_CHECK = ck_health.check_douyu_cookie
|
||||
|
||||
|
||||
def _fake_check(*, valid=True, raises=False):
|
||||
def _fake_check(*, valid=True, raises=False, message=None):
|
||||
def fake(cookie: str) -> dict:
|
||||
if raises:
|
||||
raise RuntimeError("网络异常")
|
||||
return {
|
||||
"valid": valid,
|
||||
"message": "ok" if valid else "Cookie 已失效",
|
||||
"message": message
|
||||
if message is not None
|
||||
else ("ok" if valid else "Cookie 已失效"),
|
||||
"fish_ball": 1,
|
||||
"nickname": "测试",
|
||||
"level": 30,
|
||||
@@ -393,8 +406,8 @@ class TestAutomationApi(_Base):
|
||||
assert payload["scheduler"]["tick_seconds"] == 300
|
||||
assert payload["scheduler"]["running"] is False
|
||||
keys = [item["key"] for item in payload["jobs"]]
|
||||
assert keys == [ck_health.JOB_KEY]
|
||||
job = payload["jobs"][0]
|
||||
assert ck_health.JOB_KEY in keys
|
||||
job = next(item for item in payload["jobs"] if item["key"] == ck_health.JOB_KEY)
|
||||
assert job["enabled"] is False
|
||||
assert job["interval_seconds"] == 6 * 3600
|
||||
assert job["batch_size"] == 200
|
||||
@@ -410,7 +423,11 @@ class TestAutomationApi(_Base):
|
||||
db=self.session,
|
||||
current=self.admin,
|
||||
)
|
||||
job = self.session.query(AutomationJob).one()
|
||||
job = (
|
||||
self.session.query(AutomationJob)
|
||||
.filter(AutomationJob.key == ck_health.JOB_KEY)
|
||||
.one()
|
||||
)
|
||||
assert job.enabled is True
|
||||
assert job.interval_seconds == 3600
|
||||
assert job.batch_size == 5
|
||||
@@ -467,3 +484,104 @@ class TestAutomationApi(_Base):
|
||||
)
|
||||
assert len(payload["items"]) == 1
|
||||
assert payload["items"][0]["job_key"] == ck_health.JOB_KEY
|
||||
|
||||
|
||||
class TestFailureClassification(_Base):
|
||||
"""「查不到」不等于「失效」:非鉴权类失败不能覆盖原来的结论。
|
||||
|
||||
斗鱼接口抖动/被风控时,如果不加区分地写 invalid,一小时就能把上千个好账号
|
||||
标成失效,客服会误判成 CK 大面积挂掉。这里盯三件事:分类正确、error 不改
|
||||
结论、失败占比过高时自动暂停作业。
|
||||
"""
|
||||
|
||||
def test_auth_failure_message_counts_as_invalid(self):
|
||||
assert (
|
||||
ck_health.classify_result(
|
||||
{
|
||||
"valid": False,
|
||||
"message": "鱼丸接口: 账户登陆异常,请重新登陆;等级接口: 用户未登录",
|
||||
}
|
||||
)
|
||||
== "invalid"
|
||||
)
|
||||
|
||||
def test_network_failure_counts_as_error_not_invalid(self):
|
||||
assert (
|
||||
ck_health.classify_result(
|
||||
{
|
||||
"valid": False,
|
||||
"message": "鱼丸接口: 请求失败: timeout;等级接口: 请求失败: timeout",
|
||||
}
|
||||
)
|
||||
== "error"
|
||||
)
|
||||
assert (
|
||||
ck_health.classify_result({"valid": False, "message": "响应异常"})
|
||||
== "error"
|
||||
)
|
||||
|
||||
def test_valid_still_valid(self):
|
||||
assert ck_health.classify_result({"valid": True, "message": "有效"}) == "valid"
|
||||
|
||||
def test_error_keeps_previous_verdict_but_marks_checked(self):
|
||||
job = self._job()
|
||||
task = self.make_task(self.make_account("acc"), ck_check_status="valid")
|
||||
ck_health.check_douyu_cookie = _fake_check(
|
||||
valid=False, message="请求失败: timeout"
|
||||
)
|
||||
try:
|
||||
counters = ck_health.run_ck_health(self.session, job)
|
||||
finally:
|
||||
ck_health.check_douyu_cookie = _REAL_CHECK
|
||||
self.session.refresh(task)
|
||||
assert counters["valid"] == 0 and counters["invalid"] == 0
|
||||
assert counters["skipped"] == 1 # error 计入 skipped
|
||||
assert task.ck_check_status == "valid" # 原结论保留
|
||||
assert task.ck_check_result["verdict"] == "error" # 但记录了这次查不到
|
||||
assert task.ck_checked_at is not None
|
||||
|
||||
def test_mass_network_failure_pauses_the_job(self):
|
||||
job = self._job()
|
||||
job.enabled = True
|
||||
job.batch_size = 40
|
||||
for index in range(40):
|
||||
self.make_task(self.make_account(f"a{index}"))
|
||||
ck_health.check_douyu_cookie = _fake_check(
|
||||
valid=False, message="请求失败: Connection refused"
|
||||
)
|
||||
try:
|
||||
counters = ck_health.run_ck_health(self.session, job)
|
||||
finally:
|
||||
ck_health.check_douyu_cookie = _REAL_CHECK
|
||||
assert counters["skipped"] == 40
|
||||
assert counters["detail"]["paused"] is True
|
||||
assert job.enabled is False # 自动暂停,不再继续污染
|
||||
assert "已自动暂停" in counters["message"]
|
||||
|
||||
def test_normal_invalid_does_not_pause(self):
|
||||
"""真的都是死号时不能暂停 —— 首轮 100% invalid 是合法且预期的情况。"""
|
||||
job = self._job()
|
||||
job.enabled = True
|
||||
job.batch_size = 40
|
||||
for index in range(40):
|
||||
self.make_task(self.make_account(f"a{index}"))
|
||||
ck_health.check_douyu_cookie = _fake_check(
|
||||
valid=False,
|
||||
message="鱼丸接口: 账户登陆异常,请重新登陆;等级接口: 用户未登录",
|
||||
)
|
||||
try:
|
||||
counters = ck_health.run_ck_health(self.session, job)
|
||||
finally:
|
||||
ck_health.check_douyu_cookie = _REAL_CHECK
|
||||
assert counters["invalid"] == 40
|
||||
assert counters["skipped"] == 0
|
||||
assert job.enabled is True
|
||||
assert counters["detail"]["paused"] is False
|
||||
|
||||
def _job(self):
|
||||
return AutomationJob(
|
||||
key=ck_health.JOB_KEY,
|
||||
interval_seconds=6 * 3600,
|
||||
batch_size=200,
|
||||
concurrency=3,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,377 @@
|
||||
"""P1b 回归:CK 自动重登的候选筛选、失败分型与结算。
|
||||
|
||||
两件事必须一起守住:
|
||||
|
||||
1. **分型正确**:线上 415 个重登失败里只有 35%(极验)真的需要人工,另外 64%
|
||||
(取码失败 + 重启中断)其实可自动重试。分错方向就是白扔可救名额,或者让
|
||||
极验账号反复撞风控。
|
||||
2. **选行安全**:只挑「巡检判定失效 + 允许自动管理 + 没有在途尝试 + 退避到期 +
|
||||
没转人工」的行;转人工的类型绝不能被再次自动重登。
|
||||
|
||||
结算逻辑(``settle_results``)与选行查询(``build_select_query``)都刻意抽成了
|
||||
纯函数/可编译对象,这里不碰真实登录链路。
|
||||
"""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from web.backend.database import Base
|
||||
from web.backend.models import Account, AutomationJob, LoginTask, User
|
||||
from web.backend.services.automation.jobs import ck_relogin
|
||||
|
||||
|
||||
class _Base:
|
||||
def setup_method(self):
|
||||
self.engine = create_engine("sqlite://")
|
||||
Base.metadata.create_all(self.engine)
|
||||
self.session = sessionmaker(bind=self.engine)()
|
||||
self.admin = User(
|
||||
username="admin", password_hash="h", role="super_admin", is_active=True
|
||||
)
|
||||
self.session.add(self.admin)
|
||||
self.session.commit()
|
||||
|
||||
def teardown_method(self):
|
||||
self.session.close()
|
||||
|
||||
def make_task(
|
||||
self,
|
||||
name="acc",
|
||||
*,
|
||||
ck_check_status="invalid",
|
||||
cookie="acf_uid=1",
|
||||
attempt_status="",
|
||||
attempt_message="",
|
||||
relogin_attempts=0,
|
||||
relogin_next_at=None,
|
||||
relogin_failure_kind="",
|
||||
relogin_last_error="",
|
||||
auto_managed=True,
|
||||
):
|
||||
account = Account(
|
||||
username=name,
|
||||
password="p",
|
||||
email=f"{name}@e.com",
|
||||
email_password="ep",
|
||||
auto_managed=auto_managed,
|
||||
)
|
||||
self.session.add(account)
|
||||
self.session.commit()
|
||||
task = LoginTask(
|
||||
batch_id="b",
|
||||
account_id=account.id,
|
||||
created_by=self.admin.id,
|
||||
status="success",
|
||||
cookie=cookie,
|
||||
ck_check_status=ck_check_status,
|
||||
attempt_status=attempt_status,
|
||||
attempt_message=attempt_message,
|
||||
relogin_attempts=relogin_attempts,
|
||||
relogin_next_at=relogin_next_at,
|
||||
relogin_failure_kind=relogin_failure_kind,
|
||||
relogin_last_error=relogin_last_error,
|
||||
)
|
||||
self.session.add(task)
|
||||
self.session.commit()
|
||||
return task
|
||||
|
||||
def job(self, batch_size=10):
|
||||
return AutomationJob(
|
||||
key=ck_relogin.JOB_KEY,
|
||||
interval_seconds=6 * 3600,
|
||||
batch_size=batch_size,
|
||||
concurrency=3,
|
||||
)
|
||||
|
||||
|
||||
class TestFailureClassification(_Base):
|
||||
def test_quota_wins_over_code(self):
|
||||
"""「发送次数已达上限」既含验证码又含上限,必须优先判配额。
|
||||
|
||||
判成 email_code 会按小时反复撞配额;判成 email_quota 才退避到次日。
|
||||
"""
|
||||
msg = "重新登录失败: 提交验证码失败: 您的邮箱验证码发送次数已达上限,请改天再试!(旧 Cookie 已保留)"
|
||||
assert ck_relogin.classify_failure(msg) == "email_quota"
|
||||
|
||||
def test_captcha_is_manual(self):
|
||||
assert (
|
||||
ck_relogin.classify_failure(
|
||||
"重新登录失败: 极验验证失败: slide(旧 Cookie 已保留)"
|
||||
)
|
||||
== "captcha"
|
||||
)
|
||||
assert "captcha" in ck_relogin.MANUAL_KINDS
|
||||
|
||||
def test_email_code_is_retryable(self):
|
||||
assert (
|
||||
ck_relogin.classify_failure(
|
||||
"重新登录失败: 提交验证码失败: 邮箱验证码错误,请重新输入"
|
||||
)
|
||||
== "email_code"
|
||||
)
|
||||
|
||||
def test_interrupted_is_retryable(self):
|
||||
assert (
|
||||
ck_relogin.classify_failure("登录已中断(服务重启),旧 Cookie 已保留")
|
||||
== "interrupted"
|
||||
)
|
||||
assert (
|
||||
ck_relogin.classify_failure("重新登录已停止,旧 Cookie 已保留")
|
||||
== "interrupted"
|
||||
)
|
||||
|
||||
def test_credential_is_manual(self):
|
||||
assert (
|
||||
ck_relogin.classify_failure("重新登录失败: 账号缺少密码或邮箱")
|
||||
== "credential"
|
||||
)
|
||||
assert "credential" in ck_relogin.MANUAL_KINDS
|
||||
|
||||
def test_unknown_defaults_to_retryable(self):
|
||||
"""未知文案按可重试处理:有每日上限兜底,别把可能只是抖动的账号推给人工。"""
|
||||
assert ck_relogin.classify_failure("某种没见过的报错") == "network"
|
||||
assert ck_relogin.classify_failure("") == "network"
|
||||
|
||||
|
||||
class TestBackoff(_Base):
|
||||
def test_ladder_is_escalating(self):
|
||||
now = datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
|
||||
first = ck_relogin._next_retry_at("email_code", 1, now) - now
|
||||
second = ck_relogin._next_retry_at("email_code", 2, now) - now
|
||||
third = ck_relogin._next_retry_at("email_code", 3, now) - now
|
||||
assert first == timedelta(minutes=60)
|
||||
assert second == timedelta(minutes=180)
|
||||
assert third == timedelta(minutes=720)
|
||||
|
||||
def test_quota_goes_to_next_day_with_jitter(self):
|
||||
now = datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
|
||||
nxt = ck_relogin._next_retry_at("email_quota", 1, now)
|
||||
assert nxt.date() == (now + timedelta(days=1)).date()
|
||||
assert nxt.hour == 0
|
||||
assert 0 <= nxt.minute <= ck_relogin.QUOTA_JITTER_MINUTES
|
||||
|
||||
|
||||
class TestSelection(_Base):
|
||||
def _ids(self, job):
|
||||
now = datetime.now(UTC)
|
||||
return [
|
||||
t.id
|
||||
for t in ck_relogin.build_select_query(
|
||||
self.session, job, now, max_attempts=2
|
||||
).all()
|
||||
]
|
||||
|
||||
def test_picks_invalid_with_expired_backoff(self):
|
||||
job = self.job()
|
||||
ready = self.make_task("ready")
|
||||
assert self._ids(job) == [ready.id]
|
||||
|
||||
def test_skips_valid_and_empty_cookie_and_opted_out(self):
|
||||
job = self.job()
|
||||
keep = self.make_task("keep")
|
||||
self.make_task("valid", ck_check_status="valid")
|
||||
self.make_task("nocookie", cookie="")
|
||||
self.make_task("optedout", auto_managed=False)
|
||||
assert self._ids(job) == [keep.id]
|
||||
|
||||
def test_skips_inflight_attempt(self):
|
||||
job = self.job()
|
||||
keep = self.make_task("keep")
|
||||
self.make_task("running", attempt_status="running")
|
||||
self.make_task("pending", attempt_status="pending")
|
||||
assert self._ids(job) == [keep.id]
|
||||
|
||||
def test_respects_backoff_window(self):
|
||||
job = self.job()
|
||||
due = self.make_task(
|
||||
"due", relogin_next_at=datetime.now(UTC) - timedelta(minutes=1)
|
||||
)
|
||||
self.make_task("later", relogin_next_at=datetime.now(UTC) + timedelta(hours=3))
|
||||
assert self._ids(job) == [due.id]
|
||||
|
||||
def test_skips_when_attempts_exhausted(self):
|
||||
job = self.job()
|
||||
keep = self.make_task("keep")
|
||||
self.make_task("exhausted", relogin_attempts=2)
|
||||
assert self._ids(job) == [keep.id]
|
||||
|
||||
def test_never_retries_manual_kinds(self):
|
||||
"""已判定极验/凭证问题的账号,绝不能再次自动重登。"""
|
||||
job = self.job()
|
||||
keep = self.make_task("keep")
|
||||
self.make_task("captcha", relogin_failure_kind="captcha")
|
||||
self.make_task("credential", relogin_failure_kind="credential")
|
||||
assert self._ids(job) == [keep.id]
|
||||
|
||||
def test_retryable_kinds_stay_eligible(self):
|
||||
job = self.job()
|
||||
code = self.make_task("code", relogin_failure_kind="email_code")
|
||||
net = self.make_task("net", relogin_failure_kind="network")
|
||||
assert sorted(self._ids(job)) == sorted([code.id, net.id])
|
||||
|
||||
def test_generated_sql_is_mysql_compatible(self):
|
||||
from sqlalchemy.dialects import mysql
|
||||
|
||||
query = ck_relogin.build_select_query(
|
||||
self.session, self.job(), datetime.now(UTC), max_attempts=2
|
||||
)
|
||||
sql = str(query.statement.compile(dialect=mysql.dialect())).upper()
|
||||
assert "NULLS FIRST" not in sql and "NULLS LAST" not in sql
|
||||
|
||||
def test_batch_size_caps_the_round(self):
|
||||
job = self.job(batch_size=3)
|
||||
for index in range(6):
|
||||
self.make_task(f"a{index}")
|
||||
assert len(self._ids(job)) == 3
|
||||
|
||||
|
||||
class TestSettlement(_Base):
|
||||
"""结算:成功清零;失败按分型决定重试还是转人工。"""
|
||||
|
||||
def _settle(self, tasks, *, max_attempts=2):
|
||||
now = datetime.now(UTC)
|
||||
fresh = {t.id: t for t in tasks}
|
||||
counters = ck_relogin.settle_results(
|
||||
fresh, [t.id for t in tasks], now=now, max_attempts=max_attempts
|
||||
)
|
||||
self.session.commit()
|
||||
return counters, now
|
||||
|
||||
def test_success_resets_state(self):
|
||||
task = self.make_task(
|
||||
"ok",
|
||||
attempt_status="success",
|
||||
relogin_attempts=1,
|
||||
relogin_failure_kind="email_code",
|
||||
relogin_last_error="旧的报错",
|
||||
relogin_next_at=datetime.now(UTC) + timedelta(hours=1),
|
||||
)
|
||||
counters, _ = self._settle([task])
|
||||
self.session.refresh(task)
|
||||
assert counters["valid"] == 1 and counters["invalid"] == 0
|
||||
assert task.relogin_attempts == 0
|
||||
assert task.relogin_next_at is None
|
||||
assert task.relogin_failure_kind == ""
|
||||
assert task.relogin_last_error == ""
|
||||
|
||||
def test_retryable_failure_schedules_next_attempt(self):
|
||||
task = self.make_task(
|
||||
"retry",
|
||||
attempt_status="failed",
|
||||
attempt_message="等待验证码超时(旧 Cookie 已保留)",
|
||||
)
|
||||
counters, now = self._settle([task])
|
||||
self.session.refresh(task)
|
||||
assert counters["invalid"] == 1 and counters["retry"] == 1
|
||||
assert task.relogin_failure_kind == "email_code"
|
||||
assert task.relogin_attempts == 1
|
||||
assert task.relogin_next_at is not None and task.relogin_next_at > now
|
||||
assert "旧 Cookie" in task.relogin_last_error
|
||||
|
||||
def test_captcha_goes_to_manual_without_schedule(self):
|
||||
task = self.make_task(
|
||||
"cap", attempt_status="failed", attempt_message="极验验证失败: slide"
|
||||
)
|
||||
counters, _ = self._settle([task])
|
||||
self.session.refresh(task)
|
||||
assert counters["manual"] == 1 and counters["retry"] == 0
|
||||
assert task.relogin_failure_kind == "captcha"
|
||||
assert task.relogin_next_at is None # 不再自动排期
|
||||
|
||||
def test_quota_backs_off_to_next_day(self):
|
||||
task = self.make_task(
|
||||
"quota",
|
||||
attempt_status="failed",
|
||||
attempt_message="您的邮箱验证码发送次数已达上限,请改天再试!",
|
||||
)
|
||||
counters, now = self._settle([task])
|
||||
self.session.refresh(task)
|
||||
assert counters["email_quota"] == 1 and counters["retry"] == 1
|
||||
assert task.relogin_next_at.date() == (now + timedelta(days=1)).date()
|
||||
|
||||
def test_attempts_exhausted_stops_retrying(self):
|
||||
task = self.make_task(
|
||||
"used",
|
||||
attempt_status="failed",
|
||||
attempt_message="等待验证码超时",
|
||||
relogin_attempts=1,
|
||||
)
|
||||
counters, _ = self._settle([task], max_attempts=2)
|
||||
self.session.refresh(task)
|
||||
assert counters["manual"] == 1 and counters["retry"] == 0
|
||||
assert task.relogin_next_at is None
|
||||
|
||||
def test_settlement_never_touches_cookie(self):
|
||||
task = self.make_task(
|
||||
"keepck", attempt_status="failed", attempt_message="极验验证失败: slide"
|
||||
)
|
||||
before = (task.cookie, task.status)
|
||||
self._settle([task])
|
||||
self.session.refresh(task)
|
||||
assert (task.cookie, task.status) == before
|
||||
|
||||
|
||||
class TestManualQueueApi(_Base):
|
||||
"""待人工处理队列:只列自动重登救不了的,按原因分组。"""
|
||||
|
||||
def _queue(self):
|
||||
from web.backend.routers import automation as api
|
||||
|
||||
return api.manual_queue(limit=20, db=self.session, current=self.admin)
|
||||
|
||||
def test_groups_manual_kinds_only(self):
|
||||
captcha = self.make_task(
|
||||
"cap",
|
||||
attempt_status="failed",
|
||||
attempt_message="极验验证失败: slide",
|
||||
relogin_failure_kind="captcha",
|
||||
relogin_attempts=1,
|
||||
relogin_last_error="极验验证失败: slide",
|
||||
)
|
||||
self.make_task(
|
||||
"cred",
|
||||
attempt_status="failed",
|
||||
attempt_message="账号缺少密码或邮箱",
|
||||
relogin_failure_kind="credential",
|
||||
relogin_attempts=1,
|
||||
relogin_last_error="账号缺少密码或邮箱",
|
||||
)
|
||||
# 可自动重试的不该出现在人工队列里
|
||||
self.make_task(
|
||||
"retryable",
|
||||
attempt_status="failed",
|
||||
attempt_message="等待验证码超时",
|
||||
relogin_failure_kind="email_code",
|
||||
relogin_attempts=1,
|
||||
relogin_next_at=datetime.now(UTC) + timedelta(hours=1),
|
||||
relogin_last_error="等待验证码超时",
|
||||
)
|
||||
payload = self._queue()
|
||||
kinds = [group["kind"] for group in payload["groups"]]
|
||||
assert sorted(kinds) == ["captcha", "credential"]
|
||||
assert payload["total"] == 2
|
||||
captcha_group = next(g for g in payload["groups"] if g["kind"] == "captcha")
|
||||
assert captcha_group["count"] == 1
|
||||
assert captcha_group["samples"][0]["task_id"] == captcha.id
|
||||
assert "极验" in captcha_group["label"]
|
||||
|
||||
def test_exhausted_retries_show_up_as_manual(self):
|
||||
"""次数用尽的(next_run_at 已清空)也要冒出来,否则会静默卡住。"""
|
||||
self.make_task(
|
||||
"used",
|
||||
attempt_status="failed",
|
||||
attempt_message="等待验证码超时",
|
||||
relogin_failure_kind="email_code",
|
||||
relogin_attempts=2,
|
||||
relogin_next_at=None,
|
||||
relogin_last_error="等待验证码超时",
|
||||
)
|
||||
payload = self._queue()
|
||||
assert payload["total"] == 1
|
||||
assert "重试次数用尽" in payload["groups"][0]["label"]
|
||||
|
||||
def test_empty_queue(self):
|
||||
payload = self._queue()
|
||||
assert payload["total"] == 0 and payload["groups"] == []
|
||||
@@ -156,4 +156,4 @@ def test_solver_sms_flow():
|
||||
mock_submit.assert_called_once()
|
||||
verify_url, verify_payload = mock_submit.call_args[0]
|
||||
assert "verify-sms-code" in verify_url
|
||||
assert verify_payload["data"]["smsCode"] == "654321".encode().hex()
|
||||
assert verify_payload["data"]["smsCode"] == b"654321".hex()
|
||||
|
||||
@@ -22,7 +22,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
||||
PROJECT_ROOT = TESTS_DIR.parent
|
||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||
|
||||
HEAD_REVISION = "20261002_0037"
|
||||
HEAD_REVISION = "20261002_0038"
|
||||
|
||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||
EXTRA_INDEXES = (
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
"""回归:时间列统一走 ``UTCDateTime`` —— 读出来必须带时区,写进去必须存 UTC。
|
||||
|
||||
背景:库里存的是 naive UTC,读出来也是裸时间,于是每一处比较/输出都要自己记得
|
||||
补时区。项目里因此散了三份 ``_as_utc`` 和一堆 ``replace(tzinfo=UTC)``,还踩过一次
|
||||
|
||||
TypeError: can't compare offset-naive and offset-aware datetimes
|
||||
|
||||
(P1a 的 CK 巡检排下一轮时间时炸的)。现在把边界收在 ``UTCDateTime``:
|
||||
写时 aware→UTC 裸值、naive 视为 UTC;读时一律补 UTC 时区。
|
||||
|
||||
这组测试盯三件事:读出来是 aware、能和 ``datetime.now(UTC)`` 直接比、写进去
|
||||
落的是 UTC 而不是本地时间。
|
||||
"""
|
||||
|
||||
from datetime import UTC, datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import create_engine, text
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
|
||||
from web.backend.database import Base, UTCDateTime
|
||||
from web.backend.models import AutomationRun, LoginTask
|
||||
|
||||
|
||||
class TestUtcDateTime:
|
||||
def setup_method(self):
|
||||
self.engine = create_engine("sqlite://")
|
||||
Base.metadata.create_all(self.engine)
|
||||
self.session = sessionmaker(bind=self.engine)()
|
||||
|
||||
def teardown_method(self):
|
||||
self.session.close()
|
||||
|
||||
def _row(self, started_at):
|
||||
self.session.add(
|
||||
AutomationRun(job_key="k", started_at=started_at, status="success")
|
||||
)
|
||||
self.session.commit()
|
||||
return self.session.query(AutomationRun).one()
|
||||
|
||||
def test_read_back_is_timezone_aware(self):
|
||||
row = self._row(datetime(2026, 10, 2, 12, 0, tzinfo=UTC))
|
||||
assert row.started_at.tzinfo is not None
|
||||
assert row.started_at.utcoffset() == timedelta(0)
|
||||
|
||||
def test_read_back_value_can_compare_with_now(self):
|
||||
"""这条就是当初炸掉的写法:库里的时间直接和 datetime.now(UTC) 比。"""
|
||||
row = self._row(datetime.now(UTC) - timedelta(minutes=1))
|
||||
assert row.started_at < datetime.now(UTC) # 不再 TypeError
|
||||
|
||||
def test_write_converts_local_aware_to_utc(self):
|
||||
"""带 +08:00 的时间要按 UTC 落库,不能把本地壁钟直接存进去。"""
|
||||
local = datetime(2026, 10, 2, 20, 0, tzinfo=timezone(timedelta(hours=8)))
|
||||
row = self._row(local)
|
||||
assert row.started_at == datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
|
||||
raw = self.session.execute(
|
||||
text("SELECT started_at FROM automation_runs")
|
||||
).scalar()
|
||||
assert str(raw).startswith("2026-10-02 12:00")
|
||||
|
||||
def test_naive_write_is_treated_as_utc(self):
|
||||
"""库里读出来的裸值再写回去(常见于搬迁/复制)不能被当成本地时间再减 8 小时。"""
|
||||
naive_utc = datetime(2026, 10, 2, 12, 0) # noqa: DTZ001 刻意构造裸 UTC
|
||||
row = self._row(naive_utc)
|
||||
assert row.started_at == datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
|
||||
|
||||
def test_none_stays_none(self):
|
||||
assert UTCDateTime().process_bind_param(None, None) is None
|
||||
assert UTCDateTime().process_result_value(None, None) is None
|
||||
|
||||
def test_all_model_datetime_columns_use_utc_type(self):
|
||||
"""新增时间列若忘了用 UTCDateTime,这里直接失败。"""
|
||||
offenders = []
|
||||
for table in Base.metadata.sorted_tables:
|
||||
for column in table.columns:
|
||||
if isinstance(column.type, UTCDateTime):
|
||||
continue
|
||||
if str(column.type).upper().startswith("DATETIME"):
|
||||
offenders.append(f"{table.name}.{column.name}")
|
||||
assert not offenders, f"这些时间列没用 UTCDateTime: {offenders}"
|
||||
|
||||
def test_login_task_attempt_at_round_trips_as_utc(self):
|
||||
"""真实模型抽查:写 aware、读 aware、能直接比较。"""
|
||||
task = LoginTask(
|
||||
batch_id="b",
|
||||
account_id=1,
|
||||
created_by=1,
|
||||
attempt_at=datetime(2026, 10, 2, 12, 0, tzinfo=UTC),
|
||||
)
|
||||
self.session.add(task)
|
||||
self.session.commit()
|
||||
self.session.refresh(task)
|
||||
assert task.attempt_at == datetime(2026, 10, 2, 12, 0, tzinfo=UTC)
|
||||
# 模型侧保证 aware,所以业务代码可以直接比较
|
||||
assert task.attempt_at < datetime.now(UTC)
|
||||
+38
-1
@@ -1,11 +1,13 @@
|
||||
"""数据库引擎与会话管理"""
|
||||
|
||||
import os
|
||||
from datetime import UTC, datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote_plus
|
||||
|
||||
from sqlalchemy import create_engine, event
|
||||
from sqlalchemy import DateTime, create_engine, event
|
||||
from sqlalchemy.orm import declarative_base, sessionmaker
|
||||
from sqlalchemy.types import TypeDecorator
|
||||
|
||||
PROJECT_ROOT = Path(__file__).resolve().parents[2]
|
||||
|
||||
@@ -86,6 +88,41 @@ SessionLocal = sessionmaker(bind=engine, autocommit=False, autoflush=False)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class UTCDateTime(TypeDecorator):
|
||||
"""时间列统一走这里:**库里存 naive UTC,Python 侧永远是 tz-aware UTC**。
|
||||
|
||||
之前是全靠约定:写入用 ``datetime.now(UTC)``(MySQL 绑定参数会丢掉 tzinfo,
|
||||
落库成 UTC 裸值),读出是裸值,谁要比较或输出就得自己记得补时区 —— 项目里
|
||||
因此散了三份 ``_as_utc`` 和一堆 ``replace(tzinfo=UTC)``,还踩过一次
|
||||
``TypeError: can't compare offset-naive and offset-aware datetimes``。
|
||||
|
||||
这个装饰器把边界收在一处:
|
||||
|
||||
- 写:aware → 转 UTC 后去掉 tzinfo;naive → 视为已是 UTC,原样存;
|
||||
- 读:一律补上 UTC 时区。
|
||||
|
||||
于是模型上的时间字段永远不会是裸时间,比较、相减、序列化都不必再各自处理。
|
||||
底层 DDL 仍是 DATETIME(``impl`` 不变),**不需要迁移**。
|
||||
"""
|
||||
|
||||
impl = DateTime
|
||||
cache_ok = True
|
||||
|
||||
def process_bind_param(self, value: datetime | None, dialect):
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
return value
|
||||
return value.astimezone(UTC).replace(tzinfo=None)
|
||||
|
||||
def process_result_value(self, value: datetime | None, dialect):
|
||||
if value is None:
|
||||
return None
|
||||
if value.tzinfo is None:
|
||||
return value.replace(tzinfo=UTC)
|
||||
return value.astimezone(UTC)
|
||||
|
||||
|
||||
def get_db():
|
||||
"""FastAPI 依赖:提供数据库会话,请求结束自动关闭。"""
|
||||
db = SessionLocal()
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""登录记录增加自动重登的失败分型字段。
|
||||
|
||||
P1b 的自动重登不能把「失败」笼统对待:线上 415 个失败里,极验滑块(144)与
|
||||
凭证问题必须转人工,而取码失败(144)与中断(121)其实可自动重试 —— 不分型
|
||||
就会把 265 个可救名额一起推给人工。
|
||||
|
||||
这个字段落分型结果,供作业决定「继续退避重试」还是「转人工」;页面也按它分组
|
||||
展示待处理项。不要用 attempt_message 做字符串匹配:文案一改就失效。
|
||||
"""
|
||||
|
||||
from collections.abc import Sequence
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "20261002_0038"
|
||||
down_revision: str | None = "20261002_0037"
|
||||
branch_labels: str | Sequence[str] | None = None
|
||||
depends_on: str | Sequence[str] | None = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
columns = {item["name"] for item in sa.inspect(bind).get_columns("login_tasks")}
|
||||
if "relogin_failure_kind" not in columns:
|
||||
op.add_column(
|
||||
"login_tasks",
|
||||
sa.Column(
|
||||
"relogin_failure_kind",
|
||||
sa.String(length=16),
|
||||
nullable=False,
|
||||
server_default="",
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
bind = op.get_bind()
|
||||
columns = {item["name"] for item in sa.inspect(bind).get_columns("login_tasks")}
|
||||
if "relogin_failure_kind" in columns:
|
||||
op.drop_column("login_tasks", "relogin_failure_kind")
|
||||
+54
-46
@@ -7,7 +7,6 @@ from datetime import UTC, datetime
|
||||
from sqlalchemy import (
|
||||
JSON,
|
||||
Boolean,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Integer,
|
||||
String,
|
||||
@@ -17,7 +16,7 @@ from sqlalchemy import (
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
|
||||
from .crypto_storage import EncryptedText
|
||||
from .database import Base
|
||||
from .database import Base, UTCDateTime
|
||||
from .huya_defaults import (
|
||||
HUYA_DEFAULT_BIND_ACT_ID,
|
||||
HUYA_DEFAULT_OUTER_ACT_ID,
|
||||
@@ -50,12 +49,12 @@ class User(Base):
|
||||
custom_permissions: Mapped[list[str] | None] = mapped_column(
|
||||
JSON, nullable=True, comment="自定义权限列表,null表示使用角色默认权限"
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
deleted_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime, nullable=True, index=True
|
||||
UTCDateTime, nullable=True, index=True
|
||||
)
|
||||
deleted_username: Mapped[str] = mapped_column(String(64), default="")
|
||||
|
||||
@@ -121,9 +120,9 @@ class Account(Base):
|
||||
xpd_balance: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
xpd_fragments: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
xpd_bind_status: Mapped[str] = mapped_column(String(32), default="")
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
assigned_user: Mapped[User | None] = relationship(
|
||||
@@ -153,8 +152,8 @@ class LoginTask(Base):
|
||||
cookie: Mapped[str] = mapped_column(EncryptedText(), default="")
|
||||
message: Mapped[str] = mapped_column(String(512), default="")
|
||||
created_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
# Cookie 有效性检测结果(持久化,刷新不丢失)
|
||||
ck_check_status: Mapped[str] = mapped_column(
|
||||
String(16), default=""
|
||||
@@ -162,7 +161,7 @@ class LoginTask(Base):
|
||||
ck_check_result: Mapped[dict | None] = mapped_column(
|
||||
JSON, nullable=True
|
||||
) # {fish_ball, nickname, level, message}
|
||||
ck_checked_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
ck_checked_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
# 最近一次登录尝试的状态。批次只写 attempt_*,只有登录成功才会把新 CK
|
||||
# 写回 status/cookie/message,因此停止、失败、进程重启都不会破坏已有 CK。
|
||||
attempt_status: Mapped[str] = mapped_column(
|
||||
@@ -174,15 +173,20 @@ class LoginTask(Base):
|
||||
attempt_batch_id: Mapped[str] = mapped_column(
|
||||
String(64), default="", server_default=""
|
||||
)
|
||||
attempt_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
attempt_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
# 自动重登(P1b)用的退避状态。P1a 的巡检不碰这几个字段。
|
||||
relogin_attempts: Mapped[int] = mapped_column(
|
||||
Integer, default=0, server_default="0"
|
||||
) # 连续重登尝试次数,成功即清零
|
||||
relogin_next_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
relogin_next_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
relogin_last_error: Mapped[str] = mapped_column(
|
||||
String(512), default="", server_default=""
|
||||
)
|
||||
# 失败分型:captcha / credential 转人工,email_code / email_quota /
|
||||
# interrupted / network 自动重试(见规划 §7.4.3)。空 = 没失败过。
|
||||
relogin_failure_kind: Mapped[str] = mapped_column(
|
||||
String(16), default="", server_default=""
|
||||
)
|
||||
|
||||
account: Mapped[Account] = relationship("Account", back_populates="login_tasks")
|
||||
|
||||
@@ -208,8 +212,8 @@ class DouyuTask(Base):
|
||||
message: Mapped[str] = mapped_column(String(512), default="")
|
||||
result: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
created_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
|
||||
account: Mapped[Account] = relationship("Account", back_populates="douyu_tasks")
|
||||
|
||||
@@ -227,7 +231,7 @@ class DouyuWorkbenchAccount(Base):
|
||||
account_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("accounts.id"), nullable=False, index=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
@@ -247,7 +251,7 @@ class DouyuWorkbench(Base):
|
||||
)
|
||||
handbook_scope: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
@@ -288,15 +292,17 @@ class YybRechargeTask(Base):
|
||||
result: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
login_qr_data: Mapped[str] = mapped_column(EncryptedText(), default="")
|
||||
payment_qr_data: Mapped[str] = mapped_column(EncryptedText(), default="")
|
||||
payment_started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
payment_started_at: Mapped[datetime | None] = mapped_column(
|
||||
UTCDateTime, nullable=True
|
||||
)
|
||||
payment_qr_created_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime, nullable=True
|
||||
UTCDateTime, nullable=True
|
||||
)
|
||||
payment_last_checked_at: Mapped[datetime | None] = mapped_column(
|
||||
DateTime, nullable=True
|
||||
UTCDateTime, nullable=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
|
||||
|
||||
class DouyuConfig(Base):
|
||||
@@ -331,7 +337,7 @@ class DouyuConfig(Base):
|
||||
gift_id: Mapped[str] = mapped_column(String(64), default="23643")
|
||||
skin_id: Mapped[str] = mapped_column(String(64), default="2942")
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
@@ -347,7 +353,7 @@ class DouyuGoodsSnapshot(Base):
|
||||
status: Mapped[str] = mapped_column(String(32), default="")
|
||||
raw: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
@@ -365,7 +371,7 @@ class DouyuXpdGoodsSnapshot(Base):
|
||||
goods_left: Mapped[int | None] = mapped_column(Integer, nullable=True)
|
||||
raw: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
@@ -381,7 +387,7 @@ class DouyuEsportsGoodsSnapshot(Base):
|
||||
status: Mapped[str] = mapped_column(String(32), default="")
|
||||
raw: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
@@ -414,9 +420,9 @@ class HuyaAccount(Base):
|
||||
assigned_to: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id"), nullable=True, index=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
assigned_user: Mapped[User | None] = relationship(
|
||||
@@ -450,9 +456,9 @@ class HuyaRegisterBatch(Base):
|
||||
success_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
failed_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
stopped_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
started_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
|
||||
items: Mapped[list[HuyaRegisterItem]] = relationship(
|
||||
"HuyaRegisterItem", back_populates="batch", cascade="all, delete-orphan"
|
||||
@@ -487,8 +493,8 @@ class HuyaRegisterItem(Base):
|
||||
password: Mapped[str] = mapped_column(EncryptedText(), default="")
|
||||
password_changed: Mapped[bool] = mapped_column(Boolean, default=False)
|
||||
cookie: Mapped[str] = mapped_column(EncryptedText(), default="")
|
||||
started_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
started_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
|
||||
batch: Mapped[HuyaRegisterBatch] = relationship(
|
||||
"HuyaRegisterBatch", back_populates="items"
|
||||
@@ -516,7 +522,9 @@ class HuyaRegisterSuccessLog(Base):
|
||||
created_by: Mapped[int | None] = mapped_column(
|
||||
ForeignKey("users.id"), nullable=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
UTCDateTime, default=_utcnow, index=True
|
||||
)
|
||||
|
||||
|
||||
class HuyaTask(Base):
|
||||
@@ -538,8 +546,8 @@ class HuyaTask(Base):
|
||||
message: Mapped[str] = mapped_column(String(512), default="")
|
||||
result: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
created_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
|
||||
account: Mapped[HuyaAccount] = relationship("HuyaAccount", back_populates="tasks")
|
||||
|
||||
@@ -557,7 +565,7 @@ class HuyaWorkbenchAccount(Base):
|
||||
account_id: Mapped[int] = mapped_column(
|
||||
ForeignKey("huya_accounts.id"), nullable=False, index=True
|
||||
)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
|
||||
__table_args__ = (
|
||||
UniqueConstraint(
|
||||
@@ -580,7 +588,7 @@ class HuyaWorkbench(Base):
|
||||
)
|
||||
handbook_scope: Mapped[str] = mapped_column(String(16), nullable=False, index=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
__table_args__ = (
|
||||
@@ -606,7 +614,7 @@ class HuyaConfig(Base):
|
||||
String(16), default=HUYA_DEFAULT_PAY_CHANNEL
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
@@ -624,7 +632,7 @@ class HuyaGoodsSnapshot(Base):
|
||||
remain_text: Mapped[str] = mapped_column(String(64), default="")
|
||||
raw: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
@@ -648,7 +656,7 @@ class HuyaRechargeGoodsSnapshot(Base):
|
||||
task_name: Mapped[str] = mapped_column(String(256), default="")
|
||||
raw: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
@@ -684,7 +692,7 @@ class AuditLog(Base):
|
||||
detail: Mapped[str] = mapped_column(Text, default="")
|
||||
# 旧记录未标记结果时为 NULL,避免把历史操作误判成失败。
|
||||
success: Mapped[bool | None] = mapped_column(Boolean, nullable=True, index=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
|
||||
|
||||
class AutomationJob(Base):
|
||||
@@ -702,14 +710,14 @@ class AutomationJob(Base):
|
||||
batch_size: Mapped[int] = mapped_column(Integer, default=200, server_default="200")
|
||||
concurrency: Mapped[int] = mapped_column(Integer, default=5, server_default="5")
|
||||
config: Mapped[dict | None] = mapped_column(JSON, nullable=True)
|
||||
last_run_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
next_run_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
last_run_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
next_run_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
last_status: Mapped[str] = mapped_column(String(16), default="", server_default="")
|
||||
last_message: Mapped[str] = mapped_column(
|
||||
String(512), default="", server_default=""
|
||||
)
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime, default=_utcnow, onupdate=_utcnow
|
||||
UTCDateTime, default=_utcnow, onupdate=_utcnow
|
||||
)
|
||||
|
||||
|
||||
@@ -720,8 +728,8 @@ class AutomationRun(Base):
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
|
||||
job_key: Mapped[str] = mapped_column(String(64), nullable=False, index=True)
|
||||
started_at: Mapped[datetime] = mapped_column(DateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime, nullable=True)
|
||||
started_at: Mapped[datetime] = mapped_column(UTCDateTime, default=_utcnow)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(UTCDateTime, nullable=True)
|
||||
status: Mapped[str] = mapped_column(
|
||||
String(16), default="running", server_default="running"
|
||||
) # running / success / failed / skipped
|
||||
|
||||
@@ -12,11 +12,12 @@ from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import and_, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..database import get_db
|
||||
from ..deps import require_permission
|
||||
from ..models import AutomationJob, AutomationRun, User
|
||||
from ..models import Account, AutomationJob, AutomationRun, LoginTask, User
|
||||
from ..services.audit_service import record_audit
|
||||
from ..services.automation import (
|
||||
ensure_jobs,
|
||||
@@ -168,6 +169,83 @@ def run_job(
|
||||
return outcome
|
||||
|
||||
|
||||
# 失败分型 → 页面展示用的中文说明。「转人工」的两种要写清为什么,
|
||||
# 否则客服不知道该做什么。
|
||||
MANUAL_KIND_LABELS = {
|
||||
"captcha": "极验滑块:需要人工过一次验证",
|
||||
"credential": "凭证问题:需要核对账号密码 / 邮箱",
|
||||
"": "重试次数用尽:需要人工确认账号是否还可用",
|
||||
}
|
||||
|
||||
|
||||
def _manual_kind_label(kind: str) -> str:
|
||||
return MANUAL_KIND_LABELS.get(kind, f"待确认({kind})")
|
||||
|
||||
|
||||
@router.get("/manual-queue")
|
||||
def manual_queue(
|
||||
limit: int = Query(default=20, ge=1, le=100),
|
||||
db: Session = Depends(get_db),
|
||||
current: User = Depends(require_permission("automation:view")),
|
||||
):
|
||||
"""待人工处理的重登失败账号,按失败原因分组。
|
||||
|
||||
自动重登只处理「还能自动救」的失败;极验滑块、凭证问题、以及重试次数用尽的
|
||||
必须交给人 —— 这个接口就是那份清单(规划 §7.4.6)。
|
||||
"""
|
||||
from ..services.automation.jobs.ck_relogin import MANUAL_KINDS
|
||||
|
||||
# 转人工 = 分型属于需人工,或者次数用尽(next_run_at 已清空且失败过)。
|
||||
manual_filter = or_(
|
||||
LoginTask.relogin_failure_kind.in_(tuple(MANUAL_KINDS)),
|
||||
and_(
|
||||
LoginTask.relogin_last_error != "",
|
||||
LoginTask.relogin_next_at.is_(None),
|
||||
LoginTask.relogin_attempts > 0,
|
||||
),
|
||||
)
|
||||
rows = (
|
||||
db.query(LoginTask, Account.username)
|
||||
.join(Account, LoginTask.account_id == Account.id)
|
||||
.filter(LoginTask.ck_check_status == "invalid")
|
||||
.filter(LoginTask.relogin_failure_kind != "")
|
||||
.filter(manual_filter)
|
||||
.order_by(LoginTask.attempt_at.desc(), LoginTask.id.desc())
|
||||
.all()
|
||||
)
|
||||
grouped: dict[str, dict] = {}
|
||||
for task, username in rows:
|
||||
kind = task.relogin_failure_kind or ""
|
||||
# 可重试的类型却已经没有下次排期 = 次数用尽,单独成组。
|
||||
# 否则它会混进「验证码失败」组里,客服看不出「这个已经不会再自动试了」。
|
||||
if kind not in MANUAL_KINDS:
|
||||
kind = ""
|
||||
group = grouped.setdefault(
|
||||
kind,
|
||||
{
|
||||
"kind": kind,
|
||||
"label": _manual_kind_label(kind),
|
||||
"count": 0,
|
||||
"samples": [],
|
||||
},
|
||||
)
|
||||
group["count"] += 1
|
||||
if len(group["samples"]) < limit:
|
||||
group["samples"].append(
|
||||
{
|
||||
"task_id": task.id,
|
||||
"account_username": username,
|
||||
"relogin_attempts": int(task.relogin_attempts or 0),
|
||||
"last_error": task.relogin_last_error or task.attempt_message or "",
|
||||
"attempt_at": task.attempt_at.isoformat()
|
||||
if task.attempt_at
|
||||
else None,
|
||||
}
|
||||
)
|
||||
groups = sorted(grouped.values(), key=lambda item: -item["count"])
|
||||
return {"total": len(rows), "groups": groups}
|
||||
|
||||
|
||||
@router.get("/runs")
|
||||
def list_runs(
|
||||
job_key: str | None = Query(default=None),
|
||||
|
||||
@@ -8,6 +8,8 @@ from __future__ import annotations
|
||||
|
||||
from .jobs.ck_health import JOB_KEY as CK_HEALTH_KEY
|
||||
from .jobs.ck_health import run_ck_health
|
||||
from .jobs.ck_relogin import JOB_KEY as CK_RELOGIN_KEY
|
||||
from .jobs.ck_relogin import run_ck_relogin
|
||||
from .scheduler import (
|
||||
JobSpec,
|
||||
automation_enabled,
|
||||
@@ -24,6 +26,7 @@ from .scheduler import (
|
||||
|
||||
__all__ = [
|
||||
"CK_HEALTH_KEY",
|
||||
"CK_RELOGIN_KEY",
|
||||
"JobSpec",
|
||||
"automation_enabled",
|
||||
"ensure_jobs",
|
||||
@@ -32,6 +35,7 @@ __all__ = [
|
||||
"registered_jobs",
|
||||
"reset_registry",
|
||||
"run_ck_health",
|
||||
"run_ck_relogin",
|
||||
"run_due_jobs",
|
||||
"run_job_now",
|
||||
"scheduler_status",
|
||||
@@ -42,6 +46,18 @@ __all__ = [
|
||||
|
||||
def register_default_jobs() -> None:
|
||||
"""登记内置作业(幂等)。"""
|
||||
register_job(
|
||||
JobSpec(
|
||||
key=CK_RELOGIN_KEY,
|
||||
title="CK 自动重登",
|
||||
# interval_seconds 同样是「同一行多久重试一次」的兜底(真实节奏由
|
||||
# relogin_next_at 的退避表决定);批次小、跑得慢,单轮 10 条。
|
||||
interval_seconds=6 * 3600,
|
||||
batch_size=10,
|
||||
concurrency=3,
|
||||
run=run_ck_relogin,
|
||||
)
|
||||
)
|
||||
register_job(
|
||||
JobSpec(
|
||||
key=CK_HEALTH_KEY,
|
||||
|
||||
@@ -23,6 +23,41 @@ from ...douyu_service import cookie_operable_filter
|
||||
JOB_KEY = "ck_health"
|
||||
FLUSH_EVERY = 25
|
||||
|
||||
# 斗鱼明确表示「这个 CK 不能用」的说法。只有命中这些才算真的失效。
|
||||
AUTH_FAILURE_MARKERS = (
|
||||
"登陆异常",
|
||||
"登录异常",
|
||||
"未登录",
|
||||
"登陆失效",
|
||||
"登录失效",
|
||||
"重新登陆",
|
||||
"重新登录",
|
||||
"账户登陆",
|
||||
)
|
||||
|
||||
# 非鉴权类失败(网络超时、响应异常、被判风控)占比超过它就自动暂停作业。
|
||||
# 这类失败说明「我们查不到」,不是「这个 CK 失效了」;如果不加区分地写
|
||||
# invalid,斗鱼接口抖动一小时就能把上千个好账号标成失效,客服会误判成
|
||||
# CK 大面积挂掉。
|
||||
ERROR_PAUSE_RATIO = 0.3
|
||||
ERROR_PAUSE_MIN_SCANNED = 20
|
||||
|
||||
|
||||
def classify_result(result: dict[str, Any]) -> str:
|
||||
"""把检测结果分成三类:valid / invalid(真失效)/ error(查不到)。
|
||||
|
||||
- ``valid``:斗鱼两个接口都通过;
|
||||
- ``invalid``:斗鱼明确回复「未登录 / 登陆异常」之类的鉴权失败;
|
||||
- ``error``:其余失败(请求失败、超时、响应异常、未知结构)——
|
||||
**不能当成失效**,也不覆盖该行原来的结论。
|
||||
"""
|
||||
if result.get("valid"):
|
||||
return "valid"
|
||||
message = str(result.get("message") or "")
|
||||
if any(marker in message for marker in AUTH_FAILURE_MARKERS):
|
||||
return "invalid"
|
||||
return "error"
|
||||
|
||||
|
||||
def build_select_query(db: Session, job: AutomationJob, now: datetime):
|
||||
"""构造本轮要检测记录的查询(与取行分开,便于按方言编译做回归)。
|
||||
@@ -88,22 +123,27 @@ def run_ck_health(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
results[task.id] = future.result()
|
||||
|
||||
# 只写检测结果三件套;cookie / status / attempt_* 一律不动。
|
||||
valid = invalid = 0
|
||||
valid = invalid = errors = 0
|
||||
for index, task in enumerate(tasks, start=1):
|
||||
result = results.get(task.id)
|
||||
if result is None:
|
||||
continue
|
||||
is_valid = bool(result.get("valid"))
|
||||
if is_valid:
|
||||
verdict = classify_result(result)
|
||||
if verdict == "valid":
|
||||
valid += 1
|
||||
else:
|
||||
elif verdict == "invalid":
|
||||
invalid += 1
|
||||
task.ck_check_status = "valid" if is_valid else "invalid"
|
||||
else:
|
||||
errors += 1
|
||||
# error 时保留该行原来的结论:查不到不等于失效,宁可维持上一次判断。
|
||||
if verdict != "error":
|
||||
task.ck_check_status = verdict
|
||||
task.ck_check_result = {
|
||||
"fish_ball": result.get("fish_ball"),
|
||||
"nickname": result.get("nickname"),
|
||||
"level": result.get("level"),
|
||||
"message": result.get("message", ""),
|
||||
"verdict": verdict,
|
||||
}
|
||||
task.ck_checked_at = now
|
||||
if index % FLUSH_EVERY == 0:
|
||||
@@ -125,12 +165,30 @@ def run_ck_health(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
)
|
||||
.count()
|
||||
)
|
||||
error_ratio = errors / len(tasks) if tasks else 0.0
|
||||
paused = False
|
||||
if errors >= ERROR_PAUSE_MIN_SCANNED and error_ratio > ERROR_PAUSE_RATIO:
|
||||
# 大面积「查不到」通常是斗鱼接口抖动或被风控,继续跑只会污染更多账号。
|
||||
job.enabled = False
|
||||
job.updated_at = datetime.now(UTC)
|
||||
paused = True
|
||||
|
||||
message = f"本轮检测 {len(tasks)} 条,剩余待检 {remaining} 条"
|
||||
if errors:
|
||||
message += f";非鉴权类失败 {errors} 条({error_ratio:.0%})"
|
||||
if paused:
|
||||
message += ";失败占比过高,已自动暂停作业"
|
||||
return {
|
||||
"scanned": len(tasks),
|
||||
"valid": valid,
|
||||
"invalid": invalid,
|
||||
"skipped": 0,
|
||||
"skipped": errors,
|
||||
"message": message,
|
||||
"detail": {"remaining": remaining, "concurrency": concurrency},
|
||||
"detail": {
|
||||
"remaining": remaining,
|
||||
"concurrency": concurrency,
|
||||
"errors": errors,
|
||||
"error_ratio": round(error_ratio, 4),
|
||||
"paused": paused,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -0,0 +1,274 @@
|
||||
"""CK 自动重登作业(P1b)。
|
||||
|
||||
和巡检(P1a)是一对:巡检只产出「谁失效了」的清单,本作业负责把能救的救回来。
|
||||
线上实测(2026-10-02)20 个失效账号重登 **20/20 成功** —— 失效是会话级过期,
|
||||
不是凭证问题。
|
||||
|
||||
**核心设计:失败必须分型。** 线上数据表明 415 个重登失败里只有 35% 是真正需要
|
||||
人工的(极验滑块),另外 64%(取码失败 + 重启中断)其实可自动重试;不分型就会
|
||||
把可救名额一起推给人工。分型结果落 ``login_tasks.relogin_failure_kind``。
|
||||
|
||||
本作业**默认关闭**,且按规划 §7.4.7 分三段上线(小规模实测已完成 → 限量 → 全量)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import random
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ....database import SessionLocal
|
||||
from ....models import Account, AutomationJob, LoginTask, User
|
||||
from ....models import ProxyConfig as ProxyConfigModel
|
||||
from ...douyu_service import LOGIN_ATTEMPT_IN_FLIGHT_STATUSES, cookie_holding_filter
|
||||
from ...login_service import LoginBatchRunner, get_relogin_limits
|
||||
|
||||
JOB_KEY = "ck_relogin"
|
||||
|
||||
# 失败分型 → 后续动作。
|
||||
# 需要人工的:极验滑块(自动重试只会加重风控)、凭证问题(重试多少次都一样)。
|
||||
MANUAL_KINDS = frozenset({"captcha", "credential"})
|
||||
# 可自动重试的:取码失败/超时(多为邮件延迟)、中断(服务重启或人工停止)、
|
||||
# 网络异常。email_quota 单列,因为它要退避到次日而不是按小时退避。
|
||||
RETRYABLE_KINDS = frozenset({"email_code", "interrupted", "network"})
|
||||
|
||||
# 退避阶梯(分钟):1h → 3h → 12h → 24h,超出取最后一级。
|
||||
BACKOFF_MINUTES = (60, 180, 720, 1440)
|
||||
|
||||
# 自动重登时给 runner 的总时长上限。默认的 600 秒会长时间占住调度线程,
|
||||
# 自动化场景压到 240 秒:一轮跑不完的账号留着下一轮(它们本来就有退避)。
|
||||
AUTO_MAX_TOTAL_TIME = 240
|
||||
|
||||
# 邮箱配额打满后退避到次日零点,再叠加随机抖动,避免整点齐发。
|
||||
QUOTA_JITTER_MINUTES = 30
|
||||
|
||||
|
||||
def classify_failure(message: str | None) -> str:
|
||||
"""把重登失败消息映射成分型(见规划 §7.4.3)。
|
||||
|
||||
顺序很重要:「邮箱验证码发送次数已达上限」既含「验证码」也含「上限」,
|
||||
必须先在 ``email_quota`` 命中,否则会被归到可重试的 ``email_code`` 上,
|
||||
导致次日才该重试的账号被按小时反复撞配额。
|
||||
"""
|
||||
text = message or ""
|
||||
if "上限" in text or "配额" in text:
|
||||
return "email_quota"
|
||||
if "极验" in text or "验证" in text and "滑块" in text:
|
||||
return "captcha"
|
||||
if "验证码" in text:
|
||||
return "email_code"
|
||||
if "中断" in text or "已停止" in text or "任务已停止" in text:
|
||||
return "interrupted"
|
||||
if "密码" in text or "账号不存在" in text or "缺少密码或邮箱" in text:
|
||||
return "credential"
|
||||
# 请求失败/超时/连接异常,以及未知文案:都按可重试处理。
|
||||
# 宁可多给一次机会(有每日上限兜底),也不要把可能只是抖动的账号推给人工。
|
||||
return "network"
|
||||
|
||||
|
||||
def _cutoff(now: datetime) -> datetime:
|
||||
return now
|
||||
|
||||
|
||||
def build_select_query(
|
||||
db: Session,
|
||||
job: AutomationJob,
|
||||
now: datetime,
|
||||
*,
|
||||
max_attempts: int = 2,
|
||||
system_user_id: int | None = None,
|
||||
):
|
||||
"""构造本轮重登候选的查询(与取行分开,便于按方言编译做回归)。"""
|
||||
query = (
|
||||
db.query(LoginTask)
|
||||
.join(Account, LoginTask.account_id == Account.id)
|
||||
.filter(LoginTask.ck_check_status == "invalid")
|
||||
.filter(cookie_holding_filter())
|
||||
.filter(
|
||||
func.coalesce(LoginTask.attempt_status, "").notin_(
|
||||
LOGIN_ATTEMPT_IN_FLIGHT_STATUSES
|
||||
)
|
||||
)
|
||||
.filter(Account.auto_managed.is_(True))
|
||||
.filter(LoginTask.relogin_attempts < max_attempts)
|
||||
.filter(
|
||||
or_(
|
||||
LoginTask.relogin_next_at.is_(None),
|
||||
LoginTask.relogin_next_at <= _cutoff(now),
|
||||
)
|
||||
)
|
||||
)
|
||||
# 已判定需要人工的类型不再自动重试(极验/凭证)。空值用 coalesce 兜住历史行。
|
||||
query = query.filter(
|
||||
func.coalesce(LoginTask.relogin_failure_kind, "").notin_(tuple(MANUAL_KINDS))
|
||||
)
|
||||
if system_user_id is not None:
|
||||
pass # 预留:将来若需要限制到某个归属人,在这里加过滤
|
||||
return query.order_by(
|
||||
LoginTask.relogin_next_at.is_(None).desc(),
|
||||
LoginTask.relogin_next_at.asc(),
|
||||
LoginTask.id.asc(),
|
||||
).limit(max(int(job.batch_size or 0), 1))
|
||||
|
||||
|
||||
def _system_user_id(db: Session) -> int | None:
|
||||
"""自动重登要用一个真实用户身份落 ``created_by``(外键非空,且便于追责)。
|
||||
|
||||
取最早创建的超管作为「系统操作人」;库是空的就返回 None,作业会跳过本轮。
|
||||
"""
|
||||
row = (
|
||||
db.query(User.id)
|
||||
.filter(User.role == "super_admin")
|
||||
.order_by(User.id.asc())
|
||||
.first()
|
||||
)
|
||||
if row:
|
||||
return int(row[0])
|
||||
row = db.query(User.id).order_by(User.id.asc()).first()
|
||||
return int(row[0]) if row else None
|
||||
|
||||
|
||||
def _next_retry_at(kind: str, attempts: int, now: datetime) -> datetime:
|
||||
if kind == "email_quota":
|
||||
tomorrow = (now + timedelta(days=1)).replace(
|
||||
hour=0, minute=0, second=0, microsecond=0
|
||||
)
|
||||
return tomorrow + timedelta(minutes=random.uniform(0, QUOTA_JITTER_MINUTES))
|
||||
step = BACKOFF_MINUTES[min(max(attempts, 1), len(BACKOFF_MINUTES)) - 1]
|
||||
return now + timedelta(minutes=step)
|
||||
|
||||
|
||||
def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]:
|
||||
now = datetime.now(UTC)
|
||||
config = job.config or {}
|
||||
max_attempts = int(config.get("max_attempts_per_day", 2) or 2)
|
||||
|
||||
system_user_id = _system_user_id(db)
|
||||
if system_user_id is None:
|
||||
return {
|
||||
"scanned": 0,
|
||||
"valid": 0,
|
||||
"invalid": 0,
|
||||
"skipped": 0,
|
||||
"message": "库里没有可用用户,无法以系统身份发起重登",
|
||||
}
|
||||
|
||||
tasks = build_select_query(db, job, now, max_attempts=max_attempts).all()
|
||||
if not tasks:
|
||||
return {"scanned": 0, "valid": 0, "invalid": 0, "skipped": 0}
|
||||
|
||||
task_ids = [task.id for task in tasks]
|
||||
proxy = db.query(ProxyConfigModel).first()
|
||||
_, max_total_time = get_relogin_limits()
|
||||
|
||||
# 批次用独立会话(runner 会在自己的线程/会话里写库),跑完再回来读结果。
|
||||
runner_db = SessionLocal()
|
||||
runner = LoginBatchRunner(
|
||||
db=runner_db,
|
||||
account_ids=[],
|
||||
created_by=system_user_id,
|
||||
# 自动化要对全库生效,不受「只能操作分配给自己的账号」限制。
|
||||
creator_permissions=["login:view_all", "cookie:operate"],
|
||||
max_login_retries=int(config.get("max_login_retries", 5) or 5),
|
||||
max_total_time=min(int(max_total_time), AUTO_MAX_TOTAL_TIME),
|
||||
proxy_config=proxy,
|
||||
log_queue=None,
|
||||
loop=None,
|
||||
concurrency=max(min(int(job.concurrency or 3), 8), 1),
|
||||
mode="relogin",
|
||||
relogin_task_ids=task_ids,
|
||||
)
|
||||
batch_id = runner.batch_id
|
||||
try:
|
||||
runner.run()
|
||||
finally:
|
||||
runner_db.close()
|
||||
|
||||
# runner 用的是另一个会话,这里必须重新查,不能读旧对象。
|
||||
db.expire_all()
|
||||
fresh = {
|
||||
row.id: row
|
||||
for row in db.query(LoginTask).filter(LoginTask.id.in_(task_ids)).all()
|
||||
}
|
||||
|
||||
counters = settle_results(fresh, task_ids, now=now, max_attempts=max_attempts)
|
||||
db.commit()
|
||||
|
||||
parts = [
|
||||
f"本轮重登 {counters['scanned']} 条",
|
||||
f"成功 {counters['valid']}",
|
||||
f"失败 {counters['invalid']}",
|
||||
]
|
||||
if counters["retry"]:
|
||||
parts.append(f"待重试 {counters['retry']}")
|
||||
if counters["email_quota"]:
|
||||
parts.append(f"其中配额满 {counters['email_quota']}(退避到次日)")
|
||||
if counters["manual"]:
|
||||
parts.append(f"转人工 {counters['manual']}")
|
||||
return {
|
||||
"scanned": counters["scanned"],
|
||||
"valid": counters["valid"],
|
||||
"invalid": counters["invalid"],
|
||||
"relogin_started": counters["scanned"],
|
||||
"relogin_success": counters["valid"],
|
||||
"skipped": 0,
|
||||
"message": ",".join(parts),
|
||||
"detail": {
|
||||
"batch_id": batch_id,
|
||||
"manual": counters["manual"],
|
||||
"retry": counters["retry"],
|
||||
"email_quota": counters["email_quota"],
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def settle_results(
|
||||
fresh: dict[int, LoginTask],
|
||||
task_ids: list[int],
|
||||
*,
|
||||
now: datetime,
|
||||
max_attempts: int = 2,
|
||||
) -> dict[str, int]:
|
||||
"""批次跑完后结算:成功的清零,失败的按分型决定重试还是转人工。
|
||||
|
||||
单独抽出来是因为这段是 P1b 的核心决策逻辑,必须能脱离真实登录做单测。
|
||||
只改 ``relogin_*`` 四个字段,**不碰 CK 本体**(CK 由 runner 在成功时替换)。
|
||||
"""
|
||||
counters = {
|
||||
"scanned": len(task_ids),
|
||||
"valid": 0,
|
||||
"invalid": 0,
|
||||
"manual": 0,
|
||||
"retry": 0,
|
||||
"email_quota": 0,
|
||||
}
|
||||
for task_id in task_ids:
|
||||
task = fresh.get(task_id)
|
||||
if task is None:
|
||||
continue
|
||||
if task.attempt_status == "success":
|
||||
counters["valid"] += 1
|
||||
task.relogin_attempts = 0
|
||||
task.relogin_next_at = None
|
||||
task.relogin_failure_kind = ""
|
||||
task.relogin_last_error = ""
|
||||
continue
|
||||
|
||||
counters["invalid"] += 1
|
||||
kind = classify_failure(task.attempt_message)
|
||||
task.relogin_failure_kind = kind
|
||||
task.relogin_last_error = (task.attempt_message or "")[:500]
|
||||
task.relogin_attempts = int(task.relogin_attempts or 0) + 1
|
||||
if kind in MANUAL_KINDS or task.relogin_attempts >= max_attempts:
|
||||
# 转人工:极验/凭证问题重试无意义,次数用尽也不该无限撞。
|
||||
counters["manual"] += 1
|
||||
task.relogin_next_at = None
|
||||
continue
|
||||
if kind == "email_quota":
|
||||
counters["email_quota"] += 1
|
||||
counters["retry"] += 1
|
||||
task.relogin_next_at = _next_retry_at(kind, task.relogin_attempts, now)
|
||||
return counters
|
||||
@@ -1,18 +1,35 @@
|
||||
import api from './client';
|
||||
import api from "./client";
|
||||
import type {
|
||||
AutomationJobItem,
|
||||
AutomationManualQueue,
|
||||
AutomationJobUpdate,
|
||||
AutomationJobsResponse,
|
||||
AutomationRunOutcome,
|
||||
AutomationRunsResponse,
|
||||
} from './types';
|
||||
} from "./types";
|
||||
|
||||
export const automationApi = {
|
||||
jobs: () => api.get<AutomationJobsResponse, AutomationJobsResponse>('/automation/jobs'),
|
||||
jobs: () =>
|
||||
api.get<AutomationJobsResponse, AutomationJobsResponse>("/automation/jobs"),
|
||||
updateJob: (key: string, payload: AutomationJobUpdate) =>
|
||||
api.patch<AutomationJobItem, AutomationJobItem>(`/automation/jobs/${key}`, payload),
|
||||
api.patch<AutomationJobItem, AutomationJobItem>(
|
||||
`/automation/jobs/${key}`,
|
||||
payload,
|
||||
),
|
||||
runJob: (key: string) =>
|
||||
api.post<AutomationRunOutcome, AutomationRunOutcome>(`/automation/jobs/${key}/run`),
|
||||
api.post<AutomationRunOutcome, AutomationRunOutcome>(
|
||||
`/automation/jobs/${key}/run`,
|
||||
),
|
||||
runs: (params: { job_key?: string; limit?: number }) =>
|
||||
api.get<AutomationRunsResponse, AutomationRunsResponse>('/automation/runs', { params }),
|
||||
api.get<AutomationRunsResponse, AutomationRunsResponse>(
|
||||
"/automation/runs",
|
||||
{ params },
|
||||
),
|
||||
manualQueue: (limit = 20) =>
|
||||
api.get<AutomationManualQueue, AutomationManualQueue>(
|
||||
"/automation/manual-queue",
|
||||
{
|
||||
params: { limit },
|
||||
},
|
||||
),
|
||||
};
|
||||
|
||||
@@ -174,7 +174,7 @@ export interface YybTask {
|
||||
created_by: number;
|
||||
created_by_username?: string;
|
||||
provider: string;
|
||||
platform: 'android' | 'ios';
|
||||
platform: "android" | "ios";
|
||||
points: number | null;
|
||||
price_fen?: number | null;
|
||||
product_id: string;
|
||||
@@ -185,7 +185,10 @@ export interface YybTask {
|
||||
status: string;
|
||||
phase: string;
|
||||
message: string;
|
||||
result: { logs?: string[]; payment_status?: Record<string, unknown> | null } | null;
|
||||
result: {
|
||||
logs?: string[];
|
||||
payment_status?: Record<string, unknown> | null;
|
||||
} | null;
|
||||
login_qr_data?: string;
|
||||
login_qr_mime_type?: string;
|
||||
payment_qr_data?: string;
|
||||
@@ -198,10 +201,22 @@ export interface YybTask {
|
||||
}
|
||||
|
||||
export interface YybSelectionOptions {
|
||||
products: Array<{ points: number; product_id: string; price_fen: number; offer_id: string; name: string }>;
|
||||
products: Array<{
|
||||
points: number;
|
||||
product_id: string;
|
||||
price_fen: number;
|
||||
offer_id: string;
|
||||
name: string;
|
||||
}>;
|
||||
zones: Array<{ zone_id: string; name: string }>;
|
||||
roles: Array<{ role_id: string; name: string; ban_status: string }>;
|
||||
default_product: { points: number; product_id: string; price_fen: number; offer_id: string; name: string } | null;
|
||||
default_product: {
|
||||
points: number;
|
||||
product_id: string;
|
||||
price_fen: number;
|
||||
offer_id: string;
|
||||
name: string;
|
||||
} | null;
|
||||
default_zone: { zone_id: string; name: string } | null;
|
||||
}
|
||||
|
||||
@@ -280,7 +295,7 @@ export interface CookieOperationItem {
|
||||
ck_check_status: string;
|
||||
ck_checked_at: string | null;
|
||||
created_at: string | null;
|
||||
relogin_status: '' | 'relogin_pending' | 'relogin_running' | 'relogin_failed';
|
||||
relogin_status: "" | "relogin_pending" | "relogin_running" | "relogin_failed";
|
||||
relogin_message: string;
|
||||
relogin_batch_id: string;
|
||||
}
|
||||
@@ -379,7 +394,7 @@ export interface DouyuConfig {
|
||||
xpd_act_id: string;
|
||||
xpd_rid: string;
|
||||
gold_pay_type: number;
|
||||
gold_recharge_channel: 'wechat_qr' | 'supplier_api';
|
||||
gold_recharge_channel: "wechat_qr" | "supplier_api";
|
||||
gold_api_product_id: string;
|
||||
gold_api_account_template_name: string;
|
||||
gift_id: string;
|
||||
@@ -388,13 +403,13 @@ export interface DouyuConfig {
|
||||
}
|
||||
|
||||
export interface DouyuRechargeChannel {
|
||||
gold_recharge_channel: 'wechat_qr' | 'supplier_api';
|
||||
gold_recharge_channel: "wechat_qr" | "supplier_api";
|
||||
}
|
||||
|
||||
export interface DouyuTaskBatchRequest {
|
||||
account_ids: number[];
|
||||
task_type: string;
|
||||
handbook_scope: 'elite' | 'esports' | 'peace';
|
||||
handbook_scope: "elite" | "esports" | "peace";
|
||||
concurrency?: number;
|
||||
payload?: Record<string, unknown>;
|
||||
}
|
||||
@@ -413,7 +428,7 @@ export interface DouyuTaskItem {
|
||||
account_uid: string;
|
||||
account_nickname: string;
|
||||
task_type: string;
|
||||
handbook_scope: 'elite' | 'esports' | 'peace' | 'legacy';
|
||||
handbook_scope: "elite" | "esports" | "peace" | "legacy";
|
||||
status: string;
|
||||
message: string;
|
||||
result: Record<string, unknown> | null;
|
||||
@@ -474,10 +489,10 @@ export interface HuyaFetchSmsCodeResult {
|
||||
message: string;
|
||||
}
|
||||
/** 工作台账号集合范围: elite=精英宝典 / browser_exchange=浏览器兑换 */
|
||||
export type HuyaWorkbenchScope = 'elite' | 'browser_exchange';
|
||||
export type HuyaWorkbenchScope = "elite" | "browser_exchange";
|
||||
|
||||
/** 浏览器兑换目标页: live_room=直播间 / elite=精英宝典 / esports=电竞宝典 */
|
||||
export type HuyaExchangeTargetKey = 'live_room' | 'elite' | 'esports';
|
||||
export type HuyaExchangeTargetKey = "live_room" | "elite" | "esports";
|
||||
|
||||
export interface HuyaExchangeTargetOption {
|
||||
key: HuyaExchangeTargetKey;
|
||||
@@ -592,7 +607,7 @@ export interface HuyaAutoRegisterRequest {
|
||||
|
||||
export interface HuyaAutoRegisterRetryRequest {
|
||||
/** continue=从停止处继续(默认,不重试失败);retry_failed=只重试失败;all_unfinished=失败+未完成 */
|
||||
mode?: 'continue' | 'retry_failed' | 'all_unfinished';
|
||||
mode?: "continue" | "retry_failed" | "all_unfinished";
|
||||
concurrency?: number;
|
||||
wait_seconds?: number;
|
||||
poll_interval?: number;
|
||||
@@ -720,7 +735,7 @@ export interface HuyaConfig {
|
||||
export interface HuyaTaskBatchRequest {
|
||||
account_ids: number[];
|
||||
task_type: string;
|
||||
handbook_scope?: 'legacy' | 'elite';
|
||||
handbook_scope?: "legacy" | "elite";
|
||||
concurrency?: number;
|
||||
payload?: Record<string, unknown>;
|
||||
}
|
||||
@@ -754,7 +769,7 @@ export interface HuyaTaskItem {
|
||||
account_uid: string;
|
||||
account_nickname: string;
|
||||
task_type: string;
|
||||
handbook_scope: 'legacy' | 'elite';
|
||||
handbook_scope: "legacy" | "elite";
|
||||
status: string;
|
||||
message: string;
|
||||
result: Record<string, unknown> | null;
|
||||
@@ -891,3 +906,23 @@ export interface AutomationRunOutcome {
|
||||
invalid: number;
|
||||
skipped: number;
|
||||
}
|
||||
|
||||
export interface AutomationManualSample {
|
||||
task_id: number;
|
||||
account_username: string;
|
||||
relogin_attempts: number;
|
||||
last_error: string;
|
||||
attempt_at: string | null;
|
||||
}
|
||||
|
||||
export interface AutomationManualGroup {
|
||||
kind: string;
|
||||
label: string;
|
||||
count: number;
|
||||
samples: AutomationManualSample[];
|
||||
}
|
||||
|
||||
export interface AutomationManualQueue {
|
||||
total: number;
|
||||
groups: AutomationManualGroup[];
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
import {
|
||||
Alert,
|
||||
Button,
|
||||
@@ -12,20 +12,26 @@ import {
|
||||
Table,
|
||||
Tag,
|
||||
Typography,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
import { ReloadOutlined, ThunderboltOutlined } from '@ant-design/icons';
|
||||
import { message } from '../utils/antdMessage';
|
||||
import { getErrorMessage } from '../utils/error';
|
||||
import { automationApi, type AutomationJobItem, type AutomationRunItem } from '../api/modules';
|
||||
import { usePermissions } from '../hooks/usePermissions';
|
||||
import { formatTime } from '../utils/time';
|
||||
} from "antd";
|
||||
import type { ColumnsType } from "antd/es/table";
|
||||
import { ReloadOutlined, ThunderboltOutlined } from "@ant-design/icons";
|
||||
import { message } from "../utils/antdMessage";
|
||||
import { getErrorMessage } from "../utils/error";
|
||||
import {
|
||||
automationApi,
|
||||
type AutomationJobItem,
|
||||
type AutomationManualGroup,
|
||||
type AutomationManualSample,
|
||||
type AutomationRunItem,
|
||||
} from "../api/modules";
|
||||
import { usePermissions } from "../hooks/usePermissions";
|
||||
import { formatTime } from "../utils/time";
|
||||
|
||||
const STATUS_TAG: Record<string, { color: string; text: string }> = {
|
||||
success: { color: 'green', text: '成功' },
|
||||
failed: { color: 'red', text: '失败' },
|
||||
running: { color: 'blue', text: '执行中' },
|
||||
skipped: { color: 'default', text: '已跳过' },
|
||||
success: { color: "green", text: "成功" },
|
||||
failed: { color: "red", text: "失败" },
|
||||
running: { color: "blue", text: "执行中" },
|
||||
skipped: { color: "default", text: "已跳过" },
|
||||
};
|
||||
|
||||
function secondsToHours(seconds: number): number {
|
||||
@@ -37,12 +43,14 @@ export default function AutomationPage() {
|
||||
const [schedulerEnabled, setSchedulerEnabled] = useState(true);
|
||||
const [schedulerRunning, setSchedulerRunning] = useState(false);
|
||||
const [runs, setRuns] = useState<AutomationRunItem[]>([]);
|
||||
const [manualGroups, setManualGroups] = useState<AutomationManualGroup[]>([]);
|
||||
const [manualTotal, setManualTotal] = useState(0);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [savingKey, setSavingKey] = useState<string | null>(null);
|
||||
const [runningKey, setRunningKey] = useState<string | null>(null);
|
||||
const [forms] = Form.useForm();
|
||||
const { can } = usePermissions();
|
||||
const canManage = can('automation:manage');
|
||||
const canManage = can("automation:manage");
|
||||
|
||||
const load = useCallback(async () => {
|
||||
setLoading(true);
|
||||
@@ -53,6 +61,9 @@ export default function AutomationPage() {
|
||||
setSchedulerRunning(data.scheduler.running);
|
||||
const history = await automationApi.runs({ limit: 50 });
|
||||
setRuns(history.items);
|
||||
const manual = await automationApi.manualQueue();
|
||||
setManualGroups(manual.groups);
|
||||
setManualTotal(manual.total);
|
||||
// 统一回填表单:initialValue 只在首次渲染生效,刷新后不会跟着变。
|
||||
forms.setFieldsValue(
|
||||
Object.fromEntries(
|
||||
@@ -84,7 +95,10 @@ export default function AutomationPage() {
|
||||
try {
|
||||
await automationApi.updateJob(job.key, {
|
||||
enabled: values.enabled,
|
||||
interval_seconds: Math.max(Math.round((values.interval_hours ?? 6) * 3600), 300),
|
||||
interval_seconds: Math.max(
|
||||
Math.round((values.interval_hours ?? 6) * 3600),
|
||||
300,
|
||||
),
|
||||
batch_size: values.batch_size,
|
||||
concurrency: values.concurrency,
|
||||
});
|
||||
@@ -112,41 +126,76 @@ export default function AutomationPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const manualColumns: ColumnsType<AutomationManualSample> = [
|
||||
{ title: "记录", dataIndex: "task_id", width: 80 },
|
||||
{
|
||||
title: "账号",
|
||||
dataIndex: "account_username",
|
||||
width: 160,
|
||||
ellipsis: true,
|
||||
},
|
||||
{ title: "已重试", dataIndex: "relogin_attempts", width: 80 },
|
||||
{
|
||||
title: "失败原因",
|
||||
dataIndex: "last_error",
|
||||
ellipsis: true,
|
||||
render: (value: string) => value || "-",
|
||||
},
|
||||
{
|
||||
title: "最近尝试",
|
||||
dataIndex: "attempt_at",
|
||||
width: 160,
|
||||
render: (value: string | null) => formatTime(value),
|
||||
},
|
||||
];
|
||||
|
||||
const runColumns: ColumnsType<AutomationRunItem> = [
|
||||
{
|
||||
title: '开始时间',
|
||||
dataIndex: 'started_at',
|
||||
title: "开始时间",
|
||||
dataIndex: "started_at",
|
||||
width: 180,
|
||||
render: (value: string | null) => formatTime(value),
|
||||
},
|
||||
{
|
||||
title: '作业',
|
||||
dataIndex: 'job_key',
|
||||
title: "作业",
|
||||
dataIndex: "job_key",
|
||||
width: 120,
|
||||
},
|
||||
{
|
||||
title: '结果',
|
||||
dataIndex: 'status',
|
||||
title: "结果",
|
||||
dataIndex: "status",
|
||||
width: 90,
|
||||
render: (value: string) => {
|
||||
const tag = STATUS_TAG[value] ?? { color: 'default', text: value || '-' };
|
||||
const tag = STATUS_TAG[value] ?? {
|
||||
color: "default",
|
||||
text: value || "-",
|
||||
};
|
||||
return <Tag color={tag.color}>{tag.text}</Tag>;
|
||||
},
|
||||
},
|
||||
{ title: '扫描', dataIndex: 'scanned', width: 80 },
|
||||
{ title: '有效', dataIndex: 'valid', width: 80 },
|
||||
{ title: "扫描", dataIndex: "scanned", width: 80 },
|
||||
{ title: "有效", dataIndex: "valid", width: 80 },
|
||||
{
|
||||
title: '失效',
|
||||
dataIndex: 'invalid',
|
||||
title: "失效",
|
||||
dataIndex: "invalid",
|
||||
width: 80,
|
||||
render: (value: number) => (value > 0 ? <Typography.Text type="warning">{value}</Typography.Text> : 0),
|
||||
render: (value: number) =>
|
||||
value > 0 ? (
|
||||
<Typography.Text type="warning">{value}</Typography.Text>
|
||||
) : (
|
||||
0
|
||||
),
|
||||
},
|
||||
{ title: '耗时', width: 90, render: (_, row) => formatDuration(row.started_at, row.finished_at) },
|
||||
{ title: '说明', dataIndex: 'message', ellipsis: true },
|
||||
{
|
||||
title: "耗时",
|
||||
width: 90,
|
||||
render: (_, row) => formatDuration(row.started_at, row.finished_at),
|
||||
},
|
||||
{ title: "说明", dataIndex: "message", ellipsis: true },
|
||||
];
|
||||
|
||||
return (
|
||||
<Space direction="vertical" size="middle" style={{ width: '100%' }}>
|
||||
<Space direction="vertical" size="middle" style={{ width: "100%" }}>
|
||||
<Card
|
||||
title="自动巡检"
|
||||
extra={
|
||||
@@ -182,7 +231,12 @@ export default function AutomationPage() {
|
||||
/>
|
||||
|
||||
{jobs.map((job) => (
|
||||
<Card key={job.key} type="inner" title={job.title} style={{ marginBottom: 16 }}>
|
||||
<Card
|
||||
key={job.key}
|
||||
type="inner"
|
||||
title={job.title}
|
||||
style={{ marginBottom: 16 }}
|
||||
>
|
||||
<Descriptions size="small" column={2} style={{ marginBottom: 16 }}>
|
||||
<Descriptions.Item label="最近运行">
|
||||
{formatTime(job.last_run_at)}
|
||||
@@ -192,34 +246,36 @@ export default function AutomationPage() {
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="最近结果">
|
||||
{job.last_status ? (
|
||||
<Tag color={STATUS_TAG[job.last_status]?.color ?? 'default'}>
|
||||
<Tag color={STATUS_TAG[job.last_status]?.color ?? "default"}>
|
||||
{STATUS_TAG[job.last_status]?.text ?? job.last_status}
|
||||
</Tag>
|
||||
) : (
|
||||
'-'
|
||||
"-"
|
||||
)}
|
||||
</Descriptions.Item>
|
||||
<Descriptions.Item label="最近说明">{job.last_message || '-'}</Descriptions.Item>
|
||||
<Descriptions.Item label="最近说明">
|
||||
{job.last_message || "-"}
|
||||
</Descriptions.Item>
|
||||
</Descriptions>
|
||||
|
||||
<Form form={forms} layout="inline" onFinish={() => saveJob(job)}>
|
||||
<Form.Item
|
||||
name={[job.key, 'enabled']}
|
||||
name={[job.key, "enabled"]}
|
||||
label="启用"
|
||||
valuePropName="checked"
|
||||
>
|
||||
<Switch disabled={!canManage} />
|
||||
</Form.Item>
|
||||
<Form.Item
|
||||
name={[job.key, 'interval_hours']}
|
||||
name={[job.key, "interval_hours"]}
|
||||
label="单账号重检间隔(小时)"
|
||||
>
|
||||
<InputNumber min={0.1} step={1} disabled={!canManage} />
|
||||
</Form.Item>
|
||||
<Form.Item name={[job.key, 'batch_size']} label="每轮条数">
|
||||
<Form.Item name={[job.key, "batch_size"]} label="每轮条数">
|
||||
<InputNumber min={1} max={2000} disabled={!canManage} />
|
||||
</Form.Item>
|
||||
<Form.Item name={[job.key, 'concurrency']} label="并发">
|
||||
<Form.Item name={[job.key, "concurrency"]} label="并发">
|
||||
<InputNumber min={1} max={16} disabled={!canManage} />
|
||||
</Form.Item>
|
||||
<Form.Item>
|
||||
@@ -258,6 +314,38 @@ export default function AutomationPage() {
|
||||
))}
|
||||
</Card>
|
||||
|
||||
<Card
|
||||
title="待人工处理"
|
||||
extra={
|
||||
<Typography.Text type="secondary">
|
||||
自动重登救不了的类型(共 {manualTotal} 个)
|
||||
</Typography.Text>
|
||||
}
|
||||
>
|
||||
{manualGroups.length === 0 ? (
|
||||
<Typography.Text type="secondary">
|
||||
暂无 —— 能自动重试的都会自己重试,需要人工的才出现在这里。
|
||||
</Typography.Text>
|
||||
) : (
|
||||
manualGroups.map((group) => (
|
||||
<Card
|
||||
key={group.kind || "exhausted"}
|
||||
type="inner"
|
||||
title={`${group.label}(${group.count} 个)`}
|
||||
style={{ marginBottom: 12 }}
|
||||
>
|
||||
<Table
|
||||
rowKey="task_id"
|
||||
size="small"
|
||||
pagination={false}
|
||||
dataSource={group.samples}
|
||||
columns={manualColumns}
|
||||
/>
|
||||
</Card>
|
||||
))
|
||||
)}
|
||||
</Card>
|
||||
|
||||
<Card title="运行历史">
|
||||
<Table
|
||||
rowKey="id"
|
||||
@@ -273,9 +361,9 @@ export default function AutomationPage() {
|
||||
}
|
||||
|
||||
function formatDuration(start: string | null, end: string | null): string {
|
||||
if (!start || !end) return '-';
|
||||
if (!start || !end) return "-";
|
||||
const ms = new Date(end).getTime() - new Date(start).getTime();
|
||||
if (!Number.isFinite(ms) || ms < 0) return '-';
|
||||
if (!Number.isFinite(ms) || ms < 0) return "-";
|
||||
if (ms < 1000) return `${ms}ms`;
|
||||
return `${(ms / 1000).toFixed(1)}s`;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user