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>
124 lines
4.7 KiB
Python
124 lines
4.7 KiB
Python
"""Local backend entry point: logging, app, middleware, routers, startup.
|
|
|
|
Schema is created/upgraded only by Alembic (core/schema.py::upgrade_to_head, D-13).
|
|
The v1 create_all + _run_migrations() ALTER list was deleted in platform-v2 step 1.0.
|
|
"""
|
|
import os
|
|
import logging
|
|
from contextlib import asynccontextmanager
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.staticfiles import StaticFiles
|
|
|
|
from core.logging import setup_logging, apply_retention_setting, RequestContextMiddleware
|
|
|
|
# First thing: every logger below (and uvicorn's) writes through these handlers.
|
|
setup_logging()
|
|
logger = logging.getLogger("xenia.main")
|
|
|
|
from config import settings
|
|
from database import SessionLocal
|
|
from services.cloud_sync import start_cloud_sync
|
|
|
|
# Every model must be registered before the routers import them (see models/all.py).
|
|
import models.all # noqa: F401
|
|
|
|
|
|
|
|
def _init_chat():
|
|
"""Bootstrap the system group chat and sync all active users into it."""
|
|
from services.chat_service import ensure_system_group, add_user_to_system_group
|
|
from models.user import User
|
|
from database import SessionLocal
|
|
db = SessionLocal()
|
|
try:
|
|
ensure_system_group(db)
|
|
active_users = db.query(User).filter(User.is_active == True).all() # noqa: E712
|
|
for u in active_users:
|
|
add_user_to_system_group(db, u.id)
|
|
finally:
|
|
db.close()
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
import asyncio
|
|
from services.sse_bus import init_loop as sse_init_loop
|
|
from services.ws_bus import init_loop as ws_init_loop, prune_old_events
|
|
from services.reservation_tasks import start_reservation_tasks
|
|
from services.printer_service import start_print_retry_thread
|
|
loop = asyncio.get_running_loop()
|
|
sse_init_loop(loop)
|
|
ws_init_loop(loop)
|
|
# Schema = Alembic revisions only (core/schema.py, APPS_PLATFORM D-13). Refuses v1 databases.
|
|
from core.schema import upgrade_to_head
|
|
upgrade_to_head()
|
|
_db = SessionLocal()
|
|
try:
|
|
apply_retention_setting(_db)
|
|
finally:
|
|
_db.close()
|
|
logger.info("startup version=%s", settings.VERSION)
|
|
# Before the app reports healthy: the proxy's :8443 needs these files to start
|
|
from services.tls_identity import ensure_tls_identity
|
|
ensure_tls_identity()
|
|
start_print_retry_thread()
|
|
pruned = prune_old_events(hours=24)
|
|
if pruned:
|
|
logger.info("ws_bus: pruned %d old sync_events", pruned)
|
|
_init_chat()
|
|
from services.cloud_sync import load_license_at_startup
|
|
load_license_at_startup() # entitlements from the stored token (or free tier / dev)
|
|
sync_task = await start_cloud_sync() # license heartbeat (core, always on)
|
|
# Module workers (connect_* pushes/pulls...) run only while their module is effective
|
|
from core.modules import supervisor
|
|
supervisor.start(loop)
|
|
reservation_task = await start_reservation_tasks()
|
|
yield
|
|
supervisor.stop_all()
|
|
sync_task.cancel()
|
|
reservation_task.cancel()
|
|
|
|
|
|
app = FastAPI(title="POS Local Backend", lifespan=lifespan)
|
|
|
|
# Error responses: {"error": {code, params, message}, "detail"} (core/errors.py, §3.2)
|
|
from core.errors import install_error_handlers # noqa: E402
|
|
install_error_handlers(app)
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"],
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
# (v1's LicenseCheckMiddleware is gone: an unlicensed site gets the free tier, module by module, D-5.)
|
|
# Added last = outermost: the request id exists before any other middleware runs.
|
|
app.add_middleware(RequestContextMiddleware)
|
|
|
|
# Serve product images as static files
|
|
IMAGE_DIR = "/app/data/product_images"
|
|
os.makedirs(IMAGE_DIR, exist_ok=True)
|
|
app.mount("/static/product_images", StaticFiles(directory=IMAGE_DIR), name="product_images")
|
|
|
|
# Serve waiter avatars as static files
|
|
AVATAR_DIR = "/app/data/avatars"
|
|
os.makedirs(AVATAR_DIR, exist_ok=True)
|
|
app.mount("/static/avatars", StaticFiles(directory=AVATAR_DIR), name="avatars")
|
|
|
|
# Routers come from the module manifests (modules/<key>/manifest.py, APPS_PLATFORM D-19).
|
|
# All are always mounted; non-core ones answer `module.disabled` while their module is off.
|
|
def _mount_module_routers(app: FastAPI) -> None:
|
|
import importlib
|
|
from fastapi import Depends
|
|
from core.modules.registry import registry
|
|
from core.modules.state import module_required
|
|
for m in registry().values():
|
|
deps = [] if m.kind == "core" else [Depends(module_required(m.key))]
|
|
for mt in m.routers:
|
|
r = getattr(importlib.import_module(mt.module), mt.attr)
|
|
app.include_router(r, prefix=mt.prefix, tags=list(mt.tags) or [m.key], dependencies=deps)
|
|
|
|
|
|
_mount_module_routers(app)
|