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
+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
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:
"""优先使用完整连接串,否则按 DB_* 环境变量构造 MySQL 连接。"""
database_url = os.getenv("DATABASE_URL", "").strip()
@@ -62,6 +98,8 @@ connect_args = (
else {}
)
_POOL_LIMITS = resolve_pool_limits()
engine_options = {
"connect_args": connect_args,
"echo": False,
@@ -72,8 +110,8 @@ if not DATABASE_URL.startswith("sqlite"):
else:
engine_options["pool_pre_ping"] = True
engine_options.update(
pool_size=_env_int("DB_POOL_SIZE", 20),
max_overflow=_env_int("DB_MAX_OVERFLOW", 20),
pool_size=_POOL_LIMITS["api_pool_size"],
max_overflow=_POOL_LIMITS["api_max_overflow"],
pool_timeout=_env_int("DB_POOL_TIMEOUT", 30),
pool_recycle=_env_int("DB_POOL_RECYCLE", 1800),
)
@@ -96,9 +134,9 @@ if not DATABASE_URL.startswith("sqlite"):
else:
worker_engine_options["pool_pre_ping"] = True
worker_engine_options.update(
pool_size=_env_int("WORKER_DB_POOL_SIZE", 12),
max_overflow=_env_int("WORKER_DB_MAX_OVERFLOW", 4),
pool_timeout=_env_int("WORKER_DB_POOL_TIMEOUT", 30),
pool_size=_POOL_LIMITS["worker_pool_size"],
max_overflow=_POOL_LIMITS["worker_max_overflow"],
pool_timeout=_env_int("WORKER_DB_POOL_TIMEOUT", 60),
pool_recycle=_env_int("DB_POOL_RECYCLE", 1800),
)
+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
+67 -24
View File
@@ -26,12 +26,36 @@ def active_account_work_exists(*, work_type: str):
.where(
AccountWorkItem.account_id == Account.id,
AccountWorkItem.work_type == work_type,
AccountWorkItem.status.in_(("pending", "running")),
AccountWorkItem.active_dedupe_key.isnot(None),
)
.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(
db: Session,
*,
@@ -44,7 +68,7 @@ def active_account_work_count(
return 0
query = db.query(func.count(AccountWorkItem.id)).filter(
AccountWorkItem.work_type.in_(work_types),
AccountWorkItem.status.in_(("pending", "running")),
AccountWorkItem.active_dedupe_key.isnot(None),
)
if reason_prefix:
query = query.filter(AccountWorkItem.reason.like(f"{reason_prefix}%"))
@@ -83,29 +107,48 @@ def enqueue_account_work(
existing.due_at = due_at
db.flush()
return existing
item = AccountWorkItem(
account_id=account_id,
work_type=work_type[:32],
priority=int(priority),
# MySQL DATETIME 不保存微秒;立即到期的工作项必须落在当前秒,
# 否则四舍五入到下一秒后,本轮 claim 会误判“还没到期”。
due_at=(due_at or datetime.now(UTC)).replace(microsecond=0),
max_attempts=max(1, int(max_attempts)),
dedupe_key=dedupe_key[:191],
reason=reason[:255],
payload_json=payload,
)
try:
with db.begin_nested():
db.add(item)
db.flush()
return item
except IntegrityError:
return (
db.query(AccountWorkItem)
.filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191])
.one()
bind = db.get_bind()
last_exc: IntegrityError | None = None
for _ in range(3):
item = AccountWorkItem(
account_id=account_id,
work_type=work_type[:32],
priority=int(priority),
# MySQL DATETIME 不保存微秒;立即到期的工作项必须落在当前秒,
# 否则四舍五入到下一秒后,本轮 claim 会误判“还没到期”。
due_at=(due_at or datetime.now(UTC)).replace(microsecond=0),
max_attempts=max(1, int(max_attempts)),
dedupe_key=dedupe_key[:191],
reason=reason[:255],
payload_json=payload,
)
try:
with db.begin_nested():
db.add(item)
db.flush()
return item
except IntegrityError as exc:
last_exc = exc
existing = (
db.query(AccountWorkItem)
.filter(AccountWorkItem.active_dedupe_key == dedupe_key[:191])
.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(
+8 -3
View File
@@ -238,8 +238,13 @@ class DouyuBatchRunner(
self.db.commit()
for task in tasks:
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)
pending: dict = {}
next_index = 0
@@ -249,11 +254,11 @@ class DouyuBatchRunner(
and next_index < total
and len(pending) < self.concurrency
):
task = tasks[next_index]
task_id = task_ids[next_index]
future = submit(
lane,
self._execute_one,
task.id,
task_id,
config,
total,
stopped=self._stop.is_set,
+102 -52
View File
@@ -130,6 +130,7 @@ class DouyuBatchRunnerCore:
self.log_sink = log_sink
self._stop = threading.Event()
self._counter_lock = threading.Lock()
self._hook_local = threading.local()
self._started = 0
# 代理接入 (配置源 = 代理配置页, 与 CK 检测/虎牙注册同款):
# 仅兑换/锁单/支付/充值/送礼等写操作任务走代理, 查询/刷新/绑定类直连
@@ -245,25 +246,39 @@ class DouyuBatchRunnerCore:
except Exception: # noqa: BLE001 - 日志落库不能中断任务
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。"""
if not enabled:
return
active_db: Session | None = getattr(self._hook_local, "db", None)
sync_db: Session | None = None
try:
from ..database import WorkerSessionLocal
from .platform_fulfillment.service import sync_task_from_binding_runner
# 当前批次会话刚刚提交过任务结果。履约投影使用独立短会话,避免
# get_task_detail 留下的只读事务在下一轮外部 HTTP 轮询期间占连接。
if active_db is not None:
sync_task_from_binding_runner(active_db, douyu_task_id=int(douyu_task_id))
return
from ..database import WorkerSessionLocal
sync_db = WorkerSessionLocal()
try:
sync_task_from_binding_runner(sync_db, douyu_task_id=int(douyu_task_id))
finally:
sync_db.close()
sync_task_from_binding_runner(sync_db, douyu_task_id=int(douyu_task_id))
except Exception: # noqa: BLE001 - 履约投影失败不能覆盖任务执行结果
if active_db is not None:
active_db.rollback()
elif sync_db is not None:
sync_db.rollback()
logger.exception(
"[douyu] 同步直播账号履约状态失败: task_id={}", douyu_task_id
)
finally:
if sync_db is not None:
sync_db.close()
def _verify_platform_binding(
self,
@@ -274,27 +289,39 @@ class DouyuBatchRunnerCore:
"""确认绑定完成后,再去斗鱼实时查询复核一次。"""
if not enabled:
return
active_db: Session | None = getattr(self._hook_local, "db", None)
verify_db: Session | None = None
try:
from ..database import WorkerSessionLocal
from .platform_fulfillment.service import verify_active_binding_for_douyu_task
from .platform_fulfillment.service import (
verify_active_binding_for_douyu_task,
)
verify_db = WorkerSessionLocal()
try:
task = verify_db.get(DouyuTask, int(douyu_task_id))
if task is None or task.status != "success":
return
verify_active_binding_for_douyu_task(
verify_db,
douyu_task_id=int(douyu_task_id),
actor_id=int(task.created_by),
)
finally:
verify_db.close()
target_db = active_db
if target_db is None:
from ..database import WorkerSessionLocal
verify_db = WorkerSessionLocal()
target_db = verify_db
task = target_db.get(DouyuTask, int(douyu_task_id))
if task is None or task.status != "success":
return
verify_active_binding_for_douyu_task(
target_db,
douyu_task_id=int(douyu_task_id),
actor_id=int(task.created_by),
)
except Exception: # noqa: BLE001 - 复核异常不能覆盖主任务提交
if active_db is not None:
active_db.rollback()
elif verify_db is not None:
verify_db.rollback()
logger.exception(
"[douyu] 自动复核直播履约绑定状态失败: task_id={}",
douyu_task_id,
)
finally:
if verify_db is not None:
verify_db.close()
def _refresh_platform_exchange_eligibility(
self,
@@ -305,30 +332,40 @@ class DouyuBatchRunnerCore:
"""账号积分/宝典变化后,自动刷新当前履约任务的兑换投影。"""
if not enabled:
return
active_db: Session | None = getattr(self._hook_local, "db", None)
refresh_db: Session | None = None
try:
from ..database import WorkerSessionLocal
from .platform_fulfillment.service import (
refresh_active_exchange_eligibility_for_account,
)
refresh_db = WorkerSessionLocal()
try:
task = refresh_db.get(DouyuTask, int(douyu_task_id))
if task is None or task.status != "success":
return
refresh_active_exchange_eligibility_for_account(
refresh_db,
account_id=int(task.account_id),
scope=str(task.handbook_scope or "elite"),
actor_id=int(task.created_by),
)
finally:
refresh_db.close()
target_db = active_db
if target_db is None:
from ..database import WorkerSessionLocal
refresh_db = WorkerSessionLocal()
target_db = refresh_db
task = target_db.get(DouyuTask, int(douyu_task_id))
if task is None or task.status != "success":
return
refresh_active_exchange_eligibility_for_account(
target_db,
account_id=int(task.account_id),
scope=str(task.handbook_scope or "elite"),
actor_id=int(task.created_by),
)
except Exception: # noqa: BLE001 - 自动刷新不能覆盖任务执行结果
if active_db is not None:
active_db.rollback()
elif refresh_db is not None:
refresh_db.rollback()
logger.exception(
"[douyu] 自动刷新直播履约兑换资格失败: task_id={}",
douyu_task_id,
)
finally:
if refresh_db is not None:
refresh_db.close()
def _sync_platform_fulfillment_operation(
self,
@@ -432,21 +469,26 @@ class DouyuBatchRunnerCore:
logger.exception(
"[douyu] 写入账号任务结果事件失败: task_id={}", task.id
)
self._sync_platform_fulfillment(
task_id,
enabled=sync_platform_fulfillment,
)
self._verify_platform_binding(
task_id,
enabled=(status == "success" and task.task_type == "confirm_bind"),
)
self._refresh_platform_exchange_eligibility(
task_id,
enabled=(
status == "success"
and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES
),
)
previous_db = getattr(self._hook_local, "db", None)
self._hook_local.db = db
try:
self._sync_platform_fulfillment(
task_id,
enabled=sync_platform_fulfillment,
)
self._verify_platform_binding(
task_id,
enabled=(status == "success" and task.task_type == "confirm_bind"),
)
self._refresh_platform_exchange_eligibility(
task_id,
enabled=(
status == "success"
and task.task_type in AUTO_EXCHANGE_ELIGIBILITY_TASK_TYPES
),
)
finally:
self._hook_local.db = previous_db
def _schedule_payment_poll(
self,
@@ -488,7 +530,15 @@ class DouyuBatchRunnerCore:
db.commit()
self._push_task_event(task)
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:
upsert_goods_snapshot(db, goods)
+169 -16
View File
@@ -4,7 +4,10 @@ from __future__ import annotations
import os
import socket
import threading
import time
import uuid
from collections import deque
from datetime import UTC, datetime, timedelta
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(
*,
job_id: int,
@@ -323,23 +354,143 @@ def append_execution_event(
message: str = "",
payload: dict[str, Any] | None = None,
) -> None:
db = WorkerSessionLocal()
try:
db.add(
ExecutionJobEvent(
job_id=int(job_id),
batch_id=batch_id[:64],
level=level[:16],
message=(message or "")[:8000],
payload_json=payload,
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,
)
)
db.commit()
except Exception: # noqa: BLE001 - 日志旁路不能中断任务
db.rollback()
logger.exception("写入执行任务事件失败 job_id={}", job_id)
finally:
db.close()
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:
with self._write_lock:
append_execution_events(batch)
finally:
with self._cond:
self._flushing = False
self._cond.notify_all()
def execution_events_after(
@@ -380,7 +531,9 @@ __all__ = [
"STATUS_QUEUED",
"STATUS_RUNNING",
"STATUS_SUCCEEDED",
"ExecutionEventBatchWriter",
"append_execution_event",
"append_execution_events",
"claim_execution_jobs",
"enqueue_execution_job",
"event_payload",
+41 -21
View File
@@ -23,7 +23,7 @@ from .execution_jobs import (
LANE_FULFILLMENT,
STATUS_CANCELLED,
STATUS_SUCCEEDED,
append_execution_event,
ExecutionEventBatchWriter,
claim_execution_jobs,
execution_worker_owner,
fail_execution_job,
@@ -99,12 +99,14 @@ class ExecutionJobWorker:
self._executors: dict[str, ThreadPoolExecutor] = {}
self._inflight: dict[str, int] = {}
self._owner = execution_worker_owner()
self._event_writer = ExecutionEventBatchWriter()
def start(self) -> bool:
with self._lock:
if self._thread is not None and self._thread.is_alive():
return False
self._stop.clear()
self._event_writer.start()
lane_limits = _lane_slot_limits()
self._executors = {
lane: ThreadPoolExecutor(
@@ -142,6 +144,8 @@ class ExecutionJobWorker:
thread.join(timeout=5)
for executor in executors:
executor.shutdown(wait=True, cancel_futures=True)
if not self._event_writer.stop():
logger.warning("执行任务事件写入线程停机超时,仍有事件等待排空")
def _run(self) -> None:
futures: dict[Future, str] = {}
@@ -214,18 +218,24 @@ class ExecutionJobWorker:
job = db.get(ExecutionJob, int(job_id))
if job is None or job.status != "running":
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 {})
user = db.get(User, int(job.created_by))
user = db.get(User, current_created_by)
if user is None:
raise RuntimeError("执行任务创建人不存在")
creator_permissions = get_user_permissions(user)
def log_sink(event: dict[str, Any]) -> None:
event_payload = dict(event)
level = str(event_payload.pop("level", "info") or "info")
message = str(event_payload.pop("message", "") or "")
append_execution_event(
job_id=int(job.id),
batch_id=job.batch_id,
self._event_writer.enqueue(
job_id=current_job_id,
batch_id=current_batch_id,
level=level,
message=message,
payload=event_payload or None,
@@ -239,7 +249,7 @@ class ExecutionJobWorker:
runner.stop()
return
held, cancel_requested = heartbeat_execution_job(
job_id=int(job.id),
job_id=current_job_id,
owner=self._owner,
)
if not held:
@@ -258,20 +268,20 @@ class ExecutionJobWorker:
heartbeat = threading.Thread(
target=heartbeat_loop,
name=f"execution-heartbeat-{job.id}",
name=f"execution-heartbeat-{current_job_id}",
daemon=True,
)
heartbeat.start()
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()
runner = LoginBatchRunner(
db=db,
account_ids=[
int(value) for value in payload.get("account_ids", [])
],
created_by=int(job.created_by),
creator_permissions=get_user_permissions(user),
created_by=current_created_by,
creator_permissions=creator_permissions,
max_login_retries=int(payload.get("max_login_retries", 0) or 0),
max_total_time=float(payload.get("max_total_time", 300) or 0),
proxy_config=proxy,
@@ -283,16 +293,16 @@ class ExecutionJobWorker:
trigger_source=str(
payload.get("trigger_source", "manual") or "manual"
),
batch_id=job.batch_id,
batch_id=current_batch_id,
log_sink=log_sink,
)
runner.run()
elif job.job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}:
if int(job.attempt_count or 0) > 1:
elif current_job_type in {JOB_DOUYU_BATCH, JOB_DOUYU_BINDING}:
if current_attempt_count > 1:
# 进程中断会留下 pending/running 的初始任务;支付轮询有独立
# queue_lane,不能被重放。重试只重置尚无后置 lane 的行。
db.query(DouyuTask).filter(
DouyuTask.batch_id == job.batch_id,
DouyuTask.batch_id == current_batch_id,
DouyuTask.status.in_(("planned", "pending", "running")),
DouyuTask.queue_lane == "",
).update(
@@ -305,27 +315,32 @@ class ExecutionJobWorker:
db.commit()
runner = DouyuBatchRunner(
db=db,
batch_id=job.batch_id,
batch_id=current_batch_id,
task_type=str(payload.get("task_type") or ""),
payload=dict(payload.get("payload") or {}),
log_queue=None,
loop=None,
concurrency=int(payload.get("concurrency", 3) or 3),
close_db=False,
close_db=True,
log_sink=log_sink,
)
runner.run()
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()}
held, cancel_requested = heartbeat_execution_job(
job_id=int(job.id),
job_id=current_job_id,
owner=self._owner,
)
if not held:
return
finish_execution_job(
job_id=int(job.id),
job_id=current_job_id,
owner=self._owner,
status=(
STATUS_CANCELLED
@@ -336,12 +351,17 @@ class ExecutionJobWorker:
)
except Exception as exc: # noqa: BLE001 - job 边界必须收口
logger.exception("执行任务失败 job_id={}", job_id)
append_execution_event(
self._event_writer.enqueue(
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",
message=f"{type(exc).__name__}: {exc}",
)
if not self._event_writer.flush():
logger.error(
"失败收尾阶段执行任务事件落库未全部确认 job_id={}",
job_id,
)
fail_execution_job(
job_id=int(job_id),
owner=self._owner,
+3
View File
@@ -1124,6 +1124,9 @@ class LoginBatchRunner:
_append_task_info(task, acc)
self.db.commit()
# 后续阶段只通过 TaskLane.LOGIN 的独立 worker_db 执行,外层协调会话
# 若不先释放会在等邮箱验证码期间空占连接池长达 25 分钟。
self.db.close()
total = len(task_infos)
if total == 0:
self._push_log("warning", "没有可执行的账号")
@@ -10,7 +10,7 @@ from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
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.orm import Session, aliased
@@ -39,7 +39,7 @@ from ..account_query_filters import (
valid_ck_filter,
)
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 (
PRIORITY_KEY_BUNDLE_MATCH,
PRIORITY_KEY_CK_FRESHNESS,
@@ -666,52 +666,65 @@ def capability_refresh_candidate_accounts(
)
.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 = (
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id == commodity_id,
or_(
AccountCommodityState.valid_until.is_(None),
AccountCommodityState.valid_until <= moment,
AccountCommodityState.next_check_at.is_(None),
AccountCommodityState.next_check_at <= moment,
),
)
.exists()
)
refresh_needed.append(
state_due = (
select(AccountCommodityState.id)
.where(
AccountCommodityState.account_id == Account.id,
AccountCommodityState.platform == "douyu",
AccountCommodityState.scope == scope,
AccountCommodityState.commodity_id.in_(commodities),
or_(
and_(~fresh_storehome, ~state_exists),
state_due,
AccountCommodityState.valid_until.is_(None),
AccountCommodityState.valid_until <= moment,
AccountCommodityState.next_check_at.is_(None),
AccountCommodityState.next_check_at <= moment,
),
)
.exists()
)
if len(commodities) == 1:
missing_state = ~(
select(AccountCommodityState.id)
.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)
)
query = db.query(Account).filter(
or_(
state_due,
and_(~fresh_storehome, missing_state),
),
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
)
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 (
db.query(Account)
.filter(
or_(*refresh_needed),
cookie_present_filter(),
valid_ck_filter(),
automatable_account_filter(),
assigned_to_pool_filter(),
~active_account_work_exists(work_type=WORK_STOREHOME_SYNC),
)
.order_by(*_refresh_candidate_order_by(moment))
query.order_by(*_refresh_candidate_order_by(moment))
.limit(max(1, min(int(limit), 100)))
.all()
)
@@ -791,8 +804,12 @@ def storehome_refresh_candidate_accounts(
valid_ck_filter(),
automatable_account_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:
query = query.filter(~Account.id.in_(excluded_ids))
order_by: list[Any] = []