feat(account-check): 增加履约账号 CK 保护目标
This commit is contained in:
@@ -0,0 +1,341 @@
|
||||
"""斗鱼履约账号 CK 保护目标。
|
||||
|
||||
保护目标不是新的账号价值分类,也不固定挑选若干账号。成员始终由当前履约
|
||||
关系动态计算:
|
||||
|
||||
- ``presale_bound``:仍在履约中的预售任务所分配的账号;
|
||||
- ``collab_bound``:仍在进行中的斗鱼外部协作单所绑定的账号。
|
||||
|
||||
配置保存在 ``ck_health.config["protection_groups"]``。这样不需要扩容账号表,
|
||||
也不会污染高价值/普通的库存供给口径。目标数量用于预警缺口;只要组已启用,
|
||||
当前全部绑定账号都会获得更短的 CK 巡检间隔。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from datetime import UTC, datetime
|
||||
from typing import Any
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import (
|
||||
Account,
|
||||
AutomationJob,
|
||||
DouyuExternalOrder,
|
||||
PlatformFulfillmentTask,
|
||||
)
|
||||
|
||||
CK_HEALTH_JOB_KEY = "ck_health"
|
||||
PROTECTION_CONFIG_KEY = "protection_groups"
|
||||
|
||||
DEFAULT_PROBE_INTERVAL_MINUTES = 60
|
||||
MIN_PROBE_INTERVAL_MINUTES = 15
|
||||
MAX_PROBE_INTERVAL_MINUTES = 24 * 60
|
||||
MAX_TARGET_COUNT = 100_000
|
||||
|
||||
# 与 douyu_collab_service.COLLAB_LEASE_STATUSES 保持一致。这里只放状态值,
|
||||
# 避免服务层为了两个常量导入整个协作业务模块。
|
||||
COLLAB_ACTIVE_STATUSES = (
|
||||
"incomplete",
|
||||
"to_recharge",
|
||||
"recharged",
|
||||
"scripted",
|
||||
"points_error",
|
||||
"role_error",
|
||||
"failed",
|
||||
)
|
||||
|
||||
GROUP_DEFINITIONS: dict[str, dict[str, Any]] = {
|
||||
"presale_bound": {
|
||||
"label": "预售绑定账号",
|
||||
"description": "仍在履约中的斗鱼预售任务所分配的全部账号",
|
||||
"enabled": True,
|
||||
"target_count": 0,
|
||||
"probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES,
|
||||
"auto_relogin": True,
|
||||
},
|
||||
"collab_bound": {
|
||||
"label": "协作单绑定账号",
|
||||
"description": "未归档且仍在进行中的斗鱼外部协作单所绑定账号",
|
||||
"enabled": True,
|
||||
"target_count": 0,
|
||||
"probe_interval_minutes": DEFAULT_PROBE_INTERVAL_MINUTES,
|
||||
"auto_relogin": True,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _clamp_int(value: Any, default: int, minimum: int, maximum: int) -> int:
|
||||
try:
|
||||
parsed = int(value)
|
||||
except (TypeError, ValueError):
|
||||
parsed = default
|
||||
return max(minimum, min(parsed, maximum))
|
||||
|
||||
|
||||
def normalize_group_config(
|
||||
group_key: str,
|
||||
raw: dict[str, Any] | None,
|
||||
) -> dict[str, Any]:
|
||||
definition = GROUP_DEFINITIONS[group_key]
|
||||
value = raw or {}
|
||||
return {
|
||||
"key": group_key,
|
||||
"label": definition["label"],
|
||||
"description": definition["description"],
|
||||
"enabled": bool(value.get("enabled", definition["enabled"])),
|
||||
"target_count": _clamp_int(
|
||||
value.get("target_count"),
|
||||
int(definition["target_count"]),
|
||||
0,
|
||||
MAX_TARGET_COUNT,
|
||||
),
|
||||
"probe_interval_minutes": _clamp_int(
|
||||
value.get("probe_interval_minutes"),
|
||||
int(definition["probe_interval_minutes"]),
|
||||
MIN_PROBE_INTERVAL_MINUTES,
|
||||
MAX_PROBE_INTERVAL_MINUTES,
|
||||
),
|
||||
"auto_relogin": bool(
|
||||
value.get("auto_relogin", definition["auto_relogin"])
|
||||
),
|
||||
}
|
||||
|
||||
|
||||
def normalize_protection_config(
|
||||
config: dict[str, Any] | None,
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
raw_groups = (config or {}).get(PROTECTION_CONFIG_KEY)
|
||||
if not isinstance(raw_groups, dict):
|
||||
raw_groups = {}
|
||||
return {
|
||||
key: normalize_group_config(
|
||||
key,
|
||||
raw_groups.get(key) if isinstance(raw_groups.get(key), dict) else None,
|
||||
)
|
||||
for key in GROUP_DEFINITIONS
|
||||
}
|
||||
|
||||
|
||||
def _presale_account_ids(db: Session) -> set[int]:
|
||||
rows = (
|
||||
db.query(PlatformFulfillmentTask.account_id)
|
||||
.filter(
|
||||
PlatformFulfillmentTask.sale_mode == "presale",
|
||||
PlatformFulfillmentTask.account_id.isnot(None),
|
||||
PlatformFulfillmentTask.execution_status.notin_(
|
||||
("completed", "cancelled")
|
||||
),
|
||||
)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {int(row[0]) for row in rows if row[0] is not None}
|
||||
|
||||
|
||||
def _collab_account_ids(db: Session) -> set[int]:
|
||||
rows = (
|
||||
db.query(DouyuExternalOrder.account_id)
|
||||
.filter(
|
||||
DouyuExternalOrder.account_id.isnot(None),
|
||||
DouyuExternalOrder.archived_at.is_(None),
|
||||
DouyuExternalOrder.status.in_(COLLAB_ACTIVE_STATUSES),
|
||||
)
|
||||
.distinct()
|
||||
.all()
|
||||
)
|
||||
return {int(row[0]) for row in rows if row[0] is not None}
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ProtectionSnapshot:
|
||||
groups: dict[str, dict[str, Any]]
|
||||
group_account_ids: dict[str, frozenset[int]]
|
||||
|
||||
@property
|
||||
def monitored_ids(self) -> frozenset[int]:
|
||||
ids: set[int] = set()
|
||||
for key, group in self.groups.items():
|
||||
if group["enabled"]:
|
||||
ids.update(self.group_account_ids.get(key, ()))
|
||||
return frozenset(ids)
|
||||
|
||||
@property
|
||||
def relogin_ids(self) -> frozenset[int]:
|
||||
ids: set[int] = set()
|
||||
for key, group in self.groups.items():
|
||||
if group["enabled"] and group["auto_relogin"]:
|
||||
ids.update(self.group_account_ids.get(key, ()))
|
||||
return frozenset(ids)
|
||||
|
||||
@property
|
||||
def suppressed_relogin_ids(self) -> frozenset[int]:
|
||||
return self.monitored_ids - self.relogin_ids
|
||||
|
||||
def probe_intervals_by_account(self) -> dict[int, int]:
|
||||
intervals: dict[int, int] = {}
|
||||
for key, group in self.groups.items():
|
||||
if not group["enabled"]:
|
||||
continue
|
||||
seconds = int(group["probe_interval_minutes"]) * 60
|
||||
for account_id in self.group_account_ids.get(key, ()):
|
||||
current = intervals.get(account_id)
|
||||
intervals[account_id] = (
|
||||
seconds if current is None else min(current, seconds)
|
||||
)
|
||||
return intervals
|
||||
|
||||
|
||||
def load_protection_snapshot(
|
||||
db: Session,
|
||||
*,
|
||||
job_config: dict[str, Any] | None = None,
|
||||
) -> ProtectionSnapshot:
|
||||
if job_config is None:
|
||||
job = db.get(AutomationJob, CK_HEALTH_JOB_KEY)
|
||||
job_config = job.config if job is not None else None
|
||||
groups = normalize_protection_config(job_config)
|
||||
return ProtectionSnapshot(
|
||||
groups=groups,
|
||||
group_account_ids={
|
||||
"presale_bound": frozenset(_presale_account_ids(db)),
|
||||
"collab_bound": frozenset(_collab_account_ids(db)),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def update_protection_group(
|
||||
db: Session,
|
||||
*,
|
||||
group_key: str,
|
||||
enabled: bool,
|
||||
target_count: int,
|
||||
probe_interval_minutes: int,
|
||||
auto_relogin: bool,
|
||||
) -> tuple[AutomationJob, dict[str, dict[str, Any]]]:
|
||||
if group_key not in GROUP_DEFINITIONS:
|
||||
raise KeyError(group_key)
|
||||
job = db.get(AutomationJob, CK_HEALTH_JOB_KEY)
|
||||
if job is None:
|
||||
raise LookupError("CK 自动巡检作业尚未初始化")
|
||||
|
||||
groups = normalize_protection_config(job.config)
|
||||
groups[group_key] = normalize_group_config(
|
||||
group_key,
|
||||
{
|
||||
"enabled": enabled,
|
||||
"target_count": target_count,
|
||||
"probe_interval_minutes": probe_interval_minutes,
|
||||
"auto_relogin": auto_relogin,
|
||||
},
|
||||
)
|
||||
job.config = {
|
||||
**(job.config or {}),
|
||||
PROTECTION_CONFIG_KEY: groups,
|
||||
}
|
||||
job.updated_at = datetime.now(UTC)
|
||||
return job, groups
|
||||
|
||||
|
||||
def evaluate_protection_targets(
|
||||
db: Session,
|
||||
*,
|
||||
job_config: dict[str, Any] | None = None,
|
||||
now: datetime | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
moment = now or datetime.now(UTC)
|
||||
snapshot = load_protection_snapshot(db, job_config=job_config)
|
||||
all_ids = {
|
||||
account_id
|
||||
for ids in snapshot.group_account_ids.values()
|
||||
for account_id in ids
|
||||
}
|
||||
accounts = (
|
||||
db.query(Account).filter(Account.id.in_(all_ids)).all() if all_ids else []
|
||||
)
|
||||
account_map = {int(account.id): account for account in accounts}
|
||||
|
||||
rows: list[dict[str, Any]] = []
|
||||
for key, group in snapshot.groups.items():
|
||||
account_ids = snapshot.group_account_ids.get(key, frozenset())
|
||||
group_accounts = [
|
||||
account_map[account_id]
|
||||
for account_id in account_ids
|
||||
if account_id in account_map
|
||||
]
|
||||
status_counts = {
|
||||
"ck_valid": 0,
|
||||
"ck_invalid": 0,
|
||||
"ck_error": 0,
|
||||
"ck_unchecked": 0,
|
||||
"without_cookie": 0,
|
||||
}
|
||||
for account in group_accounts:
|
||||
status = str(account.ck_check_status or "")
|
||||
if status == "valid":
|
||||
status_counts["ck_valid"] += 1
|
||||
elif status == "invalid":
|
||||
status_counts["ck_invalid"] += 1
|
||||
elif status == "error":
|
||||
status_counts["ck_error"] += 1
|
||||
else:
|
||||
status_counts["ck_unchecked"] += 1
|
||||
if not account.cookie:
|
||||
status_counts["without_cookie"] += 1
|
||||
|
||||
target = int(group["target_count"])
|
||||
shortage = max(target - status_counts["ck_valid"], 0)
|
||||
probe_seconds = int(group["probe_interval_minutes"]) * 60
|
||||
due_at = moment.timestamp() - probe_seconds
|
||||
due_count = sum(
|
||||
1
|
||||
for account in group_accounts
|
||||
if account.ck_checked_at is None
|
||||
or (
|
||||
account.ck_checked_at.replace(tzinfo=UTC)
|
||||
if account.ck_checked_at.tzinfo is None
|
||||
else account.ck_checked_at
|
||||
).timestamp()
|
||||
<= due_at
|
||||
)
|
||||
needs_attention = bool(
|
||||
group["enabled"]
|
||||
and (
|
||||
status_counts["ck_invalid"]
|
||||
or status_counts["ck_error"]
|
||||
or status_counts["without_cookie"]
|
||||
or shortage
|
||||
)
|
||||
)
|
||||
rows.append(
|
||||
{
|
||||
"group_key": key,
|
||||
"label": group["label"],
|
||||
"description": group["description"],
|
||||
"enabled": bool(group["enabled"]),
|
||||
"target_count": target,
|
||||
"probe_interval_minutes": int(group["probe_interval_minutes"]),
|
||||
"auto_relogin": bool(group["auto_relogin"]),
|
||||
"bound_count": len(group_accounts),
|
||||
**status_counts,
|
||||
"target_shortage": shortage,
|
||||
"probe_due_count": due_count,
|
||||
"needs_attention": needs_attention,
|
||||
}
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
__all__ = [
|
||||
"CK_HEALTH_JOB_KEY",
|
||||
"COLLAB_ACTIVE_STATUSES",
|
||||
"GROUP_DEFINITIONS",
|
||||
"PROTECTION_CONFIG_KEY",
|
||||
"ProtectionSnapshot",
|
||||
"evaluate_protection_targets",
|
||||
"load_protection_snapshot",
|
||||
"normalize_group_config",
|
||||
"normalize_protection_config",
|
||||
"update_protection_group",
|
||||
]
|
||||
Reference in New Issue
Block a user