Add admin panel, WebSocket support, and API versioning
Introduce an admin portal (React + Nginx), WebSocket routing, and API versioning middleware with `/api/v1/` prefix deprecation. Add master API key authentication, new Prometheus metrics for AI token consumption and active WebSockets, and extend S3 config with a public endpoint URL. Update test paths and fixtures to align with the new routing structure.
This commit is contained in:
+99
-19
@@ -12,9 +12,10 @@ from slowapi.errors import RateLimitExceeded
|
||||
from app.config import settings
|
||||
from app.database import init_db
|
||||
from app.logging_config import configure_logging
|
||||
from app.routers import images_router, ai_router, auth_router, files_router
|
||||
from app.routers import images_router, ai_router, auth_router, files_router, ws_router, admin_router
|
||||
from app.middleware import limiter
|
||||
from app.middleware.logging_middleware import LoggingMiddleware
|
||||
from app.middleware.versioning import APIVersioningMiddleware
|
||||
from app.workers.redis_client import get_redis_pool, close_redis_pool
|
||||
|
||||
# Configure le logging structuré dès l'import
|
||||
@@ -144,13 +145,15 @@ class _FallbackArqPool:
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
|
||||
app = FastAPI(
|
||||
title=settings.APP_NAME,
|
||||
title=f"{settings.APP_NAME} API",
|
||||
version=settings.APP_VERSION,
|
||||
description="""
|
||||
## Imago
|
||||
## Imago API (v1)
|
||||
|
||||
Backend de gestion d'images et fonctionnalités AI pour l'interface Shaarli.
|
||||
|
||||
> **Note de versionnement :** L'API principale est désormais servie sous le préfixe `/api/v1/`. Les anciennes routes sans ce préfixe sont dépréciées.
|
||||
|
||||
### Fonctionnalités
|
||||
- 📸 **Upload et stockage d'images** avec génération de thumbnails
|
||||
- 🔍 **Extraction EXIF** automatique (appareil, GPS, paramètres de prise de vue)
|
||||
@@ -182,6 +185,12 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Middleware de Versionnement API
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
|
||||
app.add_middleware(APIVersioningMiddleware)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Middleware Logging HTTP
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
@@ -216,12 +225,24 @@ if settings.STORAGE_BACKEND == "local":
|
||||
app.mount("/static/thumbnails", StaticFiles(directory=str(settings.thumbnails_path)), name="thumbnails")
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Routers
|
||||
# Routers Versionnés (/api/v1/)
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
from fastapi import APIRouter
|
||||
|
||||
api_v1_router = APIRouter(prefix="/api/v1")
|
||||
api_v1_router.include_router(images_router)
|
||||
api_v1_router.include_router(ai_router)
|
||||
api_v1_router.include_router(auth_router)
|
||||
|
||||
# Mount the versioned router on the app
|
||||
app.include_router(api_v1_router)
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
# Routers Non-Versionnés (WebSockets, Fichiers, Santé, Metrics)
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
|
||||
app.include_router(images_router)
|
||||
app.include_router(ai_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(ws_router)
|
||||
app.include_router(admin_router)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────
|
||||
@@ -261,7 +282,14 @@ async def health_detailed(request: Request):
|
||||
"""Endpoint de santé détaillé pour monitoring avancé."""
|
||||
checks = {}
|
||||
|
||||
# DB check
|
||||
# 1. Backend check
|
||||
checks["backend"] = {
|
||||
"status": "ok",
|
||||
"version": settings.APP_VERSION,
|
||||
"uptime": "N/A" # Optionnel: ajouter un tracker d'uptime si nécessaire
|
||||
}
|
||||
|
||||
# 2. Database check
|
||||
try:
|
||||
from app.database import AsyncSessionLocal
|
||||
from sqlalchemy import text
|
||||
@@ -271,7 +299,7 @@ async def health_detailed(request: Request):
|
||||
except Exception as e:
|
||||
checks["database"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Redis check
|
||||
# 3. Redis check
|
||||
redis = getattr(request.app.state, "redis", None)
|
||||
if redis:
|
||||
try:
|
||||
@@ -282,25 +310,77 @@ async def health_detailed(request: Request):
|
||||
else:
|
||||
checks["redis"] = {"status": "not_configured"}
|
||||
|
||||
# ARQ check
|
||||
# 4. Worker & Queue check (ARQ)
|
||||
arq_pool = getattr(request.app.state, "arq_pool", None)
|
||||
if arq_pool and not isinstance(arq_pool, _FallbackArqPool):
|
||||
checks["arq"] = {"status": "ok"}
|
||||
try:
|
||||
# On essaye de voir le nombre de jobs en attente
|
||||
queued_jobs = await arq_pool.zcard("arq:queue")
|
||||
checks["queue"] = {
|
||||
"status": "ok",
|
||||
"pending_jobs": queued_jobs
|
||||
}
|
||||
|
||||
# Pour le worker, on vérifie la clé de health check déposée par ARQ
|
||||
# Par défaut c'est <queue_name>:health-check
|
||||
hc_key = f"{settings.S3_PREFIX or 'arq'}:queue:health-check"
|
||||
# On ré-essaye avec la queue par défaut si le préfixe est différent
|
||||
if not await redis.exists(hc_key):
|
||||
hc_key = "arq:queue:health-check"
|
||||
|
||||
worker_active = await redis.exists(hc_key)
|
||||
checks["worker"] = {
|
||||
"status": "ok" if worker_active else "error",
|
||||
"active_workers": 1 if worker_active else 0,
|
||||
"detail": "Worker opérationnel" if worker_active else "Aucun worker détecté"
|
||||
}
|
||||
except Exception as e:
|
||||
checks["queue"] = {"status": "error", "error": str(e)}
|
||||
checks["worker"] = {"status": "error", "error": str(e)}
|
||||
else:
|
||||
checks["arq"] = {"status": "fallback"}
|
||||
checks["queue"] = {"status": "fallback"}
|
||||
checks["worker"] = {"status": "error", "detail": "ARQ non disponible"}
|
||||
|
||||
# OCR check
|
||||
checks["ocr"] = {"status": "enabled" if settings.OCR_ENABLED else "disabled"}
|
||||
# 5. MinIO / Storage check
|
||||
from app.services.storage_backend import get_storage_backend, S3Storage
|
||||
storage = get_storage_backend()
|
||||
try:
|
||||
if isinstance(storage, S3Storage):
|
||||
# On vérifie la connexion réelle à MinIO en listant les objets (ou head bucket)
|
||||
# Pour faire simple/rapide on vérifie juste si on peut accéder au bucket
|
||||
# via l'interface du storage qui a déjà les sessions asynchrones
|
||||
exists = await storage.exists(".health-check") # path arbitraire
|
||||
checks["minio"] = {
|
||||
"status": "ok",
|
||||
"backend": "s3",
|
||||
"bucket": settings.S3_BUCKET
|
||||
}
|
||||
else:
|
||||
checks["minio"] = {
|
||||
"status": "ok",
|
||||
"backend": "local",
|
||||
"path": settings.UPLOAD_DIR
|
||||
}
|
||||
except Exception as e:
|
||||
checks["minio"] = {"status": "error", "error": str(e)}
|
||||
|
||||
# Storage check
|
||||
checks["storage"] = {
|
||||
"backend": settings.STORAGE_BACKEND,
|
||||
"status": "ok",
|
||||
# 6. OCR check (Tesseract)
|
||||
checks["tesseract"] = {"status": "ok" if settings.OCR_ENABLED else "disabled"}
|
||||
|
||||
# 7. AI Provider check
|
||||
ai_configured = (
|
||||
(settings.AI_PROVIDER == "gemini" and bool(settings.GEMINI_API_KEY)) or
|
||||
(settings.AI_PROVIDER == "openrouter" and bool(settings.OPENROUTER_API_KEY))
|
||||
)
|
||||
checks["ai"] = {
|
||||
"status": "ok" if ai_configured else "warning",
|
||||
"provider": settings.AI_PROVIDER,
|
||||
"configured": ai_configured
|
||||
}
|
||||
|
||||
overall = "healthy" if all(
|
||||
c.get("status") in ("ok", "enabled", "disabled", "not_configured", "fallback")
|
||||
for c in checks.values()
|
||||
for k, c in checks.items() if k != "ai" # On tolère AI warning
|
||||
) else "degraded"
|
||||
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user