From 2549511598922925bbbf4b941853d7db75b379fd Mon Sep 17 00:00:00 2001 From: yml Date: Mon, 23 Nov 2026 15:07:31 +0800 Subject: [PATCH] =?UTF-8?q?perf(automation):=20=E6=8C=81=E4=B9=85=E9=98=9F?= =?UTF-8?q?=E5=88=97=E9=A9=B1=E5=8A=A8=E5=B9=B6=E4=BC=98=E5=8C=96=E5=B1=A5?= =?UTF-8?q?=E7=BA=A6=E7=83=AD=E8=B7=AF=E5=BE=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .env.example | 3 + docker-compose.yml | 4 + docker-entrypoint.sh | 31 ++ tests/test_account_supply_service.py | 74 ++++ tests/test_account_value_projection.py | 68 ++++ tests/test_automation_ck_relogin.py | 117 ++++++ tests/test_background_runtime.py | 94 +++++ tests/test_migrations.py | 3 +- tests/test_platform_fulfillment.py | 60 ++- web/backend/background_runtime.py | 124 ++++++ web/backend/background_worker.py | 46 +++ web/backend/main.py | 102 +---- .../migrations/migration_manifest.json | 12 + .../20261123_0119_account_supply_snapshots.py | 51 +++ .../20261123_0120_account_value_projection.py | 85 +++++ ...261123_0121_douyu_tasks_retention_index.py | 41 ++ web/backend/models.py | 41 ++ web/backend/routers/douyu.py | 6 +- web/backend/routers/platform_fulfillment.py | 10 + web/backend/services/account_observability.py | 18 +- .../services/account_supply_service.py | 125 +++++- web/backend/services/account_value.py | 55 ++- web/backend/services/account_work_queue.py | 14 +- web/backend/services/automation/__init__.py | 20 + .../jobs/account_supply_replenishment.py | 7 +- .../jobs/account_value_projection.py | 32 ++ .../services/automation/jobs/ck_relogin.py | 361 ++++++++++++++---- .../automation/jobs/douyu_tasks_retention.py | 75 ++-- .../platform_fulfillment/repository.py | 4 + .../services/platform_fulfillment/views.py | 204 ++++++++-- .../src/pages/PlatformFulfillmentPage.tsx | 6 +- 31 files changed, 1658 insertions(+), 235 deletions(-) create mode 100644 tests/test_account_value_projection.py create mode 100644 tests/test_background_runtime.py create mode 100644 web/backend/background_runtime.py create mode 100644 web/backend/background_worker.py create mode 100644 web/backend/migrations/versions/20261123_0119_account_supply_snapshots.py create mode 100644 web/backend/migrations/versions/20261123_0120_account_value_projection.py create mode 100644 web/backend/migrations/versions/20261123_0121_douyu_tasks_retention_index.py create mode 100644 web/backend/services/automation/jobs/account_value_projection.py diff --git a/.env.example b/.env.example index 2e99825..3089904 100644 --- a/.env.example +++ b/.env.example @@ -22,6 +22,8 @@ ADMIN_PASSWORD=admin123 # Docker 对外端口(容器内仍监听 8800;服务器当前使用 8000) APP_PORT=8000 +# true:调度/轮询/Outbox 在独立 Python 进程运行;false:回到单进程调试模式。 +BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS=true # 应用日志等级:DEBUG、INFO、WARNING、ERROR、CRITICAL;生产环境建议保持 INFO。 LOG_LEVEL=INFO @@ -209,6 +211,7 @@ PLATFORM_FULFILLMENT_RECONCILE_SECONDS=900 # PLATFORM_FULFILLMENT_INTEGRATION_ACTOR_ID=1 # 不稳定能力快照的兜底有效期(秒);库存/未知状态默认使用下面的独立短 TTL ACCOUNT_COMMODITY_STATE_TTL_SECONDS=900 +ACCOUNT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS=900 # 稳定能力:账号具备活动资格、未开放等,默认 6 小时;兑换前仍会实时复核 ACCOUNT_COMMODITY_STABLE_TTL_SECONDS=21600 ACCOUNT_COMMODITY_LIMITED_TTL_SECONDS=86400 diff --git a/docker-compose.yml b/docker-compose.yml index 296a7db..a9c86f1 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -111,6 +111,9 @@ services: # 这个开关只决定「是否起调度线程」;各作业还有自己的开关,默认关闭, # 在 /automation 页面打开。 - AUTOMATION_ENABLED=${AUTOMATION_ENABLED:-false} + # 生产默认把调度/轮询/Outbox 放到独立 Python 进程,避免重作业占住 API 的 GIL。 + # 本地调试可设为 false,回到单进程兼容模式。 + - BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS=${BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS:-true} # order_site 订单只读库(P0 订单读取适配层用;未配置时适配层整体降级) - ORDER_SITE_DATABASE_URL=${ORDER_SITE_DATABASE_URL:-} - ORDER_SITE_LOOKUP_ENABLED=${ORDER_SITE_LOOKUP_ENABLED:-false} @@ -123,6 +126,7 @@ services: - ACCOUNT_COMMODITY_LIMITED_TTL_SECONDS=${ACCOUNT_COMMODITY_LIMITED_TTL_SECONDS:-86400} - ACCOUNT_COMMODITY_NO_STOCK_TTL_SECONDS=${ACCOUNT_COMMODITY_NO_STOCK_TTL_SECONDS:-900} - ACCOUNT_COMMODITY_UNKNOWN_TTL_SECONDS=${ACCOUNT_COMMODITY_UNKNOWN_TTL_SECONDS:-300} + - ACCOUNT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS=${ACCOUNT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS:-900} - PLATFORM_FULFILLMENT_MATCH_MODE=${PLATFORM_FULFILLMENT_MATCH_MODE:-hybrid} - PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH=${PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH:-20} - PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT=${PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT:-20} diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 21a6624..142ac25 100644 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -17,13 +17,20 @@ python /app/services/yyb-worker/runtime/scripts/yyb-worker.py \ --data-dir /app/data/yyb-worker-jobs & worker_pid=$! web_pid="" +background_pid="" stop_processes() { kill -TERM "$worker_pid" 2>/dev/null || true + if [ -n "$background_pid" ]; then + kill -TERM "$background_pid" 2>/dev/null || true + fi if [ -n "$web_pid" ]; then kill -TERM "$web_pid" 2>/dev/null || true fi wait "$worker_pid" 2>/dev/null || true + if [ -n "$background_pid" ]; then + wait "$background_pid" 2>/dev/null || true + fi if [ -n "$web_pid" ]; then wait "$web_pid" 2>/dev/null || true fi @@ -31,6 +38,14 @@ stop_processes() { trap stop_processes INT TERM +if [ "${BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS:-true}" = "true" ]; then + RUNTIME_ROLE=background python -m web.backend.background_worker & + background_pid=$! + export RUNTIME_ROLE=api +else + export RUNTIME_ROLE=all +fi + python -m uvicorn web.backend.main:app --host 0.0.0.0 --port 8800 --workers 1 & web_pid=$! @@ -39,12 +54,28 @@ while :; do if wait "$worker_pid"; then exit_code=0; else exit_code=$?; fi kill -TERM "$web_pid" 2>/dev/null || true wait "$web_pid" 2>/dev/null || true + if [ -n "$background_pid" ]; then + kill -TERM "$background_pid" 2>/dev/null || true + wait "$background_pid" 2>/dev/null || true + fi exit "$exit_code" fi if ! kill -0 "$web_pid" 2>/dev/null; then if wait "$web_pid"; then exit_code=0; else exit_code=$?; fi kill -TERM "$worker_pid" 2>/dev/null || true wait "$worker_pid" 2>/dev/null || true + if [ -n "$background_pid" ]; then + kill -TERM "$background_pid" 2>/dev/null || true + wait "$background_pid" 2>/dev/null || true + fi + exit "$exit_code" + fi + if [ -n "$background_pid" ] && ! kill -0 "$background_pid" 2>/dev/null; then + if wait "$background_pid"; then exit_code=0; else exit_code=$?; fi + kill -TERM "$web_pid" 2>/dev/null || true + wait "$web_pid" 2>/dev/null || true + kill -TERM "$worker_pid" 2>/dev/null || true + wait "$worker_pid" 2>/dev/null || true exit "$exit_code" fi sleep 1 diff --git a/tests/test_account_supply_service.py b/tests/test_account_supply_service.py index 79c9a13..d1d3be5 100644 --- a/tests/test_account_supply_service.py +++ b/tests/test_account_supply_service.py @@ -11,6 +11,7 @@ from web.backend.models import ( AccountCommodityState, AccountEvent, AccountLease, + AccountSupplySnapshot, AccountSupplyTarget, AccountSyncRun, AccountSyncState, @@ -37,6 +38,8 @@ from web.backend.services.account_supply_service import ( ensure_default_supply_targets, evaluate_supply_target, evaluate_supply_targets, + load_supply_snapshot_inventories, + refresh_supply_snapshots, upsert_supply_target, ) from web.backend.services.account_work_queue import enqueue_account_work @@ -122,6 +125,77 @@ def test_supply_inventory_separates_available_and_allocatable(db): assert inventory.needs_replenishment is True +def test_fresh_supply_snapshot_avoids_live_account_scan(db, monkeypatch): + account = _account("supply-snapshot", points=400) + db.add(account) + db.flush() + db.add_all( + [ + _state(account, commodity_id="SNAP"), + AccountSupplyTarget( + platform="douyu", + scope="elite", + commodity_id="SNAP", + value_class=VALUE_HIGH, + target_covered=2, + target_available=2, + target_allocatable=2, + ), + ] + ) + db.commit() + + refreshed = refresh_supply_snapshots(db, now=NOW) + assert refreshed[0].covered == 1 + assert db.query(AccountSupplySnapshot).count() == 1 + + monkeypatch.setattr( + "web.backend.services.account_supply_service.evaluate_supply_targets", + lambda *_args, **_kwargs: (_ for _ in ()).throw( + AssertionError("fresh snapshot must not rescan accounts") + ), + ) + loaded = load_supply_snapshot_inventories( + db, + now=NOW + timedelta(minutes=5), + ) + + assert (loaded[0].covered, loaded[0].available, loaded[0].allocatable) == ( + 1, + 1, + 1, + ) + + +def test_stale_supply_snapshot_is_rebuilt(db): + account = _account("supply-snapshot-stale", points=400) + db.add(account) + db.flush() + db.add_all( + [ + _state(account, commodity_id="STALE"), + AccountSupplyTarget( + platform="douyu", + scope="elite", + commodity_id="STALE", + value_class=VALUE_HIGH, + target_covered=1, + target_available=1, + target_allocatable=1, + ), + ] + ) + db.commit() + refresh_supply_snapshots(db, now=NOW) + + later = NOW + timedelta(minutes=20) + loaded = load_supply_snapshot_inventories(db, now=later) + + snapshot = db.query(AccountSupplySnapshot).one() + assert loaded[0].available == 1 + assert snapshot.checked_at == later + + def test_supply_allocatable_uses_the_same_pool_owner_filter_as_selection(db): customer = User( username="supply-customer", diff --git a/tests/test_account_value_projection.py b/tests/test_account_value_projection.py new file mode 100644 index 0000000..331c290 --- /dev/null +++ b/tests/test_account_value_projection.py @@ -0,0 +1,68 @@ +"""账号价值投影刷新与灰度回退测试。""" + +from __future__ import annotations + +from datetime import UTC, datetime + +from web.backend.models import Account +from web.backend.services.account_value import ( + refresh_account_value_tiers, + value_tier_expr, +) + + +def _account(name: str, **overrides) -> Account: + values = { + "username": name, + "password": "p", + "email": f"{name}@example.com", + "email_password": "ep", + } + values.update(overrides) + return Account(**values) + + +def test_value_projection_refreshes_only_changed_accounts(db): + now = datetime.now(UTC) + accounts = [ + _account( + "tier-one", + high_value_bairimeng_status="available", + high_value_mengtu_status="available", + high_value_checked_at=now, + ), + _account("tier-two-points", points=400), + _account("tier-three-gold", gold_balance=1), + _account("tier-four-queried", overview_queried_at=now), + _account("tier-five-new"), + ] + db.add_all(accounts) + db.commit() + + changed = refresh_account_value_tiers(db, now=now, batch_size=2) + + assert changed == 5 + assert [ + db.get(Account, account.id).value_tier for account in accounts + ] == [1, 2, 3, 4, 5] + assert refresh_account_value_tiers(db, now=now, batch_size=2) == 0 + + +def test_value_tier_expression_falls_back_for_unprojected_account(db): + now = datetime.now(UTC) + account = _account( + "fallback", + points=400, + high_value_checked_at=now, + ) + db.add(account) + db.commit() + + tier = ( + db.query(value_tier_expr(now=now)) + .filter(Account.id == account.id) + .scalar() + ) + + assert account.value_tier is None + assert tier == 2 diff --git a/tests/test_automation_ck_relogin.py b/tests/test_automation_ck_relogin.py index 416a537..f19de09 100644 --- a/tests/test_automation_ck_relogin.py +++ b/tests/test_automation_ck_relogin.py @@ -30,6 +30,10 @@ from web.backend.models import ( User, ) from web.backend.services.account_lifecycle import derive_status +from web.backend.services.account_protection_service import ( + load_protection_snapshot, +) +from web.backend.services.account_work_queue import enqueue_account_work from web.backend.services.automation import register_default_jobs, reset_registry from web.backend.services.automation.jobs import ck_relogin @@ -325,6 +329,21 @@ class TestAdaptiveBatch(_Base): assert decision.batch_size == 10 assert decision.action == "shrink" + def test_legacy_batch_ceiling_no_longer_blocks_adaptive_capacity(self): + job = self.job(batch_size=5) + job.config = {} + self.session.commit() + + decision = ck_relogin.resolve_adaptive_batch_size( + self.session, + job, + now=datetime.now(UTC), + pending=100, + ) + + assert decision.configured_max == 20 + assert decision.batch_size == 10 + class TestBackoff(_Base): def test_ladder_is_escalating(self): @@ -424,6 +443,87 @@ class TestSelection(_Base): self.make_account(f"a{index}") assert len(self._ids(job)) == 3 + def test_claim_uses_existing_persistent_queue(self): + job = self.job() + account = self.make_account("queued") + now = datetime.now(UTC) + work = enqueue_account_work( + self.session, + account_id=account.id, + work_type=ck_relogin.WORK_LOGIN_RELOGIN, + priority=30, + due_at=now - timedelta(hours=1), + max_attempts=20, + ) + self.session.commit() + + claimed = ck_relogin._claim_relogin_work( + self.session, + job, + now, + max_attempts=2, + protection=load_protection_snapshot(self.session), + limit=5, + ) + + assert [item.id for item in claimed] == [work.id] + + def test_replenishment_only_enqueues_due_actionable_accounts(self): + job = self.job() + ready = self.make_account("ready") + self.make_account("captcha", relogin_failure_kind="captcha") + self.make_account("future", relogin_next_at=datetime.now(UTC) + timedelta(hours=1)) + self.make_account("disabled", auto_managed=False) + now = datetime.now(UTC) + + added = ck_relogin._enqueue_due_relogin_work( + self.session, + job, + now, + max_attempts=2, + protection=load_protection_snapshot(self.session), + limit=10, + ) + self.session.commit() + + queued = self.session.query(AccountWorkItem).all() + assert added == 1 + assert [item.account_id for item in queued] == [ready.id] + + def test_aged_work_item_preempts_new_high_priority_item(self): + job = self.job() + old = self.make_account("old-work") + new = self.make_account("new-work") + now = datetime.now(UTC) + old_work = enqueue_account_work( + self.session, + account_id=old.id, + work_type=ck_relogin.WORK_LOGIN_RELOGIN, + priority=30, + due_at=now - timedelta(seconds=ck_relogin.WORK_AGING_SECONDS + 60), + max_attempts=20, + ) + enqueue_account_work( + self.session, + account_id=new.id, + work_type=ck_relogin.WORK_LOGIN_RELOGIN, + priority=10, + due_at=now, + max_attempts=20, + ) + self.session.commit() + + claimed = ck_relogin._claim_relogin_work( + self.session, + job, + now, + max_attempts=2, + protection=load_protection_snapshot(self.session), + limit=1, + ) + + assert [item.id for item in claimed] == [old_work.id] + def test_high_value_is_picked_before_plain(self): """名额先给第 1 档,其次第 2 档,普通失效号排最后。""" job = self.job(batch_size=3) @@ -674,6 +774,23 @@ class TestLinkageWithHealthJob(_Base): assert relogin["batch_size"] == 10 assert payload["pending_relogin"] == 25 # 不被 limit 10 截断 + def test_pending_count_prefers_persistent_queue(self): + account = self.make_account( + "scheduled", + relogin_next_at=datetime.now(UTC) + timedelta(hours=2), + ) + enqueue_account_work( + self.session, + account_id=account.id, + work_type=ck_relogin.WORK_LOGIN_RELOGIN, + priority=30, + due_at=datetime.now(UTC) + timedelta(hours=2), + max_attempts=20, + ) + self.session.commit() + + assert ck_relogin.count_pending_relogin(self.session) == 1 + class TestSettlementVisibility(_Base): """回归:结算必须用**新事务**读回 runner 提交的结果。 diff --git a/tests/test_background_runtime.py b/tests/test_background_runtime.py new file mode 100644 index 0000000..ad5351a --- /dev/null +++ b/tests/test_background_runtime.py @@ -0,0 +1,94 @@ +"""独立后台进程生命周期测试。""" + +from __future__ import annotations + +from web.backend import background_runtime + + +def test_background_services_start_and_stop_once(monkeypatch): + calls: list[str] = [] + + def mark(name: str): + return lambda *_args, **_kwargs: calls.append(name) or True + + monkeypatch.setattr( + "web.backend.services.automation.register_default_jobs", + mark("register"), + ) + monkeypatch.setattr( + "web.backend.services.automation.start_scheduler", + mark("scheduler"), + ) + monkeypatch.setattr( + "web.backend.services.automation.stop_scheduler", + mark("stop-scheduler"), + ) + monkeypatch.setattr( + "web.backend.services.platform_fulfillment.reconciler." + "start_platform_fulfillment_reconciler", + mark("reconciler"), + ) + monkeypatch.setattr( + "web.backend.services.platform_fulfillment.reconciler." + "stop_platform_fulfillment_reconciler", + mark("stop-reconciler"), + ) + monkeypatch.setattr( + "web.backend.services.platform_fulfillment.auto_allocator." + "start_platform_fulfillment_auto_allocator", + mark("allocator"), + ) + monkeypatch.setattr( + "web.backend.services.platform_fulfillment.auto_allocator." + "stop_platform_fulfillment_auto_allocator", + mark("stop-allocator"), + ) + monkeypatch.setattr( + "web.backend.services.binding_poll_scheduler." + "start_binding_poll_scheduler", + mark("binding"), + ) + monkeypatch.setattr( + "web.backend.services.binding_poll_scheduler." + "stop_binding_poll_scheduler", + mark("stop-binding"), + ) + monkeypatch.setattr( + "web.backend.services.payment_poll_scheduler." + "start_payment_poll_scheduler", + mark("payment"), + ) + monkeypatch.setattr( + "web.backend.services.payment_poll_scheduler." + "stop_payment_poll_scheduler", + mark("stop-payment"), + ) + monkeypatch.setattr( + "web.backend.services.integration.start_integration_outbox_worker", + mark("outbox"), + ) + monkeypatch.setattr( + "web.backend.services.integration.stop_integration_outbox_worker", + mark("stop-outbox"), + ) + + assert background_runtime.start_background_services() is True + assert background_runtime.start_background_services() is False + background_runtime.stop_background_services() + background_runtime.stop_background_services() + + assert calls == [ + "register", + "scheduler", + "outbox", + "reconciler", + "allocator", + "binding", + "payment", + "stop-payment", + "stop-binding", + "stop-allocator", + "stop-reconciler", + "stop-outbox", + "stop-scheduler", + ] diff --git a/tests/test_migrations.py b/tests/test_migrations.py index 89c53b5..59478f2 100644 --- a/tests/test_migrations.py +++ b/tests/test_migrations.py @@ -42,7 +42,7 @@ TESTS_DIR = Path(__file__).resolve().parent PROJECT_ROOT = TESTS_DIR.parent VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions" -HEAD_REVISION = "20261123_0118" +HEAD_REVISION = "20261123_0121" # 迁移新增、但不声明在模型里的复合查询索引。 EXTRA_INDEXES = ( @@ -64,6 +64,7 @@ _ACCOUNT_PLATFORM_COLUMNS = { "ck_invalid_detected_at": "DATETIME NULL", "ck_observed_lifetime_seconds": "INTEGER NULL", "ck_expiry_source": "VARCHAR(24) NOT NULL DEFAULT ''", + "value_tier": "INTEGER NULL", } _LATER_ORM_COLUMNS = { diff --git a/tests/test_platform_fulfillment.py b/tests/test_platform_fulfillment.py index da82b3f..68aa4f7 100644 --- a/tests/test_platform_fulfillment.py +++ b/tests/test_platform_fulfillment.py @@ -8,6 +8,7 @@ from datetime import UTC, datetime, timedelta import pytest from fastapi import HTTPException +from sqlalchemy import event from tests.support.db import get_test_engine, make_test_session from web.backend.deps import require_permission @@ -35,7 +36,7 @@ from web.backend.services.account_sync_runner import WORK_STOREHOME_SYNC from web.backend.services.automation.jobs import ( platform_fulfillment_lease_reaper as reaper, ) -from web.backend.services.platform_fulfillment import account_selector, service +from web.backend.services.platform_fulfillment import account_selector, service, views NOW = datetime.now(UTC).replace(microsecond=0) COMMODITY = "20260120QYOOB_bag10" @@ -63,6 +64,7 @@ class _Base: ) self.session.commit() def teardown_method(self): + views.invalidate_task_list_count_cache() self.session.close() def account( @@ -166,6 +168,62 @@ class _Base: return row +class TestWorkbenchReadPath(_Base): + def mapped_task(self, mapping: PlatformCommodityMapping, index: int): + task = self.task(mapped=False) + task.source_order_item_id = f"workbench-{index}" + task.platform_order_id = f"WORKBENCH-{index}" + task.commodity_mapping_id = mapping.id + task.commodity_id = mapping.commodity_id + task.required_points = mapping.required_points + task.execution_status = "ready" + self.session.commit() + return task + + def test_task_list_count_uses_short_ttl_cache_until_invalidated(self): + views.invalidate_task_list_count_cache() + mapping = self.mapping() + self.mapped_task(mapping, 1) + + first = service.list_tasks(self.session, page_size=100) + assert first["pagination"]["total"] == 1 + + self.mapped_task(mapping, 2) + cached = service.list_tasks(self.session, page_size=100) + assert cached["pagination"]["total"] == 1 + + views.invalidate_task_list_count_cache() + refreshed = service.list_tasks(self.session, page_size=100) + assert refreshed["pagination"]["total"] == 2 + + def test_task_list_loads_relations_in_batches(self): + mapping = self.mapping() + for index in range(5): + self.mapped_task(mapping, index) + views.invalidate_task_list_count_cache() + queries: list[str] = [] + + def count_query( + _conn, + _cursor, + statement, + _parameters, + _context, + _executemany, + ): + queries.append(statement) + + event.listen(self.engine, "before_cursor_execute", count_query) + try: + result = service.list_tasks(self.session, page_size=100) + finally: + event.remove(self.engine, "before_cursor_execute", count_query) + + assert len(result["items"]) == 5 + # COUNT + 分页 + 固定 6 组关联数据,不再随行数增长成 N+1。 + assert len(queries) <= 10 + + class TestSyncAndMapping(_Base): def test_sync_skips_external_orders_when_no_mapping_is_configured( self, monkeypatch diff --git a/web/backend/background_runtime.py b/web/backend/background_runtime.py new file mode 100644 index 0000000..1939c19 --- /dev/null +++ b/web/backend/background_runtime.py @@ -0,0 +1,124 @@ +"""后台服务生命周期:调度、轮询、Outbox 与履约 worker。""" + +from __future__ import annotations + +from loguru import logger + +from .database import SessionLocal + +_started = False + + +def recover_orphaned_work() -> None: + """进程启动时收敛上次中断的任务和运行记录。""" + from .services.account_supply_service import ensure_default_supply_targets + from .services.account_work_queue import recover_running_account_work + from .services.automation.scheduler import cleanup_orphan_runs + from .services.douyu_service import cleanup_orphan_douyu_tasks + from .services.huya_service import cleanup_orphan_huya_tasks + from .services.login_quota_service import cleanup_orphan_login_attempts + from .services.login_service import ( + cleanup_orphan_login_tasks, + cleanup_orphan_relogin_tasks, + ) + from .services.yyb_service import cleanup_orphan_yyb_tasks + + db = SessionLocal() + try: + cleaned_huya = cleanup_orphan_huya_tasks( + db, + message="任务已中断(服务重启)", + ) + if cleaned_huya: + logger.info("启动清理虎牙残留任务: {} 条", cleaned_huya) + cleaned_douyu = cleanup_orphan_douyu_tasks( + db, + message="任务已中断(服务重启)", + ) + if cleaned_douyu: + logger.info("启动清理斗鱼残留任务: {} 条", cleaned_douyu) + cleaned_relogin = cleanup_orphan_relogin_tasks(db) + if cleaned_relogin: + logger.info("启动清理 CK 重登残留任务: {} 条", cleaned_relogin) + cleaned_runs = cleanup_orphan_runs(db) + if cleaned_runs: + logger.info("启动收尾中断的自动化运行记录: {} 条", cleaned_runs) + cleaned_login = cleanup_orphan_login_tasks(db) + if cleaned_login: + logger.info("启动清理登录残留任务: {} 条", cleaned_login) + cleaned_attempts = cleanup_orphan_login_attempts(db) + if cleaned_attempts: + logger.info("启动收敛中断的登录尝试流水: {} 条", cleaned_attempts) + recovered_work = recover_running_account_work(db) + if recovered_work: + logger.info("启动恢复中断的账号内部工作项: {} 条", recovered_work) + seeded_targets = ensure_default_supply_targets(db) + if seeded_targets: + logger.info("已建立默认账号供给目标: {} 条", seeded_targets) + cleaned_yyb = cleanup_orphan_yyb_tasks( + db, + message="任务已中断(服务重启)", + ) + if cleaned_yyb: + logger.info("启动清理应用宝残留任务: {} 条", cleaned_yyb) + finally: + db.close() + + +def start_background_services() -> bool: + global _started + if _started: + return False + from .services.automation import register_default_jobs, start_scheduler + from .services.binding_poll_scheduler import start_binding_poll_scheduler + from .services.integration import start_integration_outbox_worker + from .services.payment_poll_scheduler import start_payment_poll_scheduler + from .services.platform_fulfillment.auto_allocator import ( + start_platform_fulfillment_auto_allocator, + ) + from .services.platform_fulfillment.reconciler import ( + start_platform_fulfillment_reconciler, + ) + + register_default_jobs() + start_scheduler() + start_integration_outbox_worker() + start_platform_fulfillment_reconciler() + start_platform_fulfillment_auto_allocator() + start_binding_poll_scheduler() + start_payment_poll_scheduler() + _started = True + logger.info("后台服务已启动") + return True + + +def stop_background_services() -> None: + global _started + if not _started: + return + from .services.automation import stop_scheduler + from .services.binding_poll_scheduler import stop_binding_poll_scheduler + from .services.integration import stop_integration_outbox_worker + from .services.payment_poll_scheduler import stop_payment_poll_scheduler + from .services.platform_fulfillment.auto_allocator import ( + stop_platform_fulfillment_auto_allocator, + ) + from .services.platform_fulfillment.reconciler import ( + stop_platform_fulfillment_reconciler, + ) + + stop_payment_poll_scheduler() + stop_binding_poll_scheduler() + stop_platform_fulfillment_auto_allocator() + stop_platform_fulfillment_reconciler() + stop_integration_outbox_worker() + stop_scheduler() + _started = False + logger.info("后台服务已停止") + + +__all__ = [ + "recover_orphaned_work", + "start_background_services", + "stop_background_services", +] diff --git a/web/backend/background_worker.py b/web/backend/background_worker.py new file mode 100644 index 0000000..e4537a7 --- /dev/null +++ b/web/backend/background_worker.py @@ -0,0 +1,46 @@ +"""独立后台进程入口。""" + +from __future__ import annotations + +import signal +import threading +from pathlib import Path + +from utils import setup_logger + +from .background_runtime import ( + recover_orphaned_work, + start_background_services, + stop_background_services, +) +from .database import dispose_engines + + +def main() -> None: + import os + + log_dir = Path( + os.getenv("LOG_DIR", str(Path(__file__).resolve().parents[2] / "logs")) + ) + setup_logger( + level=os.getenv("LOG_LEVEL", "INFO"), + log_dir=str(log_dir), + ) + stopped = threading.Event() + + def handle_signal(_signum, _frame) -> None: + stopped.set() + + signal.signal(signal.SIGTERM, handle_signal) + signal.signal(signal.SIGINT, handle_signal) + recover_orphaned_work() + start_background_services() + try: + stopped.wait() + finally: + stop_background_services() + dispose_engines() + + +if __name__ == "__main__": + main() diff --git a/web/backend/main.py b/web/backend/main.py index 345d45c..7d4ad5b 100644 --- a/web/backend/main.py +++ b/web/backend/main.py @@ -54,102 +54,24 @@ async def lifespan(app: FastAPI): setup_logger(level=_log_level, log_dir=str(_log_dir)) init_db() - # 进程重启后内存批次丢失,清理历史 pending/running,避免前端被假活跃批次锁死。 - from loguru import logger - - from .database import SessionLocal, dispose_engines - from .services.account_work_queue import recover_running_account_work - from .services.douyu_service import cleanup_orphan_douyu_tasks - from .services.huya_service import cleanup_orphan_huya_tasks - from .services.login_quota_service import cleanup_orphan_login_attempts - from .services.login_service import ( - cleanup_orphan_login_tasks, - cleanup_orphan_relogin_tasks, - ) - - db = SessionLocal() - try: - cleaned = cleanup_orphan_huya_tasks(db, message="任务已中断(服务重启)") - if cleaned: - logger.info(f"启动清理虎牙残留任务: {cleaned} 条") - cleaned_douyu = cleanup_orphan_douyu_tasks(db, message="任务已中断(服务重启)") - if cleaned_douyu: - logger.info(f"启动清理斗鱼残留任务: {cleaned_douyu} 条") - cleaned_relogin = cleanup_orphan_relogin_tasks(db) - if cleaned_relogin: - logger.info(f"启动清理 CK 重登残留任务: {cleaned_relogin} 条") - from .services.automation.scheduler import cleanup_orphan_runs - - cleaned_runs = cleanup_orphan_runs(db) - if cleaned_runs: - logger.info(f"启动收尾中断的自动化运行记录: {cleaned_runs} 条") - cleaned_login = cleanup_orphan_login_tasks(db) - if cleaned_login: - logger.info(f"启动清理登录残留任务: {cleaned_login} 条") - cleaned_attempts = cleanup_orphan_login_attempts(db) - if cleaned_attempts: - logger.info(f"启动收敛中断的登录尝试流水: {cleaned_attempts} 条") - recovered_work = recover_running_account_work(db) - if recovered_work: - logger.info(f"启动恢复中断的账号内部工作项: {recovered_work} 条") - from .services.account_supply_service import ensure_default_supply_targets - - seeded_targets = ensure_default_supply_targets(db) - if seeded_targets: - logger.info(f"已建立默认账号供给目标: {seeded_targets} 条") - from .services.yyb_service import cleanup_orphan_yyb_tasks - - cleaned_yyb = cleanup_orphan_yyb_tasks(db, message="任务已中断(服务重启)") - if cleaned_yyb: - logger.info(f"启动清理应用宝残留任务: {cleaned_yyb} 条") - finally: - db.close() - - # 自动化调度器:AUTOMATION_ENABLED 未开启时不会起线程(默认关闭)。 - from .services.automation import ( - register_default_jobs, - start_scheduler, - stop_scheduler, - ) - - register_default_jobs() - start_scheduler() - from .services.binding_poll_scheduler import ( - start_binding_poll_scheduler, - stop_binding_poll_scheduler, - ) - from .services.integration import ( - start_integration_outbox_worker, - stop_integration_outbox_worker, - ) - from .services.payment_poll_scheduler import ( - start_payment_poll_scheduler, - stop_payment_poll_scheduler, - ) - from .services.platform_fulfillment.auto_allocator import ( - start_platform_fulfillment_auto_allocator, - stop_platform_fulfillment_auto_allocator, - ) - from .services.platform_fulfillment.reconciler import ( - start_platform_fulfillment_reconciler, - stop_platform_fulfillment_reconciler, + from .background_runtime import ( + recover_orphaned_work, + start_background_services, + stop_background_services, ) + from .database import dispose_engines from .services.task_runtime import shutdown as shutdown_task_runtime - start_integration_outbox_worker() - start_platform_fulfillment_reconciler() - start_platform_fulfillment_auto_allocator() - start_binding_poll_scheduler() - start_payment_poll_scheduler() + role = os.getenv("RUNTIME_ROLE", "all").strip().lower() + background_in_process = role in {"all", "background"} + if background_in_process: + recover_orphaned_work() + start_background_services() try: yield finally: - stop_payment_poll_scheduler() - stop_binding_poll_scheduler() - stop_platform_fulfillment_auto_allocator() - stop_platform_fulfillment_reconciler() - stop_integration_outbox_worker() - stop_scheduler() + if background_in_process: + stop_background_services() shutdown_task_runtime(wait=False) dispose_engines() diff --git a/web/backend/migrations/migration_manifest.json b/web/backend/migrations/migration_manifest.json index ce7214e..2489724 100644 --- a/web/backend/migrations/migration_manifest.json +++ b/web/backend/migrations/migration_manifest.json @@ -473,6 +473,18 @@ "20261123_0118_account_platform_dashboard_indexes.py": { "revision": "20261123_0118", "sha256": "18af99f5be4afba9554c12a8fe0cef553948c4db07faf14c11a612dbd2290e42" + }, + "20261123_0119_account_supply_snapshots.py": { + "revision": "20261123_0119", + "sha256": "1b5fefe06f1e17d8b5a732f4a55489b01528342b84d69b0722e80d5ff0f761f2" + }, + "20261123_0120_account_value_projection.py": { + "revision": "20261123_0120", + "sha256": "ae61b7107f99d7e7f92b3f94af791c53bae37836029653f4aa6fbeb7db715a20" + }, + "20261123_0121_douyu_tasks_retention_index.py": { + "revision": "20261123_0121", + "sha256": "82b5732895b1613cb017a7ea28f39b4c5b53bc48b0c92422b6ac2fca3bf7b92b" } } } diff --git a/web/backend/migrations/versions/20261123_0119_account_supply_snapshots.py b/web/backend/migrations/versions/20261123_0119_account_supply_snapshots.py new file mode 100644 index 0000000..bbb4b0c --- /dev/null +++ b/web/backend/migrations/versions/20261123_0119_account_supply_snapshots.py @@ -0,0 +1,51 @@ +"""add account supply snapshots. + +Revision ID: 20261123_0119 +Revises: 20261123_0118 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261123_0119" +down_revision: str | None = "20261123_0118" +branch_labels: str | None = None +depends_on: str | None = None + + +def upgrade() -> None: + if sa.inspect(op.get_bind()).has_table("account_supply_snapshots"): + return + op.create_table( + "account_supply_snapshots", + sa.Column("id", sa.BigInteger(), primary_key=True, autoincrement=True), + sa.Column( + "target_id", + sa.Integer(), + sa.ForeignKey("account_supply_targets.id", ondelete="CASCADE"), + nullable=False, + ), + sa.Column("covered", sa.Integer(), nullable=False, server_default="0"), + sa.Column("available", sa.Integer(), nullable=False, server_default="0"), + sa.Column("allocatable", sa.Integer(), nullable=False, server_default="0"), + sa.Column("checked_at", sa.DateTime(), nullable=False), + sa.Column( + "updated_at", + sa.DateTime(), + nullable=False, + server_default=sa.text("CURRENT_TIMESTAMP"), + ), + sa.UniqueConstraint("target_id", name="uq_account_supply_snapshot_target"), + ) + op.create_index( + "ix_account_supply_snapshot_checked", + "account_supply_snapshots", + ["checked_at"], + ) + + +def downgrade() -> None: + if sa.inspect(op.get_bind()).has_table("account_supply_snapshots"): + op.drop_table("account_supply_snapshots") diff --git a/web/backend/migrations/versions/20261123_0120_account_value_projection.py b/web/backend/migrations/versions/20261123_0120_account_value_projection.py new file mode 100644 index 0000000..dd17177 --- /dev/null +++ b/web/backend/migrations/versions/20261123_0120_account_value_projection.py @@ -0,0 +1,85 @@ +"""add account value tier projection. + +Revision ID: 20261123_0120 +Revises: 20261123_0119 +""" + +from __future__ import annotations + +from datetime import UTC, datetime, timedelta + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261123_0120" +down_revision: str | None = "20261123_0119" +branch_labels: str | None = None +depends_on: str | None = None + + +def upgrade() -> None: + columns = { + str(column["name"]) + for column in sa.inspect(op.get_bind()).get_columns("accounts") + } + if "value_tier" not in columns: + op.add_column( + "accounts", + sa.Column("value_tier", sa.Integer(), nullable=True), + ) + indexes = { + str(index["name"]) + for index in sa.inspect(op.get_bind()).get_indexes("accounts") + if index.get("name") + } + if "ix_accounts_value_tier" not in indexes: + op.create_index( + "ix_accounts_value_tier", + "accounts", + ["value_tier", "id"], + ) + cutoff = datetime.now(UTC) - timedelta(days=7) + op.execute( + sa.text( + """ + UPDATE accounts + SET value_tier = CASE + WHEN high_value_checked_at >= :cutoff + AND high_value_bairimeng_status = 'available' + AND high_value_mengtu_status = 'available' + THEN 1 + WHEN ( + high_value_checked_at >= :cutoff + AND ( + high_value_bairimeng_status = 'available' + OR high_value_mengtu_status = 'available' + ) + ) + OR COALESCE(points, 0) >= 300 + THEN 2 + WHEN COALESCE(gold_balance, 0) > 0 + OR elite_opened = 1 + THEN 3 + WHEN overview_queried_at IS NOT NULL + THEN 4 + ELSE 5 + END + """ + ).bindparams(cutoff=cutoff) + ) + + +def downgrade() -> None: + indexes = { + str(index["name"]) + for index in sa.inspect(op.get_bind()).get_indexes("accounts") + if index.get("name") + } + if "ix_accounts_value_tier" in indexes: + op.drop_index("ix_accounts_value_tier", table_name="accounts") + columns = { + str(column["name"]) + for column in sa.inspect(op.get_bind()).get_columns("accounts") + } + if "value_tier" in columns: + op.drop_column("accounts", "value_tier") diff --git a/web/backend/migrations/versions/20261123_0121_douyu_tasks_retention_index.py b/web/backend/migrations/versions/20261123_0121_douyu_tasks_retention_index.py new file mode 100644 index 0000000..6e65127 --- /dev/null +++ b/web/backend/migrations/versions/20261123_0121_douyu_tasks_retention_index.py @@ -0,0 +1,41 @@ +"""add douyu task retention scan index. + +Revision ID: 20261123_0121 +Revises: 20261123_0120 +""" + +from __future__ import annotations + +import sqlalchemy as sa +from alembic import op + +revision: str = "20261123_0121" +down_revision: str | None = "20261123_0120" +branch_labels: str | None = None +depends_on: str | None = None + +INDEX_NAME = "ix_douyu_tasks_retention_scan" + + +def upgrade() -> None: + indexes = { + str(index["name"]) + for index in sa.inspect(op.get_bind()).get_indexes("douyu_tasks") + if index.get("name") + } + if INDEX_NAME not in indexes: + op.create_index( + INDEX_NAME, + "douyu_tasks", + ["task_type", "status", "created_at", "id"], + ) + + +def downgrade() -> None: + indexes = { + str(index["name"]) + for index in sa.inspect(op.get_bind()).get_indexes("douyu_tasks") + if index.get("name") + } + if INDEX_NAME in indexes: + op.drop_index(INDEX_NAME, table_name="douyu_tasks") diff --git a/web/backend/models.py b/web/backend/models.py index 362ffea..7941450 100644 --- a/web/backend/models.py +++ b/web/backend/models.py @@ -150,6 +150,9 @@ class Account(Base): overview_queried_at: Mapped[datetime | None] = mapped_column( UTCDateTime, nullable=True ) + # 账号价值 1-5 档的后台投影。为空时查询会回退实时 CASE,便于新账号和 + # 灰度期间保持正确;生产行由 account_value_projection 作业周期性刷新。 + value_tier: Mapped[int | None] = mapped_column(Integer, nullable=True) # 积分**到期时刻**(斗鱼在积分查询里给 `willExpireTime`,只有送礼后的那次查询才有)。 # 积分到期是账号资产的真实减少,但斗鱼不会「通知」你 —— 所以这里记下到期时刻, # 由作业在到期后补记一条 `points_expire` 事件(否则这个减少在时间线上是空白)。 @@ -288,6 +291,7 @@ class Account(Base): Index("ix_accounts_status", "status"), # 高价值三态的过期判定和待刷新筛选 Index("ix_accounts_high_value_checked_at", "high_value_checked_at"), + Index("ix_accounts_value_tier", "value_tier", "id"), # 账号池选号:先按自动管理/生命周期过滤,再按 CK、积分和到期时间排序。 # 这条索引避免每次选号都回表扫描全部账号后再排序。 Index( @@ -463,6 +467,13 @@ class DouyuTask(Base): "next_run_at", "id", ), + Index( + "ix_douyu_tasks_retention_scan", + "task_type", + "status", + "created_at", + "id", + ), Index( "uq_douyu_tasks_active_binding", "active_binding_key", @@ -2670,6 +2681,36 @@ class AccountSupplyTarget(Base): ) +class AccountSupplySnapshot(Base): + """供给目标的最近一次聚合结果,隔离页面读取与重型账号扫描。""" + + __tablename__ = "account_supply_snapshots" + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True) + target_id: Mapped[int] = mapped_column( + ForeignKey("account_supply_targets.id", ondelete="CASCADE"), + nullable=False, + unique=True, + ) + covered: Mapped[int] = mapped_column( + Integer, nullable=False, default=0, server_default="0" + ) + available: Mapped[int] = mapped_column( + Integer, nullable=False, default=0, server_default="0" + ) + allocatable: Mapped[int] = mapped_column( + Integer, nullable=False, default=0, server_default="0" + ) + checked_at: Mapped[datetime] = mapped_column(UTCDateTime, nullable=False) + updated_at: Mapped[datetime] = mapped_column( + UTCDateTime, default=_utcnow, onupdate=_utcnow + ) + + __table_args__ = ( + Index("ix_account_supply_snapshot_checked", "checked_at"), + ) + + class LoginAttempt(Base): """一次完整登录/重登/账号检测尝试,只追加。""" diff --git a/web/backend/routers/douyu.py b/web/backend/routers/douyu.py index cabfa89..ade28cc 100644 --- a/web/backend/routers/douyu.py +++ b/web/backend/routers/douyu.py @@ -78,7 +78,7 @@ from ..services.account_protection_service import ( from ..services.account_supply_service import ( SupplyInventory, evaluate_supply_target, - evaluate_supply_targets, + load_supply_snapshot_inventories, update_supply_target, upsert_supply_target, ) @@ -1113,7 +1113,9 @@ def list_supply_targets( ) .all() ) - enabled_inventories = {item.target_id: item for item in evaluate_supply_targets(db)} + enabled_inventories = { + item.target_id: item for item in load_supply_snapshot_inventories(db) + } return [ _supply_target_out( db, diff --git a/web/backend/routers/platform_fulfillment.py b/web/backend/routers/platform_fulfillment.py index 704f369..1fee799 100644 --- a/web/backend/routers/platform_fulfillment.py +++ b/web/backend/routers/platform_fulfillment.py @@ -66,6 +66,11 @@ def update_settings( detail=result, ) db.commit() + from ..services.platform_fulfillment.views import ( + invalidate_task_list_count_cache, + ) + + invalidate_task_list_count_cache() return result @@ -115,6 +120,11 @@ def sync_tasks( detail=result, ) db.commit() + from ..services.platform_fulfillment.views import ( + invalidate_task_list_count_cache, + ) + + invalidate_task_list_count_cache() return result diff --git a/web/backend/services/account_observability.py b/web/backend/services/account_observability.py index 02cfee8..44f91ab 100644 --- a/web/backend/services/account_observability.py +++ b/web/backend/services/account_observability.py @@ -12,6 +12,8 @@ from ..models import ( Account, AccountCommodityState, AccountEvent, + AccountSupplySnapshot, + AccountSupplyTarget, AccountSyncRun, AccountSyncState, AccountWorkItem, @@ -19,7 +21,7 @@ from ..models import ( ) from .account_capability_service import AVAILABILITY_AVAILABLE, AVAILABILITY_LIMITED from .account_protection_service import evaluate_protection_targets -from .account_supply_service import evaluate_supply_targets +from .account_supply_service import load_supply_snapshot_inventories TREND_DAYS = 7 @@ -265,7 +267,7 @@ def _supply_snapshot( db: Session, moment: datetime, ) -> tuple[list[dict[str, Any]], list[dict[str, Any]]]: - inventories = evaluate_supply_targets(db, now=moment) + inventories = load_supply_snapshot_inventories(db, now=moment) supply_targets: list[dict[str, Any]] = [] alerts: list[dict[str, Any]] = [] for item in inventories: @@ -331,8 +333,18 @@ def account_supply_snapshot( """返回可延迟加载的账号供给库存,避免阻塞运行总览首屏。""" moment = now or datetime.now(UTC) supply_targets, alerts = _supply_snapshot(db, moment) + checked_at = ( + db.query(func.max(AccountSupplySnapshot.checked_at)) + .join( + AccountSupplyTarget, + AccountSupplyTarget.id == AccountSupplySnapshot.target_id, + ) + .filter(AccountSupplyTarget.enabled.is_(True)) + .scalar() + or moment + ) return { - "checked_at": moment, + "checked_at": checked_at, "supply_targets": supply_targets, "alerts": alerts, } diff --git a/web/backend/services/account_supply_service.py b/web/backend/services/account_supply_service.py index 58fc012..e993791 100644 --- a/web/backend/services/account_supply_service.py +++ b/web/backend/services/account_supply_service.py @@ -4,7 +4,7 @@ from __future__ import annotations import os from dataclasses import dataclass -from datetime import UTC, datetime +from datetime import UTC, datetime, timedelta from sqlalchemy import and_, case, func, select from sqlalchemy.exc import IntegrityError @@ -13,6 +13,7 @@ from sqlalchemy.orm import Session from ..models import ( Account, AccountCommodityState, + AccountSupplySnapshot, AccountSupplyTarget, AccountSyncState, ) @@ -58,6 +59,7 @@ DEFAULT_SUPPLY_TARGETS = ( "safety_buffer": 60, }, ) +DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS = 15 * 60 @dataclass(frozen=True) @@ -364,6 +366,123 @@ def evaluate_supply_targets( return inventories +def _enabled_supply_targets(db: Session) -> list[AccountSupplyTarget]: + return ( + db.query(AccountSupplyTarget) + .filter(AccountSupplyTarget.enabled.is_(True)) + .order_by( + AccountSupplyTarget.platform.asc(), + AccountSupplyTarget.scope.asc(), + AccountSupplyTarget.value_class.asc(), + AccountSupplyTarget.commodity_id.asc(), + ) + .all() + ) + + +def supply_snapshot_max_age_seconds() -> int: + raw = os.getenv( + "ACCOUNT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS", + str(DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS), + ) + try: + return max(30, int(raw)) + except ValueError: + return DEFAULT_SUPPLY_SNAPSHOT_MAX_AGE_SECONDS + + +def refresh_supply_snapshots( + db: Session, + *, + now: datetime | None = None, +) -> list[SupplyInventory]: + """重算并持久化供给快照;只由后台作业或明确的回源路径调用。""" + moment = now or datetime.now(UTC) + inventories = evaluate_supply_targets(db, now=moment) + existing = { + int(row.target_id): row + for row in db.query(AccountSupplySnapshot) + .filter( + AccountSupplySnapshot.target_id.in_( + [item.target_id for item in inventories] + ) + ) + .all() + } if inventories else {} + for inventory in inventories: + row = existing.get(inventory.target_id) + if row is None: + row = AccountSupplySnapshot( + target_id=inventory.target_id, + covered=inventory.covered, + available=inventory.available, + allocatable=inventory.allocatable, + checked_at=moment, + ) + try: + with db.begin_nested(): + db.add(row) + db.flush() + except IntegrityError: + row = ( + db.query(AccountSupplySnapshot) + .filter( + AccountSupplySnapshot.target_id + == inventory.target_id + ) + .one() + ) + row.covered = inventory.covered + row.available = inventory.available + row.allocatable = inventory.allocatable + row.checked_at = moment + row.updated_at = moment + if inventories: + db.commit() + return inventories + + +def load_supply_snapshot_inventories( + db: Session, + *, + now: datetime | None = None, + refresh_if_stale: bool = True, +) -> list[SupplyInventory]: + """优先读快照;缺失或超过有效期时回源一次并刷新快照。""" + moment = now or datetime.now(UTC) + targets = _enabled_supply_targets(db) + if not targets: + return [] + snapshots = { + int(row.target_id): row + for row in db.query(AccountSupplySnapshot) + .filter( + AccountSupplySnapshot.target_id.in_( + [int(target.id) for target in targets] + ) + ) + .all() + } + fresh_after = moment - timedelta(seconds=supply_snapshot_max_age_seconds()) + if all( + int(target.id) in snapshots + and snapshots[int(target.id)].checked_at >= fresh_after + for target in targets + ): + return [ + _inventory_from_counts( + target, + covered=int(snapshots[int(target.id)].covered or 0), + available=int(snapshots[int(target.id)].available or 0), + allocatable=int(snapshots[int(target.id)].allocatable or 0), + ) + for target in targets + ] + if refresh_if_stale: + return refresh_supply_snapshots(db, now=moment) + return evaluate_supply_targets(db, now=moment) + + def upsert_supply_target( db: Session, *, @@ -569,7 +688,7 @@ def enqueue_supply_replenishment( ) -> SupplyReplenishmentResult: """按本地目标缺口定向入队 storehome 同步,不发起外部请求。""" moment = now or datetime.now(UTC) - inventories = evaluate_supply_targets(db, now=moment) + inventories = load_supply_snapshot_inventories(db, now=moment) queued = 0 shortages = 0 pending = active_account_work_count( @@ -633,6 +752,8 @@ __all__ = [ "ensure_default_supply_targets", "evaluate_supply_target", "evaluate_supply_targets", + "load_supply_snapshot_inventories", + "refresh_supply_snapshots", "update_supply_target", "upsert_supply_target", ] diff --git a/web/backend/services/account_value.py b/web/backend/services/account_value.py index 479e5b6..e6bf536 100644 --- a/web/backend/services/account_value.py +++ b/web/backend/services/account_value.py @@ -19,6 +19,7 @@ from __future__ import annotations from datetime import UTC, datetime, timedelta from sqlalchemy import and_, case, or_ +from sqlalchemy.orm import Session from ..models import Account from .high_value_service import ( @@ -134,8 +135,8 @@ def high_value_needs_refresh_expr( ) -def value_tier_expr(*, now: datetime | None = None): - """1–5 档。没查过、也没有任何资产信号时落在第 5 档。""" +def _computed_value_tier_expr(*, now: datetime | None = None): + """实时计算 1–5 档,仅用于投影回填和冷启动回退。""" available_bairimeng = suit_available_expr("bairimeng", now=now) available_mengtu = suit_available_expr("mengtu", now=now) both_available = and_(available_bairimeng, available_mengtu) @@ -152,6 +153,14 @@ def value_tier_expr(*, now: datetime | None = None): ) +def value_tier_expr(*, now: datetime | None = None): + """优先读后台投影;投影缺失时回退实时计算,保证灰度期行为不变。""" + return case( + (Account.value_tier.isnot(None), Account.value_tier), + else_=_computed_value_tier_expr(now=now), + ) + + def is_high_value_expr(*, now: datetime | None = None): """第 1、2 档:巡检加密、重登插队、列表「高价值待救」都用这一条。""" return value_tier_expr(now=now) <= HIGH_VALUE_TIER_MAX @@ -175,6 +184,48 @@ def is_high_value_account( return available or int(account.points or 0) >= HIGH_VALUE_POINTS +def refresh_account_value_tiers( + db: Session, + *, + now: datetime | None = None, + batch_size: int = 1000, +) -> int: + """分批刷新账号价值投影,避免在页面请求里反复执行大 CASE。""" + moment = now or datetime.now(UTC) + batch = max(1, int(batch_size)) + last_id = 0 + changed = 0 + while True: + account_ids = [ + int(row[0]) + for row in ( + db.query(Account.id) + .filter(Account.id > last_id) + .order_by(Account.id.asc()) + .limit(batch) + .all() + ) + ] + if not account_ids: + break + tier = _computed_value_tier_expr(now=moment) + changed += int( + db.query(Account) + .filter( + Account.id.in_(account_ids), + or_( + Account.value_tier.is_(None), + Account.value_tier != tier, + ), + ) + .update({Account.value_tier: tier}, synchronize_session=False) + or 0 + ) + db.commit() + last_id = account_ids[-1] + return changed + + def suit_sort_rank_expr(*, now: datetime | None = None): """列表「高价值套装」列的排序,和格子上看到的一致。数字越小越值钱。 diff --git a/web/backend/services/account_work_queue.py b/web/backend/services/account_work_queue.py index 4766c0b..87a9e89 100644 --- a/web/backend/services/account_work_queue.py +++ b/web/backend/services/account_work_queue.py @@ -5,12 +5,14 @@ from __future__ import annotations from datetime import UTC, datetime, timedelta from typing import Any -from sqlalchemy import func, select +from sqlalchemy import case, func, select from sqlalchemy.exc import IntegrityError from sqlalchemy.orm import Session from ..models import Account, AccountWorkItem +WORK_AGING_SECONDS = 30 * 60 + def active_account_work_exists(*, work_type: str): """SQL 子查询:同一账号已有同类型的待执行或运行中工作。""" @@ -121,6 +123,16 @@ def claim_account_work( rows = ( query .order_by( + # 到期超过 30 分钟的工作优先出队,避免固定业务优先级造成永久饥饿。 + # due_at 是工作项真正可执行的起点;未来重试项不会命中这个分支。 + case( + ( + AccountWorkItem.due_at + <= moment - timedelta(seconds=WORK_AGING_SECONDS), + 0, + ), + else_=1, + ), AccountWorkItem.priority.asc(), AccountWorkItem.due_at.asc(), AccountWorkItem.id.asc(), diff --git a/web/backend/services/automation/__init__.py b/web/backend/services/automation/__init__.py index cc6f843..fd7ef2d 100644 --- a/web/backend/services/automation/__init__.py +++ b/web/backend/services/automation/__init__.py @@ -24,6 +24,12 @@ from .jobs.account_sync_queue import ( from .jobs.account_sync_queue import ( run_account_sync_queue_job, ) +from .jobs.account_value_projection import ( + JOB_KEY as ACCOUNT_VALUE_PROJECTION_KEY, +) +from .jobs.account_value_projection import ( + run_account_value_projection, +) from .jobs.ck_health import JOB_KEY as CK_HEALTH_KEY from .jobs.ck_health import run_ck_health from .jobs.ck_relogin import JOB_KEY as CK_RELOGIN_KEY @@ -60,6 +66,7 @@ __all__ = [ "ACCOUNT_CAPABILITY_REFRESH_KEY", "ACCOUNT_SUPPLY_REPLENISHMENT_KEY", "ACCOUNT_SYNC_QUEUE_KEY", + "ACCOUNT_VALUE_PROJECTION_KEY", "CK_HEALTH_KEY", "CK_RELOGIN_KEY", "DOUYU_TASKS_RETENTION_KEY", @@ -75,6 +82,7 @@ __all__ = [ "run_account_capability_refresh", "run_account_supply_replenishment", "run_account_sync_queue_job", + "run_account_value_projection", "run_ck_health", "run_ck_relogin", "run_douyu_tasks_retention", @@ -114,6 +122,18 @@ def register_default_jobs() -> None: default_enabled=True, ) ) + register_job( + JobSpec( + key=ACCOUNT_VALUE_PROJECTION_KEY, + title="账号价值投影刷新", + interval_seconds=10 * 60, + run_interval_seconds=10 * 60, + batch_size=1000, + concurrency=1, + run=run_account_value_projection, + default_enabled=True, + ) + ) register_job( JobSpec( key=ACCOUNT_CAPABILITY_REFRESH_KEY, diff --git a/web/backend/services/automation/jobs/account_supply_replenishment.py b/web/backend/services/automation/jobs/account_supply_replenishment.py index 649b7ba..829ea0a 100644 --- a/web/backend/services/automation/jobs/account_supply_replenishment.py +++ b/web/backend/services/automation/jobs/account_supply_replenishment.py @@ -7,7 +7,10 @@ from typing import Any from sqlalchemy.orm import Session from ....models import AutomationJob -from ...account_supply_service import enqueue_supply_replenishment +from ...account_supply_service import ( + enqueue_supply_replenishment, + refresh_supply_snapshots, +) JOB_KEY = "account_supply_replenishment" @@ -16,6 +19,7 @@ def run_account_supply_replenishment( db: Session, job: AutomationJob, ) -> dict[str, Any]: + snapshots = refresh_supply_snapshots(db) result = enqueue_supply_replenishment( db, max_per_target=max(1, int(job.batch_size or 50)), @@ -34,6 +38,7 @@ def run_account_supply_replenishment( "detail": { "shortages": result.shortages, "queued": result.queued, + "snapshots": len(snapshots), }, } diff --git a/web/backend/services/automation/jobs/account_value_projection.py b/web/backend/services/automation/jobs/account_value_projection.py new file mode 100644 index 0000000..b13e86b --- /dev/null +++ b/web/backend/services/automation/jobs/account_value_projection.py @@ -0,0 +1,32 @@ +"""低频刷新账号价值投影。""" + +from __future__ import annotations + +from typing import Any + +from sqlalchemy.orm import Session + +from ....models import AutomationJob +from ...account_value import refresh_account_value_tiers + +JOB_KEY = "account_value_projection" + + +def run_account_value_projection( + db: Session, + job: AutomationJob, +) -> dict[str, Any]: + changed = refresh_account_value_tiers( + db, + batch_size=max(100, min(int(job.batch_size or 1000), 5000)), + ) + return { + "scanned": changed, + "success": changed, + "invalid": 0, + "skipped": 0, + "message": f"刷新账号价值投影 {changed} 条", + } + + +__all__ = ["JOB_KEY", "run_account_value_projection"] diff --git a/web/backend/services/automation/jobs/ck_relogin.py b/web/backend/services/automation/jobs/ck_relogin.py index eebe639..9ea66bd 100644 --- a/web/backend/services/automation/jobs/ck_relogin.py +++ b/web/backend/services/automation/jobs/ck_relogin.py @@ -25,6 +25,7 @@ from sqlalchemy.orm import Session from ....database import WorkerSessionLocal from ....models import ( Account, + AccountWorkItem, AutomationJob, LoginAttempt, LoginQuotaSetting, @@ -46,6 +47,8 @@ from ...account_protection_service import ( from ...account_query_filters import automation_account_filter from ...account_value import value_tier_expr from ...account_work_queue import ( + WORK_AGING_SECONDS, + active_account_work_exists, claim_account_work, enqueue_account_work, fail_account_work_type, @@ -80,6 +83,7 @@ DEFAULT_ADAPTIVE_MIN_SAMPLE = 10 DEFAULT_ADAPTIVE_GROW_RATE = 90.0 DEFAULT_ADAPTIVE_SHRINK_RATE = 70.0 DEFAULT_ADAPTIVE_GROW_FACTOR = 1.25 +DEFAULT_ADAPTIVE_MAX_BATCH_SIZE = 20 @dataclass(frozen=True) @@ -106,6 +110,7 @@ def build_select_query( system_user_id: int | None = None, batch_limit: int | None = None, protection: ProtectionSnapshot | None = None, + apply_limit: bool = True, ): """构造本轮重登候选的查询(与取行分开,便于按方言编译做回归)。 @@ -117,31 +122,15 @@ def build_select_query( ``cookie_operable_filter`` 的 NOT EXISTS 子查询完成,走迁移 0042 新增的 ``(account_id, attempt_status)`` 索引。 """ - query = ( - db.query(Account) - .filter(Account.ck_check_status == "invalid") - .filter(automation_account_filter()) - # 停用/归档的账号一律不碰(生命周期状态机,见 account_lifecycle)。 - .filter(Account.relogin_attempts < max_attempts) - .filter( - or_( - Account.relogin_next_at.is_(None), - Account.relogin_next_at <= _cutoff(now), - ) - ) - ) - # 已判定需要人工的类型不再自动重试(极验/凭证)。空值用 coalesce 兜住历史值。 - query = query.filter( - func.coalesce(Account.relogin_failure_kind, "").notin_( - tuple(sorted(MANUAL_KINDS)) - ) - ) snapshot = protection or load_protection_snapshot(db) - suppressed_ids = snapshot.suppressed_relogin_ids - if suppressed_ids: - # 保护组可以分别关闭自动重登。账号同时属于任一已开启自动重登的组时, - # 仍按允许处理;只有完全被抑制的账号才排除。 - query = query.filter(~Account.id.in_(suppressed_ids)) + query = _eligible_account_query( + db, + now, + max_attempts=max_attempts, + protection=snapshot, + cookie_operable=True, + due_only=True, + ) relogin_ids = snapshot.relogin_ids if system_user_id is not None: pass # 预留:将来若需要限制到某个归属人,在这里加过滤 @@ -162,7 +151,208 @@ def build_select_query( 1 if relogin_ids else 0, value_tier_expr().asc(), ) - return query.order_by(*ordering).limit(max(limit, 1)) + query = query.order_by(*ordering) + return query.limit(max(limit, 1)) if apply_limit else query + + +def _eligible_account_query( + db: Session, + now: datetime, + *, + max_attempts: int, + protection: ProtectionSnapshot, + cookie_operable: bool, + due_only: bool, +): + """自动重登的账号级准入条件,执行、补货和计数共用同一套语义。""" + query = ( + db.query(Account) + .filter(Account.ck_check_status == "invalid") + .filter( + automation_account_filter(cookie_operable=cookie_operable) + ) + # 停用/归档的账号一律不碰(生命周期状态机,见 account_lifecycle)。 + .filter(Account.relogin_attempts < max_attempts) + # 已判定需要人工的类型不再自动重试。空值用 coalesce 兜住历史值。 + .filter( + func.coalesce(Account.relogin_failure_kind, "").notin_( + tuple(sorted(MANUAL_KINDS)) + ) + ) + ) + if due_only: + query = query.filter( + or_( + Account.relogin_next_at.is_(None), + Account.relogin_next_at <= _cutoff(now), + ) + ) + if protection.suppressed_relogin_ids: + # 保护组可以分别关闭自动重登。账号同时属于任一已开启自动重登的组时, + # 仍按允许处理;只有完全被抑制的账号才排除。 + query = query.filter( + ~Account.id.in_(protection.suppressed_relogin_ids) + ) + return query + + +def _pending_relogin_work_count( + db: Session, + *, + now: datetime, +) -> int: + return int( + db.query(func.count(AccountWorkItem.id)) + .filter( + AccountWorkItem.work_type == WORK_LOGIN_RELOGIN, + AccountWorkItem.status == "pending", + AccountWorkItem.due_at <= now, + ) + .scalar() + or 0 + ) + + +def _enqueue_due_relogin_work( + db: Session, + job: AutomationJob, + now: datetime, + *, + max_attempts: int, + protection: ProtectionSnapshot, + limit: int, +) -> int: + """把已判定失效但尚未进入队列的账号补成持久工作项。""" + accounts = build_select_query( + db, + job, + now, + max_attempts=max_attempts, + protection=protection, + apply_limit=False, + ).filter( + ~active_account_work_exists(work_type=WORK_LOGIN_RELOGIN) + ).limit(max(1, limit)).all() + for account in accounts: + priority = 10 if int(account.id) in protection.relogin_ids else 30 + enqueue_account_work( + db, + account_id=int(account.id), + work_type=WORK_LOGIN_RELOGIN, + priority=priority, + max_attempts=20, + due_at=now, + reason="CK 已判定失效,等待受预算控制的重登", + ) + if accounts: + db.flush() + return len(accounts) + + +def _count_actionable_relogin_accounts( + db: Session, + *, + now: datetime, + max_attempts: int, + protection: ProtectionSnapshot, + due_only: bool, +) -> int: + return int( + _eligible_account_query( + db, + now, + max_attempts=max_attempts, + protection=protection, + cookie_operable=False, + due_only=due_only, + ) + .with_entities(func.count(Account.id)) + .scalar() + or 0 + ) + + +def _queued_actionable_relogin_count( + db: Session, + *, + now: datetime, + max_attempts: int, + protection: ProtectionSnapshot, +) -> int: + eligible_ids = _eligible_account_query( + db, + now, + max_attempts=max_attempts, + protection=protection, + cookie_operable=False, + due_only=False, + ).with_entities(Account.id) + return int( + db.query(func.count(AccountWorkItem.id)) + .filter( + AccountWorkItem.work_type == WORK_LOGIN_RELOGIN, + AccountWorkItem.status == "pending", + AccountWorkItem.account_id.in_(eligible_ids), + ) + .scalar() + or 0 + ) + + +def _claim_relogin_work( + db: Session, + job: AutomationJob, + now: datetime, + *, + max_attempts: int, + protection: ProtectionSnapshot, + limit: int, +) -> list[AccountWorkItem]: + """从持久队列领取重登任务,而不是每轮重新从账号表直接选执行对象。""" + eligible_ids = build_select_query( + db, + job, + now, + max_attempts=max_attempts, + protection=protection, + apply_limit=False, + ).with_entities(Account.id) + account_ids = [ + int(account_id) + for (account_id,) in ( + db.query(AccountWorkItem.account_id) + .filter( + AccountWorkItem.work_type == WORK_LOGIN_RELOGIN, + AccountWorkItem.status == "pending", + AccountWorkItem.due_at <= now, + AccountWorkItem.account_id.in_(eligible_ids), + ) + .order_by( + case( + ( + AccountWorkItem.due_at + <= now - timedelta(seconds=WORK_AGING_SECONDS), + 0, + ), + else_=1, + ), + AccountWorkItem.priority.asc(), + AccountWorkItem.due_at.asc(), + AccountWorkItem.id.asc(), + ) + .limit(max(1, limit)) + .all() + ) + ] + if not account_ids: + return [] + return claim_account_work( + db, + work_types=(WORK_LOGIN_RELOGIN,), + account_ids=tuple(account_ids), + limit=limit, + now=now, + ) def _load_batch_state( @@ -241,22 +431,23 @@ def count_pending_relogin(db: Session, *, max_attempts: int = 2) -> int: count 只会得到批次上限(页面上显示恒等于 10),完全看不出积压。这里也**不 按退避窗口过滤** —— 退避是「什么时候试」的细节,不影响「还有多少要处理」。 """ + now = datetime.now(UTC) snapshot = load_protection_snapshot(db) - query = ( - db.query(func.count(Account.id)) - .filter(Account.ck_check_status == "invalid") - .filter(automation_account_filter(cookie_operable=False)) - # 停用/归档不计入积压(它们不会被自动处理,显示出来只会误导) - .filter(Account.relogin_attempts < max_attempts) - .filter( - func.coalesce(Account.relogin_failure_kind, "").notin_( - tuple(sorted(MANUAL_KINDS)) - ) - ) + queued = _queued_actionable_relogin_count( + db, + now=now, + max_attempts=max_attempts, + protection=snapshot, + ) + if queued: + return queued + return _count_actionable_relogin_accounts( + db, + now=now, + max_attempts=max_attempts, + protection=snapshot, + due_only=False, ) - if snapshot.suppressed_relogin_ids: - query = query.filter(~Account.id.in_(snapshot.suppressed_relogin_ids)) - return int(query.scalar() or 0) def _system_user_id(db: Session) -> int | None: @@ -376,12 +567,22 @@ def resolve_adaptive_batch_size( ) -> AdaptiveBatchDecision: """Scale the effective relogin batch inside the operator-configured ceiling.""" config = dict(job.config or {}) - configured_max = max(int(job.batch_size or 1), 1) + configured_batch_size = max(int(job.batch_size or 1), 1) + configured_max = max( + configured_batch_size, + int( + config.get( + "adaptive_max_batch_size", + DEFAULT_ADAPTIVE_MAX_BATCH_SIZE, + ) + or DEFAULT_ADAPTIVE_MAX_BATCH_SIZE + ), + ) if not bool(config.get("adaptive_batch_enabled", True)): decision = AdaptiveBatchDecision( - batch_size=configured_max, + batch_size=configured_batch_size, configured_max=configured_max, - previous_batch_size=configured_max, + previous_batch_size=configured_batch_size, success_rate=0.0, sample_size=0, pending=max(0, int(pending)), @@ -479,56 +680,61 @@ def run_ck_relogin(db: Session, job: AutomationJob) -> dict[str, Any]: "message": "库里没有可用用户,无法以系统身份发起重登", } - pending = count_pending_relogin(db, max_attempts=max_attempts) + protection = load_protection_snapshot(db) + queued_due = _pending_relogin_work_count(db, now=now) + actionable = _count_actionable_relogin_accounts( + db, + now=now, + max_attempts=max_attempts, + protection=protection, + due_only=True, + ) + pending = max(queued_due, actionable) adaptive = resolve_adaptive_batch_size( db, job, now=now, pending=pending, ) - protection = load_protection_snapshot(db) - accounts = build_select_query( + work_items = _claim_relogin_work( db, job, now, max_attempts=max_attempts, - batch_limit=adaptive.batch_size, protection=protection, - ).all() - if not accounts: - db.commit() - return {"scanned": 0, "valid": 0, "invalid": 0, "skipped": 0} - - selected_account_ids = tuple(int(account.id) for account in accounts) - for account in accounts: - priority = 10 if int(account.id) in protection.relogin_ids else 30 - enqueue_account_work( - db, - account_id=int(account.id), - work_type=WORK_LOGIN_RELOGIN, - priority=priority, - max_attempts=20, - due_at=now, - reason="CK 失效,等待自动重登", - ) - db.commit() - work_items = claim_account_work( - db, - work_types=(WORK_LOGIN_RELOGIN,), - account_ids=selected_account_ids, - limit=len(selected_account_ids), - now=now, + limit=adaptive.batch_size, ) - db.commit() - claimed_account_ids = [int(item.account_id) for item in work_items] - if not claimed_account_ids: + remaining = adaptive.batch_size - len(work_items) + if remaining > 0: + _enqueue_due_relogin_work( + db, + job, + now, + max_attempts=max_attempts, + protection=protection, + limit=remaining, + ) + work_items.extend( + _claim_relogin_work( + db, + job, + now, + max_attempts=max_attempts, + protection=protection, + limit=remaining, + ) + ) + if not work_items: + db.commit() return { "scanned": 0, "valid": 0, "invalid": 0, - "skipped": len(selected_account_ids), - "message": "候选账号的重登工作项已被其他执行器领取", + "skipped": 0, + "message": "没有到期的自动重登工作项", } + db.commit() + claimed_account_ids = [int(item.account_id) for item in work_items] account_map = { int(account.id): account for account in db.query(Account) @@ -721,12 +927,13 @@ def settle_results( if kind == "email_quota": counters["email_quota"] += 1 counters["retry"] += 1 - account.relogin_next_at = _next_retry_at(kind, account.relogin_attempts, now) + next_retry_at = _next_retry_at(kind, account.relogin_attempts, now) + account.relogin_next_at = next_retry_at reschedule_account_work_type( db, account_id=int(account.id), work_type=WORK_LOGIN_RELOGIN, - due_at=account.relogin_next_at, + due_at=next_retry_at, reason=f"自动重登未成功({kind}),按账号退避时间重试", ) # 排了下一次重试 → 仍是 invalid(不是 manual) diff --git a/web/backend/services/automation/jobs/douyu_tasks_retention.py b/web/backend/services/automation/jobs/douyu_tasks_retention.py index 03ac826..11f24ac 100644 --- a/web/backend/services/automation/jobs/douyu_tasks_retention.py +++ b/web/backend/services/automation/jobs/douyu_tasks_retention.py @@ -45,10 +45,10 @@ from datetime import UTC, datetime, timedelta from typing import Any from loguru import logger -from sqlalchemy import text +from sqlalchemy import and_, or_ from sqlalchemy.orm import Session -from ....models import AutomationJob +from ....models import AutomationJob, DouyuTask JOB_KEY = "douyu_tasks_retention" @@ -106,40 +106,55 @@ def _delete_batch( cutoff: datetime, batch: int, negate: bool = False, -) -> int: - """删一批过期行,返回删除条数。 + cursor_created_at: datetime | None = None, + cursor_id: int = 0, +) -> tuple[int, datetime | None, int]: + """按时间/主键游标取一批过期 ID,删除后返回新游标。 `negate=True` 时语义变成「**除这些类型之外**的都在这一档」—— 长保留档就是这么 表达的。这样做有个重要的安全属性:**新增的任务类型默认落在长保留档**, 不会因为「忘了往某个列表里加」而在 7 天后被误删(收集器当年就是反过来, 忘了加 allowlist 就静默丢数据)。 - `LIMIT` 让单条语句不会长时间持锁。 + 先取有限 ID 再按主键删除,单条语句不会长时间持锁;游标保证跨批次只向前扫。 """ if not task_types: - return 0 - placeholders = ", ".join(f":t{i}" for i in range(len(task_types))) - status_placeholders = ", ".join(f":s{i}" for i in range(len(IN_FLIGHT_STATUSES))) - operator = "NOT IN" if negate else "IN" - params: dict[str, Any] = { - "cutoff": cutoff, - "limit": batch, - **{f"t{i}": t for i, t in enumerate(task_types)}, - **{f"s{i}": s for i, s in enumerate(IN_FLIGHT_STATUSES)}, - } - result = db.execute( - text( - f""" - DELETE FROM douyu_tasks - WHERE task_type {operator} ({placeholders}) - AND status NOT IN ({status_placeholders}) - AND created_at < :cutoff - LIMIT :limit - """ - ), - params, + return 0, cursor_created_at, cursor_id + type_filter = ( + ~DouyuTask.task_type.in_(task_types) + if negate + else DouyuTask.task_type.in_(task_types) ) - return int(result.rowcount or 0) + query = db.query(DouyuTask.id, DouyuTask.created_at).filter( + type_filter, + ~DouyuTask.status.in_(IN_FLIGHT_STATUSES), + DouyuTask.created_at < cutoff, + ) + if cursor_created_at is not None: + query = query.filter( + or_( + DouyuTask.created_at > cursor_created_at, + and_( + DouyuTask.created_at == cursor_created_at, + DouyuTask.id > cursor_id, + ), + ) + ) + candidates = ( + query.order_by(DouyuTask.created_at.asc(), DouyuTask.id.asc()) + .limit(batch) + .all() + ) + if not candidates: + return 0, cursor_created_at, cursor_id + ids = [int(row.id) for row in candidates] + deleted = int( + db.query(DouyuTask) + .filter(DouyuTask.id.in_(ids)) + .delete(synchronize_session=False) + or 0 + ) + return deleted, candidates[-1].created_at, ids[-1] def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any]: @@ -167,13 +182,17 @@ def run_douyu_tasks_retention(db: Session, job: AutomationJob) -> dict[str, Any] per_pass: dict[str, int] = {} for cutoff, task_types, negate, label in passes: deleted_this_pass = 0 + cursor_created_at: datetime | None = None + cursor_id = 0 while batches < max_batches: - deleted = _delete_batch( + deleted, cursor_created_at, cursor_id = _delete_batch( db, task_types=task_types, cutoff=cutoff, batch=batch, negate=negate, + cursor_created_at=cursor_created_at, + cursor_id=cursor_id, ) batches += 1 total_deleted += deleted diff --git a/web/backend/services/platform_fulfillment/repository.py b/web/backend/services/platform_fulfillment/repository.py index dfd407e..330ef55 100644 --- a/web/backend/services/platform_fulfillment/repository.py +++ b/web/backend/services/platform_fulfillment/repository.py @@ -43,6 +43,10 @@ def _load_task_for_update(db: Session, task_id: int) -> PlatformFulfillmentTask: ) if task is None: raise HTTPException(status_code=404, detail="直播账号履约任务不存在") + from .views import invalidate_task_list_count_cache + + # 所有用户操作写路径都会先拿行锁;在这里失效可覆盖完成、取消、恢复等状态变更。 + invalidate_task_list_count_cache() return task diff --git a/web/backend/services/platform_fulfillment/views.py b/web/backend/services/platform_fulfillment/views.py index 2e4ce87..972ab8d 100644 --- a/web/backend/services/platform_fulfillment/views.py +++ b/web/backend/services/platform_fulfillment/views.py @@ -2,6 +2,10 @@ from __future__ import annotations +import threading +import time +import weakref +from dataclasses import dataclass from datetime import UTC, datetime from typing import Any @@ -40,6 +44,159 @@ from .common import ( ) from .repository import _load_task +_TASK_COUNT_CACHE_TTL_SECONDS = 15.0 +_TASK_COUNT_CACHE_MAX_ENTRIES = 512 +_TASK_COUNT_CACHE: weakref.WeakKeyDictionary[ + Any, dict[tuple[Any, ...], tuple[float, int]] +] = weakref.WeakKeyDictionary() +_TASK_COUNT_CACHE_LOCK = threading.Lock() + + +@dataclass +class _TaskOutputContext: + mappings: dict[int, PlatformCommodityMapping] + goods: dict[str, DouyuGoodsSnapshot] + accounts: dict[int, Account] + leases: dict[int, AccountLease] + bind_tasks: dict[int, DouyuTask] + collab_orders: dict[int, DouyuExternalOrder] + + +def invalidate_task_list_count_cache() -> None: + """任务写入后清空分页总数缓存,最多 15 秒的跨进程陈旧由 TTL 兜底。""" + with _TASK_COUNT_CACHE_LOCK: + _TASK_COUNT_CACHE.clear() + + +def _count_cache_key( + *, + cutoff: datetime | None, + status: str, + queue_bucket: str, + sale_mode: str, + keyword: str, +) -> tuple[Any, ...]: + return ( + cutoff, + status, + queue_bucket, + sale_mode, + keyword.strip(), + ) + + +def _cached_task_count( + db: Session, + query, + *, + key: tuple[Any, ...], +) -> int: + moment = time.monotonic() + bind = db.get_bind() + with _TASK_COUNT_CACHE_LOCK: + engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {}) + cached = engine_cache.get(key) + if cached and moment - cached[0] < _TASK_COUNT_CACHE_TTL_SECONDS: + return cached[1] + total = int(query.count()) + with _TASK_COUNT_CACHE_LOCK: + engine_cache = _TASK_COUNT_CACHE.setdefault(bind, {}) + if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES: + expired_before = moment - _TASK_COUNT_CACHE_TTL_SECONDS + for cache_key, (cached_at, _) in list(engine_cache.items()): + if cached_at < expired_before: + engine_cache.pop(cache_key, None) + if len(engine_cache) >= _TASK_COUNT_CACHE_MAX_ENTRIES: + engine_cache.pop(next(iter(engine_cache)), None) + engine_cache[key] = (moment, total) + return total + + +def _load_task_output_context( + db: Session, + tasks: list[PlatformFulfillmentTask], +) -> _TaskOutputContext: + mapping_ids = { + int(task.commodity_mapping_id) + for task in tasks + if task.commodity_mapping_id + } + commodity_ids = { + str(task.commodity_id) + for task in tasks + if task.commodity_id + } + account_ids = {int(task.account_id) for task in tasks if task.account_id} + lease_ids = {int(task.lease_id) for task in tasks if task.lease_id} + bind_task_ids = {int(task.bind_task_id) for task in tasks if task.bind_task_id} + task_ids = {int(task.id) for task in tasks} + + mappings = ( + { + int(row.id): row + for row in db.query(PlatformCommodityMapping) + .filter(PlatformCommodityMapping.id.in_(mapping_ids)) + .all() + } + if mapping_ids + else {} + ) + goods: dict[str, DouyuGoodsSnapshot] = {} + if commodity_ids: + for row in ( + db.query(DouyuGoodsSnapshot) + .filter(DouyuGoodsSnapshot.commodity_id.in_(commodity_ids)) + .order_by(DouyuGoodsSnapshot.id.desc()) + .all() + ): + goods.setdefault(str(row.commodity_id), row) + accounts = ( + { + int(row.id): row + for row in db.query(Account).filter(Account.id.in_(account_ids)).all() + } + if account_ids + else {} + ) + leases = ( + { + int(row.id): row + for row in db.query(AccountLease) + .filter(AccountLease.id.in_(lease_ids)) + .all() + } + if lease_ids + else {} + ) + bind_tasks = ( + { + int(row.id): row + for row in db.query(DouyuTask) + .filter(DouyuTask.id.in_(bind_task_ids)) + .all() + } + if bind_task_ids + else {} + ) + collab_orders: dict[int, DouyuExternalOrder] = {} + if task_ids: + for row in ( + db.query(DouyuExternalOrder) + .filter(DouyuExternalOrder.source_task_id.in_(task_ids)) + .order_by(DouyuExternalOrder.id.desc()) + .all() + ): + if row.source_task_id is not None: + collab_orders.setdefault(int(row.source_task_id), row) + return _TaskOutputContext( + mappings=mappings, + goods=goods, + accounts=accounts, + leases=leases, + bind_tasks=bind_tasks, + collab_orders=collab_orders, + ) + def list_tasks( db: Session, @@ -51,8 +208,9 @@ def list_tasks( page: int = 1, page_size: int = 20, ) -> dict[str, Any]: + cutoff = _order_match_started_at(db) query = db.query(PlatformFulfillmentTask) - query = _apply_order_match_cutoff(query, _order_match_started_at(db)) + query = _apply_order_match_cutoff(query, cutoff) query = query.filter( or_( PlatformFulfillmentTask.commodity_mapping_id.isnot(None), @@ -137,7 +295,17 @@ def list_tasks( Account.uid.ilike(pattern), ) ) - total = query.count() + total = _cached_task_count( + db, + query, + key=_count_cache_key( + cutoff=cutoff, + status=status, + queue_bucket=queue_bucket, + sale_mode=sale_mode, + keyword=keyword, + ), + ) rows = ( query.order_by( PlatformFulfillmentTask.paid_at.desc(), @@ -147,8 +315,9 @@ def list_tasks( .limit(max(1, min(page_size, 100))) .all() ) + context = _load_task_output_context(db, rows) return { - "items": [_task_out(db, row) for row in rows], + "items": [_task_out(db, row, context=context) for row in rows], "pagination": { "page": max(1, page), "pageSize": max(1, page_size), @@ -163,19 +332,16 @@ def _task_out( *, include_qr: bool = False, include_exchange_task: bool = False, + context: _TaskOutputContext | None = None, ) -> dict[str, Any]: + resolved = context or _load_task_output_context(db, [task]) mapping = ( - db.query(PlatformCommodityMapping) - .filter(PlatformCommodityMapping.id == task.commodity_mapping_id) - .first() + resolved.mappings.get(int(task.commodity_mapping_id)) if task.commodity_mapping_id else None ) goods = ( - db.query(DouyuGoodsSnapshot) - .filter(DouyuGoodsSnapshot.commodity_id == task.commodity_id) - .order_by(DouyuGoodsSnapshot.id.desc()) - .first() + resolved.goods.get(str(task.commodity_id)) if task.commodity_id else None ) @@ -186,25 +352,15 @@ def _task_out( or task.internal_sku_key ) account = ( - db.query(Account).filter(Account.id == task.account_id).first() - if task.account_id - else None - ) - lease = ( - db.query(AccountLease).filter(AccountLease.id == task.lease_id).first() - if task.lease_id - else None + resolved.accounts.get(int(task.account_id)) if task.account_id else None ) + lease = resolved.leases.get(int(task.lease_id)) if task.lease_id else None bind_task = ( - db.query(DouyuTask).filter(DouyuTask.id == task.bind_task_id).first() + resolved.bind_tasks.get(int(task.bind_task_id)) if task.bind_task_id else None ) - collab_order = ( - db.query(DouyuExternalOrder) - .filter(DouyuExternalOrder.source_task_id == task.id) - .first() - ) + collab_order = resolved.collab_orders.get(int(task.id)) bind_result = (bind_task.result or {}) if bind_task else {} effective_issue = _effective_binding_issue(task, bind_task, bind_result) effective_last_error = _effective_task_message(task, effective_issue) diff --git a/web/frontend/src/pages/PlatformFulfillmentPage.tsx b/web/frontend/src/pages/PlatformFulfillmentPage.tsx index d397868..d05ebea 100644 --- a/web/frontend/src/pages/PlatformFulfillmentPage.tsx +++ b/web/frontend/src/pages/PlatformFulfillmentPage.tsx @@ -474,7 +474,7 @@ export default function PlatformFulfillmentPage() { useEffect(() => { const timer = window.setInterval(() => { if (document.visibilityState === 'visible') void loadTasks(true); - }, 5000); + }, 10000); return () => window.clearInterval(timer); }, [loadTasks]); @@ -493,7 +493,7 @@ export default function PlatformFulfillmentPage() { if (!selectedId) return; const timer = window.setInterval(() => { if (document.visibilityState === 'visible') void loadDetail(selectedId, true); - }, 3000); + }, 5000); return () => window.clearInterval(timer); }, [loadDetail, selectedId]); @@ -511,7 +511,7 @@ export default function PlatformFulfillmentPage() { void loadActionTask(); const timer = window.setInterval(() => { if (document.visibilityState === 'visible') void loadActionTask(); - }, 2000); + }, 3000); return () => { stopped = true; window.clearInterval(timer);