fix(targets): the targets list counts findings live (#358)
CI / Check (push) Canceled after 0s
CI / Detect Changes (push) Canceled after 0s
CI / Deploy Agent (push) Canceled after 0s
CI / Deploy Dashboard (push) Canceled after 0s
CI / Deploy Docs (push) Canceled after 0s
CI / Deploy MCP (push) Canceled after 0s

This commit was merged in pull request #358.
This commit is contained in:
sharang committed 2026-09-23 20:39:18 +00:00
1 parent 9d23b2c8e0
commit 0441220330
2 files changed
+73 -5

No files matched your search

@@ -12,7 +12,8 @@ use mongodb::bson::{doc, oid::ObjectId, to_bson};
use serde::{Deserialize, Serialize};
use compliance_core::models::{
ArtifactKind, ComplianceProfile, Credentials, OnboardedTarget, PlcFormat, ScanRun, TargetType,
ArtifactKind, ComplianceProfile, Credentials, Finding, OnboardedTarget, PlcFormat, ScanRun,
TargetType,
};
use compliance_core::scan_matrix::{applicable_scans, supports_pentest};
use compliance_core::tenant_ctx::TenantCtx;
@@ -100,16 +101,27 @@ pub async fn list_targets(
Vec::new()
}
};
let ids = targets
let ids: Vec<String> = targets
.iter()
.filter_map(|t| t.id.map(|id| id.to_hex()))
.collect();
let mut last_scans = latest_scan_runs(&db.scan_runs(), ids).await;
// `join!` borrows its futures' arguments, so the collections need names.
let (runs, findings) = (db.scan_runs(), db.findings());
let (mut last_scans, counts) = tokio::join!(
latest_scan_runs(&runs, ids.clone()),
findings_counts(&findings, ids),
);
let data = targets
.redacted()
.into_iter()
.map(|target| {
let last_scan = target.id.and_then(|id| last_scans.remove(&id.to_hex()));
.map(|mut target| {
let hex = target.id.map(|id| id.to_hex()).unwrap_or_default();
// The stored count only moves when a scan runs; manual findings,
// imports and deletions change the real number, so count now.
if let Some(count) = counts.as_ref() {
target.findings_count = count.get(&hex).copied().unwrap_or(0);
}
let last_scan = last_scans.remove(&hex);
TargetListItem { target, last_scan }
})
.collect();
@@ -165,6 +177,44 @@ async fn latest_scan_runs(
}
}
/// The number of findings of each target in `target_ids`, in one query.
///
/// Targets without findings are absent from the map. `None` when the query
/// fails, so the caller keeps the stored counts instead of showing zeros.
async fn findings_counts(
findings: &mongodb::Collection<Finding>,
target_ids: Vec<String>,
) -> Option<HashMap<String, u32>> {
use futures_util::StreamExt;
if target_ids.is_empty() {
return Some(HashMap::new());
}
// Findings store their target's id as `repo_id`.
let pipeline = vec![
doc! { "$match": { "repo_id": { "$in": target_ids } } },
doc! { "$group": { "_id": "$repo_id", "count": { "$sum": 1 } } },
];
match findings.aggregate(pipeline).await {
Ok(cursor) => Some(
cursor
.filter_map(|row| async move {
let row = row.ok()?;
let id = row.get_str("_id").ok()?.to_string();
// `$sum` over ones yields an int32 for any count a target can hold.
let count = u32::try_from(row.get_i32("count").ok()?).ok()?;
Some((id, count))
})
.collect()
.await,
),
Err(e) => {
tracing::warn!("Failed to count the targets' findings: {e}");
None
}
}
}
/// POST /api/v1/targets — create an onboarded target.
#[tracing::instrument(skip_all)]
pub async fn create_target(