feat(accounts): 统一可换绑时间并加本地 7 天锁

- 新增官方时间、本地 bind_ok、7 天锁到期、检查时间和来源字段
- role_change_available_at 改为官方时间与本地锁取较晚者
- 绑定成功和官方探测统一写有效时间
- 分配过滤增加最近 elite bind_ok 的数据库兜底
- 迁移 0129 从 account_events 回填历史账号
- 补充字段/回填过滤测试和生命周期文档
This commit is contained in:
yml
2026-11-24 17:37:15 +08:00
parent a1530b7e74
commit 2e6303361c
11 changed files with 415 additions and 9 deletions
+61
View File
@@ -207,3 +207,64 @@ CK 本体和健康结果都在账号上:
- `web/backend/services/automation/jobs/`:巡检、重登和资料刷新
- `tests/test_account_lifecycle.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`(相对秒数)当分配依据;
- 不为了“能选中”绕过本地锁。
+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]
+9 -1
View File
@@ -44,7 +44,7 @@ TESTS_DIR = Path(__file__).resolve().parent
PROJECT_ROOT = TESTS_DIR.parent
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
HEAD_REVISION = "20261124_0128"
HEAD_REVISION = "20261124_0129"
# 迁移新增、但不声明在模型里的复合查询索引。
EXTRA_INDEXES = (
@@ -67,6 +67,11 @@ _ACCOUNT_PLATFORM_COLUMNS = {
"ck_observed_lifetime_seconds": "INTEGER NULL",
"ck_expiry_source": "VARCHAR(24) NOT NULL DEFAULT ''",
"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 = {
@@ -399,6 +404,7 @@ class TestMigrationSmoke:
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0123")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session:
user = User(
username="binding-sync-user",
@@ -490,6 +496,7 @@ class TestMigrationSmoke:
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0125")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session:
user = User(
username="false-binding-user",
@@ -607,6 +614,7 @@ class TestMigrationSmoke:
cfg = _migration_config()
cfg.set_main_option("sqlalchemy.url", mig_url)
command.upgrade(cfg, "20261123_0126")
_add_account_platform_columns(mig_engine)
with Session(mig_engine) as session:
user = User(
username="pending-link-user",
@@ -513,6 +513,10 @@
"20261124_0128_account_supply_profiles.py": {
"revision": "20261124_0128",
"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(
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)。
# manualType 只表示开过;写入时还要按 expireTime 判断是否已过期。
# 光看积分区分不了「开通后积分花完」和「从未开通」,必须单独落库。
+27
View File
@@ -285,6 +285,33 @@ def role_change_available_at(
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"]
+26 -3
View File
@@ -9,6 +9,7 @@ from sqlalchemy import and_, func, or_, select
from ..models import (
Account,
AccountCommodityState,
AccountEvent,
AccountLease,
DouyuExternalOrder,
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):
return or_(
Account.role_change_available_at.is_(None),
Account.role_change_available_at <= now,
return and_(
or_(
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_eligible_state_filter",
"pool_owner_ids",
"recent_elite_bind_lock_exists",
"role_change_ready_filter",
"valid_ck_filter",
]
+19 -2
View File
@@ -30,13 +30,17 @@
from __future__ import annotations
from datetime import datetime
from datetime import UTC, datetime
from typing import Any
from loguru import logger
from sqlalchemy.orm import Session
from ..models import Account
from .account_binding import (
effective_role_change_available_at,
role_bind_lock_until,
)
from .account_events_service import (
CATEGORY_ACTIVITY,
CATEGORY_BUSINESS,
@@ -467,7 +471,7 @@ def record_bind(
title += f":{role_name}"
if weak:
title += "(未回查确认)"
return emit(
emitted = emit(
db,
account_id=account.id,
event_type=EVENT_BIND_OK,
@@ -488,6 +492,19 @@ def record_bind(
actor_id=actor_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(
+8 -2
View File
@@ -32,6 +32,7 @@ from .account_binding import (
binding_pending_decision,
binding_snapshot,
derive_from_bind_info,
effective_role_change_available_at,
is_bound_act,
role_change_available_at,
set_bind_status,
@@ -1011,9 +1012,14 @@ def _apply_role_result(
account.game_name = role_name
account.game_channel = channel
account.change_role_wait_time = _to_int(role.get("change_role_wait_time"))
account.role_change_available_at = role_change_available_at(
role.get("bind_info")
official_at = role_change_available_at(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:
account.esports_game_name = role_name
account.esports_game_channel = channel
+9 -1
View File
@@ -22,6 +22,7 @@ from .account_binding import (
binding_pending_decision,
binding_snapshot,
classify_bind_cooldown,
effective_role_change_available_at,
is_bound_act,
is_pending_binding_role,
is_role_change_cooling,
@@ -408,7 +409,14 @@ class BindMixin:
snapshot["game_channel"].replace(" / ", " · ") or account.game_channel
)
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:
set_bind_status(account, SCOPE_ELITE, state)
account.updated_at = datetime.now(UTC)