381 lines
11 KiB
Python
381 lines
11 KiB
Python
"""账号平台基础闭环:全量快照、工作队列、CK 周期和登录预算。"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime, timedelta
|
|
from types import SimpleNamespace
|
|
|
|
import pytest
|
|
|
|
from web.backend.models import (
|
|
Account,
|
|
AccountCommodityState,
|
|
AccountSyncState,
|
|
AccountWorkItem,
|
|
LoginQuotaSetting,
|
|
)
|
|
from web.backend.services import account_sync_service
|
|
from web.backend.services.account_lifecycle import on_ck_verdict
|
|
from web.backend.services.account_sync_service import (
|
|
DOMAIN_STOREHOME,
|
|
sync_storehome_snapshot,
|
|
)
|
|
from web.backend.services.account_work_queue import (
|
|
complete_account_work,
|
|
enqueue_account_work,
|
|
)
|
|
from web.backend.services.automation.jobs import ck_health
|
|
from web.backend.services.douyu_account_state import DouyuLiveAccountState
|
|
from web.backend.services.douyu_read_gateway import StorehomeSnapshot
|
|
from web.backend.services.login_quota_service import (
|
|
CATEGORY_MANUAL,
|
|
finish_login_attempt,
|
|
reserve_login_attempt,
|
|
)
|
|
from web.backend.services.platform_fulfillment.service import _exchange_gate
|
|
|
|
|
|
def _account(name: str, **overrides) -> Account:
|
|
values = {
|
|
"username": name,
|
|
"password": "p",
|
|
"email": f"{name}@example.com",
|
|
"email_password": "ep",
|
|
"cookie": "acf_uid=100",
|
|
"cookie_updated_at": datetime.now(UTC),
|
|
"status": "active",
|
|
"auto_managed": True,
|
|
}
|
|
values.update(overrides)
|
|
return Account(**values)
|
|
|
|
|
|
def _snapshot(count: int = 60) -> StorehomeSnapshot:
|
|
items = tuple(
|
|
{
|
|
"commodityId": f"goods-{index}",
|
|
"commodityName": f"商品 {index}",
|
|
"score": index * 10,
|
|
"status": 1 if index == 0 else 0,
|
|
}
|
|
for index in range(count)
|
|
)
|
|
return StorehomeSnapshot(
|
|
manual_id="manual",
|
|
rid="room",
|
|
observed_at=datetime.now(UTC),
|
|
items=items,
|
|
limited_ids=frozenset({"goods-0"}),
|
|
raw={"data": {"list": list(items)}},
|
|
)
|
|
|
|
|
|
def test_storehome_snapshot_writes_all_goods_and_sync_state(db):
|
|
account = _account("snapshot-account")
|
|
db.add(account)
|
|
db.commit()
|
|
|
|
result = sync_storehome_snapshot(
|
|
db,
|
|
account,
|
|
_snapshot(),
|
|
source="test.storehome",
|
|
)
|
|
db.commit()
|
|
|
|
states = (
|
|
db.query(AccountCommodityState)
|
|
.filter(
|
|
AccountCommodityState.account_id == account.id,
|
|
AccountCommodityState.scope == "elite",
|
|
)
|
|
.all()
|
|
)
|
|
sync_state = (
|
|
db.query(AccountSyncState)
|
|
.filter(
|
|
AccountSyncState.account_id == account.id,
|
|
AccountSyncState.domain == DOMAIN_STOREHOME,
|
|
)
|
|
.one()
|
|
)
|
|
assert result.item_count == 60
|
|
assert len(states) == 60
|
|
assert {row.commodity_id for row in states} == {
|
|
f"goods-{index}" for index in range(60)
|
|
}
|
|
assert sync_state.status == "success"
|
|
assert sync_state.valid_until is not None
|
|
assert sync_state.raw_payload_json["data"]["list"][0]["commodityId"] == "goods-0"
|
|
assert len(sync_state.payload_hash) == 64
|
|
limited = next(row for row in states if row.commodity_id == "goods-0")
|
|
assert limited.raw_json["status"] == 1
|
|
|
|
|
|
def test_storehome_sync_failure_is_recorded_without_success_state(db, monkeypatch):
|
|
account = _account("snapshot-failure")
|
|
db.add(account)
|
|
db.commit()
|
|
|
|
def fail(*_args, **_kwargs):
|
|
raise RuntimeError("projection failed")
|
|
|
|
monkeypatch.setattr(account_sync_service, "sync_account_goods_states", fail)
|
|
|
|
with pytest.raises(RuntimeError, match="projection failed"):
|
|
sync_storehome_snapshot(
|
|
db,
|
|
account,
|
|
_snapshot(),
|
|
source="test.storehome",
|
|
)
|
|
|
|
sync_state = (
|
|
db.query(AccountSyncState)
|
|
.filter(
|
|
AccountSyncState.account_id == account.id,
|
|
AccountSyncState.domain == DOMAIN_STOREHOME,
|
|
)
|
|
.one()
|
|
)
|
|
assert sync_state.status == "failed"
|
|
assert "projection failed" in sync_state.error_message
|
|
assert sync_state.next_retry_at is not None
|
|
assert sync_state.raw_payload_json["data"]["list"][0]["commodityId"] == "goods-0"
|
|
|
|
|
|
def test_account_work_queue_deduplicates_only_active_items(db):
|
|
account = _account("queue-account")
|
|
db.add(account)
|
|
db.commit()
|
|
|
|
first = enqueue_account_work(
|
|
db,
|
|
account_id=account.id,
|
|
work_type="storehome_sync",
|
|
priority=80,
|
|
)
|
|
second = enqueue_account_work(
|
|
db,
|
|
account_id=account.id,
|
|
work_type="storehome_sync",
|
|
priority=20,
|
|
)
|
|
assert second.id == first.id
|
|
assert second.priority == 20
|
|
|
|
complete_account_work(db, first)
|
|
third = enqueue_account_work(
|
|
db,
|
|
account_id=account.id,
|
|
work_type="storehome_sync",
|
|
priority=80,
|
|
)
|
|
assert third.id != first.id
|
|
assert db.query(AccountWorkItem).count() == 2
|
|
|
|
|
|
def test_ck_verdict_updates_lifecycle_and_moves_relogin_work(db):
|
|
issued_at = datetime.now(UTC) - timedelta(days=7, hours=9)
|
|
account = _account("ck-lifecycle", cookie_updated_at=issued_at)
|
|
db.add(account)
|
|
db.commit()
|
|
|
|
invalid_at = datetime.now(UTC)
|
|
on_ck_verdict(
|
|
db,
|
|
account,
|
|
"invalid",
|
|
detail={"message": "未登录"},
|
|
occurred_at=invalid_at,
|
|
)
|
|
db.flush()
|
|
|
|
work = (
|
|
db.query(AccountWorkItem)
|
|
.filter(
|
|
AccountWorkItem.account_id == account.id,
|
|
AccountWorkItem.work_type == "login_relogin",
|
|
)
|
|
.one()
|
|
)
|
|
assert work.status == "pending"
|
|
assert account.ck_invalid_detected_at == invalid_at
|
|
assert account.ck_observed_lifetime_seconds is not None
|
|
assert account.ck_expected_expires_at is None
|
|
|
|
account.cookie_updated_at = datetime.now(UTC)
|
|
on_ck_verdict(
|
|
db,
|
|
account,
|
|
"valid",
|
|
detail={"message": "有效"},
|
|
occurred_at=datetime.now(UTC),
|
|
)
|
|
db.flush()
|
|
|
|
db.refresh(work)
|
|
assert work.status == "success"
|
|
assert account.ck_last_valid_at is not None
|
|
assert account.ck_expected_expires_at is not None
|
|
assert account.ck_expiry_source == "predicted"
|
|
|
|
|
|
def test_ck_health_skips_invalid_and_manual_accounts(db):
|
|
accounts = [
|
|
_account("ck-empty", ck_check_status=""),
|
|
_account("ck-valid", ck_check_status="valid"),
|
|
_account("ck-invalid", ck_check_status="invalid"),
|
|
_account("ck-manual", ck_check_status="manual"),
|
|
]
|
|
db.add_all(accounts)
|
|
db.commit()
|
|
job = SimpleNamespace(interval_seconds=3600, batch_size=200)
|
|
|
|
selected = ck_health._select_accounts(db, job, datetime.now(UTC))
|
|
|
|
assert {account.username for account in selected} == {"ck-empty", "ck-valid"}
|
|
|
|
|
|
def test_time_limited_goods_block_fulfillment_outside_window():
|
|
state = DouyuLiveAccountState(
|
|
account_id=1,
|
|
account_name="time-limited",
|
|
checked_at=datetime.now(UTC),
|
|
ck_verdict="valid",
|
|
ck_message="有效",
|
|
elite_opened=True,
|
|
points=1000,
|
|
limited_ids=frozenset(),
|
|
role_change_available_at=None,
|
|
commodity_availability={"time-goods": "expired"},
|
|
commodity_blocking_reasons={"time-goods": "限时兑换已结束"},
|
|
)
|
|
|
|
reasons = state.blocking_reasons(commodity_id="time-goods")
|
|
gate = _exchange_gate(state, "time-goods")
|
|
|
|
assert "限时兑换已结束" in reasons
|
|
assert gate == ("not_available", "commodity_expired", "限时兑换已结束")
|
|
|
|
|
|
def test_missing_storehome_goods_blocks_fulfillment_as_off_shelf():
|
|
state = DouyuLiveAccountState(
|
|
account_id=2,
|
|
account_name="off-shelf",
|
|
checked_at=datetime.now(UTC),
|
|
ck_verdict="valid",
|
|
ck_message="有效",
|
|
elite_opened=True,
|
|
points=1000,
|
|
limited_ids=frozenset(),
|
|
role_change_available_at=None,
|
|
commodity_availability={"another-goods": "available"},
|
|
)
|
|
|
|
reasons = state.blocking_reasons(commodity_id="removed-goods")
|
|
gate = _exchange_gate(state, "removed-goods")
|
|
|
|
assert any("可能已下架" in reason for reason in reasons)
|
|
assert gate[:2] == ("not_available", "commodity_not_offered")
|
|
|
|
|
|
def test_login_quota_enforces_per_account_and_hourly_budget(db):
|
|
first = _account("quota-first")
|
|
second = _account("quota-second")
|
|
third = _account("quota-third")
|
|
fourth = _account("quota-fourth")
|
|
db.add_all([first, second, third, fourth])
|
|
db.add(
|
|
LoginQuotaSetting(
|
|
id=1,
|
|
daily_attempt_limit=20,
|
|
hourly_attempt_limit=2,
|
|
per_account_daily_limit=2,
|
|
manual_daily_limit=10,
|
|
)
|
|
)
|
|
db.commit()
|
|
now = datetime.now(UTC).replace(microsecond=0)
|
|
|
|
first_attempt = reserve_login_attempt(
|
|
db,
|
|
account=first,
|
|
mode="login",
|
|
trigger_source="manual",
|
|
batch_id="batch-1",
|
|
created_by=None,
|
|
now=now.replace(hour=1),
|
|
)
|
|
assert first_attempt.allowed
|
|
assert first_attempt.attempt is not None
|
|
assert first_attempt.attempt.category == CATEGORY_MANUAL
|
|
finish_login_attempt(
|
|
db,
|
|
first_attempt.attempt,
|
|
status="success",
|
|
now=now.replace(hour=1),
|
|
)
|
|
|
|
second_attempt = reserve_login_attempt(
|
|
db,
|
|
account=first,
|
|
mode="login",
|
|
trigger_source="manual",
|
|
batch_id="batch-2",
|
|
created_by=None,
|
|
now=now.replace(hour=2),
|
|
)
|
|
assert second_attempt.allowed
|
|
assert second_attempt.attempt is not None
|
|
finish_login_attempt(
|
|
db,
|
|
second_attempt.attempt,
|
|
status="failed",
|
|
now=now.replace(hour=2),
|
|
)
|
|
|
|
denied_same_account = reserve_login_attempt(
|
|
db,
|
|
account=first,
|
|
mode="login",
|
|
trigger_source="manual",
|
|
batch_id="batch-3",
|
|
created_by=None,
|
|
now=now.replace(hour=3),
|
|
)
|
|
assert not denied_same_account.allowed
|
|
assert "上限" in denied_same_account.reason
|
|
|
|
first_hour = reserve_login_attempt(
|
|
db,
|
|
account=second,
|
|
mode="login",
|
|
trigger_source="manual",
|
|
batch_id="batch-4",
|
|
created_by=None,
|
|
now=now.replace(hour=4),
|
|
)
|
|
second_hour = reserve_login_attempt(
|
|
db,
|
|
account=third,
|
|
mode="login",
|
|
trigger_source="manual",
|
|
batch_id="batch-4",
|
|
created_by=None,
|
|
now=now.replace(hour=4),
|
|
)
|
|
third_hour = reserve_login_attempt(
|
|
db,
|
|
account=fourth,
|
|
mode="login",
|
|
trigger_source="manual",
|
|
batch_id="batch-4",
|
|
created_by=None,
|
|
now=now.replace(hour=4),
|
|
)
|
|
assert first_hour.allowed
|
|
assert second_hour.allowed
|
|
assert not third_hour.allowed
|
|
assert "每小时" in third_hour.reason
|