"""Build the data-flow graph payload consumed by the frontend. The frontend does no topology work of its own: it receives node ranks plus edge endpoints, so the picture stays stable across reloads and both the web app and any future client render exactly the same graph. """ from __future__ import annotations import sqlite3 from collections import defaultdict, deque from ..db import all_ from . import metrics from .metrics import parse_peak_hours # Column meaning inside the data-flow graph; mirrors TIER_LABELS in the frontend. TIER_LABELS = ('统一入口层', '审批 / 流程中枢', '业务系统层', '底座能力层') def tier_label(tier: int) -> str: try: return TIER_LABELS[tier] except IndexError: return f'第 {tier + 1} 层' def load_systems(conn: sqlite3.Connection) -> list[dict]: return all_( conn, """SELECT s.*, l.name AS layer_name, l.short_name AS layer_short_name, l.color AS layer_color FROM systems s LEFT JOIN layers l ON l.id = s.layer_id ORDER BY s.sort_order, s.id""", ) def load_flows(conn: sqlite3.Connection) -> list[dict]: return all_( conn, """SELECT f.*, t.name AS flow_type_name, t.color AS flow_type_color, t.line_style AS flow_type_line_style, t.default_interval AS flow_type_default_interval, s.name AS source_name, g.name AS target_name, s.tier AS source_tier, g.tier AS target_tier FROM data_flows f JOIN flow_types t ON t.id = f.flow_type_id JOIN systems s ON s.key = f.source_key JOIN systems g ON g.key = f.target_key ORDER BY f.sort_order, f.id""", ) def compute_depth(systems: list[dict], flows: list[dict]) -> dict[str, int]: """Longest-path depth from any source node, used only as a layout hint. Tiers stay authoritative for the visible columns; depth merely flags nodes whose declared tier disagrees with the direction of their edges, which is what the "layout suggestions" panel reports. """ adjacency: dict[str, list[str]] = defaultdict(list) indegree: dict[str, int] = {s["key"]: 0 for s in systems} for flow in flows: if not flow["enabled"]: continue # Bidirectional links say nothing about ordering, so they must not push a # node to the right; only strict one-way traffic implies a downstream rank. if flow.get("direction") == "bidirectional": continue source, target = flow["source_key"], flow["target_key"] if source not in indegree or target not in indegree: continue adjacency[source].append(target) indegree[target] += 1 depth = dict.fromkeys(indegree, 0) degrees = dict(indegree) queue = deque(sorted(key for key, degree in degrees.items() if degree == 0)) while queue: node = queue.popleft() for nxt in adjacency[node]: depth[nxt] = max(depth[nxt], depth[node] + 1) degrees[nxt] -= 1 if degrees[nxt] == 0: queue.append(nxt) return depth def layout_suggestions(systems: list[dict], depth: dict[str, int]) -> list[dict]: """Flag nodes whose declared tier trails the depth implied by their incoming edges.""" hints = [] for system in systems: implied = depth.get(system["key"], 0) declared = int(system["tier"]) if implied > declared: hints.append({ "key": system["key"], "name": system["name"], "tier": declared, "implied_depth": implied, "reason": "上游链路深度大于当前层级,数据显示它可能应放在更靠右的列", }) return hints def build_graph(conn: sqlite3.Connection, *, days: int = 7, include_disabled: bool = False) -> dict: metrics.ensure_history(conn) systems = load_systems(conn) flows = load_flows(conn) health = metrics.flow_health(conn, days=days) active = [f for f in flows if f["enabled"]] if not include_disabled else flows depth = compute_depth(systems, active) ranks = {s["key"]: int(s["tier"]) for s in systems} degree: dict[str, int] = defaultdict(int) for flow in active: degree[flow["source_key"]] += 1 degree[flow["target_key"]] += 1 nodes = [] for system in systems: key = system["key"] node_health = [health.get(f["id"], {}).get("health") for f in active if key in (f["source_key"], f["target_key"])] nodes.append({ "key": key, "name": system["name"], "layer_id": system["layer_id"], "layer_name": system["layer_name"], "layer_color": system["layer_color"], "dept": system["dept"], "status": system["status"], "tech": system["tech"], "url": system["url"], "domain": system["domain"], "owner": system["owner"], "impl_time": system.get("impl_time") or "", "entry_enabled": bool(system.get("entry_enabled", 1)), "description": system["description"], "tier": int(system["tier"]), "flow_x": system.get("flow_x"), "flow_y": system.get("flow_y"), "rank": ranks.get(key, int(system["tier"])), "depth": depth.get(key, 0), "degree": degree[key], "out_count": sum(1 for f in active if f["source_key"] == key), "in_count": sum(1 for f in active if f["target_key"] == key), "health": ( "risk" if "risk" in node_health else "watch" if "watch" in node_health else "healthy" if node_health else "idle" ), }) edges = [] for flow in flows: if not include_disabled and not flow["enabled"]: continue h = health.get(flow["id"], {}) edges.append({ "id": flow["id"], "source_key": flow["source_key"], "target_key": flow["target_key"], "source_name": flow["source_name"], "target_name": flow["target_name"], "flow_type_id": flow["flow_type_id"], "flow_type_name": flow["flow_type_name"], "color": flow["flow_type_color"], "line_style": flow["flow_type_line_style"], "label": flow["label"], "payload": flow["payload"], "direction": flow["direction"], "interval_sec": flow["interval_sec"], "records_per_batch": flow["records_per_batch"], "avg_payload_kb": flow["avg_payload_kb"], "latency_ms": flow["latency_ms"], "reliability": flow["reliability"], "peak_hours": sorted(parse_peak_hours(flow["peak_hours"])), "enabled": bool(flow["enabled"]), "note": flow["note"], "throughput_rps": metrics.throughput_rps(flow, h), "payload_mb_per_hour": metrics.payload_rps(flow), "health": { "batches": h.get("batches", 0), "records": h.get("records", 0), "bytes": h.get("bytes", 0), "errors": h.get("errors", 0), "error_rate": h.get("error_rate", 0), "avg_latency_ms": h.get("avg_latency_ms", flow["latency_ms"]), "peak_hour_records": h.get("peak_hour_records", 0), "state": h.get("health", "idle"), }, }) return { "nodes": nodes, "edges": edges, "ranks": ranks, "rank_count": (max(ranks.values()) + 1) if ranks else 0, "suggestions": layout_suggestions(systems, depth), # Topology counts belong to the graph itself, so the flow canvas needs no second # request (and no traffic metrics) just to label its own header. "counts": { "systems": len(systems), "layers": len({system["layer_id"] for system in systems if system["layer_id"]}), "tiers": len({int(system["tier"]) for system in systems}), "flows_total": len(flows), "flows_enabled": sum(1 for flow in flows if flow["enabled"]), "linked_systems": sum(1 for system in systems if degree[system["key"]]), }, }