Some checks failed
CI / build (push) Failing after 3s
PHASE 2.3 (AUDIT-2026-Q3.md):
Task 1 — Wire-in Wave 3 (1 router mounted, 2 deferred):
- app.routers.unified_scanner_router mounted at /api/v2/scanner/* (2 routes:
POST /api/v2/scanner/token/scan, POST /api/v2/scanner/wallet/scan).
Refactored prefix from /api/v2 -> /api/v2/scanner to avoid future conflicts
with the v1 /api/v1/scanner/ stub.
- app.routers.unified_wallet_scanner DEFERRED (no router APIRouter attribute;
library module consumed by unified_scanner_router via get_wallet_scanner()).
- app.routers.admin_extensions DEFERRED (DORMANT per audit; 25 routes at
/api/v1/admin/* would shadow /api/v1/admin/alerts_webhook).
Task 2 — Archive 136 dead-code files to app/_archive/legacy_2026_07/:
- 73 routers in app/routers/ (reach graph showed zero reach into mount.py).
- 63 flat app/*.py (domain modules never imported by live code).
- 1 file RESTORED post-archive: app/routers/x402_bridge_health.py (caught by
tests/unit/test_bridge_health.py which directly imports it; reach graph
considered tests/ only as transitive reach — to be patched in next cycle).
Forced-LIVE (NOT archived per user directive):
- app/ai_pipeline_v3.py (3 importers in audit window, importers themselves DEAD)
- app/splade_bm25.py (LIVE via app.rag_service)
- app/wallet_manager_v2.py (LIVE via x402_enforcement, x402_tools, sweep_all, sweep_now)
- app/crypto_embeddings.py (NOT in audit ARCHIVE list; heavy import graph)
Verification (forward-import closure from mount.py + main.py + factory.py + lifespan.py):
- imports = 348 app.* modules
- reached = 194 files reachable from roots
- archive set = audit_dead (186) - reached - forced_live (4) - test_live (1) = 136
- Net delta: 136 files moved, 44,932 LOC reduction, 293->295 active routes (+2 from Wave 3)
pyproject.toml updates:
- setuptools.packages.find: added exclude for app._archive*
- ruff.extend-exclude: added "app/_archive/"
- mypy.exclude: added "app/_archive/"
Smoke test: pytest tests/ — 817 passed, 3 pre-existing failures unchanged
(0 new failures; 0 routes lost; all 4 forced-LIVE files still importable).
Restoration: git mv app/_archive/legacy_2026_07/<name>.py <original-path>
and add the import to app/mount.py ROUTER_MODULES.
Refs: AUDIT-2026-Q3.md /home/dev/pry/rmi-final-deadcode-2026-07-06.md
258 lines
8 KiB
Python
258 lines
8 KiB
Python
"""
|
|
RMI Analytics API Router
|
|
==========================
|
|
REST API for real-time analytics and dashboard data.
|
|
|
|
Endpoints:
|
|
GET /api/v1/analytics/metrics - List all metrics
|
|
GET /api/v1/analytics/metrics/{name} - Get metric data
|
|
POST /api/v1/analytics/metrics/{name} - Record metric
|
|
GET /api/v1/analytics/dashboards - List dashboards
|
|
GET /api/v1/analytics/dashboards/{id} - Get dashboard data
|
|
POST /api/v1/analytics/dashboards - Create dashboard
|
|
GET /api/v1/analytics/trends/{metric} - Get trend analysis
|
|
GET /api/v1/analytics/stats - System stats
|
|
GET /api/v1/analytics/prometheus - Prometheus export
|
|
GET /api/v1/analytics/export/{metric} - Export metric
|
|
GET /api/v1/analytics/realtime/{dashboard} - WebSocket-compatible data
|
|
"""
|
|
|
|
import logging
|
|
import os
|
|
import time
|
|
from typing import Any
|
|
|
|
from fastapi import APIRouter, HTTPException, Query, Request
|
|
from pydantic import BaseModel, Field
|
|
|
|
from app.admin_backend import AuditLogger, require_admin
|
|
from app.analytics_engine import AnalyticsEngine, DashboardWidget, get_analytics_engine
|
|
|
|
logger = logging.getLogger("analytics_api")
|
|
|
|
router = APIRouter(prefix="/api/v1/analytics", tags=["analytics"])
|
|
|
|
# ── Models ────────────────────────────────────────────────────
|
|
|
|
|
|
class RecordMetricRequest(BaseModel):
|
|
value: float
|
|
labels: dict[str, str] | None = None
|
|
|
|
|
|
class CreateDashboardRequest(BaseModel):
|
|
name: str
|
|
description: str = ""
|
|
|
|
|
|
class AddWidgetRequest(BaseModel):
|
|
widget_type: str = Field(..., description="line, bar, gauge, counter, table, pie")
|
|
title: str
|
|
metric_name: str
|
|
width: int = 6
|
|
height: int = 4
|
|
refresh_interval: int = 30
|
|
config: dict[str, Any] | None = None
|
|
|
|
|
|
# ── Helper ────────────────────────────────────────────────────
|
|
|
|
|
|
def _get_engine() -> AnalyticsEngine:
|
|
return get_analytics_engine()
|
|
|
|
|
|
# ── Endpoints ─────────────────────────────────────────────────
|
|
|
|
|
|
@router.get("/metrics")
|
|
async def list_metrics(request: Request):
|
|
"""List all tracked metrics."""
|
|
await require_admin(request, "analytics.read")
|
|
|
|
engine = _get_engine()
|
|
metrics = []
|
|
for name in engine.get_metric_names():
|
|
metric = engine.get_metric(name)
|
|
if metric:
|
|
metrics.append(metric.to_dict())
|
|
|
|
return {"metrics": metrics, "total": len(metrics)}
|
|
|
|
|
|
@router.get("/metrics/{name}")
|
|
async def get_metric(request: Request, name: str, limit: int = 100):
|
|
"""Get metric data points."""
|
|
await require_admin(request, "analytics.read")
|
|
|
|
engine = _get_engine()
|
|
metric = engine.get_metric(name)
|
|
if not metric:
|
|
raise HTTPException(status_code=404, detail="Metric not found")
|
|
|
|
points = [{"timestamp": p.timestamp, "value": p.value, "labels": p.labels} for p in metric.points[-limit:]]
|
|
|
|
return {
|
|
"name": metric.name,
|
|
"description": metric.description,
|
|
"unit": metric.unit,
|
|
"latest": metric.latest(),
|
|
"avg_1m": metric.avg(60),
|
|
"trend": metric.trend(),
|
|
"points": points,
|
|
}
|
|
|
|
|
|
@router.post("/metrics/{name}")
|
|
async def record_metric(request: Request, name: str, body: RecordMetricRequest):
|
|
"""Record a metric data point."""
|
|
# Allow public recording for system metrics (from middleware)
|
|
engine = _get_engine()
|
|
engine.record_metric(name, body.value, body.labels or {})
|
|
return {"success": True}
|
|
|
|
|
|
@router.get("/dashboards")
|
|
async def list_dashboards(request: Request):
|
|
"""List all dashboards."""
|
|
await require_admin(request, "analytics.read")
|
|
|
|
engine = _get_engine()
|
|
dashboards = engine.list_dashboards()
|
|
return {
|
|
"dashboards": [
|
|
{
|
|
"dashboard_id": d.dashboard_id,
|
|
"name": d.name,
|
|
"description": d.description,
|
|
"widget_count": len(d.widgets),
|
|
"is_default": d.is_default,
|
|
}
|
|
for d in dashboards
|
|
]
|
|
}
|
|
|
|
|
|
@router.get("/dashboards/{dashboard_id}")
|
|
async def get_dashboard_data(request: Request, dashboard_id: str):
|
|
"""Get current data for a dashboard."""
|
|
await require_admin(request, "analytics.read")
|
|
|
|
engine = _get_engine()
|
|
data = engine.get_dashboard_data(dashboard_id)
|
|
if "error" in data:
|
|
raise HTTPException(status_code=404, detail=data["error"])
|
|
return data
|
|
|
|
|
|
@router.post("/dashboards")
|
|
async def create_dashboard(request: Request, body: CreateDashboardRequest):
|
|
"""Create a new dashboard."""
|
|
auth = await require_admin(request, "analytics.read")
|
|
admin = auth["admin"]
|
|
|
|
engine = _get_engine()
|
|
dashboard = engine.create_dashboard(body.name, body.description, admin["id"])
|
|
|
|
await AuditLogger.log(
|
|
admin_id=admin["id"],
|
|
admin_email=admin["email"],
|
|
action="dashboard.create",
|
|
resource_type="dashboard",
|
|
resource_id=dashboard.dashboard_id,
|
|
ip_address=request.client.host if request.client else "",
|
|
user_agent=request.headers.get("user-agent", ""),
|
|
)
|
|
|
|
return {
|
|
"success": True,
|
|
"dashboard": {"dashboard_id": dashboard.dashboard_id, "name": dashboard.name},
|
|
}
|
|
|
|
|
|
@router.post("/dashboards/{dashboard_id}/widgets")
|
|
async def add_widget(request: Request, dashboard_id: str, body: AddWidgetRequest):
|
|
"""Add widget to dashboard."""
|
|
auth = await require_admin(request, "analytics.read")
|
|
auth["admin"]
|
|
|
|
engine = _get_engine()
|
|
widget = DashboardWidget(
|
|
widget_id=f"wid_{int(time.time())}_{os.urandom(4).hex()}",
|
|
widget_type=body.widget_type,
|
|
title=body.title,
|
|
metric_name=body.metric_name,
|
|
width=body.width,
|
|
height=body.height,
|
|
refresh_interval=body.refresh_interval,
|
|
config=body.config or {},
|
|
)
|
|
|
|
result = engine.add_widget(dashboard_id, widget)
|
|
if not result:
|
|
raise HTTPException(status_code=404, detail="Dashboard not found")
|
|
|
|
return {"success": True, "widget": {"widget_id": widget.widget_id, "title": widget.title}}
|
|
|
|
|
|
@router.get("/trends/{metric_name}")
|
|
async def get_trends(request: Request, metric_name: str, window: int = 60):
|
|
"""Get trend analysis for a metric."""
|
|
await require_admin(request, "analytics.read")
|
|
|
|
engine = _get_engine()
|
|
trends = engine.detect_trends(metric_name, window)
|
|
return trends
|
|
|
|
|
|
@router.get("/stats")
|
|
async def get_stats(request: Request):
|
|
"""Get analytics system statistics."""
|
|
await require_admin(request, "analytics.read")
|
|
|
|
engine = _get_engine()
|
|
return engine.get_system_stats()
|
|
|
|
|
|
@router.get("/prometheus")
|
|
async def prometheus_export(request: Request):
|
|
"""Export metrics in Prometheus format."""
|
|
# Public endpoint for Prometheus scraping
|
|
engine = _get_engine()
|
|
return engine.to_prometheus()
|
|
|
|
|
|
@router.get("/export/{metric_name}")
|
|
async def export_metric(
|
|
request: Request,
|
|
metric_name: str,
|
|
format: str = Query("json", regex="^(json|csv)$"),
|
|
):
|
|
"""Export metric data."""
|
|
await require_admin(request, "analytics.read")
|
|
|
|
engine = _get_engine()
|
|
data = engine.export_metric(metric_name, format)
|
|
if data is None:
|
|
raise HTTPException(status_code=404, detail="Metric not found")
|
|
|
|
if format == "csv":
|
|
return {"data": data, "format": "csv"}
|
|
return data
|
|
|
|
|
|
@router.get("/realtime/{dashboard_id}")
|
|
async def realtime_data(request: Request, dashboard_id: str):
|
|
"""Get real-time dashboard data (WebSocket-compatible)."""
|
|
await require_admin(request, "analytics.read")
|
|
|
|
engine = _get_engine()
|
|
data = engine.get_dashboard_data(dashboard_id)
|
|
if "error" in data:
|
|
raise HTTPException(status_code=404, detail=data["error"])
|
|
|
|
# Add timestamp for client sync
|
|
data["server_time"] = time.time()
|
|
data["refresh_interval"] = 30
|
|
|
|
return data
|