174 lines
7.2 KiB
Python
174 lines
7.2 KiB
Python
"""Aggregated read models: the whole graph, KPI totals, live counters and audit trail."""
|
||
|
||
from __future__ import annotations
|
||
|
||
import sqlite3
|
||
from datetime import date, datetime, timedelta
|
||
from typing import Annotated
|
||
|
||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||
|
||
from ..db import all_, get_db, log_audit, one, transaction, utcnow
|
||
from ..deps import actor_from, ensure_editable
|
||
from ..schemas import LayoutIn
|
||
from ..services import metrics
|
||
from ..services.graph import build_graph, tier_label
|
||
|
||
router = APIRouter(prefix="/api", tags=["graph"])
|
||
|
||
DB = Annotated[sqlite3.Connection, Depends(get_db)]
|
||
|
||
|
||
@router.get("/graph")
|
||
def graph(db: DB, days: int = Query(7, ge=1, le=90), include_disabled: bool = False) -> dict:
|
||
return build_graph(db, days=days, include_disabled=include_disabled)
|
||
|
||
|
||
@router.put("/graph/layout")
|
||
def save_layout(payload: LayoutIn, db: DB, request: Request) -> dict:
|
||
"""Persist where the user dropped the cards on the data-flow canvas.
|
||
|
||
One request carries a whole drag gesture so the audit trail records "moved three cards"
|
||
instead of three entries per card. A coordinate sent as null puts that card back under
|
||
automatic placement.
|
||
"""
|
||
ensure_editable(db, "调整数据流向图布局")
|
||
now = utcnow()
|
||
placed = 0
|
||
cleared = 0
|
||
moved: list[str] = []
|
||
missing: list[str] = []
|
||
|
||
with transaction(db):
|
||
for item in payload.items:
|
||
row = one(db, "SELECT key, name, tier FROM systems WHERE key = ?", (item.key,))
|
||
if not row:
|
||
missing.append(item.key)
|
||
continue
|
||
given = item.model_fields_set
|
||
columns: dict[str, object] = {}
|
||
if "x" in given:
|
||
columns["flow_x"] = item.x
|
||
if "y" in given:
|
||
columns["flow_y"] = item.y
|
||
if columns:
|
||
if item.x is None and item.y is None:
|
||
cleared += 1
|
||
elif item.x is not None or item.y is not None:
|
||
placed += 1
|
||
if item.tier is not None and item.tier != row["tier"]:
|
||
columns["tier"] = item.tier
|
||
moved.append(f"{row['name']}→{tier_label(item.tier)}")
|
||
if not columns:
|
||
continue
|
||
columns["updated_at"] = now
|
||
assignments = ", ".join(f"{column} = ?" for column in columns)
|
||
db.execute(f"UPDATE systems SET {assignments} WHERE key = ?", [*columns.values(), item.key]) # noqa: S608
|
||
|
||
parts = []
|
||
if placed:
|
||
parts.append(f"手动摆放 {placed} 个系统")
|
||
if cleared:
|
||
parts.append(f"{cleared} 个恢复自动排列")
|
||
if moved:
|
||
parts.append("换列:" + "、".join(moved[:5]) + ("等" if len(moved) > 5 else ""))
|
||
summary = "数据流向图布局:" + ";".join(parts) if parts else ""
|
||
if summary:
|
||
log_audit(db, actor=actor_from(request), entity="layout", entity_id="flow_graph",
|
||
action="update", summary=summary)
|
||
|
||
return {"ok": True, "placed": placed, "cleared": cleared, "moved": len(moved), "missing": missing}
|
||
|
||
|
||
@router.post("/graph/layout/reset")
|
||
def reset_layout(db: DB, request: Request) -> dict:
|
||
"""Drop every manual position so the layout engine lays the graph out again."""
|
||
ensure_editable(db, "恢复自动排列")
|
||
with transaction(db):
|
||
cursor = db.execute(
|
||
"UPDATE systems SET flow_x = NULL, flow_y = NULL, updated_at = ? "
|
||
"WHERE flow_x IS NOT NULL OR flow_y IS NOT NULL",
|
||
(utcnow(),),
|
||
)
|
||
cleared = cursor.rowcount
|
||
if cleared:
|
||
log_audit(db, actor=actor_from(request), entity="layout", entity_id="flow_graph",
|
||
action="update", summary=f"数据流向图恢复自动排列({cleared} 个系统)")
|
||
return {"ok": True, "cleared": cleared}
|
||
|
||
|
||
@router.get("/metrics/summary")
|
||
def summary(db: DB, days: int = Query(7, ge=1, le=90)) -> dict:
|
||
totals = metrics.totals(db, days)
|
||
counts = one(db, """SELECT
|
||
(SELECT COUNT(*) FROM systems) AS systems,
|
||
(SELECT COUNT(*) FROM data_flows WHERE enabled = 1) AS flows,
|
||
(SELECT COUNT(*) FROM data_flows) AS flows_all,
|
||
(SELECT COUNT(*) FROM flow_types) AS flow_types,
|
||
(SELECT COUNT(*) FROM layers) AS layers""")
|
||
health = metrics.flow_health(db, days=days)
|
||
states = [h["health"] for h in health.values()]
|
||
return {
|
||
"range_days": days,
|
||
"totals": totals,
|
||
"counts": counts,
|
||
"health": {
|
||
"healthy": states.count("healthy"),
|
||
"watch": states.count("watch"),
|
||
"risk": states.count("risk"),
|
||
},
|
||
"generated_at": datetime.now().replace(microsecond=0).isoformat(),
|
||
}
|
||
|
||
|
||
@router.get("/metrics/hourly")
|
||
def hourly(db: DB, days: int = Query(3, ge=1, le=90)) -> dict:
|
||
"""Network-wide hourly curve plus a per-flow breakdown, for the trend charts."""
|
||
metrics.ensure_history(db)
|
||
start = (date.today() - timedelta(days=days - 1)).isoformat()
|
||
rows = all_(db, """SELECT m.day, m.hour, SUM(m.batches) AS batches, SUM(m.records) AS records,
|
||
SUM(m.bytes) AS bytes, SUM(m.errors) AS errors,
|
||
AVG(NULLIF(m.latency_ms,0)) AS latency
|
||
FROM flow_metrics m JOIN data_flows f ON f.id = m.flow_id
|
||
WHERE f.enabled = 1 AND m.day >= ?
|
||
GROUP BY m.day, m.hour ORDER BY m.day, m.hour""", (start,))
|
||
return {"days": days, "start": start, "points": rows}
|
||
|
||
|
||
@router.get("/metrics/flows/{flow_id}")
|
||
def flow_series(flow_id: int, db: DB, days: int = Query(7, ge=1, le=90)) -> dict:
|
||
if not one(db, "SELECT id FROM data_flows WHERE id = ?", (flow_id,)):
|
||
raise HTTPException(404, "数据流不存在")
|
||
return {"flow_id": flow_id, "days": days, "points": metrics.hourly_series(db, flow_id, days)}
|
||
|
||
|
||
@router.get("/metrics/live")
|
||
def live(db: DB) -> dict:
|
||
"""Current-hour snapshot for every enabled flow; drives the animated graph."""
|
||
today = date.today().isoformat()
|
||
hour = datetime.now().hour
|
||
rows = all_(db, """SELECT f.id AS flow_id, f.source_key, f.target_key, f.flow_type_id, f.label,
|
||
f.direction, f.enabled, COALESCE(m.batches,0) AS batches,
|
||
COALESCE(m.records,0) AS records, COALESCE(m.bytes,0) AS bytes,
|
||
COALESCE(m.errors,0) AS errors, COALESCE(m.latency_ms,0) AS latency_ms
|
||
FROM data_flows f
|
||
LEFT JOIN flow_metrics m ON m.flow_id = f.id AND m.day = ? AND m.hour = ?
|
||
ORDER BY f.id""", (today, hour))
|
||
return {"day": today, "hour": hour, "flows": rows}
|
||
|
||
|
||
@router.post("/metrics/tick")
|
||
def tick(db: DB) -> dict:
|
||
return metrics.live_tick(db)
|
||
|
||
|
||
@router.get("/audit")
|
||
def audit(db: DB, limit: int = Query(50, ge=1, le=500), entity: str | None = None) -> list[dict]:
|
||
sql, params = "SELECT * FROM audit_logs", []
|
||
if entity:
|
||
sql += " WHERE entity = ?"
|
||
params.append(entity)
|
||
sql += " ORDER BY id DESC LIMIT ?"
|
||
params.append(limit)
|
||
return all_(db, sql, params)
|