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_notify.py · 12.1 KB · 288 lines
| 1 | """12 notify -- turn record-change events into notifications, declaratively. |
| 2 | |
| 3 | A `notify_rules` row (app-notify) declares an event pattern, an optional flat |
| 4 | match, a recipient rule, and channels; this module turns ONE record-change |
| 5 | entry into the notification writes it implies. The engine is driven by the |
| 6 | daemon (object_daemon.process_notifications) polling the record-change log |
| 7 | (object_record_changes) rather than the synchronous HANDLES dispatch the spec |
| 8 | sketches -- HANDLES is gated behind DBBASIC_ENABLE_EVENT_HANDLERS (off in |
| 9 | prod) and we deliberately don't rewrite installed objects to track dynamic |
| 10 | event sets (see plan/vocabulary/61 removal + memory no-runtime-object-rewriting). |
| 11 | Polling the change log instead makes notify work with no event-handler |
| 12 | dependency, at-least-once (the same delivery bar 01/12 accept), reading the |
| 13 | same before/after/changed_fields/actor the change entry already carries. |
| 14 | |
| 15 | Two channels ship: `in_app` (append a `notifications` row, which the nav bell + |
| 16 | realtime already render) and `email` (enqueue into the GENERIC 01 outbox -- |
| 17 | object_email -- so notify depends only on the open adapter, never a mail |
| 18 | package). This module stays side-effect-free: it names WHO and WHAT per channel |
| 19 | (`notifications_for_change`, `email_intents_for_change`); the daemon performs |
| 20 | the writes and the address lookup + enqueue. Digest batching still waits. |
| 21 | """ |
| 22 | |
| 23 | from __future__ import annotations |
| 24 | |
| 25 | import json |
| 26 | from typing import Any, Iterable, Mapping |
| 27 | |
| 28 | import object_access |
| 29 | import object_feature_flags |
| 30 | import object_identity |
| 31 | |
| 32 | NOTIFY_RULES_COLLECTION = "notify_rules" |
| 33 | NOTIFICATIONS_COLLECTION = "notifications" |
| 34 | FEATURE_FLAGS_COLLECTION = "feature_flags" |
| 35 | NOTIFY_ENABLED_FLAG = "notify_enabled" |
| 36 | DEFAULT_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 | |
| 45 | def _event_action(change: Mapping[str, Any]) -> str: |
| 46 | raw = str(change.get("action") or "") |
| 47 | return _CHANGE_TO_EVENT.get(raw, raw) |
| 48 | |
| 49 | |
| 50 | def _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 | |
| 61 | def _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 | |
| 67 | def 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 | |
| 75 | def 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 | |
| 89 | def 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 | |
| 103 | def _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 | |
| 111 | def _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 | |
| 129 | def 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 | |
| 154 | def 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 | |
| 166 | def _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 | |
| 209 | def _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 | |
| 239 | def _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 | |
| 246 | def 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 | |
| 267 | def 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 | ] |