feat(dashboard): the code graph's card on the target page (t82) (#937)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m50s
CI / Deploy Dashboard (push) Successful in 6m20s
CI / Deploy Agent (push) Successful in 8m31s

This commit was merged in pull request #937.
This commit is contained in:
sharang committed 2026-11-07 10:24:13 +00:00
1 parent 37888af374
commit c1a70b025c
8 files changed
+234 -12

No files matched your search

+85 -1
View File
@@ -6,7 +6,9 @@ use axum::Json;
use mongodb::bson::doc;
use serde::{Deserialize, Serialize};
use compliance_core::models::graph::{CodeEdge, CodeNode, GraphBuildRun, ImpactAnalysis};
use compliance_core::models::graph::{
CodeEdge, CodeNode, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
};
use compliance_core::tenant_ctx::TenantCtx;
use crate::agent::ComplianceAgent;
@@ -188,6 +190,55 @@ pub async fn get_nodes(
}))
}
/// What the target page shows of a code graph.
#[derive(Serialize)]
pub struct GraphSummary {
/// Declarations: functions, methods, types, PLC blocks (nodes that are
/// not files).
pub units: u32,
pub entry_points: u32,
/// Language codes, sorted (`c`, `csharp`, `structured_text`, …).
pub languages: Vec<String>,
}
impl GraphSummary {
/// The summary of a completed build; `None` for one still running, a
/// failed one, or one stored before its files and entry points were
/// counted.
fn of(build: GraphBuildRun) -> Option<Self> {
if build.status != GraphBuildStatus::Completed {
return None;
}
Some(Self {
units: build.node_count.saturating_sub(build.file_count?),
entry_points: build.entry_point_count?,
languages: build.languages_parsed,
})
}
}
/// GET /api/v1/graph/:repo_id/summary — The latest build's counts, without
/// loading any node: `data` is `null` when there is none to show.
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_summary(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(repo_id): Path<String>,
) -> Result<Json<ApiResponse<Option<GraphSummary>>>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let build = db
.graph_builds()
.find_one(doc! { "repo_id": &repo_id })
.sort(doc! { "started_at": -1 })
.await
.map_err(|_| StatusCode::INTERNAL_SERVER_ERROR)?;
Ok(Json(ApiResponse {
data: build.and_then(GraphSummary::of),
total: None,
page: None,
}))
}
/// GET /api/v1/graph/:repo_id/communities — List detected communities
#[tracing::instrument(skip_all, fields(repo_id = %repo_id))]
pub async fn get_communities(
@@ -467,3 +518,36 @@ pub async fn trigger_build(
serde_json::json!({ "status": "graph_build_triggered" }),
))
}
#[cfg(test)]
mod tests {
use super::*;
fn completed(nodes: u32, files: Option<u32>, entry_points: Option<u32>) -> GraphBuildRun {
let mut build = GraphBuildRun::new("t".to_string());
build.status = GraphBuildStatus::Completed;
build.node_count = nodes;
build.file_count = files;
build.entry_point_count = entry_points;
build.languages_parsed = vec!["c".to_string()];
build
}
#[test]
fn a_completed_build_counts_its_declarations() {
let summary = GraphSummary::of(completed(120, Some(20), Some(7))).expect("shown");
assert_eq!((summary.units, summary.entry_points), (100, 7));
assert_eq!(summary.languages, ["c"]);
}
#[test]
fn running_failed_and_uncounted_builds_show_nothing() {
let mut running = completed(10, Some(2), Some(1));
running.status = GraphBuildStatus::Running;
assert!(GraphSummary::of(running).is_none());
let mut failed = completed(10, Some(2), Some(1));
failed.status = GraphBuildStatus::Failed;
assert!(GraphSummary::of(failed).is_none());
assert!(GraphSummary::of(completed(10, None, None)).is_none());
}
}
+4
View File
@@ -199,6 +199,10 @@ pub fn build_router() -> Router {
"/api/v1/graph/{repo_id}/nodes",
get(handlers::graph::get_nodes),
)
.route(
"/api/v1/graph/{repo_id}/summary",
get(handlers::graph::get_summary),
)
.route(
"/api/v1/graph/{repo_id}/communities",
get(handlers::graph::get_communities),
+10
View File
@@ -121,6 +121,14 @@ pub struct GraphBuildRun {
pub edge_count: u32,
pub community_count: u32,
pub languages_parsed: Vec<String>,
/// Nodes that are files; the other nodes are the declarations in them.
/// `None` on a build stored before it was counted.
#[serde(default)]
pub file_count: Option<u32>,
/// Nodes that are entry points (`main`, request handlers, interrupt
/// handlers, PLC programs). `None` on a build stored before it was counted.
#[serde(default)]
pub entry_point_count: Option<u32>,
pub error_message: Option<String>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub started_at: DateTime<Utc>,
@@ -139,6 +147,8 @@ impl GraphBuildRun {
edge_count: 0,
community_count: 0,
languages_parsed: Vec::new(),
file_count: None,
entry_point_count: None,
error_message: None,
started_at: Utc::now(),
completed_at: None,
+18
View File
@@ -4946,6 +4946,23 @@ tbody tr:last-child td {
padding: 1px 8px;
}
/* With the code graph's card, the CRA card keeps half the row. */
.target-summary:has(.target-graph) {
grid-template-columns: minmax(0, 2fr) minmax(0, 1fr) minmax(0, 1fr);
}
.target-graph-languages {
margin: 12px 0 4px;
font-size: 13px;
color: var(--text-secondary);
}
.target-graph-note {
margin: 0;
font-size: 12px;
color: var(--text-tertiary);
}
.target-figures {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -5204,6 +5221,7 @@ tbody tr:last-child td {
@media (max-width: 1000px) {
.target-summary,
.target-summary:has(.target-graph),
.target-columns {
grid-template-columns: 1fr;
}
+18
View File
@@ -1128,6 +1128,22 @@ pub mod targets {
de: "bekannte Schwachstellen (CVE)",
en: "known vulnerabilities (CVE)",
};
pub const GRAPH_TITLE: Text = Text {
de: "Codegraph",
en: "Code graph",
};
pub const CODE_UNITS: Text = Text {
de: "Bausteine (Funktionen, Typen)",
en: "code units (functions, types)",
};
pub const ENTRY_POINTS: Text = Text {
de: "Einstiegspunkte",
en: "entry points",
};
pub const GRAPH_NOTE: Text = Text {
de: "Die Bewertung der Befunde berücksichtigt, ob ein Einstiegspunkt die Stelle erreicht.",
en: "Triage takes into account whether an entry point reaches a finding.",
};
pub const OPEN_FINDINGS: Text = Text {
de: "Offene Befunde",
en: "Open findings",
@@ -3121,6 +3137,8 @@ pub mod compliance {
"rust" => "Rust",
"csharp" => "C#",
"swift" => "Swift",
"structured_text" => "Structured Text",
"plcopen" => "PLCopen XML",
other => other,
}
}
@@ -48,6 +48,37 @@ pub struct SearchResponse {
pub total: Option<u64>,
}
/// What the target page shows of a code graph: its declarations (functions,
/// methods, types, PLC blocks), its entry points and its languages.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct GraphSummary {
pub units: u32,
pub entry_points: u32,
pub languages: Vec<String>,
}
/// The latest code graph's summary for a target; `None` when it has no
/// completed, counted build.
#[server]
pub async fn fetch_graph_summary(repo_id: String) -> Result<Option<GraphSummary>, ServerFnError> {
#[derive(Deserialize)]
struct Body {
data: Option<GraphSummary>,
}
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/summary"))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?
.error_for_status()
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: Body = resp
.json()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
Ok(body.data)
}
#[server]
pub async fn fetch_graph(repo_id: String) -> Result<GraphDataResponse, ServerFnError> {
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}"))
+27 -1
View File
@@ -21,10 +21,11 @@ use crate::components::severity_badge::SeverityBadge;
use crate::components::toast::{ToastType, Toasts};
use crate::components::vex_panel::VexPanel;
use crate::components::webhook_deliveries::WebhookDeliveries;
use crate::i18n::texts::{common, kinds, targets as tx};
use crate::i18n::texts::{common, compliance::language_name, kinds, targets as tx};
use crate::i18n::use_lang;
use crate::infrastructure::evidence::{fetch_compliance, CraCounts};
use crate::infrastructure::findings::{fetch_findings, location, FindingsQuery};
use crate::infrastructure::graph::fetch_graph_summary;
use crate::infrastructure::onboarding::{
delete_target, fetch_applicable_scans, fetch_target, is_file_kind, set_archive_password,
trigger_target_scan, update_target, validate_artifact_ref, validate_target_name,
@@ -112,6 +113,8 @@ pub fn TargetPage(id: String) -> Element {
.await
.ok()
});
let graph =
use_resource(move || async move { fetch_graph_summary(target_id()).await.ok().flatten() });
let mut editing = use_signal(|| false);
let mut confirm_delete = use_signal(|| false);
let mut adding_manual = use_signal(|| false);
@@ -156,6 +159,8 @@ pub fn TargetPage(id: String) -> Element {
.and_then(|d| d["sbom_components"].as_u64());
let cves = status_data.as_ref().and_then(|d| d["cve_alerts"].as_u64());
let is_extra = str_at(&t, "billing") == "extra";
// The code graph's card, once a scan built one with declarations in it.
let graph = graph.read().clone().flatten().filter(|g| g.units > 0);
rsx! {
BackLink {}
@@ -266,6 +271,27 @@ pub fn TargetPage(id: String) -> Element {
}
}
}
if let Some(graph) = graph {
section { class: "card target-graph",
div { class: "target-card-head",
h3 { {tx::GRAPH_TITLE.get(lang)} }
}
div { class: "target-figures",
div {
span { class: "target-figure", "{graph.units}" }
span { class: "target-figure-label", {tx::CODE_UNITS.get(lang)} }
}
div {
span { class: "target-figure", "{graph.entry_points}" }
span { class: "target-figure-label", {tx::ENTRY_POINTS.get(lang)} }
}
}
p { class: "target-graph-languages",
{graph.languages.iter().map(|l| language_name(l)).collect::<Vec<_>>().join(", ")}
}
p { class: "target-graph-note", {tx::GRAPH_NOTE.get(lang)} }
}
}
}
section { class: "card target-open",
+41 -10
View File
@@ -236,20 +236,21 @@ impl GraphEngine {
let community_count = apply_communities(&mut code_graph);
// Collect language stats
let mut languages: Vec<String> = code_graph
.nodes
.iter()
.map(|n| n.language.clone())
.collect::<std::collections::HashSet<_>>()
.into_iter()
.collect();
languages.sort();
// The languages (sorted), files and entry points, in one pass.
let mut languages = std::collections::BTreeSet::new();
let (mut files, mut entry_points) = (0u32, 0u32);
for node in &code_graph.nodes {
languages.insert(node.language.as_str());
files += u32::from(node.kind == CodeNodeKind::File);
entry_points += u32::from(node.is_entry_point);
}
build_run.node_count = code_graph.nodes.len() as u32;
build_run.edge_count = code_graph.edges.len() as u32;
build_run.community_count = community_count;
build_run.languages_parsed = languages;
build_run.languages_parsed = languages.into_iter().map(str::to_string).collect();
build_run.file_count = Some(files);
build_run.entry_point_count = Some(entry_points);
build_run.status = GraphBuildStatus::Completed;
build_run.completed_at = Some(Utc::now());
@@ -726,4 +727,34 @@ mod tests {
);
assert_eq!(find_parent_qname("src/main.rs", &node_map), None);
}
#[test]
fn the_build_run_counts_files_entry_points_and_languages() {
let main = CodeNode {
is_entry_point: true,
..node_in("src/main.rs::main", "src/main.rs", CodeNodeKind::Function)
};
let header = CodeNode {
language: "c".to_string(),
..node_in("inc/x.h", "inc/x.h", CodeNodeKind::File)
};
let output = ParseOutput {
nodes: vec![
node_in("src/main.rs", "src/main.rs", CodeNodeKind::File),
main,
node_in("src/main.rs::helper", "src/main.rs", CodeNodeKind::Function),
header,
],
edges: Vec::new(),
};
let (_, run) = GraphEngine::new(100)
.assemble(output, "test")
.expect("assembles");
assert_eq!(run.node_count, 4);
assert_eq!(run.file_count, Some(2));
assert_eq!(run.entry_point_count, Some(1));
assert_eq!(run.languages_parsed, ["c", "rust"]);
}
}