askrobots / dbbasic-object-server
Public
Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.
object_ops_log.py · 4.6 KB · 140 lines
| 1 | """Operational event log: execution errors and auth activity. |
| 2 | |
| 3 | One append-only JSONL feed for the events operators actually page on — |
| 4 | object execution failures (with correlation ids for tracing back to source |
| 5 | versions and logs) and authentication activity (login success/failure, |
| 6 | logout, session mints). Auth failures are recorded per identifier, which is |
| 7 | the foundation the future login-lockout slice reads from. |
| 8 | |
| 9 | A third kind, ``row_filter_shadow``, records a disagreement between the |
| 10 | permission row filter's full scan and its index (``DBBASIC_ROW_FILTER_INDEX |
| 11 | =shadow``, see object_server). It shares this file's row cap, and because |
| 12 | the login lockout counts failures out of the same capped window, its writer |
| 13 | (object_server._log_row_filter_shadow) throttles itself rather than rely on |
| 14 | the cap: a flood of shadow rows must not be able to push login failures out |
| 15 | of the window. |
| 16 | |
| 17 | Rows never contain passwords, tokens, or hashes. |
| 18 | """ |
| 19 | |
| 20 | from __future__ import annotations |
| 21 | |
| 22 | import json |
| 23 | import threading |
| 24 | from datetime import datetime, timezone |
| 25 | from pathlib import Path |
| 26 | from typing import Any |
| 27 | |
| 28 | from object_versions import DEFAULT_DATA_DIR |
| 29 | |
| 30 | OPS_DIR = "ops" |
| 31 | EVENTS_FILE = "events.jsonl" |
| 32 | DEFAULT_MAX_ROWS = 5000 |
| 33 | EXECUTION_ERROR = "execution_error" |
| 34 | AUTH = "auth" |
| 35 | ROW_FILTER_SHADOW = "row_filter_shadow" |
| 36 | # A change in the permission problems while enforcement or audit is on |
| 37 | # (object_server._permission_readiness_watch). Written on transitions only, |
| 38 | # at most once a minute per process, so it cannot crowd login failures out |
| 39 | # of the capped window. |
| 40 | PERMISSION_READINESS = "permission_readiness" |
| 41 | VALID_KINDS = frozenset({EXECUTION_ERROR, AUTH, ROW_FILTER_SHADOW, PERMISSION_READINESS}) |
| 42 | |
| 43 | _LOCK = threading.Lock() |
| 44 | |
| 45 | |
| 46 | def events_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path: |
| 47 | root = Path(base_dir) / OPS_DIR |
| 48 | path = root / EVENTS_FILE |
| 49 | resolved_root = root.resolve(strict=False) |
| 50 | resolved_path = path.resolve(strict=False) |
| 51 | |
| 52 | try: |
| 53 | resolved_path.relative_to(resolved_root) |
| 54 | except ValueError as exc: |
| 55 | raise ValueError("Ops events path escapes ops directory") from exc |
| 56 | |
| 57 | return path |
| 58 | |
| 59 | |
| 60 | def append_event( |
| 61 | kind: str, |
| 62 | details: dict[str, Any], |
| 63 | *, |
| 64 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 65 | max_rows: int = DEFAULT_MAX_ROWS, |
| 66 | now: datetime | None = None, |
| 67 | ) -> dict[str, Any]: |
| 68 | """Append one ops event and return the stored entry.""" |
| 69 | if kind not in VALID_KINDS: |
| 70 | raise ValueError(f"Ops event kind must be one of: {', '.join(sorted(VALID_KINDS))}") |
| 71 | |
| 72 | entry = { |
| 73 | "timestamp": _format_timestamp(now or _now()), |
| 74 | "kind": kind, |
| 75 | **{key: value for key, value in details.items() if value is not None}, |
| 76 | } |
| 77 | |
| 78 | path = events_path(base_dir) |
| 79 | with _LOCK: |
| 80 | path.parent.mkdir(parents=True, exist_ok=True) |
| 81 | with path.open("a", encoding="utf-8") as handle: |
| 82 | handle.write(json.dumps(entry, sort_keys=True, separators=(",", ":")) + "\n") |
| 83 | |
| 84 | lines = path.read_text(encoding="utf-8").splitlines() |
| 85 | if len(lines) > max_rows: |
| 86 | temp_path = path.with_name(f".{path.name}.tmp") |
| 87 | temp_path.write_text("\n".join(lines[-max_rows:]) + "\n", encoding="utf-8") |
| 88 | temp_path.replace(path) |
| 89 | |
| 90 | return entry |
| 91 | |
| 92 | |
| 93 | def read_events( |
| 94 | *, |
| 95 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 96 | limit: int = 100, |
| 97 | kind: str | None = None, |
| 98 | event: str | None = None, |
| 99 | identifier: str | None = None, |
| 100 | ) -> list[dict[str, Any]]: |
| 101 | """Return recent ops events, newest first, optionally filtered.""" |
| 102 | if limit < 1: |
| 103 | raise ValueError("Ops events limit must be at least 1") |
| 104 | if kind is not None and kind not in VALID_KINDS: |
| 105 | raise ValueError(f"Ops event kind must be one of: {', '.join(sorted(VALID_KINDS))}") |
| 106 | |
| 107 | path = events_path(base_dir) |
| 108 | if not path.exists(): |
| 109 | return [] |
| 110 | |
| 111 | with _LOCK: |
| 112 | lines = path.read_text(encoding="utf-8").splitlines() |
| 113 | |
| 114 | events: list[dict[str, Any]] = [] |
| 115 | for line in reversed(lines): |
| 116 | line = line.strip() |
| 117 | if not line: |
| 118 | continue |
| 119 | try: |
| 120 | entry = json.loads(line) |
| 121 | except json.JSONDecodeError: |
| 122 | continue |
| 123 | if kind is not None and entry.get("kind") != kind: |
| 124 | continue |
| 125 | if event is not None and entry.get("event") != event: |
| 126 | continue |
| 127 | if identifier is not None and entry.get("identifier") != identifier: |
| 128 | continue |
| 129 | events.append(entry) |
| 130 | if len(events) >= limit: |
| 131 | break |
| 132 | return events |
| 133 | |
| 134 | |
| 135 | def _format_timestamp(value: datetime) -> str: |
| 136 | return value.astimezone(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z") |
| 137 | |
| 138 | |
| 139 | def _now() -> datetime: |
| 140 | return datetime.now(timezone.utc) |