fix(worker): 优化连接池容量拆分、并发入队与事件写入

This commit is contained in:
yml
2026-11-29 11:24:35 +08:00
parent 1d92fa6d53
commit 2ea105a924
18 changed files with 956 additions and 207 deletions
+25 -7
View File
@@ -189,12 +189,15 @@ def refresh_account_value_tiers(
*,
now: datetime | None = None,
batch_size: int = 1000,
update_chunk_size: int = 200,
) -> int:
"""分批刷新账号价值投影,避免在页面请求里反复执行大 CASE。"""
"""分批刷新账号价值投影,先只读筛选变更行再小批量加锁更新。"""
moment = now or datetime.now(UTC)
batch = max(1, int(batch_size))
chunk = max(1, int(update_chunk_size))
last_id = 0
changed = 0
tier = _computed_value_tier_expr(now=moment)
while True:
account_ids = [
int(row[0])
@@ -208,9 +211,8 @@ def refresh_account_value_tiers(
]
if not account_ids:
break
tier = _computed_value_tier_expr(now=moment)
changed += int(
db.query(Account)
stale_rows = (
db.query(Account.id, tier.label("target_tier"))
.filter(
Account.id.in_(account_ids),
or_(
@@ -218,10 +220,26 @@ def refresh_account_value_tiers(
Account.value_tier != tier,
),
)
.update({Account.value_tier: tier}, synchronize_session=False)
or 0
.all()
)
db.commit()
if not stale_rows:
db.commit()
last_id = account_ids[-1]
continue
by_tier: dict[int, list[int]] = {}
for account_id, target_tier in stale_rows:
by_tier.setdefault(int(target_tier), []).append(int(account_id))
for target_tier, ids in by_tier.items():
for offset in range(0, len(ids), chunk):
part = ids[offset : offset + chunk]
changed += int(
db.query(Account)
.filter(Account.id.in_(part))
.update({Account.value_tier: target_tier}, synchronize_session=False)
or 0
)
db.commit()
last_id = account_ids[-1]
return changed