fix(worker): 优化连接池容量拆分、并发入队与事件写入
This commit is contained in:
@@ -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,
|
||||
|
||||
Reference in New Issue
Block a user