Runs live, versioned Python application objects on one VM, with a suite of apps: projects, notes, tasks, files and more.

0 downloads

dbbasic-object-server/object_ops_log.py
Download zip
Clone
Clone with git
git clone https://gitstable.com/git/askrobots/dbbasic-object-server.git
HTTPS
https://gitstable.com/git/askrobots/dbbasic-object-server.git
SSH
ssh://git@gitstable.com:2222/askrobots/dbbasic-object-server.git

Cloning needs no sign-in. Pushing over HTTPS asks for your username and an access token. SSH needs your key under SSH keys.

danq9 signup: the person chooses the password and name on the confirm page 83c7aa6 2 weeks, 5 days ago History
object_ops_log.py · 3.8 KB · 126 lines
1"""Operational event log: execution errors and auth activity.
2
3One append-only JSONL feed for the events operators actually page on —
4object execution failures (with correlation ids for tracing back to source
5versions and logs) and authentication activity (login success/failure,
6logout, session mints). Auth failures are recorded per identifier, which is
7the foundation the future login-lockout slice reads from.
8
9Rows never contain passwords, tokens, or hashes.
10"""
11
12from __future__ import annotations
13
14import json
15import threading
16from datetime import datetime, timezone
17from pathlib import Path
18from typing import Any
19
20from object_versions import DEFAULT_DATA_DIR
21
22OPS_DIR = "ops"
23EVENTS_FILE = "events.jsonl"
24DEFAULT_MAX_ROWS = 5000
25EXECUTION_ERROR = "execution_error"
26AUTH = "auth"
27VALID_KINDS = frozenset({EXECUTION_ERROR, AUTH})
28
29_LOCK = threading.Lock()
30
31
32def events_path(base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
33 root = Path(base_dir) / OPS_DIR
34 path = root / EVENTS_FILE
35 resolved_root = root.resolve(strict=False)
36 resolved_path = path.resolve(strict=False)
37
38 try:
39 resolved_path.relative_to(resolved_root)
40 except ValueError as exc:
41 raise ValueError("Ops events path escapes ops directory") from exc
42
43 return path
44
45
46def append_event(
47 kind: str,
48 details: dict[str, Any],
49 *,
50 base_dir: Path | str = DEFAULT_DATA_DIR,
51 max_rows: int = DEFAULT_MAX_ROWS,
52 now: datetime | None = None,
53) -> dict[str, Any]:
54 """Append one ops event and return the stored entry."""
55 if kind not in VALID_KINDS:
56 raise ValueError(f"Ops event kind must be one of: {', '.join(sorted(VALID_KINDS))}")
57
58 entry = {
59 "timestamp": _format_timestamp(now or _now()),
60 "kind": kind,
61 **{key: value for key, value in details.items() if value is not None},
62 }
63
64 path = events_path(base_dir)
65 with _LOCK:
66 path.parent.mkdir(parents=True, exist_ok=True)
67 with path.open("a", encoding="utf-8") as handle:
68 handle.write(json.dumps(entry, sort_keys=True, separators=(",", ":")) + "\n")
69
70 lines = path.read_text(encoding="utf-8").splitlines()
71 if len(lines) > max_rows:
72 temp_path = path.with_name(f".{path.name}.tmp")
73 temp_path.write_text("\n".join(lines[-max_rows:]) + "\n", encoding="utf-8")
74 temp_path.replace(path)
75
76 return entry
77
78
79def read_events(
80 *,
81 base_dir: Path | str = DEFAULT_DATA_DIR,
82 limit: int = 100,
83 kind: str | None = None,
84 event: str | None = None,
85 identifier: str | None = None,
86) -> list[dict[str, Any]]:
87 """Return recent ops events, newest first, optionally filtered."""
88 if limit < 1:
89 raise ValueError("Ops events limit must be at least 1")
90 if kind is not None and kind not in VALID_KINDS:
91 raise ValueError(f"Ops event kind must be one of: {', '.join(sorted(VALID_KINDS))}")
92
93 path = events_path(base_dir)
94 if not path.exists():
95 return []
96
97 with _LOCK:
98 lines = path.read_text(encoding="utf-8").splitlines()
99
100 events: list[dict[str, Any]] = []
101 for line in reversed(lines):
102 line = line.strip()
103 if not line:
104 continue
105 try:
106 entry = json.loads(line)
107 except json.JSONDecodeError:
108 continue
109 if kind is not None and entry.get("kind") != kind:
110 continue
111 if event is not None and entry.get("event") != event:
112 continue
113 if identifier is not None and entry.get("identifier") != identifier:
114 continue
115 events.append(entry)
116 if len(events) >= limit:
117 break
118 return events
119
120
121def _format_timestamp(value: datetime) -> str:
122 return value.astimezone(timezone.utc).isoformat(timespec="seconds").replace("+00:00", "Z")
123
124
125def _now() -> datetime:
126 return datetime.now(timezone.utc)