Author SHA1 Message Date
yml b0be3d15cc test: 拆分慢速迁移测试并优化 pre-push
- 迁移测试标记 migration,单独运行约 130 秒
- 非迁移测试约 90 秒,日常开发跑快速集
- pre-push 默认跳过 migration;改迁移/模型/迁移测试时自动全量
- FULL_TESTS=1 可强制全量,不删除任何迁移测试
2026-11-24 19:14:40 +08:00
yml b10018efdd fix(fulfillment): 修复分配重试产生的孤儿租约
- 分配前锁平台任务行,避免同一任务并发领两个账
- 落库前释放同任务下其他 active 租约
- 租约回收作业增加 task/租约不一致的孤儿回收
- 补充孤儿租约回收测试与订单 2632301937741357 复盘
2026-11-24 19:03:07 +08:00
yml 1081e93522 fix(automation): 租约巡检降为4小时并收紧首次登录样本
- lease_bound 30 分钟会超出 ck_health 吞吐,改为 240 分钟
- 首次登录样本排除缺账号/密码和已判极验/凭证失败的账号
- 补充保护组和首登样本准入测试
2026-11-24 18:36:34 +08:00
yml 03c7c74eab feat(automation): 增加租约 CK 到期前刷新
- 保护组新增 lease_bound,覆盖全部生效履约/协作租约
- 新增 lease_ck_refresh 作业,提前 24h 为有效 CK 续期
- 已失效重登仍由 ck_relogin 处理
- 失败按类型设置退避,避免每轮重复撞
- 补充保护组、选行、作业执行测试
2026-11-24 18:04:09 +08:00
yml 2e6303361c feat(accounts): 统一可换绑时间并加本地 7 天锁
- 新增官方时间、本地 bind_ok、7 天锁到期、检查时间和来源字段
- role_change_available_at 改为官方时间与本地锁取较晚者
- 绑定成功和官方探测统一写有效时间
- 分配过滤增加最近 elite bind_ok 的数据库兜底
- 迁移 0129 从 account_events 回填历史账号
- 补充字段/回填过滤测试和生命周期文档
2026-11-24 17:37:15 +08:00
29 changed files with 1052 additions and 19 deletions
+11 -2
View File
@@ -18,6 +18,7 @@ fi
python_files=() python_files=()
frontend_changed=0 frontend_changed=0
migration_changed=0
while read -r local_ref local_sha remote_ref remote_sha; do while read -r local_ref local_sha remote_ref remote_sha; do
[ -z "$local_sha" ] && continue [ -z "$local_sha" ] && continue
if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then if [ "$local_sha" = "0000000000000000000000000000000000000000" ]; then
@@ -37,6 +38,9 @@ while read -r local_ref local_sha remote_ref remote_sha; do
web/frontend/*) web/frontend/*)
frontend_changed=1 frontend_changed=1
;; ;;
web/backend/migrations/*|web/backend/models.py|tests/test_migrations.py|tests/test_migration_*.py|tests/test_login_attempt_migration.py)
migration_changed=1
;;
esac esac
done <<< "$changed_paths" done <<< "$changed_paths"
done <<< "$push_lines" done <<< "$push_lines"
@@ -88,6 +92,11 @@ ensure_test_mysql() {
ensure_test_mysql ensure_test_mysql
echo "[pre-push] 运行 pytest..." if [ "${FULL_TESTS:-0}" = "1" ] || [ "$migration_changed" -eq 1 ]; then
./dev.sh test -q echo "[pre-push] 运行全量 pytest(含迁移测试)..."
./dev.sh test -q
else
echo "[pre-push] 运行 pytest(跳过慢速迁移测试;FULL_TESTS=1 可跑全量)..."
./dev.sh test -q -m "not migration"
fi
echo "[pre-push] pytest 通过" echo "[pre-push] pytest 通过"
+9 -2
View File
@@ -142,7 +142,9 @@ python3 -c 'import secrets; print(secrets.token_urlsafe(32))'
## 运行测试 ## 运行测试
```bash ```bash
uv run --group dev pytest # 或 ./dev.sh test uv run --group dev pytest # 全量(含迁移测试,约 3-4 分钟)
./dev.sh test -q -m "not migration" # 日常快速:约 90 秒,跳过 22 个慢速迁移测试
./dev.sh test -q -m migration # 只跑迁移/回填测试
uv run --group dev pytest tests/test_cookie_operations.py uv run --group dev pytest tests/test_cookie_operations.py
./dev.sh format tests conftest.py ./dev.sh format tests conftest.py
./dev.sh format-check tests conftest.py ./dev.sh format-check tests conftest.py
@@ -150,6 +152,11 @@ uv run --group dev pytest tests/test_cookie_operations.py
docker compose --profile test run --rm test docker compose --profile test run --rm test
``` ```
迁移测试会为每个用例创建临时 MySQL 库并重跑 Alembic 链,约占全量时间
**60%**;保留它们,不改历史迁移数据。pre-push 默认跳过迁移测试,只有改到
`web/backend/migrations/`、`web/backend/models.py` 或迁移测试文件时才跑全量;
需要强制全量时用 `FULL_TESTS=1 git push`。
测试跑在**真实 MySQL** 上(不再使用 SQLite):生产是 MySQL,SQLite 与它有方言差异, 测试跑在**真实 MySQL** 上(不再使用 SQLite):生产是 MySQL,SQLite 与它有方言差异,
曾出现「`ORDER BY ... NULLS FIRST` 本地全绿、生产直接 1064」的事故。因此: 曾出现「`ORDER BY ... NULLS FIRST` 本地全绿、生产直接 1064」的事故。因此:
@@ -170,7 +177,7 @@ docker compose --profile test run --rm test
``` ```
- **pre-commit**:暂存的 Python 文件做 Ruff 格式检查;改了 `web/frontend/` 则跑 `tsc -b` - **pre-commit**:暂存的 Python 文件做 Ruff 格式检查;改了 `web/frontend/` 则跑 `tsc -b`
- **pre-push**:上述检查 + 全量 pytest - **pre-push**:上述检查 + pytest(普通改动跳过 migration marker;迁移/模型改动自动全量)
- Pyright 默认不开(噪音大):`TYPECHECK=1 git push` - Pyright 默认不开(噪音大):`TYPECHECK=1 git push`
- 紧急绕过:`git push --no-verify` 或 `SKIP_TESTS=1 git push` - 紧急绕过:`git push --no-verify` 或 `SKIP_TESTS=1 git push`
+27
View File
@@ -288,3 +288,30 @@ live-hub 创建新的绑定任务。
- 自动兑换 - 自动兑换
- 多数量拆分 - 多数量拆分
- 电竞手册、和平小店、虎牙和微博 - 电竞手册、和平小店、虎牙和微博
## 租约孤儿与协作单接管冲突(2026-11-24)
订单 `2632301937741357` / 任务 #1057 在“当前待办”搜不到,是因为任务已经是
`manual_required` / `lease_expired`,需要到“需要人工”里查。
协作单编辑报“平台履约任务 #7482 与账号租约不一致”,根因不是 #1057,而是
任务 #7482 的分配重试留下了孤儿租约:
```text
lease 8877 account 5566 batch_id pf:7482
task 7482 account 5567 lease_id 8879
```
协作单按 `batch_id=pf:7482` 找到任务,再核对账号/租约不一致,拒绝接管。
修复:
1. `allocate_task` 先对平台任务行加锁,避免同一任务并发领到两个租约;
2. 分配落库前释放同任务下其他 active 租约(reason=`allocation_replaced`);
3. `platform_fulfillment_lease_reaper` 增加孤儿租约回收:
- active 租约的 `batch_id=pf:<task>`;
- task 不存在,或 task.account_id / task.lease_id 与租约不一致;
- 释放 reason=`lease_task_mismatch`。
这条回收会顺带释放账号 5566 的 8877。释放后把任务 #1057 重新分配到 5566,
协作单才能正常接管。
+108
View File
@@ -207,3 +207,111 @@ CK 本体和健康结果都在账号上:
- `web/backend/services/automation/jobs/`:巡检、重登和资料刷新 - `web/backend/services/automation/jobs/`:巡检、重登和资料刷新
- `tests/test_account_lifecycle.py`:状态真值表、漂移检查和写入点约束 - `tests/test_account_lifecycle.py`:状态真值表、漂移检查和写入点约束
- `tests/test_account_overview.py`:一键查询、字段落库和高价值资产判定 - `tests/test_account_overview.py`:一键查询、字段落库和高价值资产判定
## 可换绑时间与本地 7 天锁(2026-11-24)
### 为什么要拆开
`accounts.role_change_available_at` 原来只存官方 `canChangeTime`。但账号还有一个
**本地规则**:同一斗鱼账号 7 天内只能绑定一个精英角色(`account_events.bind_ok`)。
两个时间不一致时,分配器按官方时间选中账号,真正绑定时才被
`binding_account_locked_elsewhere` 拦下。
订单 `2632801766531717` / 账号 23168 就是实例:
```text
官方 canChangeTime: 2026-11-24 00:00
本地 bind_ok: 2026-11-17 22:49
本地锁到期: 2026-11-24 22:49
```
分配器只看官方时间,于是 16:47 选中;17:00 释放后又选回同一个;17:07 人工强制确认。
### 字段
| 字段 | 含义 |
| --- | --- |
| `role_change_official_at` | 官方 `canChangeTime` / `now+wait_time` |
| `last_bind_ok_at` | 最近一次精英 `bind_ok` |
| `role_bind_lock_until` | `last_bind_ok_at + 7d` |
| `role_change_available_at` | **有效可换绑时间 = max(官方, 本地锁)** |
| `role_change_checked_at` | 最近一次判断时间 |
| `role_change_source` | `official` / `local_bind` / `backfill` |
### 写入规则
1. 官方 `bindInfo` / probe:
- 写 `role_change_official_at`、`role_change_checked_at`;
- `role_change_available_at = max(官方, role_bind_lock_until)`。
2. `record_bind` 真正绑定成功:
- 写 `last_bind_ok_at`、`role_bind_lock_until`;
- 有效时间取大;
- `role_change_source=local_bind`。
3. 分配/人工选号:
- 只判断 `role_change_available_at <= now`;
- 同时加数据库兜底:最近 7 天有 `elite_role` 的 `bind_ok` 直接排除。
4. 同账号同角色复用不产生新的 `bind_ok`,不重置本地锁。
### 迁移与回填
`20261124_0129`:
- 新增上述字段;
- 从 `account_events`(`event_type=bind_ok`、`subject_type=elite_role`)回填
`last_bind_ok_at`;
- 有效时间取官方与本地锁的较大值;
- 旧 `role_change_available_at` 保留到 `role_change_official_at`。
### 不做什么
- 不新增同义的 `can_change_time` 字段;
- 不用官方时间替换本地 7 天规则;
- 不把 `change_role_wait_time`(相对秒数)当分配依据;
- 不为了“能选中”绕过本地锁。
## P1:租约 CK 到期前刷新(2026-11-24)
生产基线:3,973 个生效租约,其中约 293 个有效 CK 预测 24 小时内到期
(`platform_fulfillment` 202,`douyu_collab` 91)。
### 保护组
`ck_health.config["protection_groups"]` 新增 `lease_bound`:
- 成员:`account_leases.status=active` 且 purpose 为
`platform_fulfillment` / `douyu_collab`;
- 默认开启;
- 巡检间隔 240 分钟(比普通账号更短,且不挤占 ck_health 吞吐);
- 自动重登开启。
这样所有生效租约账号都会进入 CK 巡检和失效重登保护,不再只覆盖预售/协作单。
### 到期前刷新作业
新增 `lease_ck_refresh`:
- 只处理仍为 `ck_check_status=valid` 的生效租约账号;
- 预测到期时间在 24h 内;
- 有 Cookie、可自动管理、没有在途登录;
- 人工失败分型和退避中的账号跳过;
- 每轮 batch=10,10 分钟一轮,默认开启;
- 走 `run_login_batch_with_fallback`,与首次登录/重登共用登录配额和审计。
与 `ck_relogin` 的分工:
| 作业 | 对象 |
| --- | --- |
| `lease_ck_refresh` | 仍有效、但 24h 内到期的租约账号,提前续 CK |
| `ck_relogin` | 已经 invalid 的账号,失效后重登 |
### 为什么不是等失效再登
租约账号在履约期间 CK 失效会出现不可用窗口;提前登录可以把窗口前移到空闲时段。
作业不直接改绑定或订单,只刷新 Cookie。
### 首次登录样本
`account_onboarding` 保持默认关闭。先点“立即跑一次”跑 20 个样本,不打开自动作业;
样本账号会排除缺账号/密码和已判定极验/凭证失败的账号,避免样本被必失败账号污染。
确认成功率、失败分型和登录后商品能力同步后,再启用作业放量。
+3
View File
@@ -44,6 +44,9 @@ packages = ["core", "utils", "web"]
[tool.pytest.ini_options] [tool.pytest.ini_options]
testpaths = ["tests"] testpaths = ["tests"]
markers = [
"migration: 创建临时 MySQL 库并执行 Alembic 迁移链;比普通用例慢很多",
]
[tool.ruff.lint.per-file-ignores] [tool.ruff.lint.per-file-ignores]
# FastAPI evaluates dependency metadata in route parameter defaults by design. # FastAPI evaluates dependency metadata in route parameter defaults by design.
+13
View File
@@ -70,6 +70,19 @@ def test_selector_only_picks_unlogged_automatable_accounts(db):
assert job.count_pending_onboarding(db) == 1 assert job.count_pending_onboarding(db) == 1
def test_selector_skips_missing_password_and_manual_failure(db):
_admin(db)
selectable = _account("onboarding-eligible")
missing_password = _account("onboarding-no-password", password="")
manual_failure = _account("onboarding-captcha", relogin_failure_kind="captcha")
db.add_all([selectable, missing_password, manual_failure])
db.commit()
rows = job.build_select_query(db, _job()).all()
assert [row.id for row in rows] == [selectable.id]
def test_run_account_onboarding_returns_batch_summary(db, monkeypatch): def test_run_account_onboarding_returns_batch_summary(db, monkeypatch):
_admin(db) _admin(db)
first = _account("onboarding-first") first = _account("onboarding-first")
+53
View File
@@ -6,6 +6,7 @@ from datetime import UTC, datetime, timedelta
from web.backend.models import ( from web.backend.models import (
Account, Account,
AccountLease,
AutomationJob, AutomationJob,
DouyuExternalOrder, DouyuExternalOrder,
PlatformFulfillmentTask, PlatformFulfillmentTask,
@@ -123,6 +124,58 @@ def test_protection_membership_uses_active_fulfillment_relationships(db):
) )
def test_lease_bound_includes_all_active_lease_purposes(db):
user = User(
username="lease-protection-user",
password_hash="h",
role="super_admin",
is_active=True,
)
leased = _account("protection-leased")
collab_leased = _account("protection-collab-leased")
released = _account("protection-released")
other_purpose = _account("protection-other-purpose")
db.add_all([user, leased, collab_leased, released, other_purpose])
db.flush()
db.add_all(
[
AccountLease(
account_id=leased.id,
holder_user_id=user.id,
purpose="platform_fulfillment",
status="active",
),
AccountLease(
account_id=collab_leased.id,
holder_user_id=user.id,
purpose="douyu_collab",
status="active",
),
AccountLease(
account_id=released.id,
holder_user_id=user.id,
purpose="platform_fulfillment",
status="released",
),
AccountLease(
account_id=other_purpose.id,
holder_user_id=user.id,
purpose="other",
status="active",
),
]
)
db.commit()
snapshot = load_protection_snapshot(db, job_config=None)
assert snapshot.group_account_ids["lease_bound"] == frozenset(
{leased.id, collab_leased.id}
)
assert snapshot.groups["lease_bound"]["probe_interval_minutes"] == 240
assert leased.id in snapshot.relogin_ids
def test_protection_target_reports_ck_health_and_shortage(db): def test_protection_target_reports_ck_health_and_shortage(db):
valid = _account("protection-valid") valid = _account("protection-valid")
invalid = _account("protection-invalid", ck_status="invalid") invalid = _account("protection-invalid", ck_status="invalid")
+135
View File
@@ -0,0 +1,135 @@
"""账号可换绑时间:本地 7 天锁、有效时间与分配过滤。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from web.backend.models import Account, AccountEvent
from web.backend.services.account_binding import (
effective_role_change_available_at,
role_bind_lock_until,
)
from web.backend.services.account_query_filters import role_change_ready_filter
from web.backend.services.business_events import record_bind
NOW = datetime.now(UTC).replace(microsecond=0)
def _account(name: str, **overrides) -> Account:
values = {
"username": name,
"password": "p",
"email": f"{name}@example.com",
"email_password": "ep",
"status": "active",
"auto_managed": True,
"cookie": "acf_uid=1",
"ck_check_status": "valid",
"ck_checked_at": NOW,
"cookie_updated_at": NOW,
}
values.update(overrides)
return Account(**values)
def _bind_event(account: Account, occurred_at: datetime, ref: str) -> AccountEvent:
return AccountEvent(
account_id=account.id,
event_type="bind_ok",
category="business",
occurred_at=occurred_at,
title="精英宝典绑定:旧角色",
detail={"scope": "elite", "role_name": "旧角色"},
source="douyu_task",
subject_type="elite_role",
subject_key="旧角色",
source_ref=ref,
)
def test_effective_time_uses_later_of_official_and_local_lock():
official = datetime(2026, 11, 24, 0, 0, tzinfo=UTC)
bound = datetime(2026, 11, 17, 14, 49, 25, tzinfo=UTC)
assert role_bind_lock_until(bound) == datetime(2026, 11, 24, 14, 49, 25, tzinfo=UTC)
assert effective_role_change_available_at(
official_at=official, last_bind_ok_at=bound
) == datetime(2026, 11, 24, 14, 49, 25, tzinfo=UTC)
assert effective_role_change_available_at(
official_at=official, last_bind_ok_at=None
) == official
assert effective_role_change_available_at(
official_at=None, last_bind_ok_at=None
) is None
def test_record_bind_sets_local_lock_and_effective_time(db):
account = _account(
"role-lock-bind",
role_change_official_at=datetime(2026, 11, 24, 0, 0, tzinfo=UTC),
role_change_available_at=datetime(2026, 11, 24, 0, 0, tzinfo=UTC),
)
db.add(account)
db.commit()
occurred = datetime(2026, 11, 17, 14, 49, 25, tzinfo=UTC)
assert record_bind(
db,
account,
task_id=990001,
scope="elite",
role_name="旧角色",
occurred_at=occurred,
actor_id=1,
)
db.commit()
db.refresh(account)
assert account.last_bind_ok_at == occurred
assert account.role_bind_lock_until == datetime(2026, 11, 24, 14, 49, 25, tzinfo=UTC)
assert account.role_change_available_at == account.role_bind_lock_until
assert account.role_change_source == "local_bind"
def test_role_change_filter_rejects_recent_bind_even_if_field_says_ready(db):
ready = _account(
"role-lock-ready",
role_change_available_at=NOW - timedelta(days=1),
)
locked = _account(
"role-lock-recent",
role_change_available_at=NOW - timedelta(days=1),
)
db.add_all([ready, locked])
db.flush()
db.add(_bind_event(locked, NOW - timedelta(days=1), "role-filter:recent"))
db.commit()
rows = (
db.query(Account.id)
.filter(role_change_ready_filter(NOW))
.filter(Account.id.in_([ready.id, locked.id]))
.all()
)
assert [row[0] for row in rows] == [ready.id]
def test_role_change_filter_allows_old_bind(db):
old = _account(
"role-lock-old",
role_change_available_at=NOW - timedelta(days=8),
)
db.add(old)
db.flush()
db.add(_bind_event(old, NOW - timedelta(days=8), "role-filter:old"))
db.commit()
rows = (
db.query(Account.id)
.filter(role_change_ready_filter(NOW))
.filter(Account.id == old.id)
.all()
)
assert [row[0] for row in rows] == [old.id]
+131
View File
@@ -0,0 +1,131 @@
"""租约 CK 到期前刷新的选行和作业测试。"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from types import SimpleNamespace
from web.backend.models import Account, AccountLease, AutomationJob, User
from web.backend.services.automation.jobs import lease_ck_refresh
def _account(name: str, *, cookie_updated_at: datetime, ck_status: str = "valid", **overrides) -> Account:
values = {
"username": name,
"password": "p",
"email": f"{name}@example.com",
"email_password": "ep",
"cookie": "acf_uid=1",
"cookie_updated_at": cookie_updated_at,
"ck_check_status": ck_status,
"ck_checked_at": cookie_updated_at,
"status": "active",
"auto_managed": True,
}
values.update(overrides)
return Account(**values)
def _user(db) -> User:
user = User(
username="lease-refresh-admin",
password_hash="h",
role="super_admin",
is_active=True,
)
db.add(user)
db.commit()
return user
def _lease(db, user: User, account: Account, *, purpose: str = "platform_fulfillment", status: str = "active") -> AccountLease:
lease = AccountLease(
account_id=account.id,
holder_user_id=user.id,
purpose=purpose,
status=status,
)
db.add(lease)
return lease
def test_select_due_lease_accounts_only_returns_valid_expiring_leases(db):
now = datetime.now(UTC).replace(microsecond=0)
user = _user(db)
due = _account("lease-due", cookie_updated_at=now - timedelta(days=6, hours=20))
due_collab = _account("lease-due-collab", cookie_updated_at=now - timedelta(days=6, hours=21))
fresh = _account("lease-fresh", cookie_updated_at=now - timedelta(days=1))
invalid = _account("lease-invalid", cookie_updated_at=now - timedelta(days=6, hours=20), ck_status="invalid")
no_lease = _account("lease-none", cookie_updated_at=now - timedelta(days=6, hours=20))
manual = _account("lease-manual", cookie_updated_at=now - timedelta(days=6, hours=20), auto_managed=False)
db.add_all([due, due_collab, fresh, invalid, no_lease, manual])
db.flush()
_lease(db, user, due)
_lease(db, user, due_collab, purpose="douyu_collab")
_lease(db, user, fresh)
_lease(db, user, invalid)
_lease(db, user, manual)
db.commit()
rows = lease_ck_refresh.select_due_lease_accounts(db, now=now, limit=10)
assert {row.id for row in rows} == {due.id, due_collab.id}
def test_select_due_lease_accounts_skips_released_lease(db):
now = datetime.now(UTC).replace(microsecond=0)
user = _user(db)
released = _account("lease-released", cookie_updated_at=now - timedelta(days=6, hours=20))
db.add(released)
db.flush()
_lease(db, user, released, status="released")
db.commit()
assert lease_ck_refresh.select_due_lease_accounts(db, now=now, limit=10) == []
def test_run_lease_ck_refresh_calls_login_for_selected_accounts(db, monkeypatch):
from web.backend.services.automation.jobs import lease_ck_refresh as job_module
now = datetime.now(UTC).replace(microsecond=0)
user = _user(db)
due = _account("lease-run-due", cookie_updated_at=now - timedelta(days=6, hours=20))
db.add(due)
db.flush()
_lease(db, user, due)
db.commit()
job = AutomationJob(
key=job_module.JOB_KEY,
title=job_module.TITLE,
enabled=True,
batch_size=10,
concurrency=3,
config={},
)
db.add(job)
db.commit()
calls: dict[str, object] = {}
def fake_run(db_session, **kwargs):
calls["db"] = db_session
calls["kwargs"] = kwargs
return SimpleNamespace(
success_ids=[due.id],
failed_ids=[],
skipped_ids=[],
fallback_used=False,
batch_ids=["lease-batch"],
fallback_batch_ids=[],
)
monkeypatch.setattr(job_module, "run_login_batch_with_fallback", fake_run)
result = job_module.run_lease_ck_refresh(db, job)
assert calls["kwargs"]["account_ids"] == [due.id]
assert calls["kwargs"]["mode"] == "login"
assert result["scanned"] == 1
assert result["success"] == 1
assert result["batchIds"] == ["lease-batch"]
+2
View File
@@ -10,6 +10,7 @@ import secrets
from pathlib import Path from pathlib import Path
from urllib.parse import quote_plus from urllib.parse import quote_plus
import pytest
from alembic import command from alembic import command
from alembic.config import Config from alembic.config import Config
from sqlalchemy import create_engine, text from sqlalchemy import create_engine, text
@@ -45,6 +46,7 @@ def _insert_task(conn, *, status: str, cookie: str, message: str = "") -> None:
) )
@pytest.mark.migration
class TestLoginAttemptMigration: class TestLoginAttemptMigration:
def setup_method(self): def setup_method(self):
creds = get_mysql_credentials() creds = get_mysql_credentials()
@@ -5,6 +5,7 @@ import secrets
from datetime import UTC, datetime from datetime import UTC, datetime
from urllib.parse import quote_plus from urllib.parse import quote_plus
import pytest
from alembic import command from alembic import command
from alembic.config import Config from alembic.config import Config
from sqlalchemy import create_engine, inspect, text from sqlalchemy import create_engine, inspect, text
@@ -15,6 +16,7 @@ from tests.support.db import get_mysql_credentials
TARGET_REVISION = "20261106_0065" TARGET_REVISION = "20261106_0065"
@pytest.mark.migration
def test_0065_upgrade_downgrade_roundtrip(): def test_0065_upgrade_downgrade_roundtrip():
creds = get_mysql_credentials() creds = get_mysql_credentials()
mig_db = f"douyu_login_mig_rt_{secrets.token_hex(4)}" mig_db = f"douyu_login_mig_rt_{secrets.token_hex(4)}"
+11 -1
View File
@@ -15,6 +15,7 @@ from datetime import UTC, datetime
from pathlib import Path from pathlib import Path
from urllib.parse import quote_plus from urllib.parse import quote_plus
import pytest
from alembic import command from alembic import command
from alembic.config import Config from alembic.config import Config
from alembic.script import ScriptDirectory from alembic.script import ScriptDirectory
@@ -44,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261124_0128" HEAD_REVISION = "20261124_0129"
# 迁移新增、但不声明在模型里的复合查询索引。 # 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = ( EXTRA_INDEXES = (
@@ -67,6 +68,11 @@ _ACCOUNT_PLATFORM_COLUMNS = {
"ck_observed_lifetime_seconds": "INTEGER NULL", "ck_observed_lifetime_seconds": "INTEGER NULL",
"ck_expiry_source": "VARCHAR(24) NOT NULL DEFAULT ''", "ck_expiry_source": "VARCHAR(24) NOT NULL DEFAULT ''",
"value_tier": "INTEGER NULL", "value_tier": "INTEGER NULL",
"role_change_official_at": "DATETIME NULL",
"last_bind_ok_at": "DATETIME NULL",
"role_bind_lock_until": "DATETIME NULL",
"role_change_checked_at": "DATETIME NULL",
"role_change_source": "VARCHAR(16) NULL",
} }
_LATER_ORM_COLUMNS = { _LATER_ORM_COLUMNS = {
@@ -127,6 +133,7 @@ def _migration_config() -> Config:
return config return config
@pytest.mark.migration
class TestMigrationSmoke: class TestMigrationSmoke:
def test_chain_is_linear_and_head_matches_latest_file(self): def test_chain_is_linear_and_head_matches_latest_file(self):
directory = ScriptDirectory.from_config(_migration_config()) directory = ScriptDirectory.from_config(_migration_config())
@@ -399,6 +406,7 @@ class TestMigrationSmoke:
cfg = _migration_config() cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url) cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0123") command.upgrade(cfg, "20261123_0123")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session: with Session(mig_engine) as session:
user = User( user = User(
username="binding-sync-user", username="binding-sync-user",
@@ -490,6 +498,7 @@ class TestMigrationSmoke:
cfg = _migration_config() cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url) cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0125") command.upgrade(cfg, "20261123_0125")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session: with Session(mig_engine) as session:
user = User( user = User(
username="false-binding-user", username="false-binding-user",
@@ -607,6 +616,7 @@ class TestMigrationSmoke:
cfg = _migration_config() cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url) cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0126") command.upgrade(cfg, "20261123_0126")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session: with Session(mig_engine) as session:
user = User( user = User(
username="pending-link-user", username="pending-link-user",
+32
View File
@@ -4915,6 +4915,38 @@ class TestBindingAndCompletion(_Base):
assert result["expired"] == 0 assert result["expired"] == 0
assert task.execution_status == "allocated" assert task.execution_status == "allocated"
def test_reaper_releases_orphan_active_lease_from_task_retry(self):
task = self._allocated()
orphan_account = self.account("orphan-retry-account")
orphan_lease = AccountLease(
account_id=orphan_account.id,
holder_user_id=self.admin_id,
purpose="platform_fulfillment",
status="active",
batch_id=f"pf:{task.id}",
commodity_id=task.commodity_id,
)
self.session.add(orphan_lease)
self.session.commit()
job = AutomationJob(key=reaper.JOB_KEY, batch_size=100)
result = reaper.run_platform_fulfillment_lease_reaper(
self.session,
job,
now=NOW,
)
self.session.refresh(orphan_lease)
task_lease = (
self.session.query(AccountLease)
.filter(AccountLease.id == task.lease_id)
.one()
)
assert result["orphan_released"] == 1
assert orphan_lease.status == "released"
assert task_lease.status == "active"
assert task.account_id is not None
def test_expired_platform_lease_hands_off_to_active_collab(self): def test_expired_platform_lease_hands_off_to_active_collab(self):
task = self._allocated() task = self._allocated()
lease = self.session.query(AccountLease).one() lease = self.session.query(AccountLease).one()
@@ -513,6 +513,10 @@
"20261124_0128_account_supply_profiles.py": { "20261124_0128_account_supply_profiles.py": {
"revision": "20261124_0128", "revision": "20261124_0128",
"sha256": "4a95dfe1e6634cb318710423f8ab8d06321e09a7a58548bd3a159f3445f72ea7" "sha256": "4a95dfe1e6634cb318710423f8ab8d06321e09a7a58548bd3a159f3445f72ea7"
},
"20261124_0129_account_role_change_lock.py": {
"revision": "20261124_0129",
"sha256": "75b97c990e0c870add48073da26a9d2ac9ffd75ba1ffe477ae97268155cab42c"
} }
} }
} }
@@ -0,0 +1,98 @@
"""账号可换绑时间:官方时间、本地 7 天锁、有效时间与来源
背景:`accounts.role_change_available_at` 原来只存官方 `canChangeTime`,
而本地规则是「同一账号 7 天内只能绑一个精英角色」。两者不一致时,分配器
按官方时间选中了账号,真正绑定时才被 `binding_account_locked_elsewhere`
拦下(订单 2632801766531717 / 账号 23168:官方 11-24 00:00,本地锁 11-24 22:49)。
本迁移:
1. 新增 `role_change_official_at`、`last_bind_ok_at`、`role_bind_lock_until`、
`role_change_checked_at`、`role_change_source`;
2. 从 `account_events.bind_ok`(subject_type=elite_role)回填最近绑定时间;
3. `role_change_available_at` 改为「官方时间与本地锁取较晚者」;
4. 保留原 `role_change_available_at` 到 `role_change_official_at`。
可重跑:列存在性守卫;回填 SQL 幂等。
"""
from __future__ import annotations
import sqlalchemy as sa
from alembic import op
revision: str = "20261124_0129"
down_revision: str | None = "20261124_0128"
branch_labels: str | None = None
depends_on: str | None = None
TABLE = "accounts"
COLUMNS = {
"role_change_official_at": sa.DateTime(),
"last_bind_ok_at": sa.DateTime(),
"role_bind_lock_until": sa.DateTime(),
"role_change_checked_at": sa.DateTime(),
"role_change_source": sa.String(length=16),
}
BACKFILL_SQL = """
UPDATE accounts a
LEFT JOIN (
SELECT account_id, MAX(occurred_at) AS last_bind_ok_at
FROM account_events
WHERE event_type = 'bind_ok'
AND subject_type = 'elite_role'
GROUP BY account_id
) e ON e.account_id = a.id
SET
a.role_change_official_at = COALESCE(
a.role_change_official_at,
a.role_change_available_at
),
a.last_bind_ok_at = e.last_bind_ok_at,
a.role_bind_lock_until = CASE
WHEN e.last_bind_ok_at IS NULL THEN NULL
ELSE DATE_ADD(e.last_bind_ok_at, INTERVAL 7 DAY)
END,
a.role_change_available_at = GREATEST(
COALESCE(a.role_change_official_at, a.role_change_available_at),
COALESCE(DATE_ADD(e.last_bind_ok_at, INTERVAL 7 DAY), a.role_change_available_at)
),
a.role_change_checked_at = UTC_TIMESTAMP(),
a.role_change_source = CASE
WHEN e.last_bind_ok_at IS NOT NULL THEN 'backfill'
ELSE COALESCE(a.role_change_source, 'official')
END
"""
def _column_exists(name: str) -> bool:
conn = op.get_bind()
count = conn.execute(
sa.text(
"SELECT COUNT(*) FROM information_schema.columns "
"WHERE table_schema = DATABASE() AND table_name = :table "
"AND column_name = :name"
),
{"table": TABLE, "name": name},
).scalar()
return bool(count)
def upgrade() -> None:
for name, column_type in COLUMNS.items():
if not _column_exists(name):
op.add_column(TABLE, sa.Column(name, column_type, nullable=True))
op.execute(sa.text(BACKFILL_SQL))
def downgrade() -> None:
# 先恢复官方时间,再删除新增列;本地锁信息随列一起丢弃。
op.execute(
sa.text(
"UPDATE accounts SET role_change_available_at = "
"role_change_official_at WHERE role_change_official_at IS NOT NULL"
)
)
for name in reversed(tuple(COLUMNS)):
if _column_exists(name):
op.drop_column(TABLE, name)
+19
View File
@@ -173,6 +173,25 @@ class Account(Base):
role_change_available_at: Mapped[datetime | None] = mapped_column( role_change_available_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True UTCDateTime, nullable=True
) )
# 官方接口给出的可换绑时刻(canChangeTime / now+wait_time)。与下面的本地
# 7 天锁分开存:官方时间可能早于本地锁,不能直接用于分配。
role_change_official_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
# 最近一次精英 bind_ok 的业务发生时间,以及本地“一个账号 7 天只能绑一个角色”
# 的锁到期时间。分配只看 role_change_available_at(官方时间与本地锁取大)。
last_bind_ok_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
role_bind_lock_until: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
role_change_checked_at: Mapped[datetime | None] = mapped_column(
UTCDateTime, nullable=True
)
role_change_source: Mapped[str | None] = mapped_column(
String(16), nullable=True
)
# 精英宝典当前有效开通状态(getUserInfo 的 manualType + expireTime)。 # 精英宝典当前有效开通状态(getUserInfo 的 manualType + expireTime)。
# manualType 只表示开过;写入时还要按 expireTime 判断是否已过期。 # manualType 只表示开过;写入时还要按 expireTime 判断是否已过期。
# 光看积分区分不了「开通后积分花完」和「从未开通」,必须单独落库。 # 光看积分区分不了「开通后积分花完」和「从未开通」,必须单独落库。
+27
View File
@@ -285,6 +285,33 @@ def role_change_available_at(
return None return None
#: 本地规则:同一斗鱼账号 7 天内只能绑定一个精英角色。
ROLE_BIND_LOCK = timedelta(days=7)
def role_bind_lock_until(last_bind_ok_at: datetime | None) -> datetime | None:
if last_bind_ok_at is None:
return None
return last_bind_ok_at + ROLE_BIND_LOCK
def effective_role_change_available_at(
*,
official_at: datetime | None,
last_bind_ok_at: datetime | None,
) -> datetime | None:
"""官方可换绑时间与本地 7 天锁取较晚者。
分配/人工选号只看这个结果;官方时间早于本地锁时,本地锁优先。
"""
candidates = [
value
for value in (official_at, role_bind_lock_until(last_bind_ok_at))
if value is not None
]
return max(candidates) if candidates else None
BindCooldownKind = Literal["platform", "customer"] BindCooldownKind = Literal["platform", "customer"]
@@ -22,6 +22,7 @@ from sqlalchemy.orm import Session
from ..models import ( from ..models import (
Account, Account,
AccountLease,
AutomationJob, AutomationJob,
DouyuExternalOrder, DouyuExternalOrder,
PlatformFulfillmentTask, PlatformFulfillmentTask,
@@ -55,6 +56,14 @@ GROUP_DEFINITIONS: dict[str, dict[str, Any]] = {
"probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES, "probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES,
"auto_relogin": True, "auto_relogin": True,
}, },
"lease_bound": {
"label": "生效租约账号",
"description": "当前所有生效的直播履约/协作租约账号,优先 CK 巡检和到期前刷新",
"enabled": True,
"target_count": 0,
"probe_interval_minutes": 240,
"auto_relogin": True,
},
} }
@@ -136,6 +145,19 @@ def _collab_account_ids(db: Session) -> set[int]:
return {int(row[0]) for row in rows if row[0] is not None} return {int(row[0]) for row in rows if row[0] is not None}
def _lease_account_ids(db: Session) -> set[int]:
rows = (
db.query(AccountLease.account_id)
.filter(
AccountLease.status == "active",
AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")),
)
.distinct()
.all()
)
return {int(row[0]) for row in rows if row[0] is not None}
@dataclass(frozen=True) @dataclass(frozen=True)
class ProtectionSnapshot: class ProtectionSnapshot:
groups: dict[str, dict[str, Any]] groups: dict[str, dict[str, Any]]
@@ -189,6 +211,7 @@ def load_protection_snapshot(
group_account_ids={ group_account_ids={
"presale_bound": frozenset(_presale_account_ids(db)), "presale_bound": frozenset(_presale_account_ids(db)),
"collab_bound": frozenset(_collab_account_ids(db)), "collab_bound": frozenset(_collab_account_ids(db)),
"lease_bound": frozenset(_lease_account_ids(db)),
}, },
) )
+26 -3
View File
@@ -9,6 +9,7 @@ from sqlalchemy import and_, func, or_, select
from ..models import ( from ..models import (
Account, Account,
AccountCommodityState, AccountCommodityState,
AccountEvent,
AccountLease, AccountLease,
DouyuExternalOrder, DouyuExternalOrder,
LoginTask, LoginTask,
@@ -121,10 +122,31 @@ def active_collab_order_exists():
) )
def recent_elite_bind_lock_exists(now: datetime):
"""本地 7 天规则:最近 7 天有精英 bind_ok 的账号不能再接新角色。
这是 `role_change_available_at` 的数据库兜底:即使字段回填/写入有遗漏,
分配前也不会选中一个刚绑定过的账号。
"""
return (
select(AccountEvent.id)
.where(
AccountEvent.account_id == Account.id,
AccountEvent.event_type == "bind_ok",
AccountEvent.subject_type == "elite_role",
AccountEvent.occurred_at > now - timedelta(days=7),
)
.exists()
)
def role_change_ready_filter(now: datetime): def role_change_ready_filter(now: datetime):
return or_( return and_(
Account.role_change_available_at.is_(None), or_(
Account.role_change_available_at <= now, Account.role_change_available_at.is_(None),
Account.role_change_available_at <= now,
),
~recent_elite_bind_lock_exists(now),
) )
@@ -167,6 +189,7 @@ __all__ = [
"fresh_ck_cutoff", "fresh_ck_cutoff",
"fresh_eligible_state_filter", "fresh_eligible_state_filter",
"pool_owner_ids", "pool_owner_ids",
"recent_elite_bind_lock_exists",
"role_change_ready_filter", "role_change_ready_filter",
"valid_ck_filter", "valid_ck_filter",
] ]
@@ -52,6 +52,8 @@ from .jobs.douyu_tasks_retention import (
from .jobs.douyu_tasks_retention import ( from .jobs.douyu_tasks_retention import (
run_douyu_tasks_retention, run_douyu_tasks_retention,
) )
from .jobs.lease_ck_refresh import JOB_KEY as LEASE_CK_REFRESH_KEY
from .jobs.lease_ck_refresh import run_lease_ck_refresh
from .jobs.platform_fulfillment_lease_reaper import ( from .jobs.platform_fulfillment_lease_reaper import (
JOB_KEY as PLATFORM_FULFILLMENT_LEASE_REAPER_KEY, JOB_KEY as PLATFORM_FULFILLMENT_LEASE_REAPER_KEY,
) )
@@ -84,6 +86,7 @@ __all__ = [
"CK_HEALTH_KEY", "CK_HEALTH_KEY",
"CK_RELOGIN_KEY", "CK_RELOGIN_KEY",
"DOUYU_TASKS_RETENTION_KEY", "DOUYU_TASKS_RETENTION_KEY",
"LEASE_CK_REFRESH_KEY",
"PLATFORM_FULFILLMENT_LEASE_REAPER_KEY", "PLATFORM_FULFILLMENT_LEASE_REAPER_KEY",
"POINTS_EXPIRE_KEY", "POINTS_EXPIRE_KEY",
"JobSpec", "JobSpec",
@@ -104,6 +107,7 @@ __all__ = [
"run_douyu_tasks_retention", "run_douyu_tasks_retention",
"run_due_jobs", "run_due_jobs",
"run_job_now", "run_job_now",
"run_lease_ck_refresh",
"run_platform_fulfillment_lease_reaper", "run_platform_fulfillment_lease_reaper",
"run_points_expire_check", "run_points_expire_check",
"scheduler_status", "scheduler_status",
@@ -226,6 +230,20 @@ def register_default_jobs() -> None:
run=run_ck_relogin, run=run_ck_relogin,
) )
) )
register_job(
JobSpec(
key=LEASE_CK_REFRESH_KEY,
title="租约 CK 到期前刷新",
# 只处理仍有效、但预测 24h 内到期的生效租约账号;提前续 CK,
# 不参与普通失效重登的批次。
interval_seconds=600,
run_interval_seconds=600,
batch_size=10,
concurrency=3,
run=run_lease_ck_refresh,
default_enabled=True,
)
)
register_job( register_job(
JobSpec( JobSpec(
key=CK_HEALTH_KEY, key=CK_HEALTH_KEY,
@@ -9,7 +9,7 @@ from sqlalchemy import func, or_, select
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ....models import Account, AutomationJob, LoginTask from ....models import Account, AutomationJob, LoginTask
from ...account_lifecycle import MANUAL_STATES, STATUS_MANUAL from ...account_lifecycle import MANUAL_KINDS, MANUAL_STATES, STATUS_MANUAL
from ...login_automation import run_login_batch_with_fallback, system_user_id from ...login_automation import run_login_batch_with_fallback, system_user_id
JOB_KEY = "account_onboarding" JOB_KEY = "account_onboarding"
@@ -38,6 +38,13 @@ def build_select_query(
.filter( .filter(
Account.auto_managed.is_(True), Account.auto_managed.is_(True),
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)), Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
# 缺账号/密码的账号首登必失败,不能占样本名额。
Account.username != "",
Account.password != "",
# 已经判定为极验/凭证问题的账号不再自动首登。
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(Account.cookie.is_(None), Account.cookie == ""), or_(Account.cookie.is_(None), Account.cookie == ""),
~_in_flight_login_exists(), ~_in_flight_login_exists(),
) )
@@ -53,6 +60,11 @@ def count_pending_onboarding(db: Session) -> int:
.filter( .filter(
Account.auto_managed.is_(True), Account.auto_managed.is_(True),
Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)), Account.status.notin_((*MANUAL_STATES, STATUS_MANUAL)),
Account.username != "",
Account.password != "",
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(Account.cookie.is_(None), Account.cookie == ""), or_(Account.cookie.is_(None), Account.cookie == ""),
~_in_flight_login_exists(), ~_in_flight_login_exists(),
) )
@@ -0,0 +1,170 @@
"""租约账号 CK 到期前刷新(P1)。
`ck_relogin` 只处理已经 `ck_check_status=invalid` 的账号;但租约账号如果等到
失效再重登,履约期间会出现一段不可用窗口。这个作业专门在 CK **预测到期前
24 小时**,对仍持有有效 CK 的生效租约账号做一次主动登录,延长 CK 生命周期。
范围:
- `account_leases.status=active` 且 purpose 为 `platform_fulfillment` / `douyu_collab`;
- `ck_check_status=valid`、有 Cookie、可自动管理、没有在途登录;
- 预测到期时间 <= now + 24h(`ck_expected_expires_at` 或 `cookie_updated_at + 7d`);
- 失败分型为人工的账号、仍在退避窗口内的账号不碰。
作业只负责“提前续 CK”,不替代 `ck_relogin` 的失效重登;两者共用登录配额和
登录任务审计。
"""
from __future__ import annotations
from datetime import UTC, datetime, timedelta
from typing import Any
from sqlalchemy import func, or_
from sqlalchemy.orm import Session
from ....models import Account, AccountLease, AutomationJob, User
from ...account_lifecycle import DEFAULT_CK_LIFETIME, MANUAL_KINDS
from ...account_query_filters import automation_account_filter
from ...login_automation import run_login_batch_with_fallback
JOB_KEY = "lease_ck_refresh"
TITLE = "租约 CK 到期前刷新"
REFRESH_BEFORE = timedelta(hours=24)
def _system_user_id(db: Session) -> int | 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 due_lease_account_query(
db: Session,
now: datetime | None = None,
):
"""到期前 24h 的租约账号查询(执行和测试共用)。"""
moment = now or datetime.now(UTC)
cutoff = moment + REFRESH_BEFORE
return (
db.query(Account)
.join(AccountLease, AccountLease.account_id == Account.id)
.filter(
AccountLease.status == "active",
AccountLease.purpose.in_(("platform_fulfillment", "douyu_collab")),
Account.ck_check_status == "valid",
Account.cookie_updated_at.isnot(None),
automation_account_filter(cookie_operable=True),
func.coalesce(Account.relogin_failure_kind, "").notin_(
tuple(sorted(MANUAL_KINDS))
),
or_(
Account.ck_expected_expires_at <= cutoff,
Account.cookie_updated_at <= cutoff - DEFAULT_CK_LIFETIME,
),
or_(
Account.relogin_next_at.is_(None),
Account.relogin_next_at <= moment,
),
)
.order_by(Account.cookie_updated_at.asc(), Account.id.asc())
)
def select_due_lease_accounts(
db: Session,
*,
now: datetime | None = None,
limit: int = 10,
) -> list[Account]:
return due_lease_account_query(db, now=now).limit(max(1, int(limit))).all()
def run_lease_ck_refresh(db: Session, job: AutomationJob) -> dict[str, Any]:
now = datetime.now(UTC)
system_user_id = _system_user_id(db)
if system_user_id is None:
return {
"scanned": 0,
"success": 0,
"failed": 0,
"message": "库里没有可用用户,无法以系统身份发起租约 CK 刷新",
}
batch_size = max(1, int(job.batch_size or 10))
accounts = select_due_lease_accounts(db, now=now, limit=batch_size)
if not accounts:
return {
"scanned": 0,
"success": 0,
"failed": 0,
"message": "没有 24h 内到期的租约账号需要刷新",
}
account_ids = [int(account.id) for account in accounts]
outcome = run_login_batch_with_fallback(
db,
account_ids=account_ids,
mode="login",
created_by=system_user_id,
concurrency=max(1, min(int(job.concurrency or 3), 8)),
max_total_time=240,
)
_settle_outcome(accounts, outcome, now=now)
db.commit()
retry = len(outcome.failed_ids) - _manual_count(outcome)
return {
"scanned": len(account_ids),
"success": len(outcome.success_ids),
"failed": len(outcome.failed_ids),
"retry": max(0, retry),
"manual": _manual_count(outcome),
"skipped": len(outcome.skipped_ids),
"fallbackUsed": outcome.fallback_used,
"batchIds": list(outcome.batch_ids) + list(outcome.fallback_batch_ids),
"message": (
f"租约 CK 到期前刷新 {len(account_ids)} 条,"
f"成功 {len(outcome.success_ids)},失败 {len(outcome.failed_ids)}"
),
}
def _manual_count(outcome) -> int:
return sum(
1
for account_id in outcome.failed_ids
if outcome.failure_kinds.get(account_id) in MANUAL_KINDS
)
def _settle_outcome(accounts: list[Account], outcome, *, now: datetime) -> None:
"""成功清退避,失败按类型设置下次重试,避免每 10 分钟撞一次。"""
by_id = {int(account.id): account for account in accounts}
for account_id in outcome.success_ids:
account = by_id.get(int(account_id))
if account is None:
continue
account.relogin_failure_kind = ""
account.relogin_last_error = ""
account.relogin_attempts = 0
account.relogin_next_at = None
for account_id in outcome.failed_ids:
account = by_id.get(int(account_id))
if account is None:
continue
kind = str(outcome.failure_kinds.get(account_id) or "unknown")
account.relogin_failure_kind = kind
account.relogin_attempts = int(account.relogin_attempts or 0) + 1
if kind in MANUAL_KINDS:
account.relogin_next_at = None
elif kind == "email_quota":
account.relogin_next_at = now + timedelta(hours=12)
else:
account.relogin_next_at = now + timedelta(hours=1)
@@ -10,6 +10,7 @@ from sqlalchemy.orm import Session
from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask from ....models import Account, AccountLease, AutomationJob, PlatformFulfillmentTask
from ...platform_fulfillment.account_selector import ( from ...platform_fulfillment.account_selector import (
expire_platform_fulfillment_leases, expire_platform_fulfillment_leases,
release_lease,
) )
from ...platform_fulfillment.service import binding_failed_lease_ttl_minutes from ...platform_fulfillment.service import binding_failed_lease_ttl_minutes
@@ -93,6 +94,44 @@ def run_platform_fulfillment_lease_reaper(
if task is not None: if task is not None:
converted_tasks[int(task.id)] = task converted_tasks[int(task.id)] = task
# 分配并发/重试可能留下「batch_id 指向 task,但 task 实际用另一个账号/租约」
# 的孤儿 active 租约。它不会自然过期(expires_at 常为 NULL),会永久占住账号,
# 并让协作单接管时报“任务与租约不一致”。这里按 task 的真实归属回收。
orphan_leases = (
db.query(AccountLease)
.filter(
AccountLease.purpose == "platform_fulfillment",
AccountLease.status == "active",
AccountLease.batch_id.like("pf:%"),
)
.order_by(AccountLease.id.asc())
.limit(max(1, int(job.batch_size or 500)))
.all()
)
orphan_released = 0
for lease in orphan_leases:
try:
task_id = int(str(lease.batch_id).removeprefix("pf:"))
except ValueError:
task_id = 0
task = (
db.get(PlatformFulfillmentTask, task_id) if task_id else None
)
if (
task is not None
and task.account_id == lease.account_id
and task.lease_id == lease.id
):
continue
if release_lease(
db,
lease,
reason="lease_task_mismatch",
now=moment,
commit=False,
):
orphan_released += 1
expired = expire_platform_fulfillment_leases( expired = expire_platform_fulfillment_leases(
db, db,
now=moment, now=moment,
@@ -126,14 +165,15 @@ def run_platform_fulfillment_lease_reaper(
task.last_error = "账号租约已过期,请重新分配账号" task.last_error = "账号租约已过期,请重新分配账号"
task.updated_at = moment task.updated_at = moment
affected += 1 affected += 1
if released_ids or converted_tasks: if released_ids or converted_tasks or orphan_released:
db.commit() db.commit()
return { return {
"scanned": expired, "scanned": expired + orphan_released,
"expired": expired, "expired": expired,
"orphan_released": orphan_released,
"stale_binding_recovered": len(stale_binding_leases), "stale_binding_recovered": len(stale_binding_leases),
"affected_tasks": affected, "affected_tasks": affected,
"message": f"直播账号履约租约回收 {expired} 条", "message": f"直播账号履约租约回收 {expired + orphan_released} 条",
} }
+19 -2
View File
@@ -30,13 +30,17 @@
from __future__ import annotations from __future__ import annotations
from datetime import datetime from datetime import UTC, datetime
from typing import Any from typing import Any
from loguru import logger from loguru import logger
from sqlalchemy.orm import Session from sqlalchemy.orm import Session
from ..models import Account from ..models import Account
from .account_binding import (
effective_role_change_available_at,
role_bind_lock_until,
)
from .account_events_service import ( from .account_events_service import (
CATEGORY_ACTIVITY, CATEGORY_ACTIVITY,
CATEGORY_BUSINESS, CATEGORY_BUSINESS,
@@ -467,7 +471,7 @@ def record_bind(
title += f":{role_name}" title += f":{role_name}"
if weak: if weak:
title += "(未回查确认)" title += "(未回查确认)"
return emit( emitted = emit(
db, db,
account_id=account.id, account_id=account.id,
event_type=EVENT_BIND_OK, event_type=EVENT_BIND_OK,
@@ -488,6 +492,19 @@ def record_bind(
actor_id=actor_id, actor_id=actor_id,
source_ref=task_ref(task_id), source_ref=task_ref(task_id),
) )
if scope == "elite":
# 本地 7 天锁:绑定事实发生即生效,不能等下一次官方查询。
moment = occurred_at or datetime.now(UTC)
if account.last_bind_ok_at is None or moment > account.last_bind_ok_at:
account.last_bind_ok_at = moment
account.role_bind_lock_until = role_bind_lock_until(moment)
account.role_change_available_at = effective_role_change_available_at(
official_at=account.role_change_official_at,
last_bind_ok_at=account.last_bind_ok_at,
)
account.role_change_checked_at = datetime.now(UTC)
account.role_change_source = "local_bind"
return emitted
def record_official_exchange( def record_official_exchange(
+8 -2
View File
@@ -32,6 +32,7 @@ from .account_binding import (
binding_pending_decision, binding_pending_decision,
binding_snapshot, binding_snapshot,
derive_from_bind_info, derive_from_bind_info,
effective_role_change_available_at,
is_bound_act, is_bound_act,
role_change_available_at, role_change_available_at,
set_bind_status, set_bind_status,
@@ -1011,9 +1012,14 @@ def _apply_role_result(
account.game_name = role_name account.game_name = role_name
account.game_channel = channel account.game_channel = channel
account.change_role_wait_time = _to_int(role.get("change_role_wait_time")) account.change_role_wait_time = _to_int(role.get("change_role_wait_time"))
account.role_change_available_at = role_change_available_at( official_at = role_change_available_at(role.get("bind_info"))
role.get("bind_info") account.role_change_official_at = official_at
account.role_change_checked_at = datetime.now(UTC)
account.role_change_available_at = effective_role_change_available_at(
official_at=official_at,
last_bind_ok_at=account.last_bind_ok_at,
) )
account.role_change_source = "official"
elif scope == SCOPE_ESPORTS: elif scope == SCOPE_ESPORTS:
account.esports_game_name = role_name account.esports_game_name = role_name
account.esports_game_channel = channel account.esports_game_channel = channel
+9 -1
View File
@@ -22,6 +22,7 @@ from .account_binding import (
binding_pending_decision, binding_pending_decision,
binding_snapshot, binding_snapshot,
classify_bind_cooldown, classify_bind_cooldown,
effective_role_change_available_at,
is_bound_act, is_bound_act,
is_pending_binding_role, is_pending_binding_role,
is_role_change_cooling, is_role_change_cooling,
@@ -408,7 +409,14 @@ class BindMixin:
snapshot["game_channel"].replace(" / ", " · ") or account.game_channel snapshot["game_channel"].replace(" / ", " · ") or account.game_channel
) )
account.change_role_wait_time = snapshot["change_role_wait_time"] account.change_role_wait_time = snapshot["change_role_wait_time"]
account.role_change_available_at = role_change_available_at(bind_info) official_at = role_change_available_at(bind_info)
account.role_change_official_at = official_at
account.role_change_checked_at = datetime.now(UTC)
account.role_change_available_at = effective_role_change_available_at(
official_at=official_at,
last_bind_ok_at=account.last_bind_ok_at,
)
account.role_change_source = "official"
if state is not None: if state is not None:
set_bind_status(account, SCOPE_ELITE, state) set_bind_status(account, SCOPE_ELITE, state)
account.updated_at = datetime.now(UTC) account.updated_at = datetime.now(UTC)
@@ -48,6 +48,7 @@ from .account_selector import (
capability_candidate_rows, capability_candidate_rows,
capability_refresh_candidate_accounts, capability_refresh_candidate_accounts,
lease_account, lease_account,
release_lease,
) )
from .common import ( from .common import (
DEFAULT_CAPABILITY_CANDIDATE_LIMIT, DEFAULT_CAPABILITY_CANDIDATE_LIMIT,
@@ -61,7 +62,7 @@ from .common import (
_now, _now,
) )
from .outbox import _emit_order_site_binding_state from .outbox import _emit_order_site_binding_state
from .repository import _load_task from .repository import _load_task, _load_task_for_update
from .runtime import ( from .runtime import (
_append_event, _append_event,
_apply_task_lease_policy, _apply_task_lease_policy,
@@ -329,6 +330,18 @@ def _allocate_task_from_capability(
current: User, current: User,
) -> dict[str, Any]: ) -> dict[str, Any]:
"""只用本地能力索引选号;外部资格查询留给独立同步队列。""" """只用本地能力索引选号;外部资格查询留给独立同步队列。"""
# 同一任务并发点击/调度重试时,先在任务行上加锁。否则两个请求会各自
# 领到一个账号租约,后提交的一方覆盖 task.lease_id,先前的 active 租约
# 就变成孤儿(生产 7482/8877 就是这么来的)。
task = _load_task_for_update(db, int(task.id))
if task.account_id and task.lease_id:
current_lease = (
db.query(AccountLease)
.filter(AccountLease.id == int(task.lease_id))
.first()
)
if current_lease is not None and current_lease.status == "active":
return get_task_detail(db, task.id)
moment = _now() moment = _now()
required_points = int(task.required_points or 0) required_points = int(task.required_points or 0)
try: try:
@@ -511,6 +524,23 @@ def _allocate_task_from_capability(
return get_task_detail(db, task.id) return get_task_detail(db, task.id)
selected_account = selected.account selected_account = selected.account
stale_leases = (
db.query(AccountLease)
.filter(
AccountLease.status == "active",
AccountLease.batch_id == f"pf:{int(task.id)}",
AccountLease.id != int(lease.id),
)
.with_for_update()
.all()
)
for stale in stale_leases:
release_lease(
db,
stale,
reason="allocation_replaced",
commit=False,
)
task.account_id = selected_account.id task.account_id = selected_account.id
task.lease_id = lease.id task.lease_id = lease.id
task.operator_id = current.id task.operator_id = current.id
+1 -1
View File
@@ -802,7 +802,7 @@ export interface DouyuSupplyTargetUpdate {
} }
export interface DouyuAccountProtectionTarget { export interface DouyuAccountProtectionTarget {
group_key: 'presale_bound' | 'collab_bound'; group_key: 'presale_bound' | 'collab_bound' | 'lease_bound';
label: string; label: string;
description: string; description: string;
enabled: boolean; enabled: boolean;
@@ -118,6 +118,12 @@ const JOB_UI: Record<string, JobUiSpec> = {
showRecheck: false, showRecheck: false,
showConcurrency: false, showConcurrency: false,
}, },
lease_ck_refresh: {
description: "对仍有效、但预测 24 小时内到期的生效租约账号提前登录续 CK;只处理 platform_fulfillment / douyu_collab 租约。",
core: true,
showRecheck: false,
showConcurrency: true,
},
account_onboarding: { account_onboarding: {
description: "对没有 CK 的未登录账号执行首次真实登录;成功后写入 CK 并联动商品能力同步。默认关闭,建议先小批量。", description: "对没有 CK 的未登录账号执行首次真实登录;成功后写入 CK 并联动商品能力同步。默认关闭,建议先小批量。",
core: true, core: true,