"""Starts and stops module workers as modules turn on and off (D-19). A worker is an async function named in a manifest ("package.module:function") that runs forever. While its module is effective it runs as an asyncio task; when the module stops being effective the task is cancelled. Enablement changes arrive from request threads, so reconcile() is scheduled onto the event loop thread-safely. Agent notes: - start(loop) is called once from main.py's lifespan, after the schema is ready. - A worker that crashes is logged and restarted after a short pause (it must never take the backend down, Rule 8). """ from __future__ import annotations import asyncio import importlib import logging from core.modules import state from core.modules.registry import registry logger = logging.getLogger("xenia.workers") _loop: asyncio.AbstractEventLoop | None = None _tasks: dict[str, asyncio.Task] = {} # "module:worker" -> task RESTART_DELAY_S = 30 def _resolve(spec: str): mod, func = spec.split(":", 1) return getattr(importlib.import_module(mod), func) async def _guarded(name: str, fn): while True: try: await fn() logger.warning("worker.exited name=%s (restarting in %ss)", name, RESTART_DELAY_S) except asyncio.CancelledError: raise except Exception: logger.exception("worker.crashed name=%s (restarting in %ss)", name, RESTART_DELAY_S) await asyncio.sleep(RESTART_DELAY_S) def _reconcile(effective: frozenset[str]) -> None: wanted = {f"{m.key}:{w}": w for m in registry().values() if m.key in effective for w in m.workers} for name in list(_tasks): if name not in wanted: _tasks.pop(name).cancel() logger.info("worker.stopped name=%s", name) for name, spec in wanted.items(): if name not in _tasks or _tasks[name].done(): _tasks[name] = asyncio.get_running_loop().create_task(_guarded(name, _resolve(spec))) logger.info("worker.started name=%s", name) def _on_change(effective: frozenset[str]) -> None: if _loop is None or _loop.is_closed(): return try: running = asyncio.get_running_loop() except RuntimeError: running = None if running is _loop: _reconcile(effective) else: _loop.call_soon_threadsafe(_reconcile, effective) def start(loop: asyncio.AbstractEventLoop) -> None: global _loop _loop = loop state.add_listener(_on_change) _reconcile(state.effective_set()) def running() -> list[str]: return sorted(n for n, t in _tasks.items() if not t.done()) def stop_all() -> None: for t in _tasks.values(): t.cancel() _tasks.clear()