File size: 4,301 Bytes
fdfe81a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
"""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",
]