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,135 @@
|
||||
"""Which modules are on, right now (APPS_PLATFORM D-4, D-19, §5.3).
|
||||
|
||||
effective(m) = entitled(m) and enabled(m) and every dependency of m is effective
|
||||
|
||||
- enabled: the site_modules table (no row = enabled). Core modules are always enabled.
|
||||
- entitled: from the license (step 1.4). Until then every module is entitled.
|
||||
- The enabled map is cached in memory; set_enabled() updates the cache in the same
|
||||
request, so a change applies at once, with no restart. Listeners (the worker
|
||||
supervisor) are told about every change.
|
||||
|
||||
module_required(key) is the FastAPI dependency main.py adds to each non-core router.
|
||||
|
||||
Agent notes:
|
||||
- Always change enablement through set_enabled(), never by writing SiteModule rows,
|
||||
or the cache and the workers won't follow.
|
||||
- Step 1.4 replaces `_entitled()` with the license evaluation (entitled ∪ free tier).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import threading
|
||||
from typing import Callable
|
||||
|
||||
from fastapi import Depends
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from core.errors import XeniaError
|
||||
from core.modules.registry import registry
|
||||
from database import get_db
|
||||
|
||||
logger = logging.getLogger("xenia.modules")
|
||||
|
||||
_lock = threading.Lock()
|
||||
_enabled_cache: dict[str, bool] | None = None
|
||||
_listeners: list[Callable[[frozenset[str]], None]] = []
|
||||
|
||||
|
||||
def invalidate() -> None:
|
||||
global _enabled_cache
|
||||
with _lock:
|
||||
_enabled_cache = None
|
||||
|
||||
|
||||
def add_listener(fn: Callable[[frozenset[str]], None]) -> None:
|
||||
"""fn(effective_keys) is called after every enablement change."""
|
||||
_listeners.append(fn)
|
||||
|
||||
|
||||
def _load(db: Session) -> dict[str, bool]:
|
||||
from models.site_module import SiteModule
|
||||
rows = {r.key: bool(r.enabled) for r in db.query(SiteModule).all()}
|
||||
return {k: (True if m.kind == "core" else rows.get(k, True)) for k, m in registry().items()}
|
||||
|
||||
|
||||
def enabled_map(db: Session | None = None) -> dict[str, bool]:
|
||||
global _enabled_cache
|
||||
with _lock:
|
||||
cached = _enabled_cache
|
||||
if cached is not None:
|
||||
return cached
|
||||
if db is None:
|
||||
from database import SessionLocal
|
||||
own = SessionLocal()
|
||||
try:
|
||||
loaded = _load(own)
|
||||
finally:
|
||||
own.close()
|
||||
else:
|
||||
loaded = _load(db)
|
||||
with _lock:
|
||||
_enabled_cache = loaded
|
||||
return loaded
|
||||
|
||||
|
||||
def _entitled(key: str) -> bool:
|
||||
return True # >>> step 1.4: license entitlements ∪ free tier
|
||||
|
||||
|
||||
def effective_set(db: Session | None = None) -> frozenset[str]:
|
||||
reg = registry()
|
||||
enabled = enabled_map(db)
|
||||
memo: dict[str, bool] = {}
|
||||
|
||||
def eff(k: str) -> bool:
|
||||
if k not in memo:
|
||||
memo[k] = _entitled(k) and enabled.get(k, True) and all(eff(d) for d in reg[k].depends)
|
||||
return memo[k]
|
||||
|
||||
return frozenset(k for k in reg if eff(k))
|
||||
|
||||
|
||||
def is_effective(key: str, db: Session | None = None) -> bool:
|
||||
return key in effective_set(db)
|
||||
|
||||
|
||||
def set_enabled(db: Session, key: str, enabled: bool, user_id: int | None = None) -> frozenset[str]:
|
||||
"""Enable/disable a module (commits). Returns the new effective set."""
|
||||
from models.site_module import SiteModule
|
||||
global _enabled_cache
|
||||
reg = registry()
|
||||
if key not in reg:
|
||||
raise XeniaError("module.unknown", module=key)
|
||||
if not reg[key].can_disable and not enabled:
|
||||
raise XeniaError("module.cannot_disable", module=key)
|
||||
row = db.get(SiteModule, key)
|
||||
if row is None:
|
||||
row = SiteModule(key=key)
|
||||
db.add(row)
|
||||
row.enabled = enabled
|
||||
row.updated_by = user_id if user_id else None
|
||||
db.commit()
|
||||
loaded = _load(db)
|
||||
with _lock:
|
||||
_enabled_cache = loaded
|
||||
eff = effective_set(db)
|
||||
logger.info("module.%s key=%s by_user=%s effective=%d", "enabled" if enabled else "disabled", key, user_id, len(eff))
|
||||
for fn in list(_listeners):
|
||||
try:
|
||||
fn(eff)
|
||||
except Exception:
|
||||
logger.exception("module listener failed")
|
||||
return eff
|
||||
|
||||
|
||||
def module_required(key: str):
|
||||
"""FastAPI dependency: the endpoint answers `module.disabled` unless the module is effective."""
|
||||
if key not in registry():
|
||||
raise ValueError(f"module_required: unknown module {key!r}")
|
||||
|
||||
def _check(db: Session = Depends(get_db)) -> None:
|
||||
if not is_effective(key, db):
|
||||
raise XeniaError("module.disabled", module=key)
|
||||
|
||||
_check.__name__ = f"module_required_{key}"
|
||||
return _check
|
||||
Reference in New Issue
Block a user