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_change_dispatch.py · 18.2 KB · 426 lines
| 1 | """Change-log event dispatch -- the real fix for docs/logic-decisions.md #9. |
| 2 | |
| 3 | The problem this closes: HANDLES-declared event handlers only fire from |
| 4 | object_server's synchronous HTTP write path (see object_handlers.py and |
| 5 | object_server._dispatch_event_handlers). A runner or an action that writes |
| 6 | through object_records directly never passes through that path, so its |
| 7 | write never triggers the reactions a handler would give an equivalent HTTP |
| 8 | write. Doctrine #9 tracked two workarounds that paid for this gap by hand |
| 9 | (action_apply_count composing its own inventory-variance journal; |
| 10 | action_resolve_bank_line composing the NSF bounce reversal) and said the |
| 11 | third instance must buy the real fix instead of a third workaround: a |
| 12 | daemon pass that dispatches handlers from the record-change log, so a |
| 13 | write reaches its reactions no matter which path wrote it -- the same |
| 14 | shape object_daemon.process_notifications already uses to avoid depending |
| 15 | on synchronous dispatch for notify_rules. |
| 16 | |
| 17 | Payload parity with the HTTP path (read this twice, it bit production |
| 18 | once): object_server's dispatcher builds |
| 19 | |
| 20 | {"event": "<collection>.record.<created|updated|deleted>", |
| 21 | "collection": collection, "record_id": record_id, "action": action} |
| 22 | |
| 23 | where ``action`` is the RAW verb from the write ("create"/"update"/ |
| 24 | "delete") and ``event`` uses the past-participle form. A handler that |
| 25 | mixed the two up (checking ``action == "created"`` instead of mapping |
| 26 | "create" -> "created" first) silently matched nothing and skipped every |
| 27 | entry in production -- see the comment in |
| 28 | packages/app-payments/objects/system/books.py's EVENT(). This module |
| 29 | builds the exact same shape from the exact same raw fields a record-change |
| 30 | entry already carries (object_record_changes stores the raw action |
| 31 | untouched), so a handler cannot tell which path dispatched it. |
| 32 | |
| 33 | Double-dispatch, honestly: an HTTP write already dispatched its handlers |
| 34 | synchronously before this pass ever sees the resulting change-log entry. |
| 35 | This module has no way to know that happened -- object_record_changes |
| 36 | does not record whether HANDLES already ran for an entry, and this file |
| 37 | is not allowed to touch object_server.py to add that bookkeeping. So this |
| 38 | pass does NOT prevent a handler from running twice across the two paths. |
| 39 | What it promises instead is the same thing doctrine #7 already requires |
| 40 | of every composer here: idempotency by provenance (a generated_from |
| 41 | marker such as "payments/{id}" or "payments/{id}:bounced"), which is |
| 42 | exactly how action_apply_count and action_resolve_bank_line stay correct |
| 43 | under the two-workaround world already. At-least-once is therefore the |
| 44 | right guarantee to promise here, not exactly-once -- a handler that isn't |
| 45 | idempotent under redelivery is a bug in the handler, not in this |
| 46 | dispatcher. |
| 47 | |
| 48 | FIRST PASS ON A BOX WITH HISTORY. The cursor starts at "now": writes made |
| 49 | before the first pass are NOT dispatched. That is a decision, not an |
| 50 | accident, because replaying history is not safe for every reaction: |
| 51 | system_order_email's idempotency marker lives on the outbox rows it has |
| 52 | itself composed, so a replay from the beginning would queue a "confirmed" |
| 53 | email for every order ever confirmed. State-based reactions (invoice_status, |
| 54 | books, stock_books, ...) are safe to replay -- they are idempotent by |
| 55 | provenance (#7) -- but the pass cannot treat reactions differently. What |
| 56 | it does instead is refuse to be silent: the first pass records how much |
| 57 | history it stepped over (``first_pass_report``, persisted in |
| 58 | .change_dispatch_baseline.json, logged as a WARNING, surfaced by |
| 59 | /daemon/status) and names the way back. The operator chooses a replay point |
| 60 | for that first pass with DBBASIC_CHANGE_DISPATCH_FROM=beginning or an ISO |
| 61 | timestamp, having read what the handlers do. (Found by simulation: the flag |
| 62 | turned on after payments landed left paid invoices "sent" and subscribers |
| 63 | past_due, with nothing saying so.) |
| 64 | |
| 65 | What this module DOES guard against is re-firing the SAME (change_id, |
| 66 | handler_object_id) pair across this pass's own polls -- a cursor file |
| 67 | (same posture as process_notifications: first run stamps "now" and never |
| 68 | backfills history) plus a small marker file recording pairs dispatched |
| 69 | since the cursor last advanced. The marker exists because the cursor only |
| 70 | advances once per successful batch; without it, a crash between |
| 71 | dispatching entry 3 of 10 and persisting the new cursor would replay |
| 72 | entries 1-10 (not just 4-10) on the next poll. The marker file is cleared |
| 73 | every time the cursor successfully advances, so it never grows past one |
| 74 | in-flight batch. |
| 75 | |
| 76 | Finally, this whole pass is opt-in: DBBASIC_ENABLE_CHANGE_DISPATCH is |
| 77 | unset (OFF) by default, mirroring object_handlers.HANDLERS_ENABLED_ENV's |
| 78 | posture that a dispatch behavior this new should be a deliberate operator |
| 79 | act, not a silent default. |
| 80 | """ |
| 81 | from __future__ import annotations |
| 82 | |
| 83 | import json |
| 84 | import logging |
| 85 | import os |
| 86 | from datetime import datetime, timezone |
| 87 | from pathlib import Path |
| 88 | from typing import Any, Iterable |
| 89 | |
| 90 | import object_collections |
| 91 | import object_handlers |
| 92 | import object_record_changes |
| 93 | from object_execution import ObjectExecutionRequest, execute_object |
| 94 | from python_object_runtime import PythonObjectRuntime |
| 95 | |
| 96 | ENABLE_ENV = "DBBASIC_ENABLE_CHANGE_DISPATCH" |
| 97 | _TRUE_VALUES = {"1", "true", "yes", "on"} |
| 98 | |
| 99 | FROM_ENV = "DBBASIC_CHANGE_DISPATCH_FROM" |
| 100 | BASELINE_FILE_NAME = ".change_dispatch_baseline.json" |
| 101 | # Reading the log in pages of this size; a pass never drops a backlog that |
| 102 | # is bigger than one page. |
| 103 | PAGE_SIZE_MAX = 1000 |
| 104 | _LOG = logging.getLogger("object_change_dispatch") |
| 105 | |
| 106 | CURSOR_FILE_NAME = ".change_dispatch_cursor" |
| 107 | MARKER_FILE_NAME = ".change_dispatch_dispatched" |
| 108 | |
| 109 | DEFAULT_LIMIT = 200 |
| 110 | |
| 111 | # One runtime, module-level, mirrors object_server.py's `_runtime = |
| 112 | # PythonObjectRuntime()` and the test fixtures' `RUNTIME = |
| 113 | # python_object_runtime.PythonObjectRuntime()` -- cheap to construct, no |
| 114 | # per-call state worth re-creating on every poll. |
| 115 | _RUNTIME = PythonObjectRuntime() |
| 116 | |
| 117 | |
| 118 | def change_dispatch_enabled(*, base_dir: Path | str) -> bool: |
| 119 | """Return True when the change-log dispatch pass may run. |
| 120 | |
| 121 | Env-only and OFF by default -- unlike object_notify's |
| 122 | notify_pass_enabled (a feature_flags row, default ON: a brownout lever |
| 123 | for a feature already adopted), this pass makes an installed handler |
| 124 | start reacting to writes that never used to reach it. That is a |
| 125 | behavior change for existing objects, not a lever on an existing one, |
| 126 | so it needs an explicit operator opt-in rather than a data default. |
| 127 | ``base_dir`` is accepted for signature symmetry with the other |
| 128 | ``*_enabled(*, base_dir)`` checks in this codebase; this particular |
| 129 | check does not read anything under it. |
| 130 | """ |
| 131 | value = os.environ.get(ENABLE_ENV, "") |
| 132 | return value.strip().lower() in _TRUE_VALUES |
| 133 | |
| 134 | |
| 135 | def dispatch_pending( |
| 136 | *, |
| 137 | base_dir: Path | str, |
| 138 | roots: Iterable[Path] | None = None, |
| 139 | limit: int = DEFAULT_LIMIT, |
| 140 | ) -> dict[str, Any]: |
| 141 | """Dispatch HANDLES handlers for record-change entries newer than the cursor. |
| 142 | |
| 143 | Returns {"processed", "dispatched", "skipped", "errors", "results"}: |
| 144 | |
| 145 | - processed: change-log entries examined this pass (across every |
| 146 | collection any installed handler declares interest in). |
| 147 | - dispatched: handler EVENT calls actually attempted (success or |
| 148 | failure both count -- this is "how much work happened", not "how |
| 149 | much succeeded"). |
| 150 | - skipped: entries whose event had no matching handler, plus |
| 151 | (change_id, handler_id) pairs already recorded as dispatched by an |
| 152 | earlier, not-yet-committed pass over the same batch. |
| 153 | - errors: dispatched calls whose handler raised or returned a |
| 154 | non-ok ObjectExecutionResult. |
| 155 | - results: one dict per attempted dispatch (change_id, collection, |
| 156 | record_id, action, event, handler_id, ok, error). |
| 157 | |
| 158 | Gracefully returns the all-zero shape (never raises) when: the pass is |
| 159 | disabled, no installed object declares a HANDLES entry shaped like |
| 160 | "<collection>.record.<created|updated|deleted>", or a collection has |
| 161 | no change log yet. One raising handler, or one unreadable change-log |
| 162 | file, never stops the rest of the batch -- same posture as |
| 163 | object_daemon.process_notifications. |
| 164 | """ |
| 165 | base_dir = Path(base_dir) |
| 166 | result: dict[str, Any] = { |
| 167 | "processed": 0, |
| 168 | "dispatched": 0, |
| 169 | "skipped": 0, |
| 170 | "errors": 0, |
| 171 | "results": [], |
| 172 | } |
| 173 | |
| 174 | if not change_dispatch_enabled(base_dir=base_dir): |
| 175 | return result |
| 176 | |
| 177 | try: |
| 178 | index = object_handlers.build_index(roots) |
| 179 | except Exception: |
| 180 | # Source discovery is best-effort here -- a broken package source |
| 181 | # elsewhere must not stop this pass either. |
| 182 | return result |
| 183 | |
| 184 | collections = _collections_with_record_handlers(index) |
| 185 | if not collections: |
| 186 | return result |
| 187 | |
| 188 | cursor_path = base_dir / CURSOR_FILE_NAME |
| 189 | try: |
| 190 | cursor = cursor_path.read_text(encoding="utf-8").strip() |
| 191 | except OSError: |
| 192 | cursor = "" |
| 193 | |
| 194 | if not cursor: |
| 195 | cursor = _first_pass_cursor(base_dir, collections, cursor_path) |
| 196 | if cursor is None: |
| 197 | return result |
| 198 | |
| 199 | fresh: list[dict[str, Any]] = [] |
| 200 | for collection in collections: |
| 201 | fresh.extend(_changes_after(collection, cursor, base_dir=base_dir, page=limit)) |
| 202 | fresh.sort(key=lambda c: str(c.get("timestamp") or "")) |
| 203 | |
| 204 | result["processed"] = len(fresh) |
| 205 | if not fresh: |
| 206 | return result |
| 207 | |
| 208 | marker_path = base_dir / MARKER_FILE_NAME |
| 209 | dispatched_pairs = _load_markers(marker_path) |
| 210 | |
| 211 | max_ts = cursor |
| 212 | for change in fresh: |
| 213 | # Per-entry isolation: a malformed change or a handler exception |
| 214 | # must never stop the rest of the batch or prevent the cursor from |
| 215 | # advancing past everything that DID work. |
| 216 | try: |
| 217 | ts = str(change.get("timestamp") or "") |
| 218 | if ts > max_ts: |
| 219 | max_ts = ts |
| 220 | |
| 221 | collection = str(change.get("collection") or "") |
| 222 | record_id = str(change.get("record_id") or "") |
| 223 | action = str(change.get("action") or "") |
| 224 | change_id = str(change.get("change_id") or "") |
| 225 | |
| 226 | event = object_handlers.event_name(collection, action) |
| 227 | handler_ids = index.get(event) if event else None |
| 228 | if not handler_ids: |
| 229 | result["skipped"] += 1 |
| 230 | continue |
| 231 | |
| 232 | # Same signal-shaped payload object_server._dispatch_event_handlers |
| 233 | # builds: no record body, RAW action, participle event name. |
| 234 | event_payload = { |
| 235 | "event": event, |
| 236 | "collection": collection, |
| 237 | "record_id": record_id, |
| 238 | "action": action, |
| 239 | } |
| 240 | |
| 241 | for handler_id in handler_ids: |
| 242 | pair_key = f"{change_id}\t{handler_id}" |
| 243 | if pair_key in dispatched_pairs: |
| 244 | result["skipped"] += 1 |
| 245 | continue |
| 246 | |
| 247 | entry: dict[str, Any] = { |
| 248 | "change_id": change_id, |
| 249 | "collection": collection, |
| 250 | "record_id": record_id, |
| 251 | "action": action, |
| 252 | "event": event, |
| 253 | "handler_id": handler_id, |
| 254 | "ok": False, |
| 255 | "error": None, |
| 256 | } |
| 257 | try: |
| 258 | request = ObjectExecutionRequest( |
| 259 | object_id=handler_id, |
| 260 | method="EVENT", |
| 261 | payload=event_payload, |
| 262 | correlation_id=change.get("correlation_id") or None, |
| 263 | ) |
| 264 | exec_result = execute_object(_RUNTIME, request, roots) |
| 265 | entry["ok"] = bool(exec_result.ok) |
| 266 | if not exec_result.ok and exec_result.error is not None: |
| 267 | entry["error"] = exec_result.error.message |
| 268 | except Exception as exc: # noqa: BLE001 -- one bad handler must not stop others |
| 269 | entry["ok"] = False |
| 270 | entry["error"] = str(exc)[:200] |
| 271 | |
| 272 | result["dispatched"] += 1 |
| 273 | if not entry["ok"]: |
| 274 | result["errors"] += 1 |
| 275 | result["results"].append(entry) |
| 276 | dispatched_pairs.add(pair_key) |
| 277 | _append_marker(marker_path, pair_key) |
| 278 | except Exception: # noqa: BLE001 -- one bad change must not stop the batch |
| 279 | continue |
| 280 | |
| 281 | if max_ts != cursor: |
| 282 | cursor_path.write_text(max_ts, encoding="utf-8") |
| 283 | # The whole batch between the old and new cursor just committed; |
| 284 | # nothing in it can ever be re-read (list_record_changes only |
| 285 | # returns entries newer than the cursor), so the markers guarding |
| 286 | # against a mid-batch crash are no longer needed. |
| 287 | _clear_markers(marker_path) |
| 288 | |
| 289 | return result |
| 290 | |
| 291 | |
| 292 | def first_pass_report(*, base_dir: Path | str) -> dict[str, Any] | None: |
| 293 | """What the first pass did about history, or None if it has not run. |
| 294 | |
| 295 | {mode: "from_now" | "replay", cursor, at, skipped_before: {collection: |
| 296 | count}, skipped_total, message}. ``from_now`` with skipped_total > 0 means |
| 297 | writes older than the install point were never dispatched to their |
| 298 | handlers (see the module docstring).""" |
| 299 | try: |
| 300 | return json.loads((Path(base_dir) / BASELINE_FILE_NAME).read_text(encoding="utf-8")) |
| 301 | except (OSError, ValueError): |
| 302 | return None |
| 303 | |
| 304 | |
| 305 | def _parse_from(value: str) -> str | None: |
| 306 | """The replay point as a cursor string, or None when it is unusable. |
| 307 | Normalised to the change log's own spelling (UTC isoformat) because two |
| 308 | spellings of one instant do not sort alike.""" |
| 309 | text = value.strip() |
| 310 | if text.lower() == "beginning": |
| 311 | return "0" |
| 312 | try: |
| 313 | parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) |
| 314 | except ValueError: |
| 315 | return None |
| 316 | if parsed.tzinfo is None: |
| 317 | parsed = parsed.replace(tzinfo=timezone.utc) |
| 318 | return parsed.astimezone(timezone.utc).isoformat() |
| 319 | |
| 320 | |
| 321 | def _first_pass_cursor(base_dir: Path, collections: list[str], cursor_path: Path) -> str | None: |
| 322 | """Decide and persist where the very first pass starts. Returns the |
| 323 | cursor to dispatch after, or None when nothing is to be dispatched this |
| 324 | pass (the default: start from now).""" |
| 325 | now_iso = datetime.now(timezone.utc).isoformat() |
| 326 | wanted = os.environ.get(FROM_ENV, "").strip() |
| 327 | replay = _parse_from(wanted) if wanted else None |
| 328 | bad_from = bool(wanted) and replay is None |
| 329 | start = replay if replay is not None else now_iso |
| 330 | |
| 331 | skipped: dict[str, int] = {} |
| 332 | for collection in collections: |
| 333 | count = 0 |
| 334 | for change in _changes_after(collection, "", base_dir=base_dir, page=PAGE_SIZE_MAX): |
| 335 | if str(change.get("timestamp") or "") <= start: |
| 336 | count += 1 |
| 337 | if count: |
| 338 | skipped[collection] = count |
| 339 | total = sum(skipped.values()) |
| 340 | |
| 341 | if replay is not None: |
| 342 | mode = "replay" |
| 343 | message = (f"Change dispatch starts from {wanted!r} ({FROM_ENV}): " |
| 344 | f"{total} older change(s) are not dispatched.") |
| 345 | else: |
| 346 | mode = "from_now" |
| 347 | message = (f"Change dispatch started at {now_iso}. {total} earlier change(s) " |
| 348 | f"across {len(skipped)} watched collection(s) were NOT dispatched to " |
| 349 | f"their handlers, so reactions to those writes (invoice status, " |
| 350 | f"books, fulfilment, ...) never ran through this pass. To replay " |
| 351 | f"them, remove {CURSOR_FILE_NAME} and set {FROM_ENV}=beginning (or an " |
| 352 | f"ISO timestamp) for one daemon start -- first read what the " |
| 353 | f"handlers do: replaying order emails queues a message per order.") |
| 354 | if bad_from: |
| 355 | message = (f"{FROM_ENV}={wanted!r} is not 'beginning' or an ISO timestamp " |
| 356 | f"and was ignored. ") + message |
| 357 | if total or bad_from: |
| 358 | _LOG.warning(message) |
| 359 | report = {"mode": mode, "cursor": start, "at": now_iso, |
| 360 | "skipped_before": skipped, "skipped_total": total, "message": message} |
| 361 | base_dir.mkdir(parents=True, exist_ok=True) |
| 362 | (base_dir / BASELINE_FILE_NAME).write_text(json.dumps(report, indent=2), encoding="utf-8") |
| 363 | cursor_path.write_text(start, encoding="utf-8") |
| 364 | return start if replay is not None else None |
| 365 | |
| 366 | |
| 367 | def _changes_after(collection: str, cursor: str, *, base_dir: Path, page: int) -> list[dict[str, Any]]: |
| 368 | """Every change in a collection's log newer than ``cursor``, paging the |
| 369 | newest-first log until a page reaches the cursor. (A single read of |
| 370 | `limit` entries used to be all there was: a backlog larger than that |
| 371 | lost its older entries when the cursor jumped to the newest.)""" |
| 372 | page = max(1, min(int(page), PAGE_SIZE_MAX)) |
| 373 | found: list[dict[str, Any]] = [] |
| 374 | offset = 0 |
| 375 | while True: |
| 376 | try: |
| 377 | payload = object_record_changes.list_record_changes( |
| 378 | collection, base_dir=base_dir, limit=page, offset=offset |
| 379 | ) |
| 380 | except (object_collections.InvalidCollectionNameError, OSError, ValueError): |
| 381 | break |
| 382 | changes = payload.get("changes") or [] |
| 383 | newer = [c for c in changes if str(c.get("timestamp") or "") > cursor] |
| 384 | found.extend(newer) |
| 385 | if len(newer) < len(changes) or not payload.get("has_more") or not changes: |
| 386 | break |
| 387 | offset += len(changes) |
| 388 | return found |
| 389 | |
| 390 | |
| 391 | def _collections_with_record_handlers(index: dict[str, list[str]]) -> list[str]: |
| 392 | """Return the sorted set of collections any HANDLES entry names. |
| 393 | |
| 394 | Only "<collection>.record.<created|updated|deleted>" shaped events are |
| 395 | record-change events this pass can act on; anything else in HANDLES |
| 396 | (a future, non-record event kind) is silently not our concern here. |
| 397 | """ |
| 398 | participles = {"created", "updated", "deleted"} |
| 399 | collections: set[str] = set() |
| 400 | for event in index: |
| 401 | parts = event.split(".record.", 1) |
| 402 | if len(parts) != 2 or parts[1] not in participles or not parts[0]: |
| 403 | continue |
| 404 | collections.add(parts[0]) |
| 405 | return sorted(collections) |
| 406 | |
| 407 | |
| 408 | def _load_markers(path: Path) -> set[str]: |
| 409 | try: |
| 410 | text = path.read_text(encoding="utf-8") |
| 411 | except OSError: |
| 412 | return set() |
| 413 | return {line for line in text.splitlines() if line.strip()} |
| 414 | |
| 415 | |
| 416 | def _append_marker(path: Path, key: str) -> None: |
| 417 | path.parent.mkdir(parents=True, exist_ok=True) |
| 418 | with path.open("a", encoding="utf-8") as handle: |
| 419 | handle.write(key + "\n") |
| 420 | |
| 421 | |
| 422 | def _clear_markers(path: Path) -> None: |
| 423 | try: |
| 424 | path.write_text("", encoding="utf-8") |
| 425 | except OSError: |
| 426 | pass |