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_change_dispatch.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_change_dispatch.py · 18.2 KB · 426 lines
1"""Change-log event dispatch -- the real fix for docs/logic-decisions.md #9.
2
3The problem this closes: HANDLES-declared event handlers only fire from
4object_server's synchronous HTTP write path (see object_handlers.py and
5object_server._dispatch_event_handlers). A runner or an action that writes
6through object_records directly never passes through that path, so its
7write never triggers the reactions a handler would give an equivalent HTTP
8write. Doctrine #9 tracked two workarounds that paid for this gap by hand
9(action_apply_count composing its own inventory-variance journal;
10action_resolve_bank_line composing the NSF bounce reversal) and said the
11third instance must buy the real fix instead of a third workaround: a
12daemon pass that dispatches handlers from the record-change log, so a
13write reaches its reactions no matter which path wrote it -- the same
14shape object_daemon.process_notifications already uses to avoid depending
15on synchronous dispatch for notify_rules.
16
17Payload parity with the HTTP path (read this twice, it bit production
18once): object_server's dispatcher builds
19
20 {"event": "<collection>.record.<created|updated|deleted>",
21 "collection": collection, "record_id": record_id, "action": action}
22
23where ``action`` is the RAW verb from the write ("create"/"update"/
24"delete") and ``event`` uses the past-participle form. A handler that
25mixed the two up (checking ``action == "created"`` instead of mapping
26"create" -> "created" first) silently matched nothing and skipped every
27entry in production -- see the comment in
28packages/app-payments/objects/system/books.py's EVENT(). This module
29builds the exact same shape from the exact same raw fields a record-change
30entry already carries (object_record_changes stores the raw action
31untouched), so a handler cannot tell which path dispatched it.
32
33Double-dispatch, honestly: an HTTP write already dispatched its handlers
34synchronously before this pass ever sees the resulting change-log entry.
35This module has no way to know that happened -- object_record_changes
36does not record whether HANDLES already ran for an entry, and this file
37is not allowed to touch object_server.py to add that bookkeeping. So this
38pass does NOT prevent a handler from running twice across the two paths.
39What it promises instead is the same thing doctrine #7 already requires
40of every composer here: idempotency by provenance (a generated_from
41marker such as "payments/{id}" or "payments/{id}:bounced"), which is
42exactly how action_apply_count and action_resolve_bank_line stay correct
43under the two-workaround world already. At-least-once is therefore the
44right guarantee to promise here, not exactly-once -- a handler that isn't
45idempotent under redelivery is a bug in the handler, not in this
46dispatcher.
47
48FIRST PASS ON A BOX WITH HISTORY. The cursor starts at "now": writes made
49before the first pass are NOT dispatched. That is a decision, not an
50accident, because replaying history is not safe for every reaction:
51system_order_email's idempotency marker lives on the outbox rows it has
52itself composed, so a replay from the beginning would queue a "confirmed"
53email for every order ever confirmed. State-based reactions (invoice_status,
54books, stock_books, ...) are safe to replay -- they are idempotent by
55provenance (#7) -- but the pass cannot treat reactions differently. What
56it does instead is refuse to be silent: the first pass records how much
57history 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
60for that first pass with DBBASIC_CHANGE_DISPATCH_FROM=beginning or an ISO
61timestamp, having read what the handlers do. (Found by simulation: the flag
62turned on after payments landed left paid invoices "sent" and subscribers
63past_due, with nothing saying so.)
64
65What this module DOES guard against is re-firing the SAME (change_id,
66handler_object_id) pair across this pass's own polls -- a cursor file
67(same posture as process_notifications: first run stamps "now" and never
68backfills history) plus a small marker file recording pairs dispatched
69since the cursor last advanced. The marker exists because the cursor only
70advances once per successful batch; without it, a crash between
71dispatching entry 3 of 10 and persisting the new cursor would replay
72entries 1-10 (not just 4-10) on the next poll. The marker file is cleared
73every time the cursor successfully advances, so it never grows past one
74in-flight batch.
75
76Finally, this whole pass is opt-in: DBBASIC_ENABLE_CHANGE_DISPATCH is
77unset (OFF) by default, mirroring object_handlers.HANDLERS_ENABLED_ENV's
78posture that a dispatch behavior this new should be a deliberate operator
79act, not a silent default.
80"""
81from __future__ import annotations
82
83import json
84import logging
85import os
86from datetime import datetime, timezone
87from pathlib import Path
88from typing import Any, Iterable
89
90import object_collections
91import object_handlers
92import object_record_changes
93from object_execution import ObjectExecutionRequest, execute_object
94from python_object_runtime import PythonObjectRuntime
95
96ENABLE_ENV = "DBBASIC_ENABLE_CHANGE_DISPATCH"
97_TRUE_VALUES = {"1", "true", "yes", "on"}
98
99FROM_ENV = "DBBASIC_CHANGE_DISPATCH_FROM"
100BASELINE_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.
103PAGE_SIZE_MAX = 1000
104_LOG = logging.getLogger("object_change_dispatch")
105
106CURSOR_FILE_NAME = ".change_dispatch_cursor"
107MARKER_FILE_NAME = ".change_dispatch_dispatched"
108
109DEFAULT_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
118def 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
135def 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
292def 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
305def _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
321def _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
367def _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
391def _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
408def _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
416def _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
422def _clear_markers(path: Path) -> None:
423 try:
424 path.write_text("", encoding="utf-8")
425 except OSError:
426 pass