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_notify.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_notify.py · 12.1 KB · 288 lines
1"""12 notify -- turn record-change events into notifications, declaratively.
2
3A `notify_rules` row (app-notify) declares an event pattern, an optional flat
4match, a recipient rule, and channels; this module turns ONE record-change
5entry into the notification writes it implies. The engine is driven by the
6daemon (object_daemon.process_notifications) polling the record-change log
7(object_record_changes) rather than the synchronous HANDLES dispatch the spec
8sketches -- HANDLES is gated behind DBBASIC_ENABLE_EVENT_HANDLERS (off in
9prod) and we deliberately don't rewrite installed objects to track dynamic
10event sets (see plan/vocabulary/61 removal + memory no-runtime-object-rewriting).
11Polling the change log instead makes notify work with no event-handler
12dependency, at-least-once (the same delivery bar 01/12 accept), reading the
13same before/after/changed_fields/actor the change entry already carries.
14
15Two channels ship: `in_app` (append a `notifications` row, which the nav bell +
16realtime already render) and `email` (enqueue into the GENERIC 01 outbox --
17object_email -- so notify depends only on the open adapter, never a mail
18package). This module stays side-effect-free: it names WHO and WHAT per channel
19(`notifications_for_change`, `email_intents_for_change`); the daemon performs
20the writes and the address lookup + enqueue. Digest batching still waits.
21"""
22
23from __future__ import annotations
24
25import json
26from typing import Any, Iterable, Mapping
27
28import object_access
29import object_feature_flags
30import object_identity
31
32NOTIFY_RULES_COLLECTION = "notify_rules"
33NOTIFICATIONS_COLLECTION = "notifications"
34FEATURE_FLAGS_COLLECTION = "feature_flags"
35NOTIFY_ENABLED_FLAG = "notify_enabled"
36DEFAULT_ACTOR = "daemon:notify"
37
38_ACTIONS = frozenset({"created", "updated", "deleted"})
39# A record-change entry stores the action in present tense (create/update/
40# delete, object_record_changes); the event grammar (and object_handlers'
41# event_name) uses the -ed event suffix. Map one to the other before matching.
42_CHANGE_TO_EVENT = {"create": "created", "update": "updated", "delete": "deleted"}
43
44
45def _event_action(change: Mapping[str, Any]) -> str:
46 raw = str(change.get("action") or "")
47 return _CHANGE_TO_EVENT.get(raw, raw)
48
49
50def _json_field(value: Any, default: Any) -> Any:
51 if value in (None, ""):
52 return default
53 if isinstance(value, (dict, list)):
54 return value
55 try:
56 return json.loads(value)
57 except (TypeError, ValueError):
58 return default
59
60
61def _truthy(value: Any, *, default: bool) -> bool:
62 if value in (None, ""):
63 return default
64 return str(value).strip().lower() not in {"off", "false", "0", "no"}
65
66
67def notify_pass_enabled(*, base_dir: Any) -> bool:
68 """Block-wide kill switch, `<block>_enabled` convention -- a feature_flags
69 row named `notify_enabled`. Default ON (brownout lever, not an adoption
70 gate; with zero rules it does nothing anyway). Mirrors
71 object_rollups.rollup_pass_enabled exactly."""
72 return object_feature_flags.kill_switch_on(NOTIFY_ENABLED_FLAG, base_dir=base_dir)
73
74
75def event_pattern_matches(pattern: str, collection: str, action: str) -> bool:
76 """`<collection>.record.<action>` with `*` allowed in the collection or
77 action segment (the spec's grammar). Anything malformed never matches."""
78 parts = str(pattern or "").split(".")
79 if len(parts) != 3 or parts[1] != "record":
80 return False
81 coll_pat, _, act_pat = parts
82 if action not in _ACTIONS:
83 return False
84 coll_ok = coll_pat == "*" or coll_pat == collection
85 act_ok = act_pat == "*" or act_pat == action
86 return coll_ok and act_ok
87
88
89def watched_collections(rules: Iterable[Mapping[str, str]], known: Iterable[str]) -> set[str]:
90 """The set of collections any enabled rule's event_pattern could fire on --
91 a specific collection, or (for a `*` collection pattern) every known one.
92 Lets the daemon poll only the change logs that matter."""
93 known = set(known)
94 watched: set[str] = set()
95 for rule in rules:
96 parts = str(rule.get("event_pattern") or "").split(".")
97 if len(parts) != 3 or parts[1] != "record":
98 continue
99 watched |= known if parts[0] == "*" else {parts[0]}
100 return watched
101
102
103def _record_for(change: Mapping[str, Any]) -> dict[str, Any]:
104 """The record state a `match`/template/recipient reads: `after` for
105 created/updated, `before` for deleted (the row is already gone)."""
106 if _event_action(change) == "deleted":
107 return dict(change.get("before") or {})
108 return dict(change.get("after") or {})
109
110
111def _match_ok(rule: Mapping[str, Any], change: Mapping[str, Any], record: Mapping[str, Any]) -> bool:
112 """Flat {field: value} equality, ANDed. On an UPDATE the condition is
113 restricted to fields the write actually CHANGED (change.changed_fields) --
114 so "notify when status becomes assigned" fires once on the transition, not
115 on every later edit that still happens to satisfy status == assigned."""
116 conditions = _json_field(rule.get("match"), {})
117 if not isinstance(conditions, dict) or not conditions:
118 return True
119 changed = set(change.get("changed_fields") or [])
120 is_update = _event_action(change) == "updated"
121 for field, want in conditions.items():
122 if is_update and field not in changed:
123 return False
124 if str(record.get(field, "")) != str(want):
125 return False
126 return True
127
128
129def resolve_recipients(rule: Mapping[str, Any], record: Mapping[str, Any], *, base_dir: Any) -> list[str]:
130 """The four recipient modes: owner / field / users / role. A resolved
131 value that isn't a usable user id (empty/unknown) is silently skipped."""
132 spec = _json_field(rule.get("recipients"), {})
133 if not isinstance(spec, dict):
134 return []
135 mode = spec.get("mode")
136 out: list[str] = []
137 if mode == "owner":
138 out = [record.get(spec.get("owner_field") or "owner_id") or ""]
139 elif mode == "field":
140 out = [record.get(spec.get("field") or "") or ""]
141 elif mode == "users":
142 ids = spec.get("user_ids")
143 out = [str(u) for u in ids] if isinstance(ids, list) else []
144 elif mode == "role":
145 want = spec.get("role")
146 try:
147 users = object_identity.list_users(base_dir=base_dir)
148 except (OSError, ValueError, AttributeError):
149 users = []
150 out = [u.get("user_id") for u in users if want and want in (u.get("roles") or [])]
151 return [str(u) for u in out if u]
152
153
154def render_template(template: str, record: Mapping[str, Any]) -> str:
155 """`{field}` substitution from the record -- no expressions, no logic.
156 An unknown field renders empty (a missing due_date shouldn't blow up)."""
157 class _Blank(dict):
158 def __missing__(self, key):
159 return ""
160 try:
161 return str(template or "").format_map(_Blank(record))
162 except (ValueError, IndexError):
163 return str(template or "")
164
165
166def _view_for_recipient(
167 user_id: str, rule: Mapping[str, Any], change: Mapping[str, Any],
168 record: Mapping[str, Any], *, base_dir: Any,
169) -> dict[str, Any] | None:
170 """The row as `user_id` may read it, or None when this change must not
171 reach them. Decided now, at delivery time, by the same read decision and
172 field redaction the record API applies to that user, WHEN permissions are
173 enforced (object_access.enforcement_enabled; otherwise the row is
174 returned whole and nothing is withheld, as before):
175
176 - the row itself is refused, or the policy / user cannot be read: nothing;
177 - the rule's `match` names a field they cannot read: firing would tell
178 them that field's value, so nothing;
179 - an UPDATE none of whose changed fields they can read: nothing (it would
180 only say "something you cannot see changed").
181
182 The returned view is all a template may render from, so a field they
183 cannot read renders empty and is never named."""
184 try:
185 enforcing = object_access.enforcement_enabled()
186 except Exception: # noqa: BLE001 - mode unknown: deliver nothing
187 return None
188 if not enforcing:
189 # Same as the record API with enforcement off or audit-only: it serves
190 # this user every row and field, so the whole row is theirs to see.
191 return dict(record)
192 access = object_access.access_for_user(user_id, base_dir=base_dir)
193 if access is None:
194 return None
195 collection = str(change.get("collection") or "")
196 view = access.readable(collection, record)
197 if view is None:
198 return None
199 conditions = _json_field(rule.get("match"), {})
200 if isinstance(conditions, dict) and any(field not in view for field in conditions):
201 return None
202 if _event_action(change) == "updated":
203 changed = change.get("changed_fields")
204 if not isinstance(changed, list) or not any(field in view for field in changed):
205 return None
206 return view
207
208
209def _match_and_recipients(
210 rule: Mapping[str, Any], change: Mapping[str, Any], *, base_dir: Any,
211) -> list[tuple[str, dict[str, Any]]]:
212 """Shared gating for every channel: apply the enabled flag, event-pattern,
213 transition-aware match, recipient resolution, suppress_self, and de-dup.
214 Returns [(user_id, view)], where view is the row cut down to what that
215 user may read (see _view_for_recipient), or [] if this rule doesn't fire on
216 this change. Keeps in_app and email delivery from drifting apart."""
217 if not _truthy(rule.get("enabled"), default=True):
218 return []
219 if not event_pattern_matches(rule.get("event_pattern"), change.get("collection"), _event_action(change)):
220 return []
221 record = _record_for(change)
222 if not _match_ok(rule, change, record):
223 return []
224 recipients = resolve_recipients(rule, record, base_dir=base_dir)
225 if _truthy(rule.get("suppress_self"), default=True):
226 actor = change.get("actor")
227 recipients = [r for r in recipients if r != actor]
228 # de-dup while preserving order (a role rule could name the same user twice)
229 seen: set[str] = set()
230 recipients = [r for r in recipients if not (r in seen or seen.add(r))]
231 out = []
232 for uid in recipients:
233 view = _view_for_recipient(uid, rule, change, record, base_dir=base_dir)
234 if view is not None:
235 out.append((uid, view))
236 return out
237
238
239def _channel(rule: Mapping[str, Any], name: str) -> dict[str, Any] | None:
240 for channel in _json_field(rule.get("channels"), []):
241 if isinstance(channel, dict) and channel.get("channel") == name:
242 return channel
243 return None
244
245
246def notifications_for_change(
247 rule: Mapping[str, Any], change: Mapping[str, Any], *, base_dir: Any,
248) -> list[dict[str, str]]:
249 """Every in_app notification record ONE rule implies for ONE change. Empty
250 when the rule doesn't match, no recipient resolves, or the rule declares no
251 in_app channel."""
252 recipients = _match_and_recipients(rule, change, base_dir=base_dir)
253 if not recipients:
254 return []
255 in_app = _channel(rule, "in_app")
256 if not in_app:
257 return []
258
259 target = f"{change.get('collection')}/{change.get('record_id')}"
260 return [
261 {"user_id": uid, "kind": "notify", "target": target, "is_read": "false",
262 "body": render_template(in_app.get("body_template") or "", view)}
263 for uid, view in recipients
264 ]
265
266
267def email_intents_for_change(
268 rule: Mapping[str, Any], change: Mapping[str, Any], *, base_dir: Any,
269) -> list[dict[str, str]]:
270 """The email messages ONE rule implies for ONE change: `{user_id, subject,
271 body}` per recipient. Empty when the rule doesn't fire or declares no email
272 channel. The engine stays side-effect-free of the actual send -- it names
273 WHO and WHAT; the daemon maps user_id -> address and enqueues via
274 object_email (01 outbox)."""
275 recipients = _match_and_recipients(rule, change, base_dir=base_dir)
276 if not recipients:
277 return []
278 email = _channel(rule, "email")
279 if not email:
280 return []
281
282 target = f"{change.get('collection')}/{change.get('record_id')}"
283 return [
284 {"user_id": uid, "target": target,
285 "subject": render_template(email.get("subject_template") or "", view),
286 "body": render_template(email.get("body_template") or "", view)}
287 for uid, view in recipients
288 ]