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:
2026-11-12 17:46:52 +02:00
co-authored by Claude Opus 5.5
parent 968b6c78fb
commit 231a97c186
69 changed files with 1396 additions and 195 deletions
+2
View File
@@ -42,6 +42,8 @@ CODES: dict[str, tuple[int, str]] = {
"access.override_possible": (403, "A manager can approve this ({key})."),
"module.disabled": (403, "The {module} module is turned off."),
"module.not_licensed": (402, "This site's license doesn't include {module}."),
"module.unknown": (404, "There is no module {module}."),
"module.cannot_disable": (400, "{module} is part of the core and can't be turned off."),
"license.limit_reached": (402, "License limit reached for {limit} ({max})."),
"license.expired": (402, "The license has expired."),
# identity
+1
View File
@@ -0,0 +1 @@
"""Module system: manifests, registry, enablement, gating, workers (APPS_PLATFORM §4, §5.3, D-19)."""
+121
View File
@@ -0,0 +1,121 @@
"""Platform endpoints (APPS_PLATFORM §4.1, §7.2, §9): /api/platform/...
GET /bootstrap what every frontend loads first: venue (name, tz, language,
currency), the effective modules, and, if logged in, the user,
their language and permission keys. Works without login (login
screens need the venue language and zone).
GET /modules the full catalogue with each module's state (logged in).
PUT /modules/{key} enable/disable a module; applies at once (D-19).
Agent notes:
- `permissions` is the caller's ROLE TEMPLATE (manifest Perm.roles) until step 1.5
adds per-user grants; superadmin gets every key (D-7).
- Access: PUT uses require_settings_manager until step 1.5 switches it to
require("core.modules.manage").
- `entitled` is True for every module until step 1.4.
"""
from __future__ import annotations
from typing import Optional
from fastapi import APIRouter, Depends
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from pydantic import BaseModel
from sqlalchemy.orm import Session
from core import i18n, timeutil
from core.modules import state
from core.modules.registry import all_permissions, registry
from database import get_db
from routers.deps import get_current_user, require_settings_manager
router = APIRouter()
_optional_bearer = HTTPBearer(auto_error=False)
def permission_keys_for(user) -> list[str]:
"""Role-template keys of a user (step 1.5 adds explicit per-user grants)."""
perms = all_permissions()
if getattr(user, "role", None) == "superadmin":
return sorted(perms)
return sorted(k for k, (p, _m) in perms.items() if user.role in p.roles)
def _setting(db: Session, key: str, default: str) -> str:
from models.settings import PosSettings
row = db.query(PosSettings).filter(PosSettings.key == key).first()
return row.value if row and row.value else default
def _module_out(m, enabled: dict, effective: frozenset) -> dict:
return {
"key": m.key, "kind": m.kind, "name": m.name, "description": m.description,
"depends": list(m.depends),
"entitled": True,
"enabled": enabled.get(m.key, True),
"effective": m.key in effective,
"can_disable": m.can_disable,
"permissions": [{"key": p.key, "description": p.description, "roles": list(p.roles)} for p in m.permissions],
"limits": [{"key": lim.key, "description": lim.description, "free": lim.free,
"licensed_default": lim.licensed_default} for lim in m.limits],
"settings": [{"key": sd.key, "type": sd.type, "default": sd.default, "description": sd.description}
for sd in m.settings],
"device_app": ({"login_modes": list(m.device_app.login_modes), "scope": list(m.device_app.scope)}
if m.device_app else None),
"workers": len(m.workers),
}
@router.get("/bootstrap")
def bootstrap(
db: Session = Depends(get_db),
credentials: Optional[HTTPAuthorizationCredentials] = Depends(_optional_bearer),
):
user = None
if credentials:
try:
user = get_current_user(credentials, db)
except Exception:
user = None # an expired/invalid token just means "not logged in" here
effective = state.effective_set(db)
out = {
"venue": {
"name": _setting(db, "venue.name", "") or None,
"timezone": timeutil.venue_tz().key,
"language": i18n.venue_language(),
"currency": _setting(db, "venue.currency", "EUR"),
"business_day_rollover_hour": timeutil.rollover_hour(),
},
"modules": [{"key": m.key, "kind": m.kind} for m in registry().values() if m.key in effective],
"languages": list(i18n.SUPPORTED_LANGUAGES),
"user": None,
"language": i18n.venue_language(),
"permissions": [],
}
if user is not None:
out["user"] = {"id": user.id, "username": user.username, "full_name": user.full_name,
"role": user.role, "language": getattr(user, "language", None)}
out["language"] = i18n.user_language(user)
out["permissions"] = [k for k in permission_keys_for(user)
if all_permissions()[k][1] in effective]
return out
@router.get("/modules")
def list_modules(db: Session = Depends(get_db), user=Depends(get_current_user)):
enabled = state.enabled_map(db)
effective = state.effective_set(db)
return {"modules": [_module_out(m, enabled, effective) for m in registry().values()],
"permissions": permission_keys_for(user)}
class ModuleToggle(BaseModel):
enabled: bool
@router.put("/modules/{key}")
def set_module(key: str, body: ModuleToggle, db: Session = Depends(get_db),
user=Depends(require_settings_manager)):
effective = state.set_enabled(db, key, body.enabled, user_id=getattr(user, "id", None) or None)
enabled = state.enabled_map(db)
return _module_out(registry()[key], enabled, effective)
+11
View File
@@ -0,0 +1,11 @@
"""The free tier (APPS_PLATFORM D-5): what a site gets with no valid license.
THE ONE PLACE to change what is free. Same shape as the license token's `modules` map:
{module key: {"limits": {...}}}. Core modules are always included.
Used from step 1.4 (entitlements): effective = (entitled ∪ FREE_TIER) ∩ enabled.
"""
FREE_TIER: dict[str, dict] = {
"core": {},
"catalog": {},
"history": {"limits": {"history_days": 31}},
}
+85
View File
@@ -0,0 +1,85 @@
"""What a module manifest is made of (APPS_PLATFORM §4.1, D-19).
A module = one thing the venue can have or not: a manager feature (tabs, CRM...), an
app a device runs (KDS, POS...), or an integration (caller ID, fiscal...). Everything
is a module, including `core`. Each one is described by modules/<key>/manifest.py,
which exports MODULE = Module(...).
Agent notes:
- Display text (name, descriptions) is the English source. The i18n key is derived:
module.<key>.name, perm.<perm key>, limit.<key>.<limit>, setting.<setting key>.
- `routers` lists Mounts: the module's existing router objects and their URL prefix.
main.py mounts every Mount from the registry; non-core mounts get
Depends(module_required(key)) so a disabled module answers `module.disabled`.
- `workers` are "package.module:function" strings naming async functions that run
forever. The supervisor imports and starts them while the module is effective and
cancels them when it isn't. Strings keep manifests cheap to import.
- Permission keys are "<module>.<area>.<action>" (or "<module>.<action>"). Role lists
are the default role template (superadmin always has every key, D-7, so it's
never listed).
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Literal, Optional
Kind = Literal["core", "feature", "app", "integration"]
SettingType = Literal["bool", "int", "str", "json", "enum"]
@dataclass(frozen=True)
class Perm:
key: str
description: str
roles: tuple[str, ...] = ()
@dataclass(frozen=True)
class Limit:
key: str
description: str
free: Optional[int] = 0 # value in the free tier (D-5); None = unlimited
licensed_default: Optional[int] = None # value when licensed but the token sets none; None = unlimited
@dataclass(frozen=True)
class SettingDef:
key: str
default: str # stored as text in pos_settings, like every setting
description: str
type: SettingType = "str"
choices: tuple[str, ...] = () # for type "enum"
@dataclass(frozen=True)
class DeviceApp:
"""For kind="app" modules that run on a paired device (step 1.8, D-8)."""
login_modes: tuple[str, ...] = ("pin", "tap", "password")
scope: tuple[str, ...] = () # permission-key patterns the device token may use
@dataclass(frozen=True)
class Mount:
module: str # python import path, e.g. "routers.tabs"
prefix: str # URL prefix, e.g. "/api/tabs"
attr: str = "router" # attribute holding the APIRouter
tags: tuple[str, ...] = ()
@dataclass(frozen=True)
class Module:
key: str
kind: Kind
name: str
description: str = ""
depends: tuple[str, ...] = ()
permissions: tuple[Perm, ...] = ()
limits: tuple[Limit, ...] = ()
settings: tuple[SettingDef, ...] = ()
device_app: Optional[DeviceApp] = None
routers: tuple[Mount, ...] = ()
workers: tuple[str, ...] = () # "package.module:async_function", imported when started
@property
def can_disable(self) -> bool:
return self.kind != "core"
+136
View File
@@ -0,0 +1,136 @@
"""Loads and validates every module manifest (APPS_PLATFORM §4.1).
registry() returns the validated, immutable catalogue, built once per process from
local_backend/modules/<key>/manifest.py. Any problem raises ManifestError at startup,
so a broken manifest never reaches a running site.
Checks: key format and folder name, kind, unique keys, dependencies exist and have no
cycles, permission keys prefixed by their module and unique, roles exist, limit keys
unique per module, setting keys unique across modules, every Mount importable and
claimed by exactly one module, device_app only on apps, workers given as "mod:func".
"""
from __future__ import annotations
import importlib
import pkgutil
import re
from functools import lru_cache
from pathlib import Path
from core.modules.model import Module
MODULES_DIR = Path(__file__).resolve().parents[2] / "modules"
_KEY = re.compile(r"^[a-z][a-z0-9_]*$")
_KINDS = {"core", "feature", "app", "integration"}
class ManifestError(ValueError):
pass
def _discover() -> list[Module]:
found = []
for info in pkgutil.iter_modules([str(MODULES_DIR)]):
if not info.ispkg:
continue
mod = importlib.import_module(f"modules.{info.name}.manifest")
m = getattr(mod, "MODULE", None)
if not isinstance(m, Module):
raise ManifestError(f"modules/{info.name}/manifest.py must define MODULE = Module(...)")
if m.key != info.name:
raise ManifestError(f"modules/{info.name}: MODULE.key is {m.key!r}, must equal the folder name")
found.append(m)
return found
def validate(modules: list[Module], check_imports: bool = True) -> dict[str, Module]:
from roles import VALID_ROLES
by_key: dict[str, Module] = {}
perm_keys: set[str] = set()
setting_keys: dict[str, str] = {}
mounts: dict[tuple[str, str], str] = {}
for m in modules:
where = f"module {m.key!r}"
if not _KEY.match(m.key):
raise ManifestError(f"{where}: key must match {_KEY.pattern}")
if m.key in by_key:
raise ManifestError(f"{where}: duplicate key")
if m.kind not in _KINDS:
raise ManifestError(f"{where}: kind {m.kind!r} not in {sorted(_KINDS)}")
if m.device_app and m.kind != "app":
raise ManifestError(f"{where}: device_app is only for kind='app'")
for p in m.permissions:
if not p.key.startswith(m.key + "."):
raise ManifestError(f"{where}: permission {p.key!r} must start with {m.key + '.'!r}")
if p.key in perm_keys:
raise ManifestError(f"{where}: duplicate permission {p.key!r}")
perm_keys.add(p.key)
bad = set(p.roles) - (set(VALID_ROLES) - {"superadmin"})
if bad:
raise ManifestError(f"{where}: permission {p.key!r} has unknown roles {sorted(bad)} "
"(superadmin is implicit and never listed)")
limit_keys = [lim.key for lim in m.limits]
if len(limit_keys) != len(set(limit_keys)):
raise ManifestError(f"{where}: duplicate limit keys")
for sd in m.settings:
if sd.key in setting_keys:
raise ManifestError(f"{where}: setting {sd.key!r} already declared by {setting_keys[sd.key]!r}")
if sd.type == "enum" and sd.default not in sd.choices:
raise ManifestError(f"{where}: setting {sd.key!r} default not in choices")
setting_keys[sd.key] = m.key
for mt in m.routers:
ident = (mt.module, mt.attr)
if ident in mounts:
raise ManifestError(f"{where}: router {mt.module}.{mt.attr} already mounted by {mounts[ident]!r}")
mounts[ident] = m.key
if check_imports:
try:
obj = getattr(importlib.import_module(mt.module), mt.attr)
except (ImportError, AttributeError) as e:
raise ManifestError(f"{where}: cannot import router {mt.module}.{mt.attr}: {e}") from e
if not hasattr(obj, "routes"):
raise ManifestError(f"{where}: {mt.module}.{mt.attr} is not an APIRouter")
for w in m.workers:
if ":" not in w:
raise ManifestError(f"{where}: worker {w!r} must be 'package.module:function'")
by_key[m.key] = m
for m in modules:
for d in m.depends:
if d not in by_key:
raise ManifestError(f"module {m.key!r}: depends on unknown module {d!r}")
# cycles
state: dict[str, int] = {}
def visit(k, path):
if state.get(k) == 1:
raise ManifestError(f"dependency cycle: {' -> '.join(path + [k])}")
if state.get(k) == 2:
return
state[k] = 1
for d in by_key[k].depends:
visit(d, path + [k])
state[k] = 2
for k in by_key:
visit(k, [])
return by_key
@lru_cache(maxsize=1)
def registry() -> dict[str, Module]:
"""The validated catalogue: {key: Module}, in discovery (alphabetical) order."""
return validate(_discover())
def setting_defs() -> dict:
"""{setting key: (SettingDef, module key)} across all modules."""
return {sd.key: (sd, m.key) for m in registry().values() for sd in m.settings}
def all_permissions() -> dict:
"""{permission key: (Perm, module key)} across all modules."""
return {p.key: (p, m.key) for m in registry().values() for p in m.permissions}
+135
View File
@@ -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
+85
View File
@@ -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()