Source code for s365b.core.runlog

"""Each job run's own log, kept in the database for download.

Every log line that carries a ``run_id`` (bound on the logger, or bound to
the running task with :func:`for_run`, which also covers the Graph client
and other module-level loggers) is copied into that run's log. Lines are
collected in memory and written in batches by :func:`collecting`, which the
worker runs for as long as it works. Lines go to stdout as before.

A run keeps at most :data:`MAX_LINES` lines; the rest are counted and the
count is noted at the end. Lines whose write failed (the database was
unreachable) are kept and written with the next batch, up to
:data:`MAX_PENDING` lines in all; past that the oldest are dropped and a
warning goes to stdout. Writing the log never fails a run. Housekeeping
deletes run logs older than its ``run_log_days`` setting.
"""

from __future__ import annotations

import asyncio
import contextlib
import contextvars
import json
import threading
from collections.abc import AsyncIterator, MutableMapping
from datetime import UTC, datetime
from typing import Any

import structlog
from sqlalchemy import insert

from s365b.db.models import JobRunLog
from s365b.db.session import Database

[docs] MAX_LINES = 20_000
[docs] MAX_PENDING = 100_000
[docs] FLUSH_SECONDS = 2.0
# Fields every line has, shown at its start rather than as key=value. class _Collector: """Lines waiting to be written, per run.""" def __init__(self) -> None: """Start empty.""" self.lock = threading.Lock() # One write at a time, so lines reach the database in logged order. self.writing = asyncio.Lock() self.pending: list[tuple[int, dict[str, Any]]] = [] self.counts: dict[int, int] = {} self.dropped: dict[int, int] = {} def add(self, run_id: int, entry: dict[str, Any]) -> None: """Queue a line unless the run's log is full. Args: run_id: The run. entry: The log line's fields. """ with self.lock: n = self.counts.get(run_id, 0) if n >= MAX_LINES: self.dropped[run_id] = self.dropped.get(run_id, 0) + 1 return self.counts[run_id] = n + 1 self.pending.append((run_id, entry)) def take(self) -> list[tuple[int, dict[str, Any]]]: """Remove and return the queued lines. Returns: ``(run_id, entry)`` pairs in the order they were logged. """ with self.lock: out, self.pending = self.pending, [] return out def put_back(self, lines: list[tuple[int, dict[str, Any]]]) -> int: """Queue lines again, ahead of newer ones, after a failed write. Args: lines: What :meth:`take` returned. Returns: How many of the oldest lines were dropped to stay within :data:`MAX_PENDING`. """ with self.lock: self.pending = lines + self.pending over = max(0, len(self.pending) - MAX_PENDING) del self.pending[:over] return over def finish(self, run_id: int) -> None: """Note how many lines the run did not keep, and forget the run. Args: run_id: The run, now finished. """ with self.lock: self.counts.pop(run_id, None) if n := self.dropped.pop(run_id, 0): entry = { "timestamp": datetime.now(UTC).isoformat(), "level": "warning", "event": "log.truncated", "lines_not_kept": n, } self.pending.append((run_id, entry)) _collector: _Collector | None = None
[docs] def capture( logger: Any, method: str, event_dict: MutableMapping[str, Any] ) -> MutableMapping[str, Any]: """Structlog processor: copy lines that name a run into its log. Args: logger: Unused. method: Unused. event_dict: The line's fields; returned unchanged. Returns: ``event_dict``. """ collector = _collector run_id = event_dict.get("run_id") if collector is not None and isinstance(run_id, int): # Plain JSON values only: anything else is written as text. entry = json.loads(json.dumps(dict(event_dict), default=str)) entry.pop("run_id", None) collector.add(run_id, entry) return event_dict
[docs] def for_run(run_id: int) -> None: """Tag every line the current task (and tasks it starts) logs with a run. Args: run_id: The run. """ structlog.contextvars.bind_contextvars(run_id=run_id)
[docs] async def flush(db: Database) -> None: """Write the queued lines now. Args: db: Database. """ if _collector is None: return collector = _collector async with collector.writing: lines = collector.take() if not lines: return try: async with db.session() as s: await s.execute( insert(JobRunLog), [ { "run_fk": run_id, "at": _when(entry.get("timestamp")), "entry": entry, } for run_id, entry in lines ], ) except BaseException: if dropped := collector.put_back(lines): # To stdout only: logging a run's line here would queue it again. print(f"run log: {dropped} lines dropped, the database is unreachable", flush=True) raise
[docs] async def finish(db: Database) -> None: """Write the current run's log now that it is done. Never raises. The run is the one bound to this task by :func:`for_run`, if any. Args: db: Database. """ run_id = structlog.contextvars.get_contextvars().get("run_id") # A worker may run its next job in the same task: it must not be tagged. structlog.contextvars.unbind_contextvars("run_id") if _collector is not None and isinstance(run_id, int): _collector.finish(run_id) with contextlib.suppress(Exception): # left queued; the writer tries again await flush(db)
def _when(value: Any) -> datetime: try: return datetime.fromisoformat(str(value)) except ValueError: return datetime.now(UTC) @contextlib.asynccontextmanager
[docs] async def collecting(db: Database) -> AsyncIterator[None]: """Collect run logs while the block runs, writing them every few seconds. Args: db: Database. Yields: Nothing. """ global _collector _collector = _Collector() async def writer() -> None: """Write queued lines every :data:`FLUSH_SECONDS`.""" while True: await asyncio.sleep(FLUSH_SECONDS) with contextlib.suppress(Exception): # a lost batch must not stop the worker await flush(db) # A fresh context: the writer's own lines belong to no run. task = asyncio.get_running_loop().create_task(writer(), context=contextvars.Context()) try: yield finally: task.cancel() with contextlib.suppress(asyncio.CancelledError): await task with contextlib.suppress(Exception): await flush(db) _collector = None
[docs] def render(entry: dict[str, Any]) -> str: """One stored line as text: time, level, event, then the other fields. Args: entry: The line's fields. Returns: The line, without a newline. """ rest = " ".join( f"{k}={_value(v)}" for k, v in entry.items() if k not in HEAD and k != "exception" ) level = str(entry.get("level", "")).upper() head = f"{entry.get('timestamp', '')} {level:<7} {entry.get('event', '')}" line = f"{head} {rest}" if rest else head if entry.get("exception"): line += "\n" + str(entry["exception"]).rstrip() return line
def _value(v: Any) -> str: text = v if isinstance(v, str) else json.dumps(v, ensure_ascii=False, separators=(",", ":")) return json.dumps(text, ensure_ascii=False) if any(c in text for c in ' "=\n') else text