"""Per-job event log for SSE streaming. The audit pipeline emits coarse-grained status snapshots into ``job.json`` which the SSE endpoint already serves. This module adds a fine-grained *event* log — JSONL appended at ``{job_dir}/events.jsonl`` — so the SSE generator can emit per-slide ``slide-reviewed`` events as each slide finishes rather than waiting for the next status snapshot. Why JSONL on disk? * Resilient to SSE reconnects: the file persists, so a client connecting mid-audit can replay everything that has already happened. * Decouples the pipeline (background task) from the SSE generator (per-request coroutine) without an in-process pubsub or shared state. * One-line append + atomic per-line write — no lock contention. The log lives next to ``job.json`` in the job directory created by ``services.jobs.JobStore``; the SSE generator tails it via :func:`read_events_since`. """ from __future__ import annotations import json import logging import os from pathlib import Path from typing import Any logger = logging.getLogger(__name__) EVENTS_FILE_NAME = "events.jsonl" def events_path(job_dir: Path) -> Path: """Return the event log path for a job.""" return Path(job_dir) / EVENTS_FILE_NAME def append_event(job_dir: Path, event_type: str, data: dict[str, Any]) -> None: """Append a single event to the job's event log. Best-effort: failures here MUST NOT crash the audit pipeline. If the file system is full / permission-denied, we log and continue — the status snapshot will still tell the client what happened. """ path = events_path(job_dir) payload = {"event": event_type, "data": data} try: path.parent.mkdir(parents=True, exist_ok=True) line = json.dumps(payload, ensure_ascii=False) # Open in append mode + write a single line (newline-terminated). # Standard POSIX append is atomic for writes <= PIPE_BUF (~4KB); # our slide-reviewed payloads are well under that. with path.open("a", encoding="utf-8") as f: f.write(line + "\n") except Exception as exc: # noqa: BLE001 logger.warning("event_log: failed to append %s: %s", event_type, exc) def read_events_since(job_dir: Path, byte_offset: int) -> tuple[list[dict[str, Any]], int]: """Read every newline-terminated event from *byte_offset* onward. Returns ``(events, new_offset)``. The new offset is the position at the end of the last *complete* line we read — partial trailing lines are NOT consumed, so a subsequent call sees them in full. This is what the SSE generator calls in its loop. It's tolerant of the file not yet existing (returns empty + offset 0). """ path = events_path(job_dir) if not path.exists(): return [], 0 try: with path.open("rb") as f: f.seek(byte_offset) buf = f.read() except OSError as exc: logger.warning("event_log: read failed for %s: %s", path, exc) return [], byte_offset if not buf: return [], byte_offset # Split on \n; the final entry may be a partial line — leave it for # the next read. lines = buf.split(b"\n") events: list[dict[str, Any]] = [] consumed = 0 for idx, raw in enumerate(lines): is_last = idx == len(lines) - 1 if is_last and not raw: # The buffer ended in a clean newline — nothing to keep. consumed += 0 continue if is_last: # Final partial line — stop here, do NOT advance past it. break consumed += len(raw) + 1 # include the trailing \n if not raw.strip(): continue try: events.append(json.loads(raw.decode("utf-8"))) except (json.JSONDecodeError, UnicodeDecodeError) as exc: logger.warning("event_log: skipping malformed line: %s", exc) return events, byte_offset + consumed def file_size(job_dir: Path) -> int: """Return current size of the event log in bytes (0 if absent).""" path = events_path(job_dir) try: return os.path.getsize(path) except OSError: return 0 __all__ = [ "EVENTS_FILE_NAME", "append_event", "events_path", "file_size", "read_events_since", ]