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
@@ -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)