SPB Git

Repository Public

app.py 12.8 KB 339 lines python

1# =============================================================================2#                  SP BOUCHER | INFRASTRUCTURE & AUTOMATION3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project          : MacLustr LLM API7# File             : src/maclustr_llm/app.py8# Description      : Application FastAPI : assemblage des services,9#                    intergiciels de sécurité, routes.10# Module           : maclustr_llm11# Repository       : https://git.spboucher.ai/maclustr-llm12# Created          : 2026-11-1913# Last Modified    : 2026-11-1914#15# Author           : Simon-Pierre Boucher16# Position         : Professor of Finance17# Institution      : Université du Québec en Outaouais (UQO)18# Organization     : SP Boucher19# Website          : https://spboucher.ai20# Git              : https://git.spboucher.ai21#22# Preferred Contact: admin@spboucher.ai23# Technical Contact: dev@spboucher.ai24# Security/Admin   : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License          : None specified (no license file in this repository)33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""Application FastAPI : assemblage des services, intergiciels de sécurité, routes."""4243from __future__ import annotations4445import json46import logging47import logging.handlers48import secrets49import time50from collections.abc import AsyncIterator51from contextlib import asynccontextmanager52from dataclasses import dataclass53from pathlib import Path5455from fastapi import FastAPI, Request56from fastapi.exceptions import RequestValidationError57from fastapi.responses import JSONResponse, Response58from starlette.datastructures import Headers, MutableHeaders59from starlette.exceptions import HTTPException as StarletteHTTPException60from starlette.types import ASGIApp, Message, Receive, Scope, Send6162from .auth import AuthService63from .config import API_VERSION, Settings, load_settings64from .db import Database65from .engine import EngineClient66from .errors import APIError67from .inference import InferenceService68from .keys import KeyService69from .limits import IPThrottle, Limiter70from .metrics import Metrics71from .scheduler import Scheduler72from .security import Hasher, load_or_create_secret73from .sysmon import SysMonitor74from .tokens import TokenCounter7576log = logging.getLogger("maclustr_llm")7778CSP_SITE = (79    "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; "80    "font-src 'self'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'; "81    "object-src 'none'"82)838485@dataclass86class Services:87    settings: Settings88    db: Database89    hasher: Hasher90    keys: KeyService91    limiter: Limiter92    scheduler: Scheduler93    engine: EngineClient94    metrics: Metrics95    sysmon: SysMonitor96    inference: InferenceService97    auth: AuthService98    auth_throttle: IPThrottle99    badkey_throttle: IPThrottle100    started_at: float101102103def build_services(settings: Settings) -> Services:104    db = Database(settings.db_path)105    db.migrate_sync()106    hasher = Hasher(load_or_create_secret(settings.secret_path))107    sysmon = SysMonitor(db, str(settings.data_dir))108    scheduler = Scheduler(109        settings.engines,110        settings.max_queue,111        settings.queue_timeout_s,112        settings.aging_s,113        pressure=lambda: sysmon.pressure_level,114    )115    engine = EngineClient(scheduler, settings.first_token_timeout_s, settings.request_timeout_s)116    limiter = Limiter(db)117    metrics = Metrics(db, settings.request_log_days, settings.usage_days)118    counters = {m.id: TokenCounter(m.engine_model) for m in settings.models.values()}119    return Services(120        settings=settings,121        db=db,122        hasher=hasher,123        keys=KeyService(db, hasher, set(settings.models)),124        limiter=limiter,125        scheduler=scheduler,126        engine=engine,127        metrics=metrics,128        sysmon=sysmon,129        inference=InferenceService(settings, scheduler, engine, limiter, metrics, counters),130        auth=AuthService(settings, db, hasher),131        auth_throttle=IPThrottle(limit=20, window_s=300),132        badkey_throttle=IPThrottle(limit=30, window_s=60),133        started_at=time.time(),134    )135136137def setup_logging(settings: Settings) -> None:138    """Journal structuré tournant. On n'y écrit ni corps de requête, ni clé, ni jeton, ni chemin /setup/."""139    log_dir = settings.data_dir / "logs"140    log_dir.mkdir(parents=True, exist_ok=True)141    handler = logging.handlers.RotatingFileHandler(log_dir / "gateway.log", maxBytes=20 << 20, backupCount=5)142    handler.setFormatter(143        logging.Formatter('{"ts":"%(asctime)s","level":"%(levelname)s","logger":"%(name)s",%(message)s}')144    )145    root = logging.getLogger("maclustr_llm")146    root.handlers[:] = [handler]147    root.setLevel(logging.INFO)148    root.propagate = False149150151def _safe_path(path: str) -> str:152    return "/setup/[redacted]" if path.startswith("/setup/") else path153154155def create_app(settings: Settings | None = None, *, services: Services | None = None) -> FastAPI:156    settings = settings or load_settings()157    svc = services or build_services(settings)158159    @asynccontextmanager160    async def lifespan(app: FastAPI) -> AsyncIterator[None]:161        await svc.sysmon.start()162        await svc.metrics.start()163        await svc.engine.start()164        log.info('"event":"gateway.start","version":"%s"', API_VERSION)165        yield166        log.info('"event":"gateway.stop"')167        await svc.engine.stop()168        await svc.metrics.stop()169        await svc.sysmon.stop()170        svc.db.close()171172    app = FastAPI(173        title="MacLustr LLM API",174        version=API_VERSION,175        docs_url=None,176        redoc_url=None,177        openapi_url=None,178        lifespan=lifespan,179    )180    app.state.svc = svc181182    app.add_middleware(Envelope, settings=settings)183184    @app.exception_handler(APIError)185    async def api_error(request: Request, exc: APIError) -> JSONResponse:186        return JSONResponse(187            exc.body(getattr(request.state, "request_id", None)), status_code=exc.status, headers=exc.headers188        )189190    @app.exception_handler(RequestValidationError)191    async def validation_error(request: Request, exc: RequestValidationError) -> JSONResponse:192        first = exc.errors()[0] if exc.errors() else {"msg": "Requête invalide.", "loc": ()}193        loc = [str(x) for x in first.get("loc", ()) if x != "body"]194        param = ".".join(loc) or None195        msg = str(first.get("msg", "Requête invalide.")).removeprefix("Value error, ")196        err = APIError(400, f"{param}: {msg}" if param else msg, param=param, code="invalid_request")197        return JSONResponse(err.body(getattr(request.state, "request_id", None)), status_code=400)198199    @app.exception_handler(StarletteHTTPException)200    async def http_error(request: Request, exc: StarletteHTTPException) -> Response:201        rid = getattr(request.state, "request_id", None)202        path = request.url.path203        if exc.status_code == 404 and not path.startswith(("/v1/", "/admin/api/", "/api/")):204            page = settings.web_dir / "404.html"205            if page.exists():206                return Response(page.read_bytes(), status_code=404, media_type="text/html; charset=utf-8")207        types = {404: ("not_found_error", "not_found"), 405: ("invalid_request_error", "method_not_allowed")}208        type_, code = types.get(exc.status_code, ("api_error", "http_error"))209        err = APIError(exc.status_code, str(exc.detail), type_=type_, code=code)210        return JSONResponse(err.body(rid), status_code=exc.status_code)211212    from .routes_admin import router as admin_router213    from .routes_openai import router as openai_router214    from .routes_public import mount_site215    from .routes_public import router as public_router216217    app.include_router(openai_router)218    app.include_router(public_router)219    app.include_router(admin_router)220    mount_site(app, settings)221    return app222223224class Envelope:225    """Intergiciel ASGI pur (pas de BaseHTTPMiddleware : celui-ci masque la déconnexion du client et226    perturbe le streaming). Identifiant de requête, limite de taille, CORS de /v1, en-têtes de sécurité,227    journal d'accès sans corps ni secret."""228229    def __init__(self, app: ASGIApp, settings: Settings) -> None:230        self.app = app231        self.settings = settings232233    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:234        if scope["type"] != "http":235            await self.app(scope, receive, send)236            return237        rid = secrets.token_hex(12)238        scope.setdefault("state", {})["request_id"] = rid239        t0 = time.monotonic()240        path: str = scope["path"]241        method: str = scope["method"]242        is_api = path.startswith("/v1/")243        headers = Headers(scope=scope)244        status = 500245        started = False246247        async def send_wrapper(message: Message) -> None:248            nonlocal status, started249            if message["type"] == "http.response.start":250                started = True251                status = message["status"]252                h = MutableHeaders(scope=message)253                if "x-request-id" not in h:254                    h["x-request-id"] = rid255                h["X-Content-Type-Options"] = "nosniff"256                h["Referrer-Policy"] = "no-referrer"257                h["Strict-Transport-Security"] = "max-age=63072000; includeSubDomains"258                if is_api:259                    for k, v in _cors().items():260                        h[k] = v261                else:262                    if "content-security-policy" not in h:263                        h["Content-Security-Policy"] = CSP_SITE264                    h["X-Frame-Options"] = "DENY"265                    h["Permissions-Policy"] = "geolocation=(), camera=(), microphone=()"266                    if path.startswith(("/admin", "/setup", "/api/setup")):267                        h["Cache-Control"] = "no-store"268            await send(message)269270        try:271            if method == "OPTIONS" and is_api:272                await Response(status_code=204)(scope, receive, send_wrapper)273                return274            length = headers.get("content-length")275            if length and length.isdigit() and int(length) > self.settings.max_body_bytes:276                err = APIError(277                    413,278                    f"Corps de requête trop volumineux (maximum {self.settings.max_body_bytes} octets).",279                    code="request_too_large",280                )281                await JSONResponse(err.body(rid), status_code=413)(scope, receive, send_wrapper)282                return283            await self.app(scope, receive, send_wrapper)284        except Exception:285            log.exception('"event":"unhandled","request_id":"%s","path":"%s"', rid, _safe_path(path))286            if started:287                raise288            err = APIError(500, "Erreur interne du serveur.", type_="api_error", code="internal_error")289            await JSONResponse(err.body(rid), status_code=500)(scope, receive, send_wrapper)290        finally:291            if path not in ("/health", "/ready"):292                log.info(293                    '"event":"http","request_id":"%s","method":"%s","path":"%s","status":%d,"ms":%d',294                    rid,295                    method,296                    _safe_path(path),297                    status,298                    int((time.monotonic() - t0) * 1000),299                )300301302def _cors() -> dict[str, str]:303    """L'API /v1 est authentifiée par jeton Bearer (jamais par cookie) : CORS ouvert, sans credentials."""304    return {305        "Access-Control-Allow-Origin": "*",306        "Access-Control-Allow-Methods": "GET, POST, OPTIONS",307        "Access-Control-Allow-Headers": "Authorization, Content-Type, X-CSRF-Token",308        "Access-Control-Expose-Headers": "x-request-id, retry-after, x-ratelimit-limit-requests, "309        "x-ratelimit-remaining-requests, x-ratelimit-limit-tokens, "310        "x-ratelimit-remaining-tokens",311        "Access-Control-Max-Age": "600",312    }313314315def read_json_file(path: Path) -> object:316    return json.loads(path.read_text())317318319def main() -> None:320    import uvicorn321322    settings = load_settings()323    setup_logging(settings)324    uvicorn.run(325        create_app(settings),326        host=settings.host,327        port=settings.port,328        log_level="warning",329        access_log=False,330        timeout_keep_alive=75,331        timeout_graceful_shutdown=30,332        proxy_headers=False,333        server_header=False,334    )335336337if __name__ == "__main__":338    main()339
Files main
Menu

Theme