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
+17 -13
View File
@@ -103,42 +103,46 @@ DEV_DB_PORT=3307
# 数据库连接策略(仅 MySQL 生效) # 数据库连接策略(仅 MySQL 生效)
# null=每次 Session 关闭即断开物理连接;queue=复用连接池。 # null=每次 Session 关闭即断开物理连接;queue=复用连接池。
# 分进程模式下(BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS=true),api 进程的 worker 池
# 会自动收紧为 4+4=8,background 进程的主池自动收紧为 2+2=4,双进程理论总上限
# 为 (20+20+4+4) + (2+2+24+16) = 92,低于 MySQL 默认 max_connections=151。
DB_POOL_MODE=queue DB_POOL_MODE=queue
WORKER_DB_POOL_MODE=queue WORKER_DB_POOL_MODE=queue
DB_POOL_SIZE=20 DB_POOL_SIZE=20
DB_MAX_OVERFLOW=20 DB_MAX_OVERFLOW=20
WORKER_DB_POOL_SIZE=10 WORKER_DB_POOL_SIZE=24
WORKER_DB_MAX_OVERFLOW=4 WORKER_DB_MAX_OVERFLOW=16
DEPLOY_STARTUP_TIMEOUT_SECONDS=1800 DEPLOY_STARTUP_TIMEOUT_SECONDS=1800
DB_POOL_TIMEOUT=30 DB_POOL_TIMEOUT=30
WORKER_DB_POOL_TIMEOUT=60
DB_POOL_RECYCLE=1800 DB_POOL_RECYCLE=1800
# 行锁 10 秒仍未拿到就失败,避免把连接池和请求线程长期堵住。 # 行锁 10 秒仍未拿到就失败,避免把连接池和请求线程长期堵住。
DB_LOCK_WAIT_TIMEOUT=10 DB_LOCK_WAIT_TIMEOUT=10
# 斗鱼批次创建并发与全局活跃量背压。 # 斗鱼批次创建并发与全局活跃量背压。
DOUYU_BATCH_CREATE_CONCURRENCY=2 DOUYU_BATCH_CREATE_CONCURRENCY=2
DOUYU_BATCH_TASK_CONCURRENCY=5 DOUYU_BATCH_TASK_CONCURRENCY=8
DOUYU_PAYMENT_QR_CONCURRENCY=10 DOUYU_PAYMENT_QR_CONCURRENCY=8
DOUYU_MAX_ACTIVE_BATCHES=10 DOUYU_MAX_ACTIVE_BATCHES=10
# 一键查询使用独立任务槽;普通查询仍为 3 个 worker。 # 一键查询使用独立任务槽;普通查询仍为 4 个 worker。
DOUYU_MAX_ACTIVE_OVERVIEW_TASKS=5 DOUYU_MAX_ACTIVE_OVERVIEW_TASKS=5
# 业务域任务槽。支付出码与到账轮询分离后,各自按实际耗时独立限流。 # 业务域任务槽。支付出码与到账轮询分离后,各自按实际耗时独立限流,总量匹配 worker 连接池。
TASK_LANE_BATCH_COORDINATOR_WORKERS=2 TASK_LANE_BATCH_COORDINATOR_WORKERS=2
TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT=2 TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT=2
TASK_LANE_INTERACTIVE_BINDING_WORKERS=3 TASK_LANE_INTERACTIVE_BINDING_WORKERS=4
TASK_LANE_BINDING_POLL_WORKERS=6 TASK_LANE_BINDING_POLL_WORKERS=6
TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT=6 TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT=6
TASK_LANE_LOGIN_WORKERS=4 TASK_LANE_LOGIN_WORKERS=4
TASK_LANE_ACCOUNT_CHECK_WORKERS=4 TASK_LANE_ACCOUNT_CHECK_WORKERS=4
TASK_LANE_ACCOUNT_SYNC_WORKERS=10 TASK_LANE_ACCOUNT_SYNC_WORKERS=6
# 账号同步队列待处理水位。通用供给只能占低水位,剩余预留给有明确订单的补货。 # 账号同步队列待处理水位。通用供给只能占低水位,剩余预留给有明确订单的补货。
ACCOUNT_SYNC_QUEUE_TARGET_PENDING=60 ACCOUNT_SYNC_QUEUE_TARGET_PENDING=60
ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING=20 ACCOUNT_SUPPLY_QUEUE_TARGET_PENDING=20
TASK_LANE_OVERVIEW_QUERY_WORKERS=5 TASK_LANE_OVERVIEW_QUERY_WORKERS=5
TASK_LANE_QUERY_BATCH_WORKERS=3 TASK_LANE_QUERY_BATCH_WORKERS=4
TASK_LANE_PAYMENT_QR_WORKERS=10 TASK_LANE_PAYMENT_QR_WORKERS=8
TASK_LANE_PAYMENT_POLL_WORKERS=3 TASK_LANE_PAYMENT_POLL_WORKERS=4
TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT=3 TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT=4
TASK_LANE_OPS_WRITE_WORKERS=2 TASK_LANE_OPS_WRITE_WORKERS=4
DOUYU_MAX_ACTIVE_TASKS=250 DOUYU_MAX_ACTIVE_TASKS=250
DOUYU_PROBE_CACHE_SECONDS=30 DOUYU_PROBE_CACHE_SECONDS=30
DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS=0.2 DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS=0.2
+1 -1
View File
@@ -1,6 +1,6 @@
# 直播账号运营后台 # 直播账号运营后台
斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.18)。 斗鱼 / 虎牙账号运营 Web 平台:批量登录拿 Cookie、按工作台跑活动任务、应用宝点券充值。版本见 `pyproject.toml`(当前 0.4.21)。
## 能做什么 ## 能做什么
+18 -18
View File
@@ -44,28 +44,28 @@ services:
- DB_POOL_RECYCLE=${DB_POOL_RECYCLE:-1800} - DB_POOL_RECYCLE=${DB_POOL_RECYCLE:-1800}
- DB_LOCK_WAIT_TIMEOUT=${DB_LOCK_WAIT_TIMEOUT:-10} - DB_LOCK_WAIT_TIMEOUT=${DB_LOCK_WAIT_TIMEOUT:-10}
- WORKER_DB_POOL_MODE=${WORKER_DB_POOL_MODE:-queue} - WORKER_DB_POOL_MODE=${WORKER_DB_POOL_MODE:-queue}
- WORKER_DB_POOL_SIZE=${WORKER_DB_POOL_SIZE:-10} - WORKER_DB_POOL_SIZE=${WORKER_DB_POOL_SIZE:-24}
- WORKER_DB_MAX_OVERFLOW=${WORKER_DB_MAX_OVERFLOW:-4} - WORKER_DB_MAX_OVERFLOW=${WORKER_DB_MAX_OVERFLOW:-16}
- WORKER_DB_POOL_TIMEOUT=${WORKER_DB_POOL_TIMEOUT:-30} - WORKER_DB_POOL_TIMEOUT=${WORKER_DB_POOL_TIMEOUT:-60}
- DOUYU_BATCH_CREATE_CONCURRENCY=${DOUYU_BATCH_CREATE_CONCURRENCY:-4} - DOUYU_BATCH_CREATE_CONCURRENCY=${DOUYU_BATCH_CREATE_CONCURRENCY:-4}
- DOUYU_BATCH_TASK_CONCURRENCY=${DOUYU_BATCH_TASK_CONCURRENCY:-10} - DOUYU_BATCH_TASK_CONCURRENCY=${DOUYU_BATCH_TASK_CONCURRENCY:-8}
- DOUYU_PAYMENT_QR_CONCURRENCY=${DOUYU_PAYMENT_QR_CONCURRENCY:-15} - DOUYU_PAYMENT_QR_CONCURRENCY=${DOUYU_PAYMENT_QR_CONCURRENCY:-8}
- DOUYU_MAX_ACTIVE_BATCHES=${DOUYU_MAX_ACTIVE_BATCHES:-25} - DOUYU_MAX_ACTIVE_BATCHES=${DOUYU_MAX_ACTIVE_BATCHES:-25}
- DOUYU_MAX_ACTIVE_OVERVIEW_TASKS=${DOUYU_MAX_ACTIVE_OVERVIEW_TASKS:-10} - DOUYU_MAX_ACTIVE_OVERVIEW_TASKS=${DOUYU_MAX_ACTIVE_OVERVIEW_TASKS:-5}
- TASK_LANE_BATCH_COORDINATOR_WORKERS=${TASK_LANE_BATCH_COORDINATOR_WORKERS:-6} - TASK_LANE_BATCH_COORDINATOR_WORKERS=${TASK_LANE_BATCH_COORDINATOR_WORKERS:-6}
- TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT=${TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT:-6} - TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT=${TASK_LANE_BATCH_COORDINATOR_MAX_IN_FLIGHT:-6}
- TASK_LANE_INTERACTIVE_BINDING_WORKERS=${TASK_LANE_INTERACTIVE_BINDING_WORKERS:-6} - TASK_LANE_INTERACTIVE_BINDING_WORKERS=${TASK_LANE_INTERACTIVE_BINDING_WORKERS:-4}
- TASK_LANE_BINDING_POLL_WORKERS=${TASK_LANE_BINDING_POLL_WORKERS:-12} - TASK_LANE_BINDING_POLL_WORKERS=${TASK_LANE_BINDING_POLL_WORKERS:-6}
- TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT=${TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT:-12} - TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT=${TASK_LANE_BINDING_POLL_MAX_IN_FLIGHT:-6}
- TASK_LANE_LOGIN_WORKERS=${TASK_LANE_LOGIN_WORKERS:-8} - TASK_LANE_LOGIN_WORKERS=${TASK_LANE_LOGIN_WORKERS:-4}
- TASK_LANE_ACCOUNT_CHECK_WORKERS=${TASK_LANE_ACCOUNT_CHECK_WORKERS:-8} - TASK_LANE_ACCOUNT_CHECK_WORKERS=${TASK_LANE_ACCOUNT_CHECK_WORKERS:-4}
- TASK_LANE_ACCOUNT_SYNC_WORKERS=${TASK_LANE_ACCOUNT_SYNC_WORKERS:-10} - TASK_LANE_ACCOUNT_SYNC_WORKERS=${TASK_LANE_ACCOUNT_SYNC_WORKERS:-6}
- TASK_LANE_OVERVIEW_QUERY_WORKERS=${TASK_LANE_OVERVIEW_QUERY_WORKERS:-10} - TASK_LANE_OVERVIEW_QUERY_WORKERS=${TASK_LANE_OVERVIEW_QUERY_WORKERS:-5}
- TASK_LANE_QUERY_BATCH_WORKERS=${TASK_LANE_QUERY_BATCH_WORKERS:-10} - TASK_LANE_QUERY_BATCH_WORKERS=${TASK_LANE_QUERY_BATCH_WORKERS:-4}
- TASK_LANE_PAYMENT_QR_WORKERS=${TASK_LANE_PAYMENT_QR_WORKERS:-12} - TASK_LANE_PAYMENT_QR_WORKERS=${TASK_LANE_PAYMENT_QR_WORKERS:-8}
- TASK_LANE_PAYMENT_POLL_WORKERS=${TASK_LANE_PAYMENT_POLL_WORKERS:-6} - TASK_LANE_PAYMENT_POLL_WORKERS=${TASK_LANE_PAYMENT_POLL_WORKERS:-4}
- TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT=${TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT:-6} - TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT=${TASK_LANE_PAYMENT_POLL_MAX_IN_FLIGHT:-4}
- TASK_LANE_OPS_WRITE_WORKERS=${TASK_LANE_OPS_WRITE_WORKERS:-6} - TASK_LANE_OPS_WRITE_WORKERS=${TASK_LANE_OPS_WRITE_WORKERS:-4}
- DOUYU_MAX_ACTIVE_TASKS=${DOUYU_MAX_ACTIVE_TASKS:-500} - DOUYU_MAX_ACTIVE_TASKS=${DOUYU_MAX_ACTIVE_TASKS:-500}
- DOUYU_PROBE_CACHE_SECONDS=${DOUYU_PROBE_CACHE_SECONDS:-30} - DOUYU_PROBE_CACHE_SECONDS=${DOUYU_PROBE_CACHE_SECONDS:-30}
- DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS=${DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS:-0.2} - DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS=${DOUYU_COLLAB_VERIFY_BATCH_INTERVAL_SECONDS:-0.2}
+1 -1
View File
@@ -1,6 +1,6 @@
[project] [project]
name = "live-hub-py" name = "live-hub-py"
version = "0.4.18" version = "0.4.21"
description = "直播账号运营 Web 后台" description = "直播账号运营 Web 后台"
readme = "README.md" readme = "README.md"
requires-python = ">=3.12,<3.13" requires-python = ">=3.12,<3.13"
@@ -614,3 +614,60 @@ def test_default_enabled_job_is_created_enabled(db, monkeypatch):
.one() .one()
) )
assert row.enabled is True assert row.enabled is True
def test_multi_commodity_refresh_handles_missing_and_due_states(db):
from web.backend.services.platform_fulfillment.account_selector import (
capability_refresh_candidate_accounts,
)
missing_one = _account(db, "cap-multi-missing-one")
fresh_storehome_missing = _account(db, "cap-multi-fresh-sh")
due_one = _account(db, "cap-multi-due-one")
all_fresh = _account(db, "cap-multi-all-fresh")
# missing_one 只有 C1 新鲜,缺少 C2,且 storehome 过期 -> 应被选中
_state(db, missing_one, commodity_id="C1", valid_until=NOW + timedelta(hours=1))
# fresh_storehome_missing 只有 C1 新鲜,缺少 C2,但 storehome 新鲜 -> 不应重复补扫
_state(
db,
fresh_storehome_missing,
commodity_id="C1",
valid_until=NOW + timedelta(hours=1),
)
db.add(
AccountSyncState(
account_id=fresh_storehome_missing.id,
platform="douyu",
domain="storehome",
status="success",
last_success_at=NOW,
valid_until=NOW + timedelta(hours=1),
)
)
# due_one 两个都有,但 C2 已过期 -> 即使 storehome 新鲜也应被选中
_state(db, due_one, commodity_id="C1", valid_until=NOW + timedelta(hours=1))
_state(db, due_one, commodity_id="C2", valid_until=NOW - timedelta(minutes=1))
db.add(
AccountSyncState(
account_id=due_one.id,
platform="douyu",
domain="storehome",
status="success",
last_success_at=NOW,
valid_until=NOW + timedelta(hours=1),
)
)
# all_fresh 两个都新鲜 -> 不应被选中
_state(db, all_fresh, commodity_id="C1", valid_until=NOW + timedelta(hours=1))
_state(db, all_fresh, commodity_id="C2", valid_until=NOW + timedelta(hours=1))
db.commit()
selected = capability_refresh_candidate_accounts(
db,
commodity_ids=["C1", "C2"],
scope="elite",
limit=10,
now=NOW,
)
assert {row.id for row in selected} == {missing_one.id, due_one.id}
+77
View File
@@ -536,3 +536,80 @@ def test_login_quota_configuration_route_updates_all_categories(db):
assert updated["relogin_high_value_daily_limit"] == 240 assert updated["relogin_high_value_daily_limit"] == 240
assert updated["failure_pause_ratio"] == 35 assert updated["failure_pause_ratio"] == 35
assert loaded["login_concurrency"] == 3 assert loaded["login_concurrency"] == 3
def test_enqueue_account_work_survives_repeatable_read_integrity_race(db):
from tests.support.db import make_test_session
account = _account("queue-race-account")
db.add(account)
db.commit()
# 先开启 db 的 REPEATABLE READ 快照,再由另一会话提交同一工作项
assert db.query(AccountWorkItem).count() == 0
other = make_test_session()
try:
committed = enqueue_account_work(
other,
account_id=account.id,
work_type="storehome_sync",
priority=20,
)
other.commit()
committed_id = int(committed.id)
finally:
other.close()
# db 的旧快照看不到 committed,INSERT 会撞唯一键,但不能抛 NoResultFound
reused = enqueue_account_work(
db,
account_id=account.id,
work_type="storehome_sync",
priority=10,
)
assert int(reused.id) == committed_id
db.commit()
# 如果并发项在另一会话中刚被完成并清空 active_dedupe_key,再次撞锁时也能重新入队
other = make_test_session()
try:
current = other.get(AccountWorkItem, committed_id)
assert current is not None
complete_account_work(other, current)
other.commit()
finally:
other.close()
# 人工模拟同一快照里先误判存在冲突后被完成:重新入队应得到一条新记录
fresh = enqueue_account_work(
db,
account_id=account.id,
work_type="storehome_sync",
priority=10,
)
db.commit()
assert int(fresh.id) != committed_id
def test_enqueue_account_work_raises_integrity_error_when_retries_exhausted(
db, monkeypatch
):
import pytest
from sqlalchemy.exc import IntegrityError
account = _account("queue-race-exhausted")
db.add(account)
db.commit()
def always_conflict() -> None:
raise IntegrityError("INSERT", {}, Exception("Duplicate entry"))
monkeypatch.setattr(db, "flush", always_conflict)
with pytest.raises(IntegrityError):
enqueue_account_work(
db,
account_id=account.id,
work_type="storehome_sync",
priority=10,
)
+41
View File
@@ -2128,3 +2128,44 @@ def test_poll_bind_role_once_records_mismatched_cjm_and_ignores_bound_action_rol
assert "妎䏓" in task.message assert "妎䏓" in task.message
assert task.result["last_mismatched_role"]["role_name"] == "妎朊" assert task.result["last_mismatched_role"]["role_name"] == "妎朊"
assert [m["role_name"] for m in task.result["mismatched_roles"]] == ["妎朊"] assert [m["role_name"] for m in task.result["mismatched_roles"]] == ["妎朊"]
def test_mark_task_reuses_worker_session_without_nested_checkout(db, monkeypatch):
from web.backend import database as database_module
from web.backend.services.platform_fulfillment import service as pf_service
_, _, task = _fixtures(db, status="running")
task.task_type = "confirm_bind"
task.handbook_scope = "elite"
db.commit()
monkeypatch.setattr(
database_module,
"WorkerSessionLocal",
lambda: (_ for _ in ()).throw(AssertionError("收尾钩子不能再嵌套借用 WorkerSessionLocal")),
)
seen_dbs: list[tuple[str, object]] = []
monkeypatch.setattr(
pf_service,
"sync_task_from_binding_runner",
lambda session, *, douyu_task_id: seen_dbs.append(("sync", session)) or 0,
)
monkeypatch.setattr(
pf_service,
"verify_active_binding_for_douyu_task",
lambda session, *, douyu_task_id, actor_id=None: seen_dbs.append(("verify", session)) or None,
)
monkeypatch.setattr(
pf_service,
"refresh_active_exchange_eligibility_for_account",
lambda session, *, account_id, scope, actor_id=None: seen_dbs.append(("eligibility", session)) or None,
)
runner = DouyuBatchRunner(db, task.batch_id, "confirm_bind", close_db=False)
runner._mark_task(db, task, "success", "确认绑定成功")
assert seen_dbs == [
("sync", db),
("verify", db),
("eligibility", db),
]
+224 -1
View File
@@ -9,14 +9,15 @@ from datetime import UTC, datetime, timedelta
from web.backend.models import ExecutionJob, User from web.backend.models import ExecutionJob, User
from web.backend.services import execution_worker from web.backend.services import execution_worker
from web.backend.services.execution_jobs import ( from web.backend.services.execution_jobs import (
JOB_LOGIN_BATCH,
JOB_DOUYU_BATCH, JOB_DOUYU_BATCH,
JOB_LOGIN_BATCH,
LANE_AUTH, LANE_AUTH,
LANE_FULFILLMENT, LANE_FULFILLMENT,
STATUS_CANCELLED, STATUS_CANCELLED,
STATUS_RUNNING, STATUS_RUNNING,
claim_execution_jobs, claim_execution_jobs,
enqueue_execution_job, enqueue_execution_job,
execution_events_after,
finish_execution_job, finish_execution_job,
heartbeat_execution_job, heartbeat_execution_job,
request_execution_cancel, request_execution_cancel,
@@ -242,3 +243,225 @@ def test_auth_batches_cannot_starve_fulfillment_lane(db, monkeypatch):
finally: finally:
release.set() release.set()
worker.stop() worker.stop()
def test_execution_worker_batches_events_and_closes_douyu_db(db, monkeypatch):
user = _user(db, "execution-batch-events")
job = enqueue_execution_job(
db,
job_type=JOB_DOUYU_BATCH,
lane_scope=LANE_FULFILLMENT,
batch_id="exec-batch-events",
payload={"task_type": "query_points", "payload": {}, "concurrency": 1},
created_by=int(user.id),
)
db.commit()
worker = execution_worker.ExecutionJobWorker()
claimed = claim_execution_jobs(
lane_scopes=(LANE_FULFILLMENT,),
owner=worker._owner,
limit=1,
)
assert [row.id for row in claimed] == [job.id]
seen: dict = {}
class FakeDouyuRunner:
def __init__(self, **kwargs):
seen.update(kwargs)
def run(self):
seen["log_sink"]({"level": "info", "message": "step-1"})
seen["log_sink"]({"level": "info", "message": "step-2"})
seen["ran"] = True
monkeypatch.setattr(execution_worker, "DouyuBatchRunner", FakeDouyuRunner)
worker._event_writer.start()
try:
worker._run_job(int(job.id))
finally:
worker._event_writer.stop()
assert seen.get("ran") is True
assert seen.get("close_db") is True
db.rollback()
events = execution_events_after(db, batch_id="exec-batch-events")
assert [item.message for item in events] == ["step-1", "step-2"]
def test_douyu_batch_runner_closes_coordinator_session_before_task_execution(
db, monkeypatch
):
from tests.support.db import make_test_session
from web.backend.models import Account, DouyuTask
from web.backend.services.douyu_runner import DouyuBatchRunner
user = _user(db, "douyu-close-session")
account = Account(
username="douyu-close-acc",
password="p",
email="douyu-close-acc@example.com",
email_password="ep",
)
db.add(account)
db.flush()
task = DouyuTask(
batch_id="douyu-close-batch",
account_id=account.id,
task_type="query_points",
status="planned",
created_by=user.id,
)
db.add(task)
db.commit()
coord_db = make_test_session()
closed = {"called": False}
orig_close = coord_db.close
def tracked_close() -> None:
closed["called"] = True
orig_close()
monkeypatch.setattr(coord_db, "close", tracked_close)
runner = DouyuBatchRunner(
coord_db,
"douyu-close-batch",
"query_points",
close_db=True,
)
observed_closed_during_exec: list[bool] = []
monkeypatch.setattr(
runner,
"_execute_one",
lambda _task_id, _cfg, _total: observed_closed_during_exec.append(
closed["called"]
),
)
runner.run()
assert observed_closed_during_exec == [True]
assert closed["called"] is True
def test_event_batch_writer_flush_timeout_preserves_fifo_and_bounds_time(monkeypatch):
from web.backend.services import execution_jobs
flushed_messages: list[str] = []
gate = threading.Event()
first_started = threading.Event()
def fake_append(events: list[dict]) -> bool:
messages = [str(item["message"]) for item in events]
if "in-flight" in messages:
first_started.set()
gate.wait(2)
flushed_messages.extend(messages)
return True
monkeypatch.setattr(execution_jobs, "append_execution_events", fake_append)
writer = execution_jobs.ExecutionEventBatchWriter(flush_interval=0.05, batch_size=1)
writer.start()
try:
writer.enqueue(job_id=1, batch_id="b1", level="info", message="in-flight")
assert first_started.wait(1)
writer.enqueue(job_id=1, batch_id="b1", level="info", message="queued-after")
# 后台线程仍在写第一批时,flush 必须在 timeout 附近立即返回 False,且不能插队写 queued-after
started_at = time.monotonic()
assert writer.flush(timeout=0.06) is False
elapsed = time.monotonic() - started_at
assert elapsed < 0.25
assert flushed_messages == []
# stop 超时同样立即返回 False,不丢线程与队列引用
assert writer.stop(timeout=0.05) is False
finally:
gate.set()
assert writer.stop(timeout=2.0) is True
# 严格按 FIFO 顺序先落第一批,再落队列后续批
assert flushed_messages == ["in-flight", "queued-after"]
# 线程未运行时残留事件也按 FIFO 同步排空
writer.enqueue(job_id=1, batch_id="b1", level="info", message="tail-1")
writer.enqueue(job_id=1, batch_id="b1", level="info", message="tail-2")
assert writer.flush(timeout=0.05) is True
assert flushed_messages == ["in-flight", "queued-after", "tail-1", "tail-2"]
def test_execution_worker_error_event_stays_after_step_logs(db, monkeypatch):
user = _user(db, "execution-error-order")
job = enqueue_execution_job(
db,
job_type=JOB_DOUYU_BATCH,
lane_scope=LANE_FULFILLMENT,
batch_id="exec-error-order",
payload={"task_type": "query_points", "payload": {}, "concurrency": 1},
created_by=int(user.id),
)
db.commit()
worker = execution_worker.ExecutionJobWorker()
claimed = claim_execution_jobs(
lane_scopes=(LANE_FULFILLMENT,),
owner=worker._owner,
limit=1,
)
assert [row.id for row in claimed] == [job.id]
class FailingDouyuRunner:
def __init__(self, **kwargs):
self.log_sink = kwargs["log_sink"]
def run(self):
self.log_sink({"level": "info", "message": "step-1"})
self.log_sink({"level": "info", "message": "step-2"})
raise RuntimeError("boom")
monkeypatch.setattr(execution_worker, "DouyuBatchRunner", FailingDouyuRunner)
worker._event_writer.start()
try:
worker._run_job(int(job.id))
finally:
assert worker._event_writer.stop() is True
db.rollback()
events = execution_events_after(db, batch_id="exec-error-order")
assert [item.message for item in events] == [
"step-1",
"step-2",
"RuntimeError: boom",
]
def test_resolve_pool_limits_by_runtime_role(monkeypatch):
from web.backend.database import resolve_pool_limits
monkeypatch.setenv("DB_POOL_SIZE", "20")
monkeypatch.setenv("DB_MAX_OVERFLOW", "20")
monkeypatch.setenv("WORKER_DB_POOL_SIZE", "24")
monkeypatch.setenv("WORKER_DB_MAX_OVERFLOW", "16")
api_limits = resolve_pool_limits("api")
assert api_limits == {
"api_pool_size": 20,
"api_max_overflow": 20,
"worker_pool_size": 4,
"worker_max_overflow": 4,
}
bg_limits = resolve_pool_limits("background")
assert bg_limits == {
"api_pool_size": 2,
"api_max_overflow": 2,
"worker_pool_size": 24,
"worker_max_overflow": 16,
}
all_limits = resolve_pool_limits("all")
assert all_limits == {
"api_pool_size": 20,
"api_max_overflow": 20,
"worker_pool_size": 24,
"worker_max_overflow": 16,
}
Generated
+1 -1
View File
@@ -381,7 +381,7 @@ wheels = [
[[package]] [[package]]
name = "live-hub-py" name = "live-hub-py"
version = "0.4.18" version = "0.4.21"
source = { editable = "." } source = { editable = "." }
dependencies = [ dependencies = [
{ name = "alembic" }, { name = "alembic" },
+43 -5
View File
@@ -27,6 +27,42 @@ def _pool_mode(name: str, default: str = "queue") -> str:
return mode if mode in {"queue", "null"} else default return mode if mode in {"queue", "null"} else default
def resolve_pool_limits(runtime_role: str | None = None) -> dict[str, int]:
"""按进程角色拆分主池与后台池上限,避免双进程同配把 MySQL 打满。
`BACKGROUND_RUNTIME_IN_SEPARATE_PROCESS=true` 时,容器内同时运行
``api`` 与 ``background`` 两个进程并共享同一份环境变量:
- ``api`` 进程几乎不跑后台 worker,把 ``worker_engine`` 压到小池;
- ``background`` 进程不接 HTTP 请求,把 ``engine`` 压到小池;
- ``all`` / 未设置(本地调试、单进程、测试)保留完整配置。
"""
role = (
runtime_role
if runtime_role is not None
else os.getenv("RUNTIME_ROLE", "all")
).strip().lower()
api_size = _env_int("DB_POOL_SIZE", 20)
api_overflow = _env_int("DB_MAX_OVERFLOW", 20)
worker_size = _env_int("WORKER_DB_POOL_SIZE", 24)
worker_overflow = _env_int("WORKER_DB_MAX_OVERFLOW", 16)
if role == "api":
worker_size = min(worker_size, _env_int("API_WORKER_DB_POOL_SIZE", 4))
worker_overflow = min(
worker_overflow, _env_int("API_WORKER_DB_MAX_OVERFLOW", 4)
)
elif role == "background":
api_size = min(api_size, _env_int("BACKGROUND_DB_POOL_SIZE", 2))
api_overflow = min(
api_overflow, _env_int("BACKGROUND_DB_MAX_OVERFLOW", 2)
)
return {
"api_pool_size": api_size,
"api_max_overflow": api_overflow,
"worker_pool_size": worker_size,
"worker_max_overflow": worker_overflow,
}
def _get_database_url() -> str: def _get_database_url() -> str:
"""优先使用完整连接串,否则按 DB_* 环境变量构造 MySQL 连接。""" """优先使用完整连接串,否则按 DB_* 环境变量构造 MySQL 连接。"""
database_url = os.getenv("DATABASE_URL", "").strip() database_url = os.getenv("DATABASE_URL", "").strip()
@@ -62,6 +98,8 @@ connect_args = (
else {} else {}
) )
_POOL_LIMITS = resolve_pool_limits()
engine_options = { engine_options = {
"connect_args": connect_args, "connect_args": connect_args,
"echo": False, "echo": False,
@@ -72,8 +110,8 @@ if not DATABASE_URL.startswith("sqlite"):
else: else:
engine_options["pool_pre_ping"] = True engine_options["pool_pre_ping"] = True
engine_options.update( engine_options.update(
pool_size=_env_int("DB_POOL_SIZE", 20), pool_size=_POOL_LIMITS["api_pool_size"],
max_overflow=_env_int("DB_MAX_OVERFLOW", 20), max_overflow=_POOL_LIMITS["api_max_overflow"],
pool_timeout=_env_int("DB_POOL_TIMEOUT", 30), pool_timeout=_env_int("DB_POOL_TIMEOUT", 30),
pool_recycle=_env_int("DB_POOL_RECYCLE", 1800), pool_recycle=_env_int("DB_POOL_RECYCLE", 1800),
) )
@@ -96,9 +134,9 @@ if not DATABASE_URL.startswith("sqlite"):
else: else:
worker_engine_options["pool_pre_ping"] = True worker_engine_options["pool_pre_ping"] = True
worker_engine_options.update( worker_engine_options.update(
pool_size=_env_int("WORKER_DB_POOL_SIZE", 12), pool_size=_POOL_LIMITS["worker_pool_size"],
max_overflow=_env_int("WORKER_DB_MAX_OVERFLOW", 4), max_overflow=_POOL_LIMITS["worker_max_overflow"],
pool_timeout=_env_int("WORKER_DB_POOL_TIMEOUT", 30), pool_timeout=_env_int("WORKER_DB_POOL_TIMEOUT", 60),
pool_recycle=_env_int("DB_POOL_RECYCLE", 1800), pool_recycle=_env_int("DB_POOL_RECYCLE", 1800),
) )
+23 -5
View File
@@ -189,12 +189,15 @@ def refresh_account_value_tiers(
*, *,
now: datetime | None = None, now: datetime | None = None,
batch_size: int = 1000, batch_size: int = 1000,
update_chunk_size: int = 200,
) -> int: ) -> int:
"""分批刷新账号价值投影,避免在页面请求里反复执行大 CASE。""" """分批刷新账号价值投影,先只读筛选变更行再小批量加锁更新。"""
moment = now or datetime.now(UTC) moment = now or datetime.now(UTC)
batch = max(1, int(batch_size)) batch = max(1, int(batch_size))
chunk = max(1, int(update_chunk_size))
last_id = 0 last_id = 0
changed = 0 changed = 0
tier = _computed_value_tier_expr(now=moment)
while True: while True:
account_ids = [ account_ids = [
int(row[0]) int(row[0])
@@ -208,9 +211,8 @@ def refresh_account_value_tiers(
] ]
if not account_ids: if not account_ids:
break break
tier = _computed_value_tier_expr(now=moment) stale_rows = (
changed += int( db.query(Account.id, tier.label("target_tier"))
db.query(Account)
.filter( .filter(
Account.id.in_(account_ids), Account.id.in_(account_ids),
or_( or_(
@@ -218,7 +220,23 @@ def refresh_account_value_tiers(
Account.value_tier != tier, Account.value_tier != tier,
), ),
) )
.update({Account.value_tier: tier}, synchronize_session=False) .all()
)
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 or 0
) )
db.commit() db.commit()
+48 -5
View File
@@ -26,12 +26,36 @@ def active_account_work_exists(*, work_type: str):
.where( .where(
AccountWorkItem.account_id == Account.id, AccountWorkItem.account_id == Account.id,
AccountWorkItem.work_type == work_type, AccountWorkItem.work_type == work_type,
AccountWorkItem.status.in_(("pending", "running")), AccountWorkItem.active_dedupe_key.isnot(None),
) )
.exists() .exists()
) )
def active_account_work_ids(
db: Session,
*,
work_type: str,
limit: int = 5000,
) -> tuple[int, ...] | None:
"""读取指定类型的在途账号 ID 集合(仅扫 active_dedupe_key 非空行)。
当在途数量超过 ``limit`` 时返回 ``None``,由调用方回退到 SQL 子查询。
"""
rows = (
db.query(AccountWorkItem.account_id)
.filter(
AccountWorkItem.active_dedupe_key.isnot(None),
AccountWorkItem.work_type == work_type,
)
.limit(max(1, int(limit)) + 1)
.all()
)
if len(rows) > limit:
return None
return tuple(dict.fromkeys(int(account_id) for (account_id,) in rows))
def active_account_work_count( def active_account_work_count(
db: Session, db: Session,
*, *,
@@ -44,7 +68,7 @@ def active_account_work_count(
return 0 return 0
query = db.query(func.count(AccountWorkItem.id)).filter( query = db.query(func.count(AccountWorkItem.id)).filter(
AccountWorkItem.work_type.in_(work_types), AccountWorkItem.work_type.in_(work_types),
AccountWorkItem.status.in_(("pending", "running")), AccountWorkItem.active_dedupe_key.isnot(None),
) )
if reason_prefix: if reason_prefix:
query = query.filter(AccountWorkItem.reason.like(f"{reason_prefix}%")) query = query.filter(AccountWorkItem.reason.like(f"{reason_prefix}%"))
@@ -83,6 +107,9 @@ def enqueue_account_work(
existing.due_at = due_at existing.due_at = due_at
db.flush() db.flush()
return existing return existing
bind = db.get_bind()
last_exc: IntegrityError | None = None
for _ in range(3):
item = AccountWorkItem( item = AccountWorkItem(
account_id=account_id, account_id=account_id,
work_type=work_type[:32], work_type=work_type[:32],
@@ -100,12 +127,28 @@ def enqueue_account_work(
db.add(item) db.add(item)
db.flush() db.flush()
return item return item
except IntegrityError: except IntegrityError as exc:
return ( last_exc = exc
existing = (
db.query(AccountWorkItem) db.query(AccountWorkItem)
.filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191]) .filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191])
.one() .first()
) )
if existing is not None:
return existing
# MySQL REPEATABLE READ 快照看不到并发事务刚提交的行(或对方刚消费完成并
# 清空 active_dedupe_key),用同 bind 的新只读会话查最新已提交状态。
with Session(bind=bind) as probe:
existing_latest = (
probe.query(AccountWorkItem)
.filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191])
.first()
)
if existing_latest is not None:
probe.expunge(existing_latest)
return existing_latest
assert last_exc is not None
raise last_exc
def claim_account_work( def claim_account_work(
+8 -3
View File
@@ -238,8 +238,13 @@ class DouyuBatchRunner(
self.db.commit() self.db.commit()
for task in tasks: for task in tasks:
self._push_task_event(task) self._push_task_event(task)
task_ids = [int(task.id) for task in tasks]
# 批次调度阶段后续只等待各任务子槽完成,不再使用外层会话;
# 尽早释放连接,避免阻塞期间白占连接池。
if getattr(self, "close_db", True):
self.db.close()
total = len(tasks) total = len(task_ids)
lane = douyu_lane_for_task(self.task_type) lane = douyu_lane_for_task(self.task_type)
pending: dict = {} pending: dict = {}
next_index = 0 next_index = 0
@@ -249,11 +254,11 @@ class DouyuBatchRunner(
and next_index < total and next_index < total
and len(pending) < self.concurrency and len(pending) < self.concurrency
): ):
task = tasks[next_index] task_id = task_ids[next_index]
future = submit( future = submit(
lane, lane,
self._execute_one, self._execute_one,
task.id, task_id,
config, config,
total, total,
stopped=self._stop.is_set, stopped=self._stop.is_set,
+70 -20
View File
@@ -130,6 +130,7 @@ class DouyuBatchRunnerCore:
self.log_sink = log_sink self.log_sink = log_sink
self._stop = threading.Event() self._stop = threading.Event()
self._counter_lock = threading.Lock() self._counter_lock = threading.Lock()
self._hook_local = threading.local()
self._started = 0 self._started = 0
# 代理接入 (配置源 = 代理配置页, 与 CK 检测/虎牙注册同款): # 代理接入 (配置源 = 代理配置页, 与 CK 检测/虎牙注册同款):
# 仅兑换/锁单/支付/充值/送礼等写操作任务走代理, 查询/刷新/绑定类直连 # 仅兑换/锁单/支付/充值/送礼等写操作任务走代理, 查询/刷新/绑定类直连
@@ -245,25 +246,39 @@ class DouyuBatchRunnerCore:
except Exception: # noqa: BLE001 - 日志落库不能中断任务 except Exception: # noqa: BLE001 - 日志落库不能中断任务
logger.exception("写入斗鱼任务事件失败: {}", self.batch_id) logger.exception("写入斗鱼任务事件失败: {}", self.batch_id)
def _sync_platform_fulfillment(self, douyu_task_id: int, *, enabled: bool) -> None: def _sync_platform_fulfillment(
self,
douyu_task_id: int,
*,
enabled: bool,
) -> None:
"""绑定/确认任务完成后立即刷新履约投影并写 Outbox。""" """绑定/确认任务完成后立即刷新履约投影并写 Outbox。"""
if not enabled: if not enabled:
return return
active_db: Session | None = getattr(self._hook_local, "db", None)
sync_db: Session | None = None
try: try:
from ..database import WorkerSessionLocal
from .platform_fulfillment.service import sync_task_from_binding_runner from .platform_fulfillment.service import sync_task_from_binding_runner
# 当前批次会话刚刚提交过任务结果。履约投影使用独立短会话,避免 if active_db is not None:
# get_task_detail 留下的只读事务在下一轮外部 HTTP 轮询期间占连接。 sync_task_from_binding_runner(active_db, douyu_task_id=int(douyu_task_id))
return
from ..database import WorkerSessionLocal
sync_db = WorkerSessionLocal() sync_db = WorkerSessionLocal()
try:
sync_task_from_binding_runner(sync_db, douyu_task_id=int(douyu_task_id)) sync_task_from_binding_runner(sync_db, douyu_task_id=int(douyu_task_id))
finally:
sync_db.close()
except Exception: # noqa: BLE001 - 履约投影失败不能覆盖任务执行结果 except Exception: # noqa: BLE001 - 履约投影失败不能覆盖任务执行结果
if active_db is not None:
active_db.rollback()
elif sync_db is not None:
sync_db.rollback()
logger.exception( logger.exception(
"[douyu] 同步直播账号履约状态失败: task_id={}", douyu_task_id "[douyu] 同步直播账号履约状态失败: task_id={}", douyu_task_id
) )
finally:
if sync_db is not None:
sync_db.close()
def _verify_platform_binding( def _verify_platform_binding(
self, self,
@@ -274,27 +289,39 @@ class DouyuBatchRunnerCore:
"""确认绑定完成后,再去斗鱼实时查询复核一次。""" """确认绑定完成后,再去斗鱼实时查询复核一次。"""
if not enabled: if not enabled:
return return
active_db: Session | None = getattr(self._hook_local, "db", None)
verify_db: Session | None = None
try: try:
from .platform_fulfillment.service import (
verify_active_binding_for_douyu_task,
)
target_db = active_db
if target_db is None:
from ..database import WorkerSessionLocal from ..database import WorkerSessionLocal
from .platform_fulfillment.service import verify_active_binding_for_douyu_task
verify_db = WorkerSessionLocal() verify_db = WorkerSessionLocal()
try: target_db = verify_db
task = verify_db.get(DouyuTask, int(douyu_task_id)) task = target_db.get(DouyuTask, int(douyu_task_id))
if task is None or task.status != "success": if task is None or task.status != "success":
return return
verify_active_binding_for_douyu_task( verify_active_binding_for_douyu_task(
verify_db, target_db,
douyu_task_id=int(douyu_task_id), douyu_task_id=int(douyu_task_id),
actor_id=int(task.created_by), actor_id=int(task.created_by),
) )
finally:
verify_db.close()
except Exception: # noqa: BLE001 - 复核异常不能覆盖主任务提交 except Exception: # noqa: BLE001 - 复核异常不能覆盖主任务提交
if active_db is not None:
active_db.rollback()
elif verify_db is not None:
verify_db.rollback()
logger.exception( logger.exception(
"[douyu] 自动复核直播履约绑定状态失败: task_id={}", "[douyu] 自动复核直播履约绑定状态失败: task_id={}",
douyu_task_id, douyu_task_id,
) )
finally:
if verify_db is not None:
verify_db.close()
def _refresh_platform_exchange_eligibility( def _refresh_platform_exchange_eligibility(
self, self,
@@ -305,30 +332,40 @@ class DouyuBatchRunnerCore:
"""账号积分/宝典变化后,自动刷新当前履约任务的兑换投影。""" """账号积分/宝典变化后,自动刷新当前履约任务的兑换投影。"""
if not enabled: if not enabled:
return return
active_db: Session | None = getattr(self._hook_local, "db", None)
refresh_db: Session | None = None
try: try:
from ..database import WorkerSessionLocal
from .platform_fulfillment.service import ( from .platform_fulfillment.service import (
refresh_active_exchange_eligibility_for_account, refresh_active_exchange_eligibility_for_account,
) )
target_db = active_db
if target_db is None:
from ..database import WorkerSessionLocal
refresh_db = WorkerSessionLocal() refresh_db = WorkerSessionLocal()
try: target_db = refresh_db
task = refresh_db.get(DouyuTask, int(douyu_task_id)) task = target_db.get(DouyuTask, int(douyu_task_id))
if task is None or task.status != "success": if task is None or task.status != "success":
return return
refresh_active_exchange_eligibility_for_account( refresh_active_exchange_eligibility_for_account(
refresh_db, target_db,
account_id=int(task.account_id), account_id=int(task.account_id),
scope=str(task.handbook_scope or "elite"), scope=str(task.handbook_scope or "elite"),
actor_id=int(task.created_by), actor_id=int(task.created_by),
) )
finally:
refresh_db.close()
except Exception: # noqa: BLE001 - 自动刷新不能覆盖任务执行结果 except Exception: # noqa: BLE001 - 自动刷新不能覆盖任务执行结果
if active_db is not None:
active_db.rollback()
elif refresh_db is not None:
refresh_db.rollback()
logger.exception( logger.exception(
"[douyu] 自动刷新直播履约兑换资格失败: task_id={}", "[douyu] 自动刷新直播履约兑换资格失败: task_id={}",
douyu_task_id, douyu_task_id,
) )
finally:
if refresh_db is not None:
refresh_db.close()
def _sync_platform_fulfillment_operation( def _sync_platform_fulfillment_operation(
self, self,
@@ -432,6 +469,9 @@ class DouyuBatchRunnerCore:
logger.exception( logger.exception(
"[douyu] 写入账号任务结果事件失败: task_id={}", task.id "[douyu] 写入账号任务结果事件失败: task_id={}", task.id
) )
previous_db = getattr(self._hook_local, "db", None)
self._hook_local.db = db
try:
self._sync_platform_fulfillment( self._sync_platform_fulfillment(
task_id, task_id,
enabled=sync_platform_fulfillment, enabled=sync_platform_fulfillment,
@@ -447,6 +487,8 @@ class DouyuBatchRunnerCore:
and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES
), ),
) )
finally:
self._hook_local.db = previous_db
def _schedule_payment_poll( def _schedule_payment_poll(
self, self,
@@ -488,7 +530,15 @@ class DouyuBatchRunnerCore:
db.commit() db.commit()
self._push_task_event(task) self._push_task_event(task)
if sync_platform: if sync_platform:
self._sync_platform_fulfillment(task_id, enabled=has_platform_task) previous_db = getattr(self._hook_local, "db", None)
self._hook_local.db = db
try:
self._sync_platform_fulfillment(
task_id,
enabled=has_platform_task,
)
finally:
self._hook_local.db = previous_db
def _upsert_goods(self, db: Session, goods: list[dict]) -> None: def _upsert_goods(self, db: Session, goods: list[dict]) -> None:
upsert_goods_snapshot(db, goods) upsert_goods_snapshot(db, goods)
+168 -15
View File
@@ -4,7 +4,10 @@ from __future__ import annotations
import os import os
import socket import socket
import threading
import time
import uuid import uuid
from collections import deque
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from typing import Any from typing import Any
@@ -315,6 +318,34 @@ def get_execution_job(
) )
def append_execution_events(events: list[dict[str, Any]]) -> bool:
"""批量写入执行任务日志事件,避免高频单条写库占满连接池。"""
if not events:
return True
db = WorkerSessionLocal()
try:
db.add_all(
[
ExecutionJobEvent(
job_id=int(item["job_id"]),
batch_id=str(item["batch_id"])[:64],
level=str(item.get("level") or "info")[:16],
message=str(item.get("message") or "")[:8000],
payload_json=item.get("payload") or None,
)
for item in events
]
)
db.commit()
return True
except Exception: # noqa: BLE001 - 日志旁路不能中断任务
db.rollback()
logger.exception("批量写入执行任务事件失败 count={}", len(events))
return False
finally:
db.close()
def append_execution_event( def append_execution_event(
*, *,
job_id: int, job_id: int,
@@ -323,23 +354,143 @@ def append_execution_event(
message: str = "", message: str = "",
payload: dict[str, Any] | None = None, payload: dict[str, Any] | None = None,
) -> None: ) -> None:
db = WorkerSessionLocal() append_execution_events(
[
{
"job_id": int(job_id),
"batch_id": batch_id,
"level": level,
"message": message,
"payload": payload,
}
]
)
class ExecutionEventBatchWriter:
"""后台聚合写入执行事件,严格保持 FIFO 顺序并遵守 flush 超时上限。"""
def __init__(
self,
*,
flush_interval: float = 0.2,
batch_size: int = 64,
) -> None:
self._flush_interval = max(0.05, float(flush_interval))
self._batch_size = max(1, int(batch_size))
self._cond = threading.Condition()
self._write_lock = threading.Lock()
self._queue: deque[dict[str, Any]] = deque()
self._flushing = False
self._stop = False
self._thread: threading.Thread | None = None
def start(self) -> None:
with self._cond:
if self._thread is not None and self._thread.is_alive():
return
self._stop = False
self._thread = threading.Thread(
target=self._run,
name="execution-event-writer",
daemon=True,
)
self._thread.start()
def is_running(self) -> bool:
with self._cond:
return self._thread is not None and self._thread.is_alive()
def _drain_sync(self) -> bool:
"""在后台线程未运行时按 FIFO 同步写完队列中剩余事件。"""
with self._write_lock:
with self._cond:
remaining = list(self._queue)
self._queue.clear()
if not remaining:
return True
return append_execution_events(remaining)
def stop(self, timeout: float = 5.0) -> bool:
with self._cond:
self._stop = True
self._cond.notify_all()
thread = self._thread
if thread is not None and thread.is_alive():
thread.join(timeout=max(0.05, float(timeout)))
with self._cond:
still_alive = thread is not None and thread.is_alive()
if not still_alive:
self._thread = None
if still_alive:
# 后台线程仍在写库:保留线程与队列交由它按 FIFO 继续排空,不插队也不丢引用
return False
return self._drain_sync()
def enqueue(
self,
*,
job_id: int,
batch_id: str,
level: str,
message: str = "",
payload: dict[str, Any] | None = None,
) -> None:
item = {
"job_id": int(job_id),
"batch_id": batch_id,
"level": level,
"message": message,
"payload": payload,
}
with self._cond:
if self._thread is not None and self._thread.is_alive():
self._queue.append(item)
if len(self._queue) >= self._batch_size:
self._cond.notify_all()
return
self._queue.append(item)
self._drain_sync()
def flush(self, timeout: float = 5.0) -> bool:
deadline = time.monotonic() + max(0.05, float(timeout))
with self._cond:
thread = self._thread
if thread is None or not thread.is_alive():
need_sync = bool(self._queue)
self._thread = None
else:
need_sync = False
self._cond.notify_all()
while self._queue or self._flushing:
left = deadline - time.monotonic()
if left <= 0:
return False
self._cond.wait(timeout=min(left, 0.05))
return True
if need_sync:
return self._drain_sync()
return True
def _run(self) -> None:
while True:
batch: list[dict[str, Any]] = []
with self._cond:
while not self._queue and not self._stop:
self._cond.wait(timeout=self._flush_interval)
if not self._queue and self._stop:
self._cond.notify_all()
return
while self._queue and len(batch) < self._batch_size:
batch.append(self._queue.popleft())
self._flushing = True
try: try:
db.add( with self._write_lock:
ExecutionJobEvent( append_execution_events(batch)
job_id=int(job_id),
batch_id=batch_id[:64],
level=level[:16],
message=(message or "")[:8000],
payload_json=payload,
)
)
db.commit()
except Exception: # noqa: BLE001 - 日志旁路不能中断任务
db.rollback()
logger.exception("写入执行任务事件失败 job_id={}", job_id)
finally: finally:
db.close() with self._cond:
self._flushing = False
self._cond.notify_all()
def execution_events_after( def execution_events_after(
@@ -380,7 +531,9 @@ __all__ = [
"STATUS_QUEUED", "STATUS_QUEUED",
"STATUS_RUNNING", "STATUS_RUNNING",
"STATUS_SUCCEEDED", "STATUS_SUCCEEDED",
"ExecutionEventBatchWriter",
"append_execution_event", "append_execution_event",
"append_execution_events",
"claim_execution_jobs", "claim_execution_jobs",
"enqueue_execution_job", "enqueue_execution_job",
"event_payload", "event_payload",
+41 -21
View File
@@ -23,7 +23,7 @@ from .execution_jobs import (
LANE_FULFILLMENT, LANE_FULFILLMENT,
STATUS_CANCELLED, STATUS_CANCELLED,
STATUS_SUCCEEDED, STATUS_SUCCEEDED,
append_execution_event, ExecutionEventBatchWriter,
claim_execution_jobs, claim_execution_jobs,
execution_worker_owner, execution_worker_owner,
fail_execution_job, fail_execution_job,
@@ -99,12 +99,14 @@ class ExecutionJobWorker:
self._executors: dict[str, ThreadPoolExecutor] = {} self._executors: dict[str, ThreadPoolExecutor] = {}
self._inflight: dict[str, int] = {} self._inflight: dict[str, int] = {}
self._owner = execution_worker_owner() self._owner = execution_worker_owner()
self._event_writer = ExecutionEventBatchWriter()
def start(self) -> bool: def start(self) -> bool:
with self._lock: with self._lock:
if self._thread is not None and self._thread.is_alive(): if self._thread is not None and self._thread.is_alive():
return False return False
self._stop.clear() self._stop.clear()
self._event_writer.start()
lane_limits = _lane_slot_limits() lane_limits = _lane_slot_limits()
self._executors = { self._executors = {
lane: ThreadPoolExecutor( lane: ThreadPoolExecutor(
@@ -142,6 +144,8 @@ class ExecutionJobWorker:
thread.join(timeout=5) thread.join(timeout=5)
for executor in executors: for executor in executors:
executor.shutdown(wait=True, cancel_futures=True) executor.shutdown(wait=True, cancel_futures=True)
if not self._event_writer.stop():
logger.warning("执行任务事件写入线程停机超时,仍有事件等待排空")
def _run(self) -> None: def _run(self) -> None:
futures: dict[Future, str] = {} futures: dict[Future, str] = {}
@@ -214,18 +218,24 @@ class ExecutionJobWorker:
job = db.get(ExecutionJob, int(job_id)) job = db.get(ExecutionJob, int(job_id))
if job is None or job.status != "running": if job is None or job.status != "running":
return return
current_job_id = int(job.id)
current_batch_id = str(job.batch_id)
current_job_type = str(job.job_type)
current_attempt_count = int(job.attempt_count or 0)
current_created_by = int(job.created_by)
payload = dict(job.payload_json or {}) payload = dict(job.payload_json or {})
user = db.get(User, int(job.created_by)) user = db.get(User, current_created_by)
if user is None: if user is None:
raise RuntimeError("执行任务创建人不存在") raise RuntimeError("执行任务创建人不存在")
creator_permissions = get_user_permissions(user)
def log_sink(event: dict[str, Any]) -> None: def log_sink(event: dict[str, Any]) -> None:
event_payload = dict(event) event_payload = dict(event)
level = str(event_payload.pop("level", "info") or "info") level = str(event_payload.pop("level", "info") or "info")
message = str(event_payload.pop("message", "") or "") message = str(event_payload.pop("message", "") or "")
append_execution_event( self._event_writer.enqueue(
job_id=int(job.id), job_id=current_job_id,
batch_id=job.batch_id, batch_id=current_batch_id,
level=level, level=level,
message=message, message=message,
payload=event_payload or None, payload=event_payload or None,
@@ -239,7 +249,7 @@ class ExecutionJobWorker:
runner.stop() runner.stop()
return return
held, cancel_requested = heartbeat_execution_job( held, cancel_requested = heartbeat_execution_job(
job_id=int(job.id), job_id=current_job_id,
owner=self._owner, owner=self._owner,
) )
if not held: if not held:
@@ -258,20 +268,20 @@ class ExecutionJobWorker:
heartbeat = threading.Thread( heartbeat = threading.Thread(
target=heartbeat_loop, target=heartbeat_loop,
name=f"execution-heartbeat-{job.id}", name=f"execution-heartbeat-{current_job_id}",
daemon=True, daemon=True,
) )
heartbeat.start() heartbeat.start()
summary: dict[str, Any] = {} summary: dict[str, Any] = {}
if job.job_type in {JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH}: if current_job_type in {JOB_LOGIN_BATCH, JOB_RELOGIN_BATCH}:
proxy = db.query(ProxyConfig).first() proxy = db.query(ProxyConfig).first()
runner = LoginBatchRunner( runner = LoginBatchRunner(
db=db, db=db,
account_ids=[ account_ids=[
int(value) for value in payload.get("account_ids", []) int(value) for value in payload.get("account_ids", [])
], ],
created_by=int(job.created_by), created_by=current_created_by,
creator_permissions=get_user_permissions(user), creator_permissions=creator_permissions,
max_login_retries=int(payload.get("max_login_retries", 0) or 0), max_login_retries=int(payload.get("max_login_retries", 0) or 0),
max_total_time=float(payload.get("max_total_time", 300) or 0), max_total_time=float(payload.get("max_total_time", 300) or 0),
proxy_config=proxy, proxy_config=proxy,
@@ -283,16 +293,16 @@ class ExecutionJobWorker:
trigger_source=str( trigger_source=str(
payload.get("trigger_source", "manual") or "manual" payload.get("trigger_source", "manual") or "manual"
), ),
batch_id=job.batch_id, batch_id=current_batch_id,
log_sink=log_sink, log_sink=log_sink,
) )
runner.run() runner.run()
elif job.job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}: elif current_job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}:
if int(job.attempt_count or 0) > 1: if current_attempt_count > 1:
# 进程中断会留下 pending/running 的初始任务;支付轮询有独立 # 进程中断会留下 pending/running 的初始任务;支付轮询有独立
# queue_lane,不能被重放。重试只重置尚无后置 lane 的行。 # queue_lane,不能被重放。重试只重置尚无后置 lane 的行。
db.query(DouyuTask).filter( db.query(DouyuTask).filter(
DouyuTask.batch_id == job.batch_id, DouyuTask.batch_id == current_batch_id,
DouyuTask.status.in_(("planned", "pending", "running")), DouyuTask.status.in_(("planned", "pending", "running")),
DouyuTask.queue_lane == "", DouyuTask.queue_lane == "",
).update( ).update(
@@ -305,27 +315,32 @@ class ExecutionJobWorker:
db.commit() db.commit()
runner = DouyuBatchRunner( runner = DouyuBatchRunner(
db=db, db=db,
batch_id=job.batch_id, batch_id=current_batch_id,
task_type=str(payload.get("task_type") or ""), task_type=str(payload.get("task_type") or ""),
payload=dict(payload.get("payload") or {}), payload=dict(payload.get("payload") or {}),
log_queue=None, log_queue=None,
loop=None, loop=None,
concurrency=int(payload.get("concurrency", 3) or 3), concurrency=int(payload.get("concurrency", 3) or 3),
close_db=False, close_db=True,
log_sink=log_sink, log_sink=log_sink,
) )
runner.run() runner.run()
else: else:
raise RuntimeError(f"不支持的执行任务类型: {job.job_type}") raise RuntimeError(f"不支持的执行任务类型: {current_job_type}")
if not self._event_writer.flush():
logger.error(
"执行任务事件落库未在超时内全部确认 job_id={}",
current_job_id,
)
summary = {"finished_at": datetime.now(UTC).isoformat()} summary = {"finished_at": datetime.now(UTC).isoformat()}
held, cancel_requested = heartbeat_execution_job( held, cancel_requested = heartbeat_execution_job(
job_id=int(job.id), job_id=current_job_id,
owner=self._owner, owner=self._owner,
) )
if not held: if not held:
return return
finish_execution_job( finish_execution_job(
job_id=int(job.id), job_id=current_job_id,
owner=self._owner, owner=self._owner,
status=( status=(
STATUS_CANCELLED STATUS_CANCELLED
@@ -336,12 +351,17 @@ class ExecutionJobWorker:
) )
except Exception as exc: # noqa: BLE001 - job 边界必须收口 except Exception as exc: # noqa: BLE001 - job 边界必须收口
logger.exception("执行任务失败 job_id={}", job_id) logger.exception("执行任务失败 job_id={}", job_id)
append_execution_event( self._event_writer.enqueue(
job_id=int(job_id), job_id=int(job_id),
batch_id=str(job.batch_id) if job is not None else "", batch_id=current_batch_id if "current_batch_id" in locals() else "",
level="error", level="error",
message=f"{type(exc).__name__}: {exc}", message=f"{type(exc).__name__}: {exc}",
) )
if not self._event_writer.flush():
logger.error(
"失败收尾阶段执行任务事件落库未全部确认 job_id={}",
job_id,
)
fail_execution_job( fail_execution_job(
job_id=int(job_id), job_id=int(job_id),
owner=self._owner, owner=self._owner,
+3
View File
@@ -1124,6 +1124,9 @@ class LoginBatchRunner:
_append_task_info(task, acc) _append_task_info(task, acc)
self.db.commit() self.db.commit()
# 后续阶段只通过 TaskLane.LOGIN 的独立 worker_db 执行,外层协调会话
# 若不先释放会在等邮箱验证码期间空占连接池长达 25 分钟。
self.db.close()
total = len(task_infos) total = len(task_infos)
if total == 0: if total == 0:
self._push_log("warning", "没有可执行的账号") self._push_log("warning", "没有可执行的账号")
@@ -10,7 +10,7 @@ from dataclasses import dataclass
from datetime import UTC, datetime, timedelta from datetime import UTC, datetime, timedelta
from typing import Any from typing import Any
from sqlalchemy import and_, case, literal, or_, select from sqlalchemy import and_, case, func, literal, or_, select
from sqlalchemy.exc import IntegrityError from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm import Session, aliased from sqlalchemy.orm import Session, aliased
@@ -39,7 +39,7 @@ from ..account_query_filters import (
valid_ck_filter, valid_ck_filter,
) )
from ..account_sync_runner import WORK_STOREHOME_SYNC from ..account_sync_runner import WORK_STOREHOME_SYNC
from ..account_work_queue import active_account_work_exists from ..account_work_queue import active_account_work_exists, active_account_work_ids
from .policy import ( from .policy import (
PRIORITY_KEY_BUNDLE_MATCH, PRIORITY_KEY_BUNDLE_MATCH,
PRIORITY_KEY_CK_FRESHNESS, PRIORITY_KEY_CK_FRESHNESS,
@@ -666,25 +666,13 @@ def capability_refresh_candidate_accounts(
) )
.exists() .exists()
) )
refresh_needed = []
for commodity_id in commodities:
state_exists = (
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
)
.exists()
)
state_due = ( state_due = (
select(AccountCommodityState.id) select(AccountCommodityState.id)
.where( .where(
AccountCommodityState.account_id == Account.id, AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu", AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope, AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id, AccountCommodityState.commodity_id.in_(commodities),
or_( or_(
AccountCommodityState.valid_until.is_(None), AccountCommodityState.valid_until.is_(None),
AccountCommodityState.valid_until <= moment, AccountCommodityState.valid_until <= moment,
@@ -694,24 +682,49 @@ def capability_refresh_candidate_accounts(
) )
.exists() .exists()
) )
refresh_needed.append( if len(commodities) == 1:
or_( missing_state = ~(
and_(~fresh_storehome, ~state_exists), select(AccountCommodityState.id)
state_due, .where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodities[0],
) )
.exists()
)
else:
# (account_id, platform, scope, commodity_id) 有唯一约束 uq_account_commodity_state,
# 行数少于待履约商品数即表示至少缺失一个商品的快照行。
missing_state = (
select(func.count(AccountCommodityState.id))
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id.in_(commodities),
)
.scalar_subquery()
< len(commodities)
) )
return ( query = db.query(Account).filter(
db.query(Account) or_(
.filter( state_due,
or_(*refresh_needed), and_(~fresh_storehome, missing_state),
),
cookie_present_filter(), cookie_present_filter(),
valid_ck_filter(), valid_ck_filter(),
automatable_account_filter(), automatable_account_filter(),
assigned_to_pool_filter(), assigned_to_pool_filter(),
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
) )
.order_by(*_refresh_candidate_order_by(moment)) active_work_ids = active_account_work_ids(db, work_type=WORK_STOREHOME_SYNC)
if active_work_ids is None:
query = query.filter(~active_account_work_exists(work_type=WORK_STOREHOME_SYNC))
elif active_work_ids:
query = query.filter(~Account.id.in_(active_work_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()
) )
@@ -791,8 +804,12 @@ def storehome_refresh_candidate_accounts(
valid_ck_filter(), valid_ck_filter(),
automatable_account_filter(), automatable_account_filter(),
assigned_to_pool_filter(), assigned_to_pool_filter(),
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
) )
active_work_ids = active_account_work_ids(db, work_type=WORK_STOREHOME_SYNC)
if active_work_ids is None:
query = query.filter(~active_account_work_exists(work_type=WORK_STOREHOME_SYNC))
elif active_work_ids:
query = query.filter(~Account.id.in_(active_work_ids))
if excluded_ids: if excluded_ids:
query = query.filter(~Account.id.in_(excluded_ids)) query = query.filter(~Account.id.in_(excluded_ids))
order_by: list[Any] = [] order_by: list[Any] = []