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.
danq9
signup: the person chooses the password and name on the confirm page
83c7aa6
2 weeks, 5 days ago
History
object_notify.py · 10.0 KB · 238 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_feature_flags |
| 29 | import object_identity |
| 30 | |
| 31 | NOTIFY_RULES_COLLECTION = "notify_rules" |
| 32 | NOTIFICATIONS_COLLECTION = "notifications" |
| 33 | FEATURE_FLAGS_COLLECTION = "feature_flags" |
| 34 | NOTIFY_ENABLED_FLAG = "notify_enabled" |
| 35 | DEFAULT_ACTOR = "daemon:notify" |
| 36 | |
| 37 | _ACTIONS = frozenset({"created", "updated", "deleted"}) |
| 38 | # A record-change entry stores the action in present tense (create/update/ |
| 39 | # delete, object_record_changes); the event grammar (and object_handlers' |
| 40 | # event_name) uses the -ed event suffix. Map one to the other before matching. |
| 41 | _CHANGE_TO_EVENT = {"create": "created", "update": "updated", "delete": "deleted"} |
| 42 | |
| 43 | |
| 44 | def _event_action(change: Mapping[str, Any]) -> str: |
| 45 | raw = str(change.get("action") or "") |
| 46 | return _CHANGE_TO_EVENT.get(raw, raw) |
| 47 | |
| 48 | |
| 49 | def _json_field(value: Any, default: Any) -> Any: |
| 50 | if value in (None, ""): |
| 51 | return default |
| 52 | if isinstance(value, (dict, list)): |
| 53 | return value |
| 54 | try: |
| 55 | return json.loads(value) |
| 56 | except (TypeError, ValueError): |
| 57 | return default |
| 58 | |
| 59 | |
| 60 | def _truthy(value: Any, *, default: bool) -> bool: |
| 61 | if value in (None, ""): |
| 62 | return default |
| 63 | return str(value).strip().lower() not in {"off", "false", "0", "no"} |
| 64 | |
| 65 | |
| 66 | def notify_pass_enabled(*, base_dir: Any) -> bool: |
| 67 | """Block-wide kill switch, `<block>_enabled` convention -- a feature_flags |
| 68 | row named `notify_enabled`. Default ON (brownout lever, not an adoption |
| 69 | gate; with zero rules it does nothing anyway). Mirrors |
| 70 | object_rollups.rollup_pass_enabled exactly.""" |
| 71 | return object_feature_flags.kill_switch_on(NOTIFY_ENABLED_FLAG, base_dir=base_dir) |
| 72 | |
| 73 | |
| 74 | def event_pattern_matches(pattern: str, collection: str, action: str) -> bool: |
| 75 | """`<collection>.record.<action>` with `*` allowed in the collection or |
| 76 | action segment (the spec's grammar). Anything malformed never matches.""" |
| 77 | parts = str(pattern or "").split(".") |
| 78 | if len(parts) != 3 or parts[1] != "record": |
| 79 | return False |
| 80 | coll_pat, _, act_pat = parts |
| 81 | if action not in _ACTIONS: |
| 82 | return False |
| 83 | coll_ok = coll_pat == "*" or coll_pat == collection |
| 84 | act_ok = act_pat == "*" or act_pat == action |
| 85 | return coll_ok and act_ok |
| 86 | |
| 87 | |
| 88 | def watched_collections(rules: Iterable[Mapping[str, str]], known: Iterable[str]) -> set[str]: |
| 89 | """The set of collections any enabled rule's event_pattern could fire on -- |
| 90 | a specific collection, or (for a `*` collection pattern) every known one. |
| 91 | Lets the daemon poll only the change logs that matter.""" |
| 92 | known = set(known) |
| 93 | watched: set[str] = set() |
| 94 | for rule in rules: |
| 95 | parts = str(rule.get("event_pattern") or "").split(".") |
| 96 | if len(parts) != 3 or parts[1] != "record": |
| 97 | continue |
| 98 | watched |= known if parts[0] == "*" else {parts[0]} |
| 99 | return watched |
| 100 | |
| 101 | |
| 102 | def _record_for(change: Mapping[str, Any]) -> dict[str, Any]: |
| 103 | """The record state a `match`/template/recipient reads: `after` for |
| 104 | created/updated, `before` for deleted (the row is already gone).""" |
| 105 | if _event_action(change) == "deleted": |
| 106 | return dict(change.get("before") or {}) |
| 107 | return dict(change.get("after") or {}) |
| 108 | |
| 109 | |
| 110 | def _match_ok(rule: Mapping[str, Any], change: Mapping[str, Any], record: Mapping[str, Any]) -> bool: |
| 111 | """Flat {field: value} equality, ANDed. On an UPDATE the condition is |
| 112 | restricted to fields the write actually CHANGED (change.changed_fields) -- |
| 113 | so "notify when status becomes assigned" fires once on the transition, not |
| 114 | on every later edit that still happens to satisfy status == assigned.""" |
| 115 | conditions = _json_field(rule.get("match"), {}) |
| 116 | if not isinstance(conditions, dict) or not conditions: |
| 117 | return True |
| 118 | changed = set(change.get("changed_fields") or []) |
| 119 | is_update = _event_action(change) == "updated" |
| 120 | for field, want in conditions.items(): |
| 121 | if is_update and field not in changed: |
| 122 | return False |
| 123 | if str(record.get(field, "")) != str(want): |
| 124 | return False |
| 125 | return True |
| 126 | |
| 127 | |
| 128 | def resolve_recipients(rule: Mapping[str, Any], record: Mapping[str, Any], *, base_dir: Any) -> list[str]: |
| 129 | """The four recipient modes: owner / field / users / role. A resolved |
| 130 | value that isn't a usable user id (empty/unknown) is silently skipped.""" |
| 131 | spec = _json_field(rule.get("recipients"), {}) |
| 132 | if not isinstance(spec, dict): |
| 133 | return [] |
| 134 | mode = spec.get("mode") |
| 135 | out: list[str] = [] |
| 136 | if mode == "owner": |
| 137 | out = [record.get(spec.get("owner_field") or "owner_id") or ""] |
| 138 | elif mode == "field": |
| 139 | out = [record.get(spec.get("field") or "") or ""] |
| 140 | elif mode == "users": |
| 141 | ids = spec.get("user_ids") |
| 142 | out = [str(u) for u in ids] if isinstance(ids, list) else [] |
| 143 | elif mode == "role": |
| 144 | want = spec.get("role") |
| 145 | try: |
| 146 | users = object_identity.list_users(base_dir=base_dir) |
| 147 | except (OSError, ValueError, AttributeError): |
| 148 | users = [] |
| 149 | out = [u.get("user_id") for u in users if want and want in (u.get("roles") or [])] |
| 150 | return [str(u) for u in out if u] |
| 151 | |
| 152 | |
| 153 | def render_template(template: str, record: Mapping[str, Any]) -> str: |
| 154 | """`{field}` substitution from the record -- no expressions, no logic. |
| 155 | An unknown field renders empty (a missing due_date shouldn't blow up).""" |
| 156 | class _Blank(dict): |
| 157 | def __missing__(self, key): |
| 158 | return "" |
| 159 | try: |
| 160 | return str(template or "").format_map(_Blank(record)) |
| 161 | except (ValueError, IndexError): |
| 162 | return str(template or "") |
| 163 | |
| 164 | |
| 165 | def _match_and_recipients( |
| 166 | rule: Mapping[str, Any], change: Mapping[str, Any], *, base_dir: Any, |
| 167 | ) -> tuple[list[str], dict[str, Any]]: |
| 168 | """Shared gating for every channel: apply the enabled flag, event-pattern, |
| 169 | transition-aware match, recipient resolution, suppress_self, and de-dup. |
| 170 | Returns (recipients, record), or ([], {}) if this rule doesn't fire on this |
| 171 | change. Keeps in_app and email delivery from drifting apart.""" |
| 172 | if not _truthy(rule.get("enabled"), default=True): |
| 173 | return [], {} |
| 174 | if not event_pattern_matches(rule.get("event_pattern"), change.get("collection"), _event_action(change)): |
| 175 | return [], {} |
| 176 | record = _record_for(change) |
| 177 | if not _match_ok(rule, change, record): |
| 178 | return [], {} |
| 179 | recipients = resolve_recipients(rule, record, base_dir=base_dir) |
| 180 | if _truthy(rule.get("suppress_self"), default=True): |
| 181 | actor = change.get("actor") |
| 182 | recipients = [r for r in recipients if r != actor] |
| 183 | # de-dup while preserving order (a role rule could name the same user twice) |
| 184 | seen: set[str] = set() |
| 185 | recipients = [r for r in recipients if not (r in seen or seen.add(r))] |
| 186 | return recipients, record |
| 187 | |
| 188 | |
| 189 | def _channel(rule: Mapping[str, Any], name: str) -> dict[str, Any] | None: |
| 190 | for channel in _json_field(rule.get("channels"), []): |
| 191 | if isinstance(channel, dict) and channel.get("channel") == name: |
| 192 | return channel |
| 193 | return None |
| 194 | |
| 195 | |
| 196 | def notifications_for_change( |
| 197 | rule: Mapping[str, Any], change: Mapping[str, Any], *, base_dir: Any, |
| 198 | ) -> list[dict[str, str]]: |
| 199 | """Every in_app notification record ONE rule implies for ONE change. Empty |
| 200 | when the rule doesn't match, no recipient resolves, or the rule declares no |
| 201 | in_app channel.""" |
| 202 | recipients, record = _match_and_recipients(rule, change, base_dir=base_dir) |
| 203 | if not recipients: |
| 204 | return [] |
| 205 | in_app = _channel(rule, "in_app") |
| 206 | if not in_app: |
| 207 | return [] |
| 208 | |
| 209 | body = render_template(in_app.get("body_template") or "", record) |
| 210 | target = f"{change.get('collection')}/{change.get('record_id')}" |
| 211 | return [ |
| 212 | {"user_id": uid, "kind": "notify", "body": body, "target": target, "is_read": "false"} |
| 213 | for uid in recipients |
| 214 | ] |
| 215 | |
| 216 | |
| 217 | def email_intents_for_change( |
| 218 | rule: Mapping[str, Any], change: Mapping[str, Any], *, base_dir: Any, |
| 219 | ) -> list[dict[str, str]]: |
| 220 | """The email messages ONE rule implies for ONE change: `{user_id, subject, |
| 221 | body}` per recipient. Empty when the rule doesn't fire or declares no email |
| 222 | channel. The engine stays side-effect-free of the actual send -- it names |
| 223 | WHO and WHAT; the daemon maps user_id -> address and enqueues via |
| 224 | object_email (01 outbox).""" |
| 225 | recipients, record = _match_and_recipients(rule, change, base_dir=base_dir) |
| 226 | if not recipients: |
| 227 | return [] |
| 228 | email = _channel(rule, "email") |
| 229 | if not email: |
| 230 | return [] |
| 231 | |
| 232 | subject = render_template(email.get("subject_template") or "", record) |
| 233 | body = render_template(email.get("body_template") or "", record) |
| 234 | target = f"{change.get('collection')}/{change.get('record_id')}" |
| 235 | return [ |
| 236 | {"user_id": uid, "subject": subject, "body": body, "target": target} |
| 237 | for uid in recipients |
| 238 | ] |