fix(fulfillment): 主动补全有效 CK 商品能力缓存
This commit is contained in:
@@ -1,6 +1,6 @@
|
|||||||
# 直播账号运营后台
|
# 直播账号运营后台
|
||||||
|
|
||||||
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.9)。
|
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.10)。
|
||||||
|
|
||||||
## 能做什么
|
## 能做什么
|
||||||
|
|
||||||
|
|||||||
@@ -343,7 +343,7 @@ issued -> valid -> expiring -> invalid -> relogin -> valid
|
|||||||
`account_sync_queue` 拆分为订单需求补货与通用供给补货两套水位,避免高频需求补货饿死通用供给刷新:
|
`account_sync_queue` 拆分为订单需求补货与通用供给补货两套水位,避免高频需求补货饿死通用供给刷新:
|
||||||
|
|
||||||
- 队列总水位 `ACCOUNT_SYNC_QUEUE_TARGET_PENDING`(默认 120),订单补货水位 `ACCOUNT_ORDER_QUEUE_TARGET_PENDING`(默认 70),供给补货水位 `ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING`(默认 50);
|
- 队列总水位 `ACCOUNT_SYNC_QUEUE_TARGET_PENDING`(默认 120),订单补货水位 `ACCOUNT_ORDER_QUEUE_TARGET_PENDING`(默认 70),供给补货水位 `ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING`(默认 50);
|
||||||
- 每批 20 条固定先领最多 `ACCOUNT_SUPPLY_QUEUE_QUOTA`(默认 8)条供给补货,其余槽位消费订单补货;
|
- 每批默认 40 条,固定先领最多 `ACCOUNT_SUPPLY_QUEUE_QUOTA`(默认 16)条供给补货,其余槽位消费订单补货和有效 CK 能力补全;
|
||||||
- 仅 `covered_shortage` / `available_shortage` 才入队,`allocatable_shortage` 不靠反复刷新能力队列解决。
|
- 仅 `covered_shortage` / `available_shortage` 才入队,`allocatable_shortage` 不靠反复刷新能力队列解决。
|
||||||
|
|
||||||
## 登录预算
|
## 登录预算
|
||||||
|
|||||||
+8
-3
@@ -87,18 +87,23 @@
|
|||||||
- 同时保存 `timeLimited`、`specTimes` 和起止时间,未开始/已结束与账号限兑分别处理;
|
- 同时保存 `timeLimited`、`specTimes` 和起止时间,未开始/已结束与账号限兑分别处理;
|
||||||
- 账号兑换资格和活动窗口默认缓存 6 小时,库存仅作展示并默认缓存 15 分钟;
|
- 账号兑换资格和活动窗口默认缓存 6 小时,库存仅作展示并默认缓存 15 分钟;
|
||||||
否则 3 万账号池不可能在 15 分钟内刷新一遍,能力索引会长期处于过期状态;
|
否则 3 万账号池不可能在 15 分钟内刷新一遍,能力索引会长期处于过期状态;
|
||||||
- 有 pending 履约需求时,`account_capability_refresh` 作业优先刷新对应商品的过期能力;
|
- `account_capability_refresh` 每轮先刷新 pending 履约商品对应的过期能力,再用剩余队列
|
||||||
|
水位补全其他 CK 有效但 `storehome` 快照缺失或过期的账号;
|
||||||
- 能力刷新和外部请求由 `account_sync_queue` 独立执行槽消费,不占用选号 worker;
|
- 能力刷新和外部请求由 `account_sync_queue` 独立执行槽消费,不占用选号 worker;
|
||||||
- 本地能力池缺失时,选号失败只向该独立队列补入最多 20 个账号,
|
- 本地能力池缺失时,选号失败只向该独立队列补入最多 20 个账号,
|
||||||
可用 `PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT` 调整;
|
可用 `PLATFORM_FULFILLMENT_CACHE_REFRESH_SEED_COUNT` 调整;
|
||||||
- 自动选号按 `next_allocate_at` 轮转,而不是永久按订单时间排在最前;
|
- 自动选号按 `next_allocate_at` 轮转,而不是永久按订单时间排在最前;
|
||||||
- 预售任务允许在活动开放前分配;直接兑换单的“未开放”任务排到商品开放时间;
|
- 预售和直接兑换任务都允许在商品开放前提前选号、绑定角色;
|
||||||
|
商品未开放只把兑换状态置为 `waiting_release`,不再阻止分配或掩盖捆绑资格缺口;
|
||||||
“账号资格快照缺失”退避 2 分钟。官方全局库存不阻止自动选号;
|
“账号资格快照缺失”退避 2 分钟。官方全局库存不阻止自动选号;
|
||||||
- 单轮默认处理 20 个本地任务,可用 `PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH` 调整。
|
- 单轮默认处理 20 个本地任务,可用 `PLATFORM_FULFILLMENT_AUTO_ALLOCATE_BATCH` 调整。
|
||||||
|
|
||||||
能力 TTL 可分别用 `ACCOUNT_COMMODITY_STABLE_TTL_SECONDS`、
|
能力 TTL 可分别用 `ACCOUNT_COMMODITY_STABLE_TTL_SECONDS`、
|
||||||
`ACCOUNT_COMMODITY_NO_STOCK_TTL_SECONDS` 和
|
`ACCOUNT_COMMODITY_NO_STOCK_TTL_SECONDS` 和
|
||||||
`ACCOUNT_COMMODITY_UNKNOWN_TTL_SECONDS` 调整。过期能力不会参与自动匹配。
|
`ACCOUNT_COMMODITY_UNKNOWN_TTL_SECONDS` 调整。过期能力不会直接参与自动匹配;
|
||||||
|
后台会按有效 CK 重新查询 `storehome` 并写回本地,使其变成新鲜能力,而不是只能等待
|
||||||
|
原本已经新鲜的账号。同步队列默认每轮处理 40 条,保证有效 CK 池能在一个 6 小时 TTL
|
||||||
|
周期内持续补全。
|
||||||
真正创建租约仍然依赖账号租约唯一约束,因此并发 worker 不会把同一账号分配给两张订单。
|
真正创建租约仍然依赖账号租约唯一约束,因此并发 worker 不会把同一账号分配给两张订单。
|
||||||
|
|
||||||
选号硬条件只保留:本地 CK 结论有效、未达到该商品官方限兑上限、角色换绑冷却已结束、
|
选号硬条件只保留:本地 CK 结论有效、未达到该商品官方限兑上限、角色换绑冷却已结束、
|
||||||
|
|||||||
+1
-1
@@ -21,7 +21,7 @@
|
|||||||
| `account_supply_replenishment` | 按供给目标缺口补充 `storehome` 能力 | 默认开启,需求补货优先、供给占固定配额,**生产运行中** |
|
| `account_supply_replenishment` | 按供给目标缺口补充 `storehome` 能力 | 默认开启,需求补货优先、供给占固定配额,**生产运行中** |
|
||||||
| `account_value_projection` | 刷新账号价值分档投影 | 默认开启,600s 一轮,`batch=1000`,**生产运行中** |
|
| `account_value_projection` | 刷新账号价值分档投影 | 默认开启,600s 一轮,`batch=1000`,**生产运行中** |
|
||||||
| `account_supply_profile_projection` | 刷新账号供给画像、质量分与冗余分类(只读投影) | 默认开启,600s 一轮,`batch=5000`,**生产运行中** |
|
| `account_supply_profile_projection` | 刷新账号供给画像、质量分与冗余分类(只读投影) | 默认开启,600s 一轮,`batch=5000`,**生产运行中** |
|
||||||
| `account_capability_refresh` | 为待履约商品筛选需补充能力目录的账号入同步队列 | 只做本地候选筛选,**生产运行中** |
|
| `account_capability_refresh` | 先补待履约商品,再用剩余水位刷新所有 CK 有效但 `storehome` 快照缺失或过期的账号 | 只做本地候选筛选,外部查询交给 `account_sync_queue`,**生产运行中** |
|
||||||
| `ck_health` | 检测持有有效 CK 的账号(含 `lease_bound` 履约保护组) | 区分 `valid`/`invalid`/`error`,`error` 不覆盖旧结论,**生产运行中** |
|
| `ck_health` | 检测持有有效 CK 的账号(含 `lease_bound` 履约保护组) | 区分 `valid`/`invalid`/`error`,`error` 不覆盖旧结论,**生产运行中** |
|
||||||
| `ck_relogin` | 对失效 CK 自动重登(受配额与熔断控制) | 支持 `wgapi → iframe` 邮箱回退与保护组优先,**生产运行中** |
|
| `ck_relogin` | 对失效 CK 自动重登(受配额与熔断控制) | 支持 `wgapi → iframe` 邮箱回退与保护组优先,**生产运行中** |
|
||||||
| `lease_ck_refresh` | 对仍有效但预计 24h 内到期的履约/协作租约账号提前续 CK | 默认开启,保护租约不掉 CK,**生产运行中** |
|
| `lease_ck_refresh` | 对仍有效但预计 24h 内到期的履约/协作租约账号提前续 CK | 默认开启,保护租约不掉 CK,**生产运行中** |
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[project]
|
[project]
|
||||||
name = "live-hub-py"
|
name = "live-hub-py"
|
||||||
version = "0.4.9"
|
version = "0.4.10"
|
||||||
description = "直播账号运营 Web 后台"
|
description = "直播账号运营 Web 后台"
|
||||||
readme = "README.md"
|
readme = "README.md"
|
||||||
requires-python = ">=3.12,<3.13"
|
requires-python = ">=3.12,<3.13"
|
||||||
|
|||||||
@@ -92,6 +92,16 @@ def test_selects_stale_and_never_scanned_demand_accounts(db):
|
|||||||
_state(db, fresh, valid_until=NOW + timedelta(hours=1))
|
_state(db, fresh, valid_until=NOW + timedelta(hours=1))
|
||||||
_state(db, other, commodity_id="OTHER", valid_until=NOW - timedelta(minutes=1))
|
_state(db, other, commodity_id="OTHER", valid_until=NOW - timedelta(minutes=1))
|
||||||
_state(db, leased, valid_until=NOW - timedelta(minutes=1))
|
_state(db, leased, valid_until=NOW - timedelta(minutes=1))
|
||||||
|
db.add(
|
||||||
|
AccountSyncState(
|
||||||
|
account_id=fresh.id,
|
||||||
|
platform="douyu",
|
||||||
|
domain="storehome",
|
||||||
|
status="success",
|
||||||
|
last_success_at=NOW,
|
||||||
|
valid_until=NOW + timedelta(hours=1),
|
||||||
|
)
|
||||||
|
)
|
||||||
db.add(
|
db.add(
|
||||||
AccountLease(
|
AccountLease(
|
||||||
account_id=leased.id,
|
account_id=leased.id,
|
||||||
@@ -115,9 +125,24 @@ def test_selects_stale_and_never_scanned_demand_accounts(db):
|
|||||||
assert [row.id for row in selected] == [stale.id, other.id, leased.id]
|
assert [row.id for row in selected] == [stale.id, other.id, leased.id]
|
||||||
|
|
||||||
|
|
||||||
def test_no_pending_task_means_no_refresh(db):
|
def test_no_pending_task_still_refreshes_stale_ck_accounts(db):
|
||||||
stale = _account(db, "cap-no-demand")
|
stale = _account(db, "cap-no-demand-stale")
|
||||||
|
fresh = _account(db, "cap-no-demand-fresh")
|
||||||
|
invalid = _account(db, "cap-no-demand-invalid")
|
||||||
_state(db, stale, valid_until=NOW - timedelta(minutes=1))
|
_state(db, stale, valid_until=NOW - timedelta(minutes=1))
|
||||||
|
_state(db, fresh, valid_until=NOW - timedelta(minutes=1))
|
||||||
|
_state(db, invalid, valid_until=NOW - timedelta(minutes=1))
|
||||||
|
invalid.ck_check_status = "invalid"
|
||||||
|
db.add(
|
||||||
|
AccountSyncState(
|
||||||
|
account_id=fresh.id,
|
||||||
|
platform="douyu",
|
||||||
|
domain="storehome",
|
||||||
|
status="success",
|
||||||
|
last_success_at=NOW,
|
||||||
|
valid_until=NOW + timedelta(hours=1),
|
||||||
|
)
|
||||||
|
)
|
||||||
db.commit()
|
db.commit()
|
||||||
automation_job = AutomationJob(
|
automation_job = AutomationJob(
|
||||||
key=job.JOB_KEY,
|
key=job.JOB_KEY,
|
||||||
@@ -127,7 +152,46 @@ def test_no_pending_task_means_no_refresh(db):
|
|||||||
concurrency=3,
|
concurrency=3,
|
||||||
)
|
)
|
||||||
|
|
||||||
assert job.build_select_query(db, automation_job, NOW).all() == []
|
selected = job.build_select_query(db, automation_job, NOW).all()
|
||||||
|
|
||||||
|
assert [row.id for row in selected] == [stale.id]
|
||||||
|
|
||||||
|
|
||||||
|
def test_demand_refresh_runs_before_global_backfill(db):
|
||||||
|
db.add(
|
||||||
|
PlatformFulfillmentTask(
|
||||||
|
source_system="order_site",
|
||||||
|
source_order_id="demand-first",
|
||||||
|
source_order_item_id="demand-first",
|
||||||
|
internal_sku_key="skin",
|
||||||
|
commodity_id="C",
|
||||||
|
execution_status="ready",
|
||||||
|
binding_status="not_started",
|
||||||
|
exchange_status="not_started",
|
||||||
|
paid_at=NOW,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
demand = _account(db, "cap-demand-first")
|
||||||
|
backfill = _account(db, "cap-backfill-second")
|
||||||
|
_state(db, demand, commodity_id="C", valid_until=NOW - timedelta(minutes=1))
|
||||||
|
_state(
|
||||||
|
db,
|
||||||
|
backfill,
|
||||||
|
commodity_id="OTHER",
|
||||||
|
valid_until=NOW - timedelta(minutes=1),
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
automation_job = AutomationJob(
|
||||||
|
key=job.JOB_KEY,
|
||||||
|
title="履约商品能力补充刷新",
|
||||||
|
interval_seconds=3600,
|
||||||
|
batch_size=2,
|
||||||
|
concurrency=3,
|
||||||
|
)
|
||||||
|
|
||||||
|
selected = job.build_select_query(db, automation_job, NOW).all()
|
||||||
|
|
||||||
|
assert [row.id for row in selected] == [demand.id, backfill.id]
|
||||||
|
|
||||||
|
|
||||||
def test_refresh_ignores_tasks_before_match_cutoff(db):
|
def test_refresh_ignores_tasks_before_match_cutoff(db):
|
||||||
@@ -239,6 +303,34 @@ def test_run_enqueues_stale_accounts_without_external_query(db):
|
|||||||
assert work.priority == 10
|
assert work.priority == 10
|
||||||
|
|
||||||
|
|
||||||
|
def test_run_without_pending_tasks_enqueues_global_backfill(db):
|
||||||
|
stale = _account(db, "cap-run-no-demand")
|
||||||
|
_state(db, stale, valid_until=NOW - timedelta(minutes=1))
|
||||||
|
db.commit()
|
||||||
|
automation_job = AutomationJob(
|
||||||
|
key=job.JOB_KEY,
|
||||||
|
title="履约商品能力补充刷新",
|
||||||
|
interval_seconds=3600,
|
||||||
|
batch_size=10,
|
||||||
|
concurrency=3,
|
||||||
|
)
|
||||||
|
|
||||||
|
result = job.run_account_capability_refresh(db, automation_job)
|
||||||
|
|
||||||
|
work = (
|
||||||
|
db.query(AccountWorkItem)
|
||||||
|
.filter_by(account_id=stale.id, work_type="storehome_sync")
|
||||||
|
.one()
|
||||||
|
)
|
||||||
|
assert result["scanned"] == 1
|
||||||
|
assert result["success"] == 1
|
||||||
|
assert result["detail"]["demand_refresh"] == 0
|
||||||
|
assert result["detail"]["backfill_refresh"] == 1
|
||||||
|
assert work.status == "pending"
|
||||||
|
assert work.priority == 30
|
||||||
|
assert work.reason == "账号商品能力补全"
|
||||||
|
|
||||||
|
|
||||||
def test_refresh_skips_accounts_with_active_sync_work(db):
|
def test_refresh_skips_accounts_with_active_sync_work(db):
|
||||||
db.add(
|
db.add(
|
||||||
PlatformFulfillmentTask(
|
PlatformFulfillmentTask(
|
||||||
|
|||||||
@@ -27,9 +27,11 @@ def test_list_jobs_registers_default_jobs_when_api_process_registry_is_empty(db)
|
|||||||
|
|
||||||
result = automation_router.list_jobs(db=db, current=admin)
|
result = automation_router.list_jobs(db=db, current=admin)
|
||||||
|
|
||||||
keys = {job["key"] for job in result["jobs"]}
|
jobs = {job["key"]: job for job in result["jobs"]}
|
||||||
|
keys = set(jobs)
|
||||||
assert "account_sync_queue" in keys
|
assert "account_sync_queue" in keys
|
||||||
assert "account_supply_replenishment" in keys
|
assert "account_supply_replenishment" in keys
|
||||||
|
assert jobs["account_sync_queue"]["batch_size"] == 40
|
||||||
assert result["scheduler"]["enabled"] is not None
|
assert result["scheduler"]["enabled"] is not None
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -45,7 +45,7 @@ TESTS_DIR = Path(__file__).resolve().parent
|
|||||||
PROJECT_ROOT = TESTS_DIR.parent
|
PROJECT_ROOT = TESTS_DIR.parent
|
||||||
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
VERSIONS_DIR = PROJECT_ROOT / "web" / "backend" / "migrations" / "versions"
|
||||||
|
|
||||||
HEAD_REVISION = "20261128_0137"
|
HEAD_REVISION = "20261128_0138"
|
||||||
|
|
||||||
# 迁移新增、但不声明在模型里的复合查询索引。
|
# 迁移新增、但不声明在模型里的复合查询索引。
|
||||||
EXTRA_INDEXES = (
|
EXTRA_INDEXES = (
|
||||||
|
|||||||
@@ -381,7 +381,7 @@ wheels = [
|
|||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "live-hub-py"
|
name = "live-hub-py"
|
||||||
version = "0.4.9"
|
version = "0.4.10"
|
||||||
source = { editable = "." }
|
source = { editable = "." }
|
||||||
dependencies = [
|
dependencies = [
|
||||||
{ name = "alembic" },
|
{ name = "alembic" },
|
||||||
|
|||||||
@@ -549,6 +549,10 @@
|
|||||||
"20261128_0137_platform_fulfillment_outbox_state_hash.py": {
|
"20261128_0137_platform_fulfillment_outbox_state_hash.py": {
|
||||||
"revision": "20261128_0137",
|
"revision": "20261128_0137",
|
||||||
"sha256": "a1ac06c57eacf11d12d75ec7a6bc9099fcafd33d6119ecdb94fd17abe99dc660"
|
"sha256": "a1ac06c57eacf11d12d75ec7a6bc9099fcafd33d6119ecdb94fd17abe99dc660"
|
||||||
|
},
|
||||||
|
"20261128_0138_account_sync_backfill_cadence.py": {
|
||||||
|
"revision": "20261128_0138",
|
||||||
|
"sha256": "12b7cc588be5da8009e8c7090087ed4ad1d5a3723b2fe8e97584208550feced4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,37 @@
|
|||||||
|
"""raise account sync queue throughput for capability backfill
|
||||||
|
|
||||||
|
Revision ID: 20261128_0138
|
||||||
|
Revises: 20261128_0137
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from alembic import op
|
||||||
|
|
||||||
|
revision: str = "20261128_0138"
|
||||||
|
down_revision: str | None = "20261128_0137"
|
||||||
|
branch_labels: str | None = None
|
||||||
|
depends_on: str | None = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
"""Set the default sync batch to 40 without overriding custom values."""
|
||||||
|
if not sa.inspect(op.get_bind()).has_table("automation_jobs"):
|
||||||
|
return
|
||||||
|
op.execute(
|
||||||
|
sa.text(
|
||||||
|
"""
|
||||||
|
UPDATE automation_jobs
|
||||||
|
SET batch_size = 40,
|
||||||
|
updated_at = CURRENT_TIMESTAMP
|
||||||
|
WHERE `key` = 'account_sync_queue'
|
||||||
|
AND batch_size = 20
|
||||||
|
"""
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
"""Do not reduce throughput when older code is rolled back."""
|
||||||
|
return
|
||||||
@@ -124,7 +124,9 @@ def register_default_jobs() -> None:
|
|||||||
title="账号内部同步队列",
|
title="账号内部同步队列",
|
||||||
interval_seconds=60,
|
interval_seconds=60,
|
||||||
run_interval_seconds=60,
|
run_interval_seconds=60,
|
||||||
batch_size=20,
|
# 有效 CK 的 storehome 快照默认 6 小时过期;1 万多个账号需要
|
||||||
|
# 至少约 30 条/分钟才能在一个 TTL 周期内补完,留出 40 条余量。
|
||||||
|
batch_size=40,
|
||||||
concurrency=3,
|
concurrency=3,
|
||||||
run=run_account_sync_queue_job,
|
run=run_account_sync_queue_job,
|
||||||
default_enabled=True,
|
default_enabled=True,
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
"""按直播履约需求把过期商品能力账号送入内部同步队列。
|
"""把待履约和全库过期的商品能力账号送入内部同步队列。
|
||||||
|
|
||||||
本作业只做本地候选筛选,不直接请求官网。真正的 ``storehome`` 查询由
|
优先处理 pending 履约商品,再用剩余水位补全所有 CK 有效但缺少新鲜
|
||||||
|
``storehome`` 快照的账号。本作业只做本地候选筛选,不直接请求官网。
|
||||||
|
真正的 ``storehome`` 查询由
|
||||||
``account_sync_queue`` 作业在独立执行槽中低并发消费,避免补货查询抢占
|
``account_sync_queue`` 作业在独立执行槽中低并发消费,避免补货查询抢占
|
||||||
履约实时复核、登录或批量任务的执行资源。
|
履约实时复核、登录或批量任务的执行资源。
|
||||||
"""
|
"""
|
||||||
@@ -27,6 +29,7 @@ from ...account_work_queue import (
|
|||||||
)
|
)
|
||||||
from ...platform_fulfillment.account_selector import (
|
from ...platform_fulfillment.account_selector import (
|
||||||
capability_refresh_candidate_accounts,
|
capability_refresh_candidate_accounts,
|
||||||
|
storehome_refresh_candidate_accounts,
|
||||||
)
|
)
|
||||||
|
|
||||||
JOB_KEY = "account_capability_refresh"
|
JOB_KEY = "account_capability_refresh"
|
||||||
@@ -37,19 +40,16 @@ def _pending_demand_rows(
|
|||||||
now: datetime,
|
now: datetime,
|
||||||
) -> list[tuple[str, int]]:
|
) -> list[tuple[str, int]]:
|
||||||
"""返回待分配商品及订单数,按缺口大小排序。"""
|
"""返回待分配商品及订单数,按缺口大小排序。"""
|
||||||
pending_commodities_query = (
|
pending_commodities_query = select(
|
||||||
select(
|
|
||||||
PlatformFulfillmentTask.commodity_id,
|
PlatformFulfillmentTask.commodity_id,
|
||||||
func.count(PlatformFulfillmentTask.id).label("waiting"),
|
func.count(PlatformFulfillmentTask.id).label("waiting"),
|
||||||
)
|
).where(
|
||||||
.where(
|
|
||||||
PlatformFulfillmentTask.execution_status == "ready",
|
PlatformFulfillmentTask.execution_status == "ready",
|
||||||
PlatformFulfillmentTask.account_id.is_(None),
|
PlatformFulfillmentTask.account_id.is_(None),
|
||||||
PlatformFulfillmentTask.commodity_id != "",
|
PlatformFulfillmentTask.commodity_id != "",
|
||||||
PlatformFulfillmentTask.target_platform == "douyu",
|
PlatformFulfillmentTask.target_platform == "douyu",
|
||||||
PlatformFulfillmentTask.scope == "elite",
|
PlatformFulfillmentTask.scope == "elite",
|
||||||
)
|
)
|
||||||
)
|
|
||||||
match_started_at = (
|
match_started_at = (
|
||||||
db.query(PlatformFulfillmentSetting.order_match_started_at)
|
db.query(PlatformFulfillmentSetting.order_match_started_at)
|
||||||
.filter(PlatformFulfillmentSetting.id == 1)
|
.filter(PlatformFulfillmentSetting.id == 1)
|
||||||
@@ -59,12 +59,13 @@ def _pending_demand_rows(
|
|||||||
pending_commodities_query = pending_commodities_query.where(
|
pending_commodities_query = pending_commodities_query.where(
|
||||||
PlatformFulfillmentTask.paid_at >= match_started_at
|
PlatformFulfillmentTask.paid_at >= match_started_at
|
||||||
)
|
)
|
||||||
statement = (
|
statement = pending_commodities_query.group_by(
|
||||||
pending_commodities_query
|
PlatformFulfillmentTask.commodity_id
|
||||||
.group_by(PlatformFulfillmentTask.commodity_id)
|
).order_by(func.count(PlatformFulfillmentTask.id).desc())
|
||||||
.order_by(func.count(PlatformFulfillmentTask.id).desc())
|
return [
|
||||||
)
|
(str(commodity_id), int(waiting))
|
||||||
return list(db.execute(statement).all())
|
for commodity_id, waiting in db.execute(statement).all()
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
def _order_queue_target_pending() -> int:
|
def _order_queue_target_pending() -> int:
|
||||||
@@ -88,27 +89,15 @@ def _build_select_query(
|
|||||||
batch_limit: int | None = None,
|
batch_limit: int | None = None,
|
||||||
):
|
):
|
||||||
moment = now or datetime.now(UTC)
|
moment = now or datetime.now(UTC)
|
||||||
demand_rows = _pending_demand_rows(db, moment)
|
accounts, _, _ = _refresh_candidates(
|
||||||
commodity_ids = [str(row[0]) for row in demand_rows if row[0]]
|
|
||||||
if not commodity_ids:
|
|
||||||
return db.query(Account).filter(Account.id == -1)
|
|
||||||
batch = max(
|
|
||||||
1,
|
|
||||||
min(
|
|
||||||
int(batch_limit if batch_limit is not None else job.batch_size or 100),
|
|
||||||
100,
|
|
||||||
),
|
|
||||||
)
|
|
||||||
candidates = capability_refresh_candidate_accounts(
|
|
||||||
db,
|
db,
|
||||||
commodity_ids=commodity_ids,
|
job,
|
||||||
scope="elite",
|
moment,
|
||||||
limit=batch,
|
batch_limit=batch_limit,
|
||||||
now=moment,
|
|
||||||
)
|
)
|
||||||
if not candidates:
|
if not accounts:
|
||||||
return db.query(Account).filter(Account.id == -1)
|
return db.query(Account).filter(Account.id == -1)
|
||||||
rank = {int(account.id): index for index, account in enumerate(candidates)}
|
rank = {int(account.id): index for index, account in enumerate(accounts)}
|
||||||
return (
|
return (
|
||||||
db.query(Account)
|
db.query(Account)
|
||||||
.filter(Account.id.in_(tuple(rank)))
|
.filter(Account.id.in_(tuple(rank)))
|
||||||
@@ -119,6 +108,50 @@ def _build_select_query(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _refresh_candidates(
|
||||||
|
db: Session,
|
||||||
|
job: AutomationJob,
|
||||||
|
moment: datetime,
|
||||||
|
*,
|
||||||
|
batch_limit: int | None = None,
|
||||||
|
) -> tuple[list[Account], set[int], list[str]]:
|
||||||
|
"""先补待履约商品,再用剩余水位补全其他 CK 有效账号。"""
|
||||||
|
demand_rows = _pending_demand_rows(db, moment)
|
||||||
|
commodity_ids = [str(row[0]) for row in demand_rows if row[0]]
|
||||||
|
batch = max(
|
||||||
|
1,
|
||||||
|
min(
|
||||||
|
int(batch_limit if batch_limit is not None else job.batch_size or 100),
|
||||||
|
100,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
demand_candidates = (
|
||||||
|
capability_refresh_candidate_accounts(
|
||||||
|
db,
|
||||||
|
commodity_ids=commodity_ids,
|
||||||
|
scope="elite",
|
||||||
|
limit=batch,
|
||||||
|
now=moment,
|
||||||
|
)
|
||||||
|
if commodity_ids
|
||||||
|
else []
|
||||||
|
)
|
||||||
|
demand_ids = {int(account.id) for account in demand_candidates}
|
||||||
|
remaining = batch - len(demand_candidates)
|
||||||
|
backfill_candidates = (
|
||||||
|
storehome_refresh_candidate_accounts(
|
||||||
|
db,
|
||||||
|
limit=remaining,
|
||||||
|
now=moment,
|
||||||
|
exclude_account_ids=tuple(demand_ids),
|
||||||
|
)
|
||||||
|
if remaining > 0
|
||||||
|
else []
|
||||||
|
)
|
||||||
|
accounts = [*demand_candidates, *backfill_candidates]
|
||||||
|
return accounts, demand_ids, commodity_ids
|
||||||
|
|
||||||
|
|
||||||
def build_select_query(
|
def build_select_query(
|
||||||
db: Session,
|
db: Session,
|
||||||
job: AutomationJob,
|
job: AutomationJob,
|
||||||
@@ -150,23 +183,23 @@ def run_account_capability_refresh(
|
|||||||
),
|
),
|
||||||
"detail": {"queued": 0, "pending": pending, "headroom": 0},
|
"detail": {"queued": 0, "pending": pending, "headroom": 0},
|
||||||
}
|
}
|
||||||
demand_rows = _pending_demand_rows(db, now)
|
accounts, demand_ids, commodity_ids = _refresh_candidates(
|
||||||
commodity_ids = [str(row[0]) for row in demand_rows if row[0]]
|
|
||||||
accounts = _build_select_query(
|
|
||||||
db,
|
db,
|
||||||
job,
|
job,
|
||||||
now,
|
now,
|
||||||
batch_limit=headroom,
|
batch_limit=headroom,
|
||||||
).all()
|
)
|
||||||
for account in accounts:
|
for account in accounts:
|
||||||
|
is_demand_refresh = int(account.id) in demand_ids
|
||||||
enqueue_account_work(
|
enqueue_account_work(
|
||||||
db,
|
db,
|
||||||
account_id=int(account.id),
|
account_id=int(account.id),
|
||||||
work_type=WORK_STOREHOME_SYNC,
|
work_type=WORK_STOREHOME_SYNC,
|
||||||
priority=10,
|
priority=10 if is_demand_refresh else 30,
|
||||||
reason=(
|
reason=(
|
||||||
"待履约商品补货: "
|
("待履约商品补货: " + ",".join(commodity_ids[:5]))
|
||||||
+ ",".join(commodity_ids[:5])
|
if is_demand_refresh and commodity_ids
|
||||||
|
else "账号商品能力补全"
|
||||||
)[:255],
|
)[:255],
|
||||||
due_at=now,
|
due_at=now,
|
||||||
)
|
)
|
||||||
@@ -178,9 +211,9 @@ def run_account_capability_refresh(
|
|||||||
"invalid": 0,
|
"invalid": 0,
|
||||||
"skipped": 0,
|
"skipped": 0,
|
||||||
"message": (
|
"message": (
|
||||||
f"本轮筛选 {len(accounts)} 个待补货账号,新入队 {queued} 个"
|
f"本轮筛选 {len(accounts)} 个需刷新能力账号,新入队 {queued} 个"
|
||||||
if accounts
|
if accounts
|
||||||
else "当前履约商品没有可补充的新鲜 CK 候选账号"
|
else "没有需要补全商品能力缓存的 CK 有效账号"
|
||||||
),
|
),
|
||||||
"detail": {
|
"detail": {
|
||||||
"queued": queued,
|
"queued": queued,
|
||||||
@@ -188,6 +221,8 @@ def run_account_capability_refresh(
|
|||||||
"order_cap": _order_queue_target_pending(),
|
"order_cap": _order_queue_target_pending(),
|
||||||
"headroom": headroom,
|
"headroom": headroom,
|
||||||
"commodities": commodity_ids[:20],
|
"commodities": commodity_ids[:20],
|
||||||
|
"demand_refresh": len(demand_ids),
|
||||||
|
"backfill_refresh": max(0, queued - len(demand_ids)),
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -623,6 +623,18 @@ def capability_candidate_accounts(
|
|||||||
]
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _refresh_candidate_order_by(now: datetime) -> tuple[Any, ...]:
|
||||||
|
return (
|
||||||
|
case((active_lease_exists(), 1), else_=0),
|
||||||
|
case((active_collab_order_exists(), 1), else_=0),
|
||||||
|
case((role_change_ready_filter(now), 0), else_=1),
|
||||||
|
case((Account.role_bind_status == "unbound", 0), else_=1),
|
||||||
|
Account.overview_queried_at.is_(None).desc(),
|
||||||
|
Account.overview_queried_at.asc(),
|
||||||
|
Account.id.asc(),
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def capability_refresh_candidate_accounts(
|
def capability_refresh_candidate_accounts(
|
||||||
db: Session,
|
db: Session,
|
||||||
*,
|
*,
|
||||||
@@ -699,15 +711,52 @@ def capability_refresh_candidate_accounts(
|
|||||||
assigned_to_pool_filter(),
|
assigned_to_pool_filter(),
|
||||||
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
|
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
|
||||||
)
|
)
|
||||||
.order_by(
|
.order_by(*_refresh_candidate_order_by(moment))
|
||||||
case((active_lease_exists(), 1), else_=0),
|
.limit(max(1, min(int(limit), 100)))
|
||||||
case((active_collab_order_exists(), 1), else_=0),
|
.all()
|
||||||
case((role_change_ready_filter(moment), 0), else_=1),
|
|
||||||
case((Account.role_bind_status == "unbound", 0), else_=1),
|
|
||||||
Account.overview_queried_at.is_(None).desc(),
|
|
||||||
Account.overview_queried_at.asc(),
|
|
||||||
Account.id.asc(),
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def storehome_refresh_candidate_accounts(
|
||||||
|
db: Session,
|
||||||
|
*,
|
||||||
|
limit: int = 20,
|
||||||
|
now: datetime | None = None,
|
||||||
|
exclude_account_ids: tuple[int, ...] | list[int] = (),
|
||||||
|
) -> list[Account]:
|
||||||
|
"""选择 CK 有效但缺少新鲜 storehome 快照的账号做全量能力补全。
|
||||||
|
|
||||||
|
能力缓存过期不等于 CK 失效。只要 CK 结论仍为有效且账号可自动操作,
|
||||||
|
就可以重新查询 storehome 并把整个商品能力目录写回本地。
|
||||||
|
"""
|
||||||
|
moment = _now(now)
|
||||||
|
fresh_storehome = (
|
||||||
|
select(AccountSyncState.id)
|
||||||
|
.where(
|
||||||
|
AccountSyncState.account_id == Account.id,
|
||||||
|
AccountSyncState.platform == "douyu",
|
||||||
|
AccountSyncState.domain == "storehome",
|
||||||
|
AccountSyncState.status == "success",
|
||||||
|
AccountSyncState.valid_until.isnot(None),
|
||||||
|
AccountSyncState.valid_until > moment,
|
||||||
|
)
|
||||||
|
.exists()
|
||||||
|
)
|
||||||
|
excluded_ids = tuple(
|
||||||
|
dict.fromkeys(int(account_id) for account_id in exclude_account_ids)
|
||||||
|
)
|
||||||
|
query = db.query(Account).filter(
|
||||||
|
~fresh_storehome,
|
||||||
|
cookie_present_filter(),
|
||||||
|
valid_ck_filter(),
|
||||||
|
automatable_account_filter(),
|
||||||
|
assigned_to_pool_filter(),
|
||||||
|
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
|
||||||
|
)
|
||||||
|
if excluded_ids:
|
||||||
|
query = query.filter(~Account.id.in_(excluded_ids))
|
||||||
|
return (
|
||||||
|
query.order_by(*_refresh_candidate_order_by(moment))
|
||||||
.limit(max(1, min(int(limit), 100)))
|
.limit(max(1, min(int(limit), 100)))
|
||||||
.all()
|
.all()
|
||||||
)
|
)
|
||||||
@@ -969,4 +1018,5 @@ __all__ = [
|
|||||||
"live_candidate_accounts",
|
"live_candidate_accounts",
|
||||||
"release_lease",
|
"release_lease",
|
||||||
"renew_lease",
|
"renew_lease",
|
||||||
|
"storehome_refresh_candidate_accounts",
|
||||||
]
|
]
|
||||||
|
|||||||
Reference in New Issue
Block a user