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_handlers.py · 5.5 KB · 167 lines
| 1 | """Event handler objects (HANDLES) — Phase 5a of the upgrade system. |
| 2 | |
| 3 | See docs/event-hooks-decisions.md and docs/upgrade-and-customization.md |
| 4 | (Rule 4) for the design and why it looks like this. Summary: an |
| 5 | operator/package object may declare a module-level ``HANDLES = [...]`` list |
| 6 | of event names it wants to run on. When a record write commits, the server |
| 7 | dispatches the matching event to each handler object, post-commit and |
| 8 | best-effort — a handler failure never breaks or rolls back the write. |
| 9 | |
| 10 | This module owns three small, independent pieces: |
| 11 | |
| 12 | - Static extraction of ``HANDLES`` from source text (AST only; never exec). |
| 13 | - A cached event -> handler-object-id index built from system object |
| 14 | sources only (Decision 2: user-authored handlers are deferred). |
| 15 | - A reentry guard so a handler's own writes cannot cause unbounded |
| 16 | recursive dispatch. |
| 17 | |
| 18 | The whole feature is gated behind ``DBBASIC_ENABLE_EVENT_HANDLERS``; when |
| 19 | unset (the default) every entry point here is inert and object_server's |
| 20 | dispatch call is a no-op. |
| 21 | """ |
| 22 | from __future__ import annotations |
| 23 | |
| 24 | import ast |
| 25 | import contextlib |
| 26 | import os |
| 27 | import threading |
| 28 | from contextvars import ContextVar |
| 29 | from pathlib import Path |
| 30 | from typing import Iterable, Iterator |
| 31 | |
| 32 | from object_namespace import iter_object_sources |
| 33 | |
| 34 | HANDLERS_ENABLED_ENV = "DBBASIC_ENABLE_EVENT_HANDLERS" |
| 35 | |
| 36 | _TRUE_VALUES = {"1", "true", "yes", "on"} |
| 37 | |
| 38 | # Present-tense past-participle event names matching the action: |
| 39 | # create -> created, update -> updated, delete -> deleted. |
| 40 | _ACTION_EVENT_SUFFIXES = { |
| 41 | "create": "created", |
| 42 | "update": "updated", |
| 43 | "delete": "deleted", |
| 44 | } |
| 45 | |
| 46 | MAX_DISPATCH_DEPTH = 4 |
| 47 | |
| 48 | _dispatch_depth: ContextVar[int] = ContextVar("dbbasic_event_dispatch_depth", default=0) |
| 49 | |
| 50 | _INDEX: dict[str, list[str]] | None = None |
| 51 | _INDEX_LOCK = threading.Lock() |
| 52 | |
| 53 | |
| 54 | def handlers_enabled() -> bool: |
| 55 | """Return True when event handler dispatch is enabled. |
| 56 | |
| 57 | Reads os.environ directly (standalone, mirrors the shape of |
| 58 | object_server's other boolean env checks without depending on it). |
| 59 | """ |
| 60 | value = os.environ.get(HANDLERS_ENABLED_ENV, "") |
| 61 | return value.strip().lower() in _TRUE_VALUES |
| 62 | |
| 63 | |
| 64 | def event_name(collection: str, action: str) -> str | None: |
| 65 | """Return "<collection>.record.<created|updated|deleted>", or None. |
| 66 | |
| 67 | None is returned for an unknown action or an empty collection name. |
| 68 | """ |
| 69 | suffix = _ACTION_EVENT_SUFFIXES.get(action) |
| 70 | if suffix is None or not collection: |
| 71 | return None |
| 72 | return f"{collection}.record.{suffix}" |
| 73 | |
| 74 | |
| 75 | def extract_handles(source_text: str) -> list[str]: |
| 76 | """Statically extract a module-level ``HANDLES = [...]`` string list. |
| 77 | |
| 78 | Pure AST parse — the source is never executed. Mirrors the safety |
| 79 | posture of object_source.source_method_report. Returns [] whenever the |
| 80 | source has a syntax error, has no ``HANDLES`` assignment, or the value |
| 81 | is not a list/tuple literal. Non-string entries inside the literal are |
| 82 | ignored rather than raising. |
| 83 | """ |
| 84 | try: |
| 85 | tree = ast.parse(source_text) |
| 86 | except SyntaxError: |
| 87 | return [] |
| 88 | |
| 89 | for node in tree.body: |
| 90 | if not isinstance(node, ast.Assign): |
| 91 | continue |
| 92 | if not any( |
| 93 | isinstance(target, ast.Name) and target.id == "HANDLES" |
| 94 | for target in node.targets |
| 95 | ): |
| 96 | continue |
| 97 | if not isinstance(node.value, (ast.List, ast.Tuple)): |
| 98 | return [] |
| 99 | return [ |
| 100 | element.value |
| 101 | for element in node.value.elts |
| 102 | if isinstance(element, ast.Constant) and isinstance(element.value, str) |
| 103 | ] |
| 104 | |
| 105 | return [] |
| 106 | |
| 107 | |
| 108 | def build_index(roots: Iterable[Path] | None = None) -> dict[str, list[str]]: |
| 109 | """Scan system object sources and map each declared event to object IDs. |
| 110 | |
| 111 | System objects only (source.kind == "system") — user and override |
| 112 | sources are skipped, per Decision 2 in docs/event-hooks-decisions.md: |
| 113 | only operator-installed objects may declare handlers in this phase. |
| 114 | """ |
| 115 | index: dict[str, set[str]] = {} |
| 116 | for source in iter_object_sources(roots): |
| 117 | if source.kind != "system": |
| 118 | continue |
| 119 | try: |
| 120 | text = source.path.read_text() |
| 121 | except OSError: |
| 122 | continue |
| 123 | for event in extract_handles(text): |
| 124 | index.setdefault(event, set()).add(source.object_id) |
| 125 | |
| 126 | return {event: sorted(object_ids) for event, object_ids in index.items()} |
| 127 | |
| 128 | |
| 129 | def get_handlers(event: str, roots: Iterable[Path] | None = None) -> list[str]: |
| 130 | """Return handler object IDs for an event, building/caching the index.""" |
| 131 | global _INDEX |
| 132 | with _INDEX_LOCK: |
| 133 | if _INDEX is None: |
| 134 | _INDEX = build_index(roots) |
| 135 | return list(_INDEX.get(event, [])) |
| 136 | |
| 137 | |
| 138 | def invalidate() -> None: |
| 139 | """Drop the cached index so the next get_handlers() call rebuilds it. |
| 140 | |
| 141 | Call this after any object source create/update/delete so a |
| 142 | newly-added or edited handler is picked up. |
| 143 | """ |
| 144 | global _INDEX |
| 145 | with _INDEX_LOCK: |
| 146 | _INDEX = None |
| 147 | |
| 148 | |
| 149 | def current_depth() -> int: |
| 150 | """Return the current event-dispatch reentry depth.""" |
| 151 | return _dispatch_depth.get() |
| 152 | |
| 153 | |
| 154 | @contextlib.contextmanager |
| 155 | def dispatch_guard() -> Iterator[None]: |
| 156 | """Track reentrant dispatch depth for the duration of one handler call. |
| 157 | |
| 158 | Belt-and-suspenders: in practice a handler's writes go through |
| 159 | object_records, which does not itself re-fire dispatch synchronously |
| 160 | into a growing call stack the way this guard assumes, but the guard |
| 161 | costs nothing and caps any future path that could recurse. |
| 162 | """ |
| 163 | token = _dispatch_depth.set(_dispatch_depth.get() + 1) |
| 164 | try: |
| 165 | yield |
| 166 | finally: |
| 167 | _dispatch_depth.reset(token) |