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_daemon_status.py · 18.5 KB · 490 lines
| 1 | """Read-only status summaries for the DBBASIC daemon primitives. |
| 2 | |
| 3 | The daemon owns delivery and scheduling. This module only reads the same TSV |
| 4 | state so Scroll and admin dashboards can see what is due, pending, failing, and |
| 5 | retained without executing objects. |
| 6 | """ |
| 7 | |
| 8 | from __future__ import annotations |
| 9 | |
| 10 | import importlib.util |
| 11 | import json |
| 12 | import time |
| 13 | from collections import Counter |
| 14 | from collections.abc import Iterable, Mapping |
| 15 | from datetime import datetime, timezone |
| 16 | from pathlib import Path |
| 17 | from typing import Any |
| 18 | |
| 19 | import object_change_dispatch |
| 20 | import object_events |
| 21 | import object_handlers |
| 22 | import object_state |
| 23 | from object_namespace import find_trigger_file, get_object_roots |
| 24 | from object_versions import DEFAULT_DATA_DIR |
| 25 | |
| 26 | # The daemon touches this file in the data dir on every poll loop |
| 27 | # (object_daemon._beat), throttled to once per DAEMON_HEARTBEAT_EVERY |
| 28 | # seconds. It is one small file, overwritten, never appended -- bounded by |
| 29 | # construction. Its only reader is reactions_status below: "is any daemon |
| 30 | # actually running against this data dir?" had no answer before, so a box |
| 31 | # with a dozen scheduled passes and no daemon looked exactly like a quiet one. |
| 32 | DAEMON_HEARTBEAT_NAME = ".daemon_heartbeat" |
| 33 | DAEMON_HEARTBEAT_EVERY = 30 |
| 34 | # A heartbeat older than this means no daemon is running here now. |
| 35 | DAEMON_STALE_AFTER_SECONDS = 600 |
| 36 | |
| 37 | |
| 38 | def daemon_status( |
| 39 | *, |
| 40 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 41 | object_roots: Iterable[Path | str] | None = None, |
| 42 | rate_limit_dir: Path | str | None = None, |
| 43 | event_keep_count: int | None = object_events.DEFAULT_EVENT_KEEP_COUNT, |
| 44 | event_keep_seconds: int | None = object_events.DEFAULT_EVENT_KEEP_SECONDS, |
| 45 | now: int | None = None, |
| 46 | ) -> dict[str, Any]: |
| 47 | """Return a read-only scheduler/queue/event summary for operators.""" |
| 48 | data_dir = Path(base_dir) |
| 49 | roots = [Path(root) for root in (object_roots if object_roots is not None else get_object_roots())] |
| 50 | current_time = int(time.time() if now is None else now) |
| 51 | |
| 52 | scheduler_source = find_trigger_file("scheduler", roots) is not None |
| 53 | queue_source = find_trigger_file("queue", roots) is not None |
| 54 | events_source = find_trigger_file("events", roots) is not None |
| 55 | |
| 56 | scheduler = _scheduler_status(data_dir, scheduler_source, current_time) |
| 57 | queue = _queue_status(data_dir, queue_source, current_time) |
| 58 | events = _events_status(data_dir, events_source) |
| 59 | cleanup = _cleanup_status( |
| 60 | rate_limit_dir=rate_limit_dir, |
| 61 | event_keep_count=event_keep_count, |
| 62 | event_keep_seconds=event_keep_seconds, |
| 63 | ) |
| 64 | |
| 65 | invalid_rows = ( |
| 66 | scheduler["tasks"]["invalid"] |
| 67 | + queue["messages"]["invalid"] |
| 68 | + events["events"]["invalid"] |
| 69 | + events["subscriptions"]["invalid"] |
| 70 | ) |
| 71 | failed_deliveries = events["subscriptions"]["by_delivery_status"].get("failed", 0) |
| 72 | |
| 73 | return { |
| 74 | "status": "degraded" if invalid_rows or failed_deliveries else "ok", |
| 75 | "timestamp": _utc_timestamp(current_time), |
| 76 | "daemon": { |
| 77 | "mode": "polling", |
| 78 | "croniter_available": importlib.util.find_spec("croniter") is not None, |
| 79 | "object_roots": {"count": len(roots)}, |
| 80 | "reactions": reactions_status(base_dir=data_dir, object_roots=roots, |
| 81 | now=current_time), |
| 82 | "triggers": { |
| 83 | "scheduler": {"object_id": "scheduler", "source_present": scheduler_source}, |
| 84 | "queue": {"object_id": "queue", "source_present": queue_source}, |
| 85 | "events": {"object_id": object_events.EVENTS_OBJECT_ID, "source_present": events_source}, |
| 86 | }, |
| 87 | }, |
| 88 | "scheduler": scheduler, |
| 89 | "queue": queue, |
| 90 | "events": events, |
| 91 | "cleanup": cleanup, |
| 92 | } |
| 93 | |
| 94 | |
| 95 | def reactions_status( |
| 96 | *, |
| 97 | base_dir: Path | str = DEFAULT_DATA_DIR, |
| 98 | object_roots: Iterable[Path | str] | None = None, |
| 99 | now: int | None = None, |
| 100 | ) -> dict[str, Any]: |
| 101 | """Would the reactions installed packages declare actually run here? |
| 102 | |
| 103 | Read-only, like object_books_status: it changes nothing, it only says |
| 104 | out loud what used to be silent. Four ways an installed app quietly |
| 105 | does nothing, each found on a real install: |
| 106 | |
| 107 | handlers_inert system objects declare HANDLES, but neither |
| 108 | DBBASIC_ENABLE_EVENT_HANDLERS nor |
| 109 | DBBASIC_ENABLE_CHANGE_DISPATCH is set (the |
| 110 | default), so no invoice flips to paid, no |
| 111 | journal composes, no stock moves. |
| 112 | storage_writes_unreacted |
| 113 | handlers are on for HTTP writes only; writes an |
| 114 | action, runner or webhook makes at storage |
| 115 | level reach no handler without change dispatch. |
| 116 | cron_needs_croniter active cron schedules exist and croniter is not |
| 117 | installed, so the daemon can never compute a |
| 118 | next run for them. |
| 119 | daemon_not_running there is daemon work (active schedules, or the |
| 120 | change-dispatch replay) and no daemon heartbeat |
| 121 | in this data dir, or only a stale one. |
| 122 | |
| 123 | Problems are reported only when something is installed that they |
| 124 | affect -- a box with no handlers and no schedules has nothing to say. |
| 125 | The flags' defaults are NOT changed here; turning reactions on is an |
| 126 | operator decision (see docs/single-vm-deployment.md). |
| 127 | """ |
| 128 | data_dir = Path(base_dir) |
| 129 | current = int(time.time() if now is None else now) |
| 130 | roots = None if object_roots is None else [Path(root) for root in object_roots] |
| 131 | |
| 132 | try: |
| 133 | index = object_handlers.build_index(roots) |
| 134 | except Exception: # a status read must never raise |
| 135 | index = {} |
| 136 | handler_ids = sorted({object_id for ids in index.values() for object_id in ids}) |
| 137 | http_on = object_handlers.handlers_enabled() |
| 138 | replay_on = object_change_dispatch.change_dispatch_enabled(base_dir=data_dir) |
| 139 | |
| 140 | try: |
| 141 | tasks, _invalid = _prefixed_json_rows(data_dir, "scheduler", "task_") |
| 142 | except Exception: |
| 143 | tasks = [] |
| 144 | active = [t for t in tasks if _status_name(t.get("status")) == "active"] |
| 145 | cron = [t for t in active if str(t.get("type") or "") == "cron"] |
| 146 | croniter_available = importlib.util.find_spec("croniter") is not None |
| 147 | |
| 148 | heartbeat = data_dir / DAEMON_HEARTBEAT_NAME |
| 149 | try: |
| 150 | last_seen = int(heartbeat.stat().st_mtime) |
| 151 | except OSError: |
| 152 | last_seen = None |
| 153 | daemon_running = last_seen is not None and current - last_seen <= DAEMON_STALE_AFTER_SECONDS |
| 154 | |
| 155 | problems: list[dict[str, str]] = [] |
| 156 | if handler_ids and not http_on and not replay_on: |
| 157 | problems.append({ |
| 158 | "id": "handlers_inert", "severity": "error", |
| 159 | "impact": (f"{len(handler_ids)} installed handler object(s) declare HANDLES " |
| 160 | f"({_names(handler_ids)}) and none of them runs: " |
| 161 | f"{object_handlers.HANDLERS_ENABLED_ENV} and " |
| 162 | f"{object_change_dispatch.ENABLE_ENV} are both unset"), |
| 163 | "fix": (f"set {object_change_dispatch.ENABLE_ENV}=true (and run the daemon) " |
| 164 | f"and/or {object_handlers.HANDLERS_ENABLED_ENV}=true"), |
| 165 | }) |
| 166 | elif handler_ids and http_on and not replay_on: |
| 167 | problems.append({ |
| 168 | "id": "storage_writes_unreacted", "severity": "warning", |
| 169 | "impact": ("handlers run for HTTP writes only: writes that actions, " |
| 170 | "scheduled runners and webhooks make at storage level reach " |
| 171 | f"no handler while {object_change_dispatch.ENABLE_ENV} is unset"), |
| 172 | "fix": f"set {object_change_dispatch.ENABLE_ENV}=true and run the daemon", |
| 173 | }) |
| 174 | baseline = object_change_dispatch.first_pass_report(base_dir=data_dir) if replay_on else None |
| 175 | if baseline and baseline.get("mode") == "from_now" and baseline.get("skipped_total"): |
| 176 | problems.append({ |
| 177 | "id": "change_dispatch_skipped_history", "severity": "warning", |
| 178 | "impact": str(baseline.get("message") or ""), |
| 179 | "fix": (f"if those reactions matter, replay them once with " |
| 180 | f"{object_change_dispatch.FROM_ENV}=beginning after removing the " |
| 181 | f"dispatch cursor (read docs/logic-decisions.md #9 first)"), |
| 182 | }) |
| 183 | if cron and not croniter_available: |
| 184 | problems.append({ |
| 185 | "id": "cron_needs_croniter", "severity": "error", |
| 186 | "impact": (f"{len(cron)} active cron schedule(s) ({_names(_task_names(cron))}) " |
| 187 | "can never run: croniter is not installed, so the daemon " |
| 188 | "cannot compute their next run"), |
| 189 | "fix": "pip install -e '.[scheduler]' (croniter) in the server's virtualenv", |
| 190 | }) |
| 191 | if (active or replay_on) and not daemon_running: |
| 192 | work = [] |
| 193 | if active: |
| 194 | work.append(f"{len(active)} active scheduled task(s)") |
| 195 | if replay_on: |
| 196 | work.append("the change-dispatch replay") |
| 197 | seen = ("no daemon has ever run against this data dir" if last_seen is None |
| 198 | else f"the daemon was last seen {current - last_seen}s ago") |
| 199 | problems.append({ |
| 200 | "id": "daemon_not_running", "severity": "error", |
| 201 | "impact": f"{' and '.join(work)} need the daemon, and {seen}", |
| 202 | "fix": "run `python object_daemon.py` as a service alongside the server", |
| 203 | }) |
| 204 | |
| 205 | return { |
| 206 | "status": "degraded" if any(p["severity"] == "error" for p in problems) else "ok", |
| 207 | "handlers": { |
| 208 | "objects": len(handler_ids), |
| 209 | "event_handlers_enabled": http_on, |
| 210 | "change_dispatch_enabled": replay_on, |
| 211 | "change_dispatch_baseline": baseline, |
| 212 | }, |
| 213 | "schedules": { |
| 214 | "active": len(active), |
| 215 | "active_cron": len(cron), |
| 216 | "croniter_available": croniter_available, |
| 217 | }, |
| 218 | "daemon": { |
| 219 | "running": daemon_running, |
| 220 | "last_seen": _epoch_iso(last_seen), |
| 221 | }, |
| 222 | "problems": problems, |
| 223 | } |
| 224 | |
| 225 | |
| 226 | def _task_names(tasks: Iterable[Mapping[str, Any]]) -> list[str]: |
| 227 | return sorted(str(t.get("id") or t.get("object_id") or "?") for t in tasks) |
| 228 | |
| 229 | |
| 230 | def _names(items: list[str], limit: int = 6) -> str: |
| 231 | shown = ", ".join(items[:limit]) |
| 232 | return shown + (f", and {len(items) - limit} more" if len(items) > limit else "") |
| 233 | |
| 234 | |
| 235 | def _scheduler_status(base_dir: Path, source_present: bool, now: int) -> dict[str, Any]: |
| 236 | rows, invalid = _prefixed_json_rows(base_dir, "scheduler", "task_") |
| 237 | by_status = _status_counts(rows) |
| 238 | active_rows = [row for row in rows if _status_name(row.get("status")) == "active"] |
| 239 | next_runs = [_coerce_epoch(row.get("next_run")) for row in active_rows] |
| 240 | next_runs = [value for value in next_runs if value is not None] |
| 241 | due_runs = [value for value in next_runs if value <= now] |
| 242 | future_runs = [value for value in next_runs if value > now] |
| 243 | earliest = min(next_runs) if next_runs else None |
| 244 | |
| 245 | return { |
| 246 | "object_id": "scheduler", |
| 247 | "source_present": source_present, |
| 248 | "state_present": _state_present(base_dir, "scheduler"), |
| 249 | "tasks": { |
| 250 | "total": len(rows) + invalid, |
| 251 | "valid": len(rows), |
| 252 | "invalid": invalid, |
| 253 | "by_status": by_status, |
| 254 | "active": len(active_rows), |
| 255 | "due": len(due_runs), |
| 256 | "future": len(future_runs), |
| 257 | "missing_next_run": len(active_rows) - len(next_runs), |
| 258 | "next_run": earliest, |
| 259 | "next_run_iso": _epoch_iso(earliest), |
| 260 | }, |
| 261 | } |
| 262 | |
| 263 | |
| 264 | def _queue_status(base_dir: Path, source_present: bool, now: int) -> dict[str, Any]: |
| 265 | rows, invalid = _prefixed_json_rows(base_dir, "queue", "msg_") |
| 266 | by_status = _status_counts(rows) |
| 267 | pending = [row for row in rows if _status_name(row.get("status")) == "pending"] |
| 268 | visible = [] |
| 269 | delayed = [] |
| 270 | expired = [] |
| 271 | |
| 272 | for row in pending: |
| 273 | expires_at = _coerce_epoch(row.get("expires_at")) |
| 274 | visible_after = _coerce_epoch(row.get("visible_after")) or 0 |
| 275 | if expires_at is not None and expires_at < now: |
| 276 | expired.append(row) |
| 277 | elif visible_after > now: |
| 278 | delayed.append((row, visible_after)) |
| 279 | else: |
| 280 | visible.append(row) |
| 281 | |
| 282 | next_visible = min((visible_after for _row, visible_after in delayed), default=None) |
| 283 | |
| 284 | return { |
| 285 | "object_id": "queue", |
| 286 | "source_present": source_present, |
| 287 | "state_present": _state_present(base_dir, "queue"), |
| 288 | "messages": { |
| 289 | "total": len(rows) + invalid, |
| 290 | "valid": len(rows), |
| 291 | "invalid": invalid, |
| 292 | "by_status": by_status, |
| 293 | "pending_visible": len(visible), |
| 294 | "pending_delayed": len(delayed), |
| 295 | "expired_pending": len(expired), |
| 296 | "next_visible_at": next_visible, |
| 297 | "next_visible_at_iso": _epoch_iso(next_visible), |
| 298 | }, |
| 299 | } |
| 300 | |
| 301 | |
| 302 | def _events_status(base_dir: Path, source_present: bool) -> dict[str, Any]: |
| 303 | event_rows, invalid_events = _prefixed_json_rows(base_dir, object_events.EVENTS_OBJECT_ID, "event_") |
| 304 | subscription_rows, invalid_subscriptions = _prefixed_json_rows( |
| 305 | base_dir, |
| 306 | object_events.EVENTS_OBJECT_ID, |
| 307 | "sub_", |
| 308 | ) |
| 309 | sorted_events = sorted( |
| 310 | event_rows, |
| 311 | key=lambda item: (_coerce_epoch(item.get("timestamp")) or 0, str(item.get("id", ""))), |
| 312 | reverse=True, |
| 313 | ) |
| 314 | latest = _sanitize_event(sorted_events[0]) if sorted_events else None |
| 315 | by_event_type = _counts_by_field(event_rows, "event_type") |
| 316 | by_delivery_status = _delivery_status_counts(subscription_rows) |
| 317 | |
| 318 | return { |
| 319 | "object_id": object_events.EVENTS_OBJECT_ID, |
| 320 | "source_present": source_present, |
| 321 | "state_present": _state_present(base_dir, object_events.EVENTS_OBJECT_ID), |
| 322 | "events": { |
| 323 | "total": len(event_rows) + invalid_events, |
| 324 | "valid": len(event_rows), |
| 325 | "invalid": invalid_events, |
| 326 | "by_event_type": by_event_type, |
| 327 | "latest": latest, |
| 328 | }, |
| 329 | "subscriptions": { |
| 330 | "total": len(subscription_rows) + invalid_subscriptions, |
| 331 | "valid": len(subscription_rows), |
| 332 | "invalid": invalid_subscriptions, |
| 333 | "by_event_type": _counts_by_field(subscription_rows, "event_type"), |
| 334 | "by_delivery_status": by_delivery_status, |
| 335 | "pending_deliveries": sum( |
| 336 | _pending_delivery_count(subscription, event_rows) |
| 337 | for subscription in subscription_rows |
| 338 | ), |
| 339 | }, |
| 340 | } |
| 341 | |
| 342 | |
| 343 | def _cleanup_status( |
| 344 | *, |
| 345 | rate_limit_dir: Path | str | None, |
| 346 | event_keep_count: int | None, |
| 347 | event_keep_seconds: int | None, |
| 348 | ) -> dict[str, Any]: |
| 349 | return { |
| 350 | "event_retention": { |
| 351 | "keep_count": event_keep_count, |
| 352 | "keep_seconds": event_keep_seconds, |
| 353 | }, |
| 354 | "rate_limit_files": _rate_limit_file_count(rate_limit_dir), |
| 355 | } |
| 356 | |
| 357 | |
| 358 | def _prefixed_json_rows( |
| 359 | base_dir: Path, |
| 360 | object_id: str, |
| 361 | prefix: str, |
| 362 | ) -> tuple[list[dict[str, Any]], int]: |
| 363 | rows: list[dict[str, Any]] = [] |
| 364 | invalid = 0 |
| 365 | |
| 366 | for key, value in object_state.get_object_state(object_id, base_dir).items(): |
| 367 | if not key.startswith(prefix): |
| 368 | continue |
| 369 | item = _json_mapping(value) |
| 370 | if item is None: |
| 371 | invalid += 1 |
| 372 | else: |
| 373 | rows.append(item) |
| 374 | |
| 375 | return rows, invalid |
| 376 | |
| 377 | |
| 378 | def _json_mapping(value: Any) -> dict[str, Any] | None: |
| 379 | if isinstance(value, Mapping): |
| 380 | return dict(value) |
| 381 | if not isinstance(value, str): |
| 382 | return None |
| 383 | try: |
| 384 | loaded = json.loads(value) |
| 385 | except (TypeError, json.JSONDecodeError): |
| 386 | return None |
| 387 | if not isinstance(loaded, Mapping): |
| 388 | return None |
| 389 | return dict(loaded) |
| 390 | |
| 391 | |
| 392 | def _status_counts(rows: Iterable[Mapping[str, Any]]) -> dict[str, int]: |
| 393 | return dict(sorted(Counter(_status_name(row.get("status")) for row in rows).items())) |
| 394 | |
| 395 | |
| 396 | def _counts_by_field(rows: Iterable[Mapping[str, Any]], field: str) -> dict[str, int]: |
| 397 | return dict(sorted(Counter(_text_or_unknown(row.get(field)) for row in rows).items())) |
| 398 | |
| 399 | |
| 400 | def _delivery_status_counts(subscriptions: Iterable[Mapping[str, Any]]) -> dict[str, int]: |
| 401 | counts = Counter() |
| 402 | for subscription in subscriptions: |
| 403 | delivery = subscription.get("delivery") |
| 404 | if isinstance(delivery, Mapping): |
| 405 | counts[_status_name(delivery.get("status"), default="idle")] += 1 |
| 406 | else: |
| 407 | counts["idle"] += 1 |
| 408 | return dict(sorted(counts.items())) |
| 409 | |
| 410 | |
| 411 | def _pending_delivery_count( |
| 412 | subscription: Mapping[str, Any], |
| 413 | events: Iterable[Mapping[str, Any]], |
| 414 | ) -> int: |
| 415 | event_type = subscription.get("event_type") |
| 416 | matching = [ |
| 417 | event for event in events |
| 418 | if event.get("event_type") == event_type |
| 419 | ] |
| 420 | matching.sort( |
| 421 | key=lambda item: (_coerce_epoch(item.get("timestamp")) or 0, str(item.get("id", ""))) |
| 422 | ) |
| 423 | if not matching: |
| 424 | return 0 |
| 425 | |
| 426 | last_event_id = subscription.get("last_event_id") |
| 427 | if not last_event_id: |
| 428 | return len(matching) |
| 429 | |
| 430 | for index, event in enumerate(matching): |
| 431 | if event.get("id") == last_event_id: |
| 432 | return max(0, len(matching) - index - 1) |
| 433 | return len(matching) |
| 434 | |
| 435 | |
| 436 | def _sanitize_event(event: Mapping[str, Any]) -> dict[str, Any]: |
| 437 | return { |
| 438 | "id": event.get("id"), |
| 439 | "event_type": event.get("event_type"), |
| 440 | "source": event.get("source"), |
| 441 | "actor": event.get("actor"), |
| 442 | "timestamp": _coerce_epoch(event.get("timestamp")), |
| 443 | "created_at": event.get("created_at"), |
| 444 | } |
| 445 | |
| 446 | |
| 447 | def _status_name(value: Any, *, default: str = "unknown") -> str: |
| 448 | if not isinstance(value, str): |
| 449 | return default |
| 450 | stripped = value.strip().lower() |
| 451 | return stripped or default |
| 452 | |
| 453 | |
| 454 | def _text_or_unknown(value: Any) -> str: |
| 455 | if not isinstance(value, str): |
| 456 | return "unknown" |
| 457 | stripped = value.strip() |
| 458 | return stripped or "unknown" |
| 459 | |
| 460 | |
| 461 | def _coerce_epoch(value: Any) -> int | None: |
| 462 | if value is None or isinstance(value, bool): |
| 463 | return None |
| 464 | try: |
| 465 | return int(float(value)) |
| 466 | except (TypeError, ValueError): |
| 467 | return None |
| 468 | |
| 469 | |
| 470 | def _epoch_iso(value: int | None) -> str | None: |
| 471 | if value is None: |
| 472 | return None |
| 473 | return _utc_timestamp(value) |
| 474 | |
| 475 | |
| 476 | def _utc_timestamp(epoch: int) -> str: |
| 477 | return datetime.fromtimestamp(epoch, tz=timezone.utc).isoformat() |
| 478 | |
| 479 | |
| 480 | def _state_present(base_dir: Path, object_id: str) -> bool: |
| 481 | return object_state.object_state_file(object_id, base_dir).exists() |
| 482 | |
| 483 | |
| 484 | def _rate_limit_file_count(rate_limit_dir: Path | str | None) -> int: |
| 485 | if rate_limit_dir is None: |
| 486 | return 0 |
| 487 | directory = Path(rate_limit_dir) |
| 488 | if not directory.exists(): |
| 489 | return 0 |
| 490 | return sum(1 for path in directory.glob("*.txt") if path.is_file()) |