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

9 downloads

dbbasic-object-server/object_record_changes.py
Install on DigitalOcean 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.

Daniel Quellhorst Changelog for this batch. 65ef78d 3 hours, 7 minutes ago History
object_record_changes.py · 23.9 KB · 645 lines
1"""Append-only change logs for TSV-backed collection records.
2
3Record changes are the durable facts behind generated admin history screens and
4record event publication. Events and listener delivery can fail or be retried;
5this file records what actually changed.
6"""
7
8from __future__ import annotations
9
10import gzip
11import json
12import os
13import threading
14from datetime import datetime, timedelta, timezone
15from pathlib import Path
16from typing import Any, Mapping
17
18import object_collections
19import object_ids
20import object_records
21from object_versions import DEFAULT_DATA_DIR
22
23RECORD_CHANGES_DIR = "record_changes"
24CHANGES_FILE = "changes.jsonl"
25DEFAULT_CHANGE_LIMIT = 100
26MAX_CHANGE_LIMIT = 1000
27VALID_ACTIONS = {"create", "update", "delete"}
28
29_LOCKS: dict[str, threading.Lock] = {}
30_LOCKS_GUARD = threading.Lock()
31
32
33class InvalidRecordChangeError(ValueError):
34 """Raised when a record change entry is not safe to write or read."""
35
36
37# --- why a change was made -------------------------------------------------------
38#
39# A change entry said who and what, never why: Corner Cup (a Haiku
40# simulation of a counter cafe) found paid lines edited with no reason
41# anywhere, and a manager reading the history could not tell a correction
42# from a mistake. The reason travels like the correlation id does: a
43# context value for the request or action, set from the
44# X-DBBASIC-Change-Reason header on an HTTP write or by an action around
45# its own writes (a void, a refund), and written as the entry's `message`
46# in place of the generic "Updated record". Nothing about the entry's shape
47# changes; an entry made without a reason reads exactly as before.
48
49from contextlib import contextmanager
50from contextvars import ContextVar
51
52CHANGE_REASON_HEADER = "x-dbbasic-change-reason"
53MAX_REASON_LENGTH = 300
54_current_reason: ContextVar[str] = ContextVar("dbbasic_change_reason", default="")
55
56
57def current_change_reason() -> str:
58 return _current_reason.get()
59
60
61def set_change_reason(reason: str | None):
62 """Set the reason for the writes that follow; returns a reset token."""
63 text = " ".join(str(reason or "").split())[:MAX_REASON_LENGTH]
64 return _current_reason.set(text)
65
66
67def reset_change_reason(token) -> None:
68 _current_reason.reset(token)
69
70
71@contextmanager
72def change_reason(reason: str | None):
73 """``with change_reason("void: customer_error"):`` -- every record
74 change written inside carries the reason as its message."""
75 token = set_change_reason(reason)
76 try:
77 yield
78 finally:
79 reset_change_reason(token)
80
81
82def append_record_change(
83 *,
84 collection: str,
85 record_id: str,
86 action: str,
87 before: dict[str, Any] | None,
88 after: dict[str, Any] | None,
89 actor: str = "api",
90 message: str = "",
91 correlation_id: str | None = None,
92 base_dir: Path | str = DEFAULT_DATA_DIR,
93) -> dict[str, Any]:
94 """Append one record change and return the stored entry."""
95 path = record_changes_file(collection, base_dir=base_dir)
96 if not object_records.validate_record_id(record_id):
97 raise object_records.InvalidRecordIdError(f"Invalid record id: {record_id}")
98 if action not in VALID_ACTIONS:
99 raise InvalidRecordChangeError(f"Invalid record change action: {action}")
100
101 before_snapshot = _normalize_snapshot(before)
102 after_snapshot = _normalize_snapshot(after)
103 if before_snapshot is None and after_snapshot is None:
104 raise InvalidRecordChangeError("Record change must include before or after")
105
106 timestamp = _utc_timestamp()
107 entry = {
108 "change_id": _change_id(timestamp, collection, record_id, action),
109 "timestamp": timestamp,
110 "collection": collection,
111 "record_id": record_id,
112 "action": action,
113 "actor": _clean_text(actor, default="api"),
114 "message": _clean_text(message or current_change_reason(),
115 default=_default_message(action)),
116 "correlation_id": correlation_id or None,
117 "changed_fields": _changed_fields(before_snapshot, after_snapshot),
118 "before": before_snapshot,
119 "after": after_snapshot,
120 }
121
122 with _file_lock(path):
123 path.parent.mkdir(parents=True, exist_ok=True)
124 with path.open("a", encoding="utf-8") as handle:
125 handle.write(json.dumps(entry, sort_keys=True, separators=(",", ":")))
126 handle.write("\n")
127
128 return entry
129
130
131def list_record_changes(
132 collection: str,
133 *,
134 record_id: str | None = None,
135 base_dir: Path | str = DEFAULT_DATA_DIR,
136 limit: int = DEFAULT_CHANGE_LIMIT,
137 offset: int = 0,
138 tail_only: bool = False,
139) -> dict[str, Any]:
140 """Return newest-first record changes for one collection or record.
141
142 `tail_only` reads just enough of the end of the log to satisfy
143 limit+offset instead of parsing the whole file. It is opt-in because
144 it makes `total` a count of what was READ rather than of what exists,
145 and a caller that shows "1 of 4,312" must not be handed "1 of 100"
146 without asking. A feed does not care; an audit page does.
147 """
148 path = record_changes_file(collection, base_dir=base_dir)
149 if record_id is not None and not object_records.validate_record_id(record_id):
150 raise object_records.InvalidRecordIdError(f"Invalid record id: {record_id}")
151 _validate_page(limit=limit, offset=offset)
152
153 changes = _read_changes(
154 path, record_id=record_id,
155 tail=(limit + offset if tail_only else None),
156 )
157 total = len(changes)
158 window = changes[offset:offset + limit]
159 payload: dict[str, Any] = {
160 "collection": collection,
161 "changes": window,
162 "count": len(window),
163 "total": total,
164 "limit": limit,
165 "offset": offset,
166 "has_more": offset + len(window) < total,
167 }
168 if record_id is not None:
169 payload["record_id"] = record_id
170 return payload
171
172
173def record_changes_file(collection: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
174 """Return the validated JSONL change-log path for a collection."""
175 if not object_collections.validate_collection_name(collection):
176 raise object_collections.InvalidCollectionNameError(
177 f"Invalid collection name: {collection}"
178 )
179
180 root = Path(base_dir) / RECORD_CHANGES_DIR
181 path = root / collection / CHANGES_FILE
182 resolved_root = root.resolve(strict=False)
183 resolved_path = path.resolve(strict=False)
184
185 try:
186 resolved_path.relative_to(resolved_root)
187 except ValueError as exc:
188 raise object_collections.InvalidCollectionNameError(
189 f"Record change path escapes change directory: {collection}"
190 ) from exc
191
192 return path
193
194
195# Reading a change log tail-first, in blocks, instead of parsing the whole
196# file. A change log only ever grows, and the newest entries are the ones
197# anybody asks for, so paying for the whole history to answer "what
198# happened lately" is a cost that rises forever while the answer stays the
199# same size.
200#
201# This was not theoretical. One collection's log reached 944MB -- a rollup
202# rewriting 1818 derived rows every five minutes, each rewrite appending a
203# row per record -- and the activity feed, which reads EVERY collection's
204# log, sat parsing a gigabyte of JSON on a single core while the page said
205# "loading..." forever. The function's own docstring had predicted it:
206# "fine at current scale... future work if/when logs grow large."
207_TAIL_BLOCK = 256 * 1024
208
209
210def _tail_lines(path: Path, wanted: int) -> list[str]:
211 """The last `wanted` non-empty lines, read backwards in blocks.
212
213 Falls back to a whole-file read only for a file smaller than one
214 block, where seeking would be more code than it saves.
215 """
216 try:
217 size = path.stat().st_size
218 except OSError:
219 return []
220 if size <= _TAIL_BLOCK:
221 return path.read_text(encoding="utf-8").splitlines()
222
223 chunks: list[bytes] = []
224 newlines = 0
225 with path.open("rb") as handle:
226 position = size
227 while position > 0 and newlines <= wanted:
228 step = min(_TAIL_BLOCK, position)
229 position -= step
230 handle.seek(position)
231 block = handle.read(step)
232 chunks.append(block)
233 newlines += block.count(b"\n")
234 text = b"".join(reversed(chunks)).decode("utf-8", "replace")
235 # The first line of the first block read is probably a fragment of a
236 # longer line; dropping it is why we read one block past `wanted`.
237 lines = text.splitlines()
238 return lines[1:] if position > 0 else lines
239
240
241def _read_changes(
242 path: Path, *, record_id: str | None, tail: int | None = None
243) -> list[dict[str, Any]]:
244 if not path.exists():
245 return []
246
247 if tail is not None and record_id is None:
248 source = _tail_lines(path, tail)
249 else:
250 # A record-scoped query still scans: the entries for one record can
251 # be anywhere in the file, and answering "show me this invoice's
252 # history" with only the recent tail would quietly lose the half
253 # that matters.
254 source = None
255
256 changes: list[dict[str, Any]] = []
257 with _file_lock(path):
258 for line in (source if source is not None
259 else path.read_text(encoding="utf-8").splitlines()):
260 if not line.strip():
261 continue
262 try:
263 entry = json.loads(line)
264 except json.JSONDecodeError:
265 continue
266 if not isinstance(entry, dict):
267 continue
268 if record_id is not None and entry.get("record_id") != record_id:
269 continue
270 changes.append(entry)
271
272 changes.reverse()
273 return changes
274
275
276def latest_record_change(
277 collection: str,
278 record_id: str,
279 *,
280 base_dir: Path | str = DEFAULT_DATA_DIR,
281) -> dict[str, Any] | None:
282 """The newest change for one record, or None. Exactly what
283 `list_record_changes(collection, record_id=..., limit=1)` would put first,
284 without parsing the whole log to find it.
285
286 The change a write just appended is the last line of the file, so a
287 newest-first scan finds it in a few lines. `list_record_changes` cannot do
288 that for a record-scoped query (a record's older history can be anywhere,
289 so a tail-only read would silently drop it) -- but asking only for the
290 NEWEST entry has no such problem: the first match from the end IS it. A
291 record that is old, or absent, widens the window (4x each time) until the
292 whole file has been covered, so the answer is never approximate.
293 """
294 path = record_changes_file(collection, base_dir=base_dir)
295 if not object_records.validate_record_id(record_id):
296 raise object_records.InvalidRecordIdError(f"Invalid record id: {record_id}")
297 if not path.exists():
298 return None
299
300 wanted = 64
301 with _file_lock(path):
302 while True:
303 lines = _tail_lines(path, wanted)
304 for line in reversed(lines):
305 if not line.strip():
306 continue
307 try:
308 entry = json.loads(line)
309 except json.JSONDecodeError:
310 continue
311 if isinstance(entry, dict) and entry.get("record_id") == record_id:
312 return entry
313 if len(lines) < wanted: # fewer than asked for: that was the whole file
314 return None
315 wanted *= 4
316
317
318def _normalize_snapshot(record: dict[str, Any] | None) -> dict[str, Any] | None:
319 if record is None:
320 return None
321 if not isinstance(record, dict):
322 raise InvalidRecordChangeError("Record snapshot must be an object")
323 return {str(key): _json_safe_value(value) for key, value in record.items()}
324
325
326def _json_safe_value(value: Any) -> Any:
327 if value is None or isinstance(value, str | int | float | bool):
328 return value
329 return str(value)
330
331
332def _changed_fields(
333 before: dict[str, Any] | None,
334 after: dict[str, Any] | None,
335) -> list[str]:
336 before_values = before or {}
337 after_values = after or {}
338 names = set(before_values) | set(after_values)
339 return sorted(name for name in names if before_values.get(name) != after_values.get(name))
340
341
342def _validate_page(*, limit: int, offset: int) -> None:
343 if limit < 1:
344 raise ValueError("limit must be at least 1")
345 if limit > MAX_CHANGE_LIMIT:
346 raise ValueError(f"limit must be at most {MAX_CHANGE_LIMIT}")
347 if offset < 0:
348 raise ValueError("offset must be at least 0")
349
350
351def _clean_text(value: str, *, default: str) -> str:
352 text = str(value).strip()
353 return text or default
354
355
356def _default_message(action: str) -> str:
357 return {
358 "create": "Created record",
359 "update": "Updated record",
360 "delete": "Deleted record",
361 }[action]
362
363
364def _change_id(timestamp: str, collection: str, record_id: str, action: str) -> str:
365 return object_ids.new_uuid4()
366
367
368def _utc_timestamp() -> str:
369 return datetime.now(timezone.utc).isoformat()
370
371
372def _file_lock(path: Path) -> threading.Lock:
373 key = str(path.resolve(strict=False))
374 with _LOCKS_GUARD:
375 lock = _LOCKS.get(key)
376 if lock is None:
377 lock = threading.Lock()
378 _LOCKS[key] = lock
379 return lock
380
381
382# --- retention -----------------------------------------------------------------
383#
384# The third unbounded log this server has grown, after page_views and the
385# package restore points, and the pattern is now unmistakable: a log
386# nobody tells how big it may get is a log that fails on the worst day
387# rather than an ordinary one.
388#
389# A change log is audit evidence, so pruning it is a genuinely different
390# act from pruning analytics. Two consequences, both deliberate:
391#
392# * Retention is OFF unless an operator turns it on. Deleting audit
393# history by default is not a performance optimisation, it is a
394# decision about accountability, and it is not this module's to make
395# quietly.
396# * The bound is stated in BOTH dimensions, because age alone does not
397# bound anything: a retention window says how far back to keep and
398# nothing at all about how much can arrive inside it.
399#
400# The rollup churn that motivated this is fixed at the source instead
401# (object_rollups writes derived rows with record_changes=False) -- which
402# is the better fix, because a log entry never written costs nothing to
403# store, nothing to read past, and nothing to decide about later.
404
405RETENTION_DAYS_ENV = "DBBASIC_CHANGE_LOG_RETENTION_DAYS"
406MAX_ENTRIES_ENV = "DBBASIC_CHANGE_LOG_MAX_ENTRIES"
407ARCHIVE_ENV = "DBBASIC_CHANGE_LOG_ARCHIVE"
408KEEP_ARCHIVES_ENV = "DBBASIC_CHANGE_LOG_KEEP_ARCHIVES"
409ARCHIVE_DIR = "archive"
410
411# Archival and retention are different questions, and conflating them is
412# what made the first version of this uncomfortable.
413#
414# ROTATION bounds the file the server reads on every feed render.
415# ARCHIVAL decides whether the entries leaving that file still exist.
416# REMOVAL decides how long the archives themselves are kept.
417#
418# An audit trail wants all three, in that order. Rotating without
419# archiving is deletion wearing a gentler word, and it is why retention
420# had to be opt-in and slightly apologetic. Archiving first inverts that:
421# pruning becomes cheap to turn on, because nothing is actually lost --
422# the entries move out of the hot read path into a compressed segment
423# that is still on disk, still greppable, and still handable to an
424# auditor. JSONL compresses roughly ten to twenty times, so the 944MB log
425# that started all this becomes a segment measured in tens of megabytes.
426#
427# Removal still has to exist, because an archive nobody ever deletes is
428# just the original problem moved one directory down. Hence
429# KEEP_ARCHIVES: the same "keep the newest N" shape object_logs already
430# uses for rotated server logs, so an operator learns the convention once.
431# Its default keeps everything, because the default for evidence should
432# never be "throw it away".
433
434
435def retention_policy(env: Mapping[str, str] | None = None) -> dict[str, int]:
436 """{"days", "max_entries"} -- 0 for either means "no bound".
437
438 Absent configuration is no bound at all, not a default window: an
439 operator who has never thought about audit retention has not thereby
440 consented to losing audit history.
441 """
442 source = os.environ if env is None else env
443
444 def _int(name: str) -> int:
445 try:
446 value = int(str(source.get(name, "")).strip())
447 except (TypeError, ValueError):
448 return 0
449 return value if value > 0 else 0
450
451 archive = str(source.get(ARCHIVE_ENV, "")).strip().lower()
452 return {
453 "days": _int(RETENTION_DAYS_ENV),
454 "max_entries": _int(MAX_ENTRIES_ENV),
455 # Archiving is the DEFAULT when a policy is set at all. Somebody
456 # asking for a smaller hot file has not asked to lose the history.
457 "archive": archive not in ("0", "false", "no", "off"),
458 "keep_archives": _int(KEEP_ARCHIVES_ENV),
459 }
460
461
462def archive_dir(collection: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> Path:
463 """Where a collection's rotated change-log segments live."""
464 return record_changes_file(collection, base_dir=base_dir).parent / ARCHIVE_DIR
465
466
467def list_archives(collection: str, base_dir: Path | str = DEFAULT_DATA_DIR) -> list[Path]:
468 """Archived segments for one collection, oldest first."""
469 directory = archive_dir(collection, base_dir=base_dir)
470 if not directory.is_dir():
471 return []
472 return sorted(p for p in directory.glob("changes-*.jsonl.gz") if p.is_file())
473
474
475def _archive_entries(collection: str, lines: list[str], *, base_dir: Path | str) -> Path:
476 """Write expired entries to a new compressed segment and return it.
477
478 A new segment per rotation rather than appending to one growing
479 archive: a gzip member you keep appending to is a file you can only
480 ever read whole, and the point of moving these out was to stop paying
481 for the whole history. Segments are timestamped and immutable, so an
482 auditor can take the three that cover a quarter and leave the rest.
483 """
484 directory = archive_dir(collection, base_dir=base_dir)
485 directory.mkdir(parents=True, exist_ok=True)
486 stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S-%f")
487 path = directory / f"changes-{stamp}.jsonl.gz"
488 temp_path = path.with_name(f".{path.name}.tmp")
489 with gzip.open(temp_path, "wt", encoding="utf-8", compresslevel=6) as handle:
490 for line in lines:
491 handle.write(line)
492 handle.write("\n")
493 temp_path.replace(path)
494 return path
495
496
497def _remove_stale_archives(
498 collection: str, *, keep: int, base_dir: Path | str
499) -> list[str]:
500 """Delete all but the newest `keep` segments; 0 keeps everything.
501
502 This is the only place in this module that destroys anything, and it
503 is deliberately the last step of the chain rather than the first: by
504 the time a segment is dropped it has already been rotated out of the
505 hot file and compressed, so an operator who never sets this keeps
506 every entry the server ever wrote.
507 """
508 if keep <= 0:
509 return []
510 segments = list_archives(collection, base_dir=base_dir)
511 stale = segments[:-keep] if len(segments) > keep else []
512 for path in stale:
513 path.unlink(missing_ok=True)
514 return [path.name for path in stale]
515
516
517def prune_record_changes(
518 collection: str,
519 *,
520 keep_newer_than: str | None = None,
521 keep_last: int | None = None,
522 archive: bool = True,
523 keep_archives: int = 0,
524 base_dir: Path | str = DEFAULT_DATA_DIR,
525) -> dict[str, Any]:
526 """Trim one collection's change log to a time window and/or a count.
527
528 Rewrites the file in one pass under the same lock every other reader
529 and writer takes, keeping entries newer than ``keep_newer_than``
530 (ISO-8601) and then the newest ``keep_last`` of whatever survives. An
531 entry with a missing or unparseable timestamp is KEPT -- never delete
532 evidence we cannot date.
533
534 Returns {"entries_before", "entries_after", "removed", "pruned"}.
535 Both bounds absent is an honest no-op rather than an error, so a
536 caller can pass an unconfigured policy straight through.
537 """
538 path = record_changes_file(collection, base_dir=base_dir)
539 if not path.exists():
540 return {"entries_before": 0, "entries_after": 0, "removed": 0, "pruned": False}
541 if not keep_newer_than and not keep_last:
542 return {"entries_before": 0, "entries_after": 0, "removed": 0, "pruned": False}
543
544 with _file_lock(path):
545 lines = path.read_text(encoding="utf-8").splitlines()
546 kept: list[str] = []
547 for line in lines:
548 if not line.strip():
549 continue
550 try:
551 entry = json.loads(line)
552 except json.JSONDecodeError:
553 kept.append(line) # unreadable is not the same as expired
554 continue
555 stamp = str(entry.get("timestamp") or "")
556 if keep_newer_than and stamp and stamp < str(keep_newer_than):
557 continue
558 kept.append(line)
559
560 if keep_last and len(kept) > keep_last:
561 # The log is append-ordered, so the tail is the newest.
562 kept = kept[len(kept) - keep_last:]
563
564 before = len([line for line in lines if line.strip()])
565 removed = before - len(kept)
566 if removed <= 0:
567 return {"entries_before": before, "entries_after": before,
568 "removed": 0, "pruned": False, "archived": None}
569
570 archived_to = None
571 if archive:
572 # Difference by COUNT, not by identity or membership: two
573 # identical entries are two facts, and a set would archive one
574 # of them while the file lost both.
575 kept_counts: dict[str, int] = {}
576 for line in kept:
577 kept_counts[line] = kept_counts.get(line, 0) + 1
578 expired = []
579 for line in lines:
580 if not line.strip():
581 continue
582 if kept_counts.get(line):
583 kept_counts[line] -= 1
584 continue
585 expired.append(line)
586 if expired:
587 archived_to = _archive_entries(
588 collection, expired, base_dir=base_dir).name
589
590 temp_path = path.with_name(f".{path.name}.tmp")
591 temp_path.write_text(
592 "".join(f"{line}\n" for line in kept), encoding="utf-8")
593 temp_path.replace(path)
594
595 dropped = _remove_stale_archives(
596 collection, keep=keep_archives, base_dir=base_dir)
597 return {"entries_before": before, "entries_after": len(kept),
598 "removed": removed, "pruned": True,
599 "archived": archived_to, "archives_removed": dropped}
600
601
602def prune_all_record_changes(
603 *,
604 base_dir: Path | str = DEFAULT_DATA_DIR,
605 days: int = 0,
606 max_entries: int = 0,
607 archive: bool = True,
608 keep_archives: int = 0,
609) -> dict[str, Any]:
610 """Apply one retention policy across every collection's change log.
611
612 One bad or unreadable log never stops the sweep: this runs unattended
613 on a timer, and a single corrupt file must not mean every other log
614 grows forever.
615 """
616 if not days and not max_entries:
617 return {"collections": 0, "removed": 0, "pruned": [], "skipped": "no policy set"}
618
619 cutoff = None
620 if days:
621 cutoff = (datetime.now(timezone.utc) - timedelta(days=days)
622 ).isoformat().replace("+00:00", "Z")
623
624 root = Path(base_dir) / RECORD_CHANGES_DIR
625 if not root.is_dir():
626 return {"collections": 0, "removed": 0, "pruned": []}
627
628 removed = 0
629 pruned: list[dict[str, Any]] = []
630 for entry in sorted(root.iterdir()):
631 if not entry.is_dir():
632 continue
633 try:
634 result = prune_record_changes(
635 entry.name, keep_newer_than=cutoff,
636 keep_last=(max_entries or None),
637 archive=archive, keep_archives=keep_archives,
638 base_dir=base_dir,
639 )
640 except Exception: # noqa: BLE001 -- one bad log must not stop the sweep
641 continue
642 if result.get("pruned"):
643 removed += result["removed"]
644 pruned.append({"collection": entry.name, **result})
645 return {"collections": len(pruned), "removed": removed, "pruned": pruned}