""" 任务事件日志(落盘版事件总线) ============================= 【功能说明】 把任务执行事件写成 JSONL 文件,供 SSE 尾随推送。 一条任务 = 一个文件:data/task_events/{task_id}.jsonl 【为什么需要】 原实现是**进程内**的 asyncio.Queue 事件总线。任务改由独立 worker 进程执行后, worker 与 API 不在同一进程,内存总线直接失效;且 API 一重启,内存里的事件全丢。 落盘到 JSONL 后: - worker 无论在哪个进程写,API 都能读到; - API 重启后 SSE 重连,能从文件续上,不丢历史事件; - 前端可以只靠 SSE 就拿到完整流式输出,无需额外轮询。 【格式】每行一个 JSON:{"event": "...", "message": "...", "data": {...}, "timestamp": "..."} 追加写(append),不改写历史行。 【并发】worker 单进程写、API 多连接读;用 append 模式 + 逐行读, 平台保证 append 的原子性对小写入是安全的(这是本场景的合理假设)。 """ from __future__ import annotations import json import logging import threading from pathlib import Path from typing import Any, Iterator logger = logging.getLogger("agent.event_log") # 同一任务的写入串行化(避免多线程交错写坏一行) _write_locks: dict[str, threading.Lock] = {} _locks_guard = threading.Lock() def _lock_for(task_id: str) -> threading.Lock: with _locks_guard: lock = _write_locks.get(task_id) if lock is None: lock = threading.Lock() _write_locks[task_id] = lock return lock class TaskEventLog: """任务事件日志:按 task_id 一个 JSONL 文件。""" def __init__(self, base_dir: Path) -> None: self._base_dir = Path(base_dir) self._base_dir.mkdir(parents=True, exist_ok=True) def path_of(self, task_id: str) -> Path: """事件文件路径。task_id 只用作文件名,需防路径穿越。""" safe = "".join(c for c in task_id if c.isalnum() or c in "-_") if not safe: safe = "unknown" return self._base_dir / f"{safe}.jsonl" def append(self, task_id: str, event: dict[str, Any]) -> None: """追加一条事件(worker 侧调用)。""" path = self.path_of(task_id) line = json.dumps(event, ensure_ascii=False) with _lock_for(task_id): try: # a=append, 不带缓冲地写完就落盘 with path.open("a", encoding="utf-8", newline="\n") as f: f.write(line + "\n") f.flush() except Exception as exc: # noqa: BLE001 - 事件落盘失败不该打断任务 logger.warning("事件写入失败(task=%s):%s", task_id, exc) def read_from(self, task_id: str, offset: int = 0) -> tuple[list[dict], int]: """ 从指定字节偏移读取新增事件。 【返回】(事件列表, 新的字节偏移) 【设计】用字节偏移做游标,SSE 可以增量尾随,不必反复读全文件。 """ path = self.path_of(task_id) if not path.exists(): return [], offset events: list[dict] = [] try: with path.open("rb") as f: f.seek(offset) chunk = f.read() new_offset = f.tell() except Exception as exc: # noqa: BLE001 logger.warning("事件读取失败(task=%s):%s", task_id, exc) return [], offset if not chunk: return [], offset for raw in chunk.split(b"\n"): if not raw.strip(): continue try: events.append(json.loads(raw.decode("utf-8"))) except Exception: # noqa: BLE001 - 半行/坏行跳过,不拖垮整批 continue return events, new_offset def clear(self, task_id: str) -> None: """删除事件文件(任务删除时调用)。""" try: self.path_of(task_id).unlink(missing_ok=True) except Exception: # noqa: BLE001 pass def tail_until_terminal( self, task_id: str, offset: int = 0, is_terminal=None, max_idle_reads: int = 30, poll_interval: float = 0.25, ) -> Iterator[tuple[list[dict], int]]: """ 持续尾随事件文件,产出新增事件,直到终态或超时。 【参数】 is_terminal:fn() -> bool,返回 True 表示任务已结束,读完剩余事件就退出 max_idle_reads:连续无新增事件的轮询次数上限(防永久空转) poll_interval:轮询间隔秒 【返回】yield (事件列表, 新偏移);事件为空也会 yield(供调用方发心跳) """ import time idle = 0 while True: events, offset = self.read_from(task_id, offset) if events: idle = 0 yield events, offset else: idle += 1 yield [], offset if is_terminal is not None and is_terminal(): # 终态:再读一次,确保把写完的尾部事件吃干净 events, offset = self.read_from(task_id, offset) if events: yield events, offset return if idle >= max_idle_reads: return time.sleep(poll_interval) # 全局单例(由 app 启动时注入真实目录) _event_log: TaskEventLog | None = None def get_event_log() -> TaskEventLog: """获取全局事件日志实例(首次调用时按 settings 初始化)。""" global _event_log if _event_log is None: from app.config.settings import load_settings _event_log = TaskEventLog(load_settings().data_root / "task_events") return _event_log def set_event_log(log: TaskEventLog) -> None: """注入自定义实例(测试用)。""" global _event_log _event_log = log