feat(backend): module registry, manifests, enable/disable without restart
Platform v2 step 1.3 (APPS_PLATFORM §4, §5.3, D-4, D-19).
- core/modules: Module/Perm/Limit/SettingDef/DeviceApp/Mount model; registry
that discovers modules/<key>/manifest.py and validates it (keys, kinds,
dependencies and cycles, permission prefixes and roles, unique settings,
each router claimed once and importable, device_app only on apps, workers);
free_tier.py (D-5 constant, used from 1.4)
- 25 manifests (the §4.2 map) with permission keys + default roles derived
from today's perm_* meaning, limits, device apps and the 55 settings
- main.py mounts every router from the manifests; non-core routers carry
Depends(module_required(key)) -> 403 module.disabled while off
- site_modules table (revision 0004), cached enablement; disabling a module
also turns off modules that depend on it; core can't be disabled
- worker supervisor: connect_menu / connect_orders / connect_remote are now
separate workers (v1's single _connect_loop split), started and stopped as
their modules turn on and off; crashes are logged and restarted
- GET /api/platform/bootstrap (venue name/tz/language/currency, effective
modules, user, language, role-template permission keys), GET /modules,
PUT /modules/{key}
- settings API derives its key list and defaults from the manifests
- reports router split: history endpoints on history_router (`history`
module, free tier later) under the same /api/reports prefix
- tests: registry validation, mount coverage, toggle round-trip, dependency
propagation, bootstrap/catalogue shape, supervisor; pack rule CS-13
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
"""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()
|
||||
Reference in New Issue
Block a user