Files
xenia-pos-local/local_backend/core/modules/state.py
T
bonaminandClaude Opus 5.5 0d43e6a111 feat(backend): license entitlements, enforced limits, free tier
Platform v2 step 1.4 (APPS_PLATFORM D-3..D-6, D-21, §5).
- core/modules/entitlements.py: compute() turns the evaluated license into
  per-module grants: the v2 token's `modules` map (own `exp` with the 5-day
  grace, never cut mid-service) + the free tier; no/invalid token, expired
  after grace, inactive, locked or clock tampering -> free tier only; core
  always. limit(module, name) with token value -> manifest licensed_default ->
  free value; None = unlimited. LICENSE_MODE=off (dev/test only) = everything
- module gating says why: module.not_licensed (402, the first unlicensed
  module in the dependency chain) before module.disabled (403)
- services/license.py accepts only v2 tokens with a modules map; the v1
  "legacy unsigned 72h" path is gone
- apply_license() always installs entitlements (startup before workers,
  every heartbeat, workday close); workers follow license changes
- the global license middleware is deleted (no more whole-API 402/423);
  license_state moved to services/license_state.py
- history_days enforced in every report/history endpoint: lower date bounds
  clamped (also when no "from" is given), and business days older than the
  limit refused by id (license.history_limited); data is never deleted
- bootstrap/modules API show license mode, entitlement source and limit values
- LICENSE_MODE=off in docker-compose.dev.yml and the e2e launchers; sites
  default to enforced
- tests: entitlement rules, limits, the three done-when checks, signed-token
  apply_license path; license tests moved to v2 tokens

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 18:32:57 +02:00

166 lines
5.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""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.
- Entitlement comes from core/modules/entitlements.py (license ∪ free tier, step 1.4).
A blocked request says why: module.not_licensed (402) before module.disabled (403).
"""
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:
from core.modules import entitlements
return entitlements.current().entitled(key)
def notify() -> None:
"""Tell listeners (the worker supervisor) the effective set may have changed,
e.g. after the license was re-evaluated."""
eff = effective_set()
for fn in list(_listeners):
try:
fn(eff)
except Exception:
logger.exception("module listener failed")
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 blocked_error(key: str, db: Session | None = None) -> XeniaError:
"""Why `key` isn't effective: not licensed (itself or a dependency) beats turned off."""
reg = registry()
seen, stack = set(), [key]
while stack:
k = stack.pop()
if k in seen:
continue
seen.add(k)
if not _entitled(k):
return XeniaError("module.not_licensed", module=k)
stack.extend(reg[k].depends)
enabled = enabled_map(db)
off = next((k for k in [key, *sorted(seen - {key})] if not enabled.get(k, True)), key)
return XeniaError("module.disabled", module=off)
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 blocked_error(key, db)
_check.__name__ = f"module_required_{key}"
return _check