Spaces:
Running
Running
| from fastapi import APIRouter, Depends, HTTPException | |
| from sqlalchemy.orm import Session | |
| from sqlalchemy import func | |
| from backend.database.postgres.db import get_db | |
| from backend.database.postgres.models import AuditLog, ChatSession as Conversation, GeneratedFile | |
| from datetime import datetime, timedelta | |
| router = APIRouter(prefix="/admin", tags=["admin"]) | |
| async def get_health_metrics(db: Session = Depends(get_db)): | |
| # 1. Latency Metrics | |
| latency_stats = db.query( | |
| func.avg(AuditLog.latency_ms).label("avg"), | |
| func.max(AuditLog.latency_ms).label("max") | |
| ).filter(AuditLog.action == "PROCESS_QUERY").first() | |
| # 2. File Generation Stats | |
| file_stats = db.query( | |
| GeneratedFile.file_type, | |
| func.count(GeneratedFile.id) | |
| ).group_by(GeneratedFile.file_type).all() | |
| # 3. Active Users (24h) | |
| yesterday = datetime.utcnow() - timedelta(days=1) | |
| active_users = db.query(func.count(func.distinct(AuditLog.user_hash))).filter( | |
| AuditLog.created_at > yesterday | |
| ).scalar() | |
| # 4. Error Rate | |
| total_requests = db.query(func.count(AuditLog.id)).scalar() or 1 | |
| errors = db.query(func.count(AuditLog.id)).filter(AuditLog.success == False).scalar() or 0 | |
| error_rate = (errors / total_requests) * 100 | |
| return { | |
| "status": "healthy", | |
| "metrics": { | |
| "avg_latency_ms": round(latency_stats.avg or 0, 2), | |
| "max_latency_ms": latency_stats.max or 0, | |
| "active_users_24h": active_users, | |
| "error_rate_pct": round(error_rate, 2), | |
| "files_generated": {t: c for t, c in file_stats} | |
| }, | |
| "system": { | |
| "timestamp": datetime.utcnow().isoformat(), | |
| "uptime": "simulated" | |
| } | |
| } | |