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_activity.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_activity.py · 8.2 KB · 185 lines
1"""Activity feed -- a fold over the record-change ledger, not a new event system.
2
3Every create/update/delete already flows through
4``object_record_changes.append_record_change`` (called from
5object_records.py's create/update/delete paths), which durably appends
6actor, action, collection, record_id, and before/after snapshots to one
7JSONL log per collection: ``data/record_changes/{collection}/changes.jsonl``.
8
9``recent_activity`` reads those logs across every collection that has one,
10merges them newest-first, and derives a human title from each change's
11snapshot. "actor ACTION collection title" is exactly the shape of a classic
12content activity feed, and it required no new storage and no new write path
13-- universal attribution already recorded everything a feed needs.
14"""
15
16from __future__ import annotations
17
18from datetime import datetime, timezone
19from pathlib import Path
20from typing import Any, Callable, Iterable, Mapping
21
22import object_collections
23import object_record_changes
24from object_versions import DEFAULT_DATA_DIR
25
26# Internal/system collections that would drown out real user activity in a
27# feed meant to answer "what did people do": shell scrollback and AI usage/
28# billing counters today, and (as they show up) any rate-limit- or
29# ops-bookkeeping-style collection whose writes aren't something a person
30# did. Extend this set rather than filtering ad hoc per call site.
31EXCLUDED_COLLECTIONS = frozenset({
32 "shell_commands",
33 "ai_usage",
34 # Derived collections. A rollup rewriting its own output is not
35 # something a person did, and a feed of "what happened" that is 99%
36 # machine churn is a feed nobody can read. These are also, by a wide
37 # margin, the largest change logs on a busy server -- one of them
38 # reached 944MB while the collection it describes held 1818 rows --
39 # because a rewrite appends an entry per row, every pass, forever.
40 "analytics_top_paths",
41 "analytics_top_ips",
42 "analytics_status",
43 "analytics_daily",
44 "page_views",
45 "attention_counts",
46})
47
48# First present of these fields on the change's snapshot becomes the feed
49# row's title; record_id is the final fallback so every entry always has
50# something to show.
51_TITLE_FIELDS = ("title", "name", "number", "subject", "body", "content", "comment", "message")
52# Text-shaped fallback fields (body/content/...) can be long; a feed row wants
53# a glance, not a paragraph, so they're truncated. Named/numbered fields are
54# already short and shown whole.
55_TITLE_TEXT_FIELDS = frozenset({"body", "content", "comment", "message"})
56_TITLE_MAX = 80
57
58
59def recent_activity(
60 *,
61 base_dir: Path | str = DEFAULT_DATA_DIR,
62 actor: str | None = None,
63 limit: int = 50,
64 roots: Iterable[Path] | None = None,
65 readable: Callable[[str, Mapping[str, Any]], Mapping[str, Any] | None] | None = None,
66) -> list[dict[str, Any]]:
67 """Return up to `limit` record-change entries across collections, newest first.
68
69 Each entry is shaped ``{actor, action, collection, record_id, title,
70 timestamp}`` -- never the full before/after snapshot. A feed is a
71 signal, not a data dump.
72
73 Scoping (v1): when `actor` is given, only entries whose actor matches
74 are returned -- the classic "your activity" feed (e.g. "dan CREATED
75 NOTE ... 2m ago" for dan's own changes across every collection). Every
76 entry here is guaranteed visible to that actor because they made the
77 change, so this sidesteps per-entry permission checks entirely.
78
79 Deferred: a broader "activity on anything I can see" feed -- changes by
80 *other* actors, filtered per record against the viewer's read access --
81 needs the permission engine's row filters threaded through here (see
82 plan/vocabulary/23-activity-spec.md's per-collection/per-record feeds).
83 That is real work (a read-policy check per candidate entry) and is not
84 attempted by this function.
85
86 `readable`, when given, is asked for each entry's snapshot and answers
87 the snapshot cut down to what the viewer may read (object_access.Access.
88 readable), or None for a row they may not read. The title is derived from
89 that, never from the whole snapshot, so a field the viewer cannot read
90 cannot become their feed's title; an unreadable row is titled by its id.
91 Without it the snapshot is used whole (a caller with no permission
92 policy in force).
93
94 `roots` mirrors object_collections.list_collections's signature for
95 symmetry; it is unused here because record-change logs live entirely
96 under `base_dir` and don't depend on which object source roots are
97 mounted.
98 """
99 if limit < 1:
100 raise ValueError("limit must be at least 1")
101
102 entries: list[dict[str, Any]] = []
103 for collection in _collections_with_changes(base_dir=base_dir):
104 if collection in EXCLUDED_COLLECTIONS:
105 continue
106 # Reads each collection's whole change log (list_record_changes
107 # loads the full JSONL regardless of `limit`) -- fine at current
108 # scale, where these logs are small. A real tail-read (seek to the
109 # last N lines instead of parsing the whole file) is future work
110 # if/when logs grow large; requesting the module's own max here
111 # avoids clipping an actor's older entries out of an otherwise
112 # chatty collection before the actor filter below gets to see them.
113 payload = object_record_changes.list_record_changes(
114 collection,
115 base_dir=base_dir,
116 limit=object_record_changes.MAX_CHANGE_LIMIT,
117 # Tail-read: a feed wants the newest entries, and this loop
118 # visits EVERY collection's log. Parsing each in full made the
119 # page cost the whole history of the server -- a gigabyte of
120 # JSON on one core, and a page that never finished loading.
121 tail_only=True,
122 )
123 for change in payload["changes"]:
124 if actor is not None and change.get("actor") != actor:
125 continue
126 entries.append(_feed_entry(change, readable))
127
128 entries.sort(key=lambda entry: _sort_key(entry["timestamp"]), reverse=True)
129 return entries[:limit]
130
131
132def _feed_entry(change: dict[str, Any], readable: Callable | None = None) -> dict[str, Any]:
133 if readable is not None:
134 snapshot = change.get("after") or change.get("before") or {}
135 try:
136 visible = readable(str(change.get("collection") or ""), snapshot)
137 except Exception: # noqa: BLE001 - cannot judge: show no field
138 visible = None
139 change = {**change, "after": visible or {}, "before": {}}
140 return {
141 "actor": change.get("actor"),
142 "action": change.get("action"),
143 "collection": change.get("collection"),
144 "record_id": change.get("record_id"),
145 "title": _derive_title(change),
146 "timestamp": change.get("timestamp"),
147 }
148
149
150def _derive_title(change: dict[str, Any]) -> str:
151 # Deletes have no `after`; fall back to the last-known `before`.
152 snapshot = change.get("after") or change.get("before") or {}
153 for field in _TITLE_FIELDS:
154 value = snapshot.get(field)
155 if value:
156 text = str(value)
157 if field in _TITLE_TEXT_FIELDS and len(text) > _TITLE_MAX:
158 text = text[:_TITLE_MAX].rstrip() + "…"
159 return text
160 return str(change.get("record_id") or "")
161
162
163def _sort_key(timestamp: Any) -> datetime:
164 try:
165 # fromisoformat accepts a trailing "Z" only from Python 3.11; on 3.10
166 # a Z stamp would raise and sort oldest. Spell it the way 3.10 reads.
167 return datetime.fromisoformat(str(timestamp).replace("Z", "+00:00"))
168 except ValueError:
169 # Malformed timestamp: sort it oldest rather than crash the whole
170 # feed over one bad entry.
171 return datetime.min.replace(tzinfo=timezone.utc)
172
173
174def _collections_with_changes(*, base_dir: Path | str) -> list[str]:
175 """Return every collection name with a record_changes log on disk."""
176 root = Path(base_dir) / object_record_changes.RECORD_CHANGES_DIR
177 if not root.exists() or not root.is_dir():
178 return []
179
180 names = []
181 for path in sorted(root.glob(f"*/{object_record_changes.CHANGES_FILE}")):
182 name = path.parent.name
183 if object_collections.validate_collection_name(name):
184 names.append(name)
185 return names