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
+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",