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:
@@ -78,6 +78,8 @@ def _venue_time():
|
||||
yield
|
||||
timeutil.invalidate()
|
||||
i18n.invalidate()
|
||||
from core.modules import state as module_state
|
||||
module_state.invalidate() # module enablement is cached; each test starts from the DB
|
||||
|
||||
|
||||
# ── schema + per-test transaction ───────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
"""Module registry, enablement, gating, workers and bootstrap (plan step 1.3, D-19, §4)."""
|
||||
import asyncio
|
||||
import importlib
|
||||
import pkgutil
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
from fastapi import APIRouter
|
||||
|
||||
from core.modules import state, supervisor
|
||||
from core.modules.model import DeviceApp, Module, Mount, Perm, SettingDef
|
||||
from core.modules.registry import ManifestError, registry, validate
|
||||
|
||||
BACKEND = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
# ── registry ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_registry_has_the_section_4_2_map():
|
||||
expected = {"core", "history", "catalog", "ordering", "waiter_app", "reports", "pricing", "tabs", "crm",
|
||||
"expenses", "inventory", "staff_planning", "notes", "chat", "reservations", "kds", "pos_counter",
|
||||
"customer_display", "signage", "menu_tablet", "connect_menu", "connect_orders", "connect_remote",
|
||||
"caller_id", "fiscal"}
|
||||
assert set(registry()) == expected
|
||||
|
||||
|
||||
def test_every_router_in_routers_is_mounted_by_exactly_one_module():
|
||||
mounted = {(mt.module, mt.attr) for m in registry().values() for mt in m.routers}
|
||||
found = set()
|
||||
for info in pkgutil.iter_modules([str(BACKEND / "routers")]):
|
||||
mod = importlib.import_module(f"routers.{info.name}")
|
||||
for attr, obj in vars(mod).items():
|
||||
if isinstance(obj, APIRouter) and obj.routes and _defined_in(mod, attr):
|
||||
found.add((f"routers.{info.name}", attr))
|
||||
assert len(found) >= 30, f"scan found too few routers: {sorted(found)}"
|
||||
assert found - mounted == set(), f"routers not mounted by any manifest: {found - mounted}"
|
||||
|
||||
|
||||
def _defined_in(mod, attr):
|
||||
"""True unless the router object was imported from another module."""
|
||||
obj = getattr(mod, attr)
|
||||
for other in list(vars(mod).values()):
|
||||
if other is not obj and hasattr(other, attr) and getattr(other, attr) is obj:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _m(key="x", **kw):
|
||||
return Module(key=key, kind=kw.pop("kind", "feature"), name=key, **kw)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("modules,msg", [
|
||||
([_m("x", permissions=(Perm("y.do", "d"),))], "must start with"),
|
||||
([_m("x", depends=("nope",))], "unknown module"),
|
||||
([_m("a", depends=("b",)), _m("b", depends=("a",))], "cycle"),
|
||||
([_m("x", permissions=(Perm("x.do", "d", roles=("emperor",)),))], "unknown roles"),
|
||||
([_m("x", permissions=(Perm("x.do", "d", roles=("superadmin",)),))], "unknown roles"),
|
||||
([_m("a", settings=(SettingDef("s.k", "1", "d"),)), _m("b", settings=(SettingDef("s.k", "1", "d"),))], "already declared"),
|
||||
([_m("a", routers=(Mount("routers.tabs", "/a"),)), _m("b", routers=(Mount("routers.tabs", "/b"),))], "already mounted"),
|
||||
([_m("x", device_app=DeviceApp())], "only for kind='app'"),
|
||||
([_m("x"), _m("x")], "duplicate key"),
|
||||
([_m("Bad-Key")], "must match"),
|
||||
([_m("x", workers=("no_colon",))], "package.module:function"),
|
||||
([_m("x", settings=(SettingDef("x.e", "c", "d", type="enum", choices=("a", "b")),))], "not in choices"),
|
||||
])
|
||||
def test_bad_manifests_are_rejected(modules, msg):
|
||||
with pytest.raises(ManifestError, match=msg):
|
||||
validate(modules, check_imports=False)
|
||||
|
||||
|
||||
def test_unimportable_router_is_rejected():
|
||||
with pytest.raises(ManifestError, match="cannot import"):
|
||||
validate([_m("x", routers=(Mount("routers.no_such_router", "/x"),))])
|
||||
|
||||
|
||||
# ── enablement + gating ──────────────────────────────────────────────────────
|
||||
|
||||
def test_disabling_tabs_blocks_its_api_and_enabling_restores_it(client, make_user, login): # "done when"
|
||||
admin = make_user(role="superadmin")
|
||||
h = login(admin)
|
||||
assert client.get("/api/tabs/", headers=h).status_code == 200
|
||||
|
||||
r = client.put("/api/platform/modules/tabs", headers=h, json={"enabled": False})
|
||||
assert r.status_code == 200 and r.json()["enabled"] is False and r.json()["effective"] is False
|
||||
blocked = client.get("/api/tabs/", headers=h)
|
||||
assert blocked.status_code == 403
|
||||
assert blocked.json()["error"] == {"code": "module.disabled", "params": {"module": "tabs"},
|
||||
"message": "The tabs module is turned off."}
|
||||
|
||||
assert client.put("/api/platform/modules/tabs", headers=h, json={"enabled": True}).status_code == 200
|
||||
assert client.get("/api/tabs/", headers=h).status_code == 200
|
||||
|
||||
|
||||
def test_disabling_a_dependency_turns_dependents_off(client, make_user, login):
|
||||
h = login(make_user(role="superadmin"))
|
||||
client.put("/api/platform/modules/crm", headers=h, json={"enabled": False})
|
||||
mods = {m["key"]: m for m in client.get("/api/platform/modules", headers=h).json()["modules"]}
|
||||
assert mods["crm"]["effective"] is False
|
||||
assert mods["tabs"]["enabled"] is True and mods["tabs"]["effective"] is False # tabs needs crm
|
||||
assert client.get("/api/tabs/", headers=h).json()["error"]["code"] == "module.disabled"
|
||||
|
||||
|
||||
def test_core_cannot_be_disabled(client, make_user, login):
|
||||
r = client.put("/api/platform/modules/core", headers=login(make_user(role="superadmin")), json={"enabled": False})
|
||||
assert r.status_code == 400 and r.json()["error"]["code"] == "module.cannot_disable"
|
||||
|
||||
|
||||
def test_unknown_module(client, make_user, login):
|
||||
r = client.put("/api/platform/modules/nope", headers=login(make_user(role="superadmin")), json={"enabled": False})
|
||||
assert r.status_code == 404 and r.json()["error"]["code"] == "module.unknown"
|
||||
|
||||
|
||||
def test_waiter_cannot_toggle_modules(client, make_user, login):
|
||||
r = client.put("/api/platform/modules/tabs", headers=login(make_user(role="waiter")), json={"enabled": False})
|
||||
assert r.status_code == 403
|
||||
|
||||
|
||||
def test_core_routes_are_never_gated(client, make_user, login):
|
||||
assert client.get("/api/auth/me", headers=login(make_user(role="waiter"))).status_code == 200
|
||||
|
||||
|
||||
# ── bootstrap + catalogue ────────────────────────────────────────────────────
|
||||
|
||||
def test_bootstrap_without_login(client):
|
||||
r = client.get("/api/platform/bootstrap")
|
||||
assert r.status_code == 200
|
||||
b = r.json()
|
||||
assert b["venue"]["timezone"] == "Europe/Athens" and b["venue"]["currency"] == "EUR"
|
||||
assert b["venue"]["language"] == "en" and b["languages"] == ["el", "en"]
|
||||
assert b["user"] is None and b["permissions"] == []
|
||||
assert {"core", "ordering", "kds"} <= {m["key"] for m in b["modules"]}
|
||||
|
||||
|
||||
def test_bootstrap_with_login_lists_role_keys_of_effective_modules(client, make_user, login):
|
||||
waiter = make_user(role="waiter", language="el")
|
||||
b = client.get("/api/platform/bootstrap", headers=login(waiter)).json()
|
||||
assert b["user"]["role"] == "waiter" and b["language"] == "el"
|
||||
assert "waiter_app.access" in b["permissions"] and "ordering.orders.open" in b["permissions"]
|
||||
assert "core.settings.manage" not in b["permissions"]
|
||||
|
||||
admin = make_user(role="superadmin")
|
||||
client.put("/api/platform/modules/kds", headers=login(admin), json={"enabled": False})
|
||||
keys = client.get("/api/platform/bootstrap", headers=login(admin)).json()["permissions"]
|
||||
assert "core.modules.manage" in keys and "kds.access" not in keys
|
||||
|
||||
|
||||
def test_bootstrap_with_bad_token_is_anonymous(client):
|
||||
r = client.get("/api/platform/bootstrap", headers={"Authorization": "Bearer nonsense"})
|
||||
assert r.status_code == 200 and r.json()["user"] is None
|
||||
|
||||
|
||||
def test_modules_catalogue_shape(client, make_user, login):
|
||||
body = client.get("/api/platform/modules", headers=login(make_user(role="store_manager"))).json()
|
||||
kds = next(m for m in body["modules"] if m["key"] == "kds")
|
||||
assert kds["kind"] == "app" and kds["depends"] == ["ordering"]
|
||||
assert kds["limits"][0]["key"] == "devices" and kds["device_app"]["login_modes"]
|
||||
assert {"entitled", "enabled", "effective", "can_disable", "permissions", "settings"} <= set(kds)
|
||||
|
||||
|
||||
def test_settings_come_from_manifests(client, make_user, login):
|
||||
s = client.get("/api/settings/", headers=login(make_user(role="superadmin"))).json()
|
||||
assert s["venue.currency"]["value"] == "EUR"
|
||||
assert s["fiscal.type"]["value"] == "txt_file"
|
||||
assert "orders.courses_enabled" in s
|
||||
|
||||
|
||||
# ── workers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
def test_supervisor_starts_and_stops_workers(monkeypatch):
|
||||
calls = []
|
||||
|
||||
async def fake_worker():
|
||||
calls.append("run")
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
monkeypatch.setattr(supervisor, "_resolve", lambda spec: fake_worker)
|
||||
|
||||
async def scenario():
|
||||
supervisor._reconcile(frozenset({"connect_menu", "connect_orders"}))
|
||||
await asyncio.sleep(0)
|
||||
started = supervisor.running()
|
||||
supervisor._reconcile(frozenset({"connect_orders"}))
|
||||
await asyncio.sleep(0)
|
||||
after = supervisor.running()
|
||||
supervisor.stop_all()
|
||||
return started, after
|
||||
|
||||
started, after = asyncio.run(scenario())
|
||||
assert started == ["connect_menu:services.cloud_sync:menu_push_worker",
|
||||
"connect_orders:services.cloud_sync:order_pull_worker"]
|
||||
assert after == ["connect_orders:services.cloud_sync:order_pull_worker"]
|
||||
assert calls == ["run", "run"]
|
||||
|
||||
|
||||
def test_worker_specs_resolve_to_coroutines():
|
||||
for m in registry().values():
|
||||
for spec in m.workers:
|
||||
assert asyncio.iscoroutinefunction(supervisor._resolve(spec)), spec
|
||||
Reference in New Issue
Block a user