Compare commits

...
Author SHA1 Message Date
sharangandClaude Opus 5.5 ca66b9a7b1 fix(scan): read UTF-16 and Windows-1252 files in the remaining readers (t84) (#942)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 51s
CI / Deploy Dashboard (push) Successful in 5m8s
CI / Deploy Agent (push) Successful in 7m21s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 09:58:55 +00:00
sharangandClaude Opus 5.5 b420b28ea8 fix(graph): read UTF-16 and Windows-1252 source files into the code graph (t84) (#941)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 4m48s
CI / Deploy Dashboard (push) Successful in 6m18s
CI / Deploy Agent (push) Successful in 8m33s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 08:13:46 +00:00
sharangandClaude Opus 5.5 d3c8eee393 fix(scan): a person's scan gets the next slot and shows as queued (t84) (#940)
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 4m47s
CI / Deploy Dashboard (push) Successful in 6m1s
CI / Deploy Agent (push) Successful in 8m15s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 07:52:24 +00:00
sharang c8deabd4d9 feat(dashboard): show the code graph, from its card and from a finding (t82) (#939)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Dashboard (push) Successful in 3m27s
2026-11-07 10:43:02 +00:00
sharang c1a70b025c 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
2026-11-07 10:24:13 +00:00
sharang 37888af374 feat(graph): PLC programs, function blocks and functions in the code graph (t82) (#936)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
CI / Deploy Agent (push) Successful in 6m46s
2026-11-07 10:05:15 +00:00
sharang 1569100721 feat(graph): C and C# in the code graph (t82) (#935)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 4s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 5m58s
CI / Deploy Dashboard (push) Successful in 7m28s
CI / Deploy Agent (push) Successful in 10m49s
2026-11-07 09:44:21 +00:00
sharang d9fcc75792 fix(nightly): start the agent in a step, not as a service (#938)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 5s
CI / Deploy Agent (push) Skipped
CI / Deploy Dashboard (push) Skipped
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Skipped
2026-11-07 09:44:11 +00:00
sharang a2699a3ec3 feat(metering): swap an extra target with an included one (t72) (#932)
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 4m54s
CI / Deploy Dashboard (push) Successful in 6m27s
CI / Deploy Agent (push) Successful in 8m36s
2026-11-07 03:11:29 +00:00
sharang 3bdaf28737 feat(metering): this month's usage on the targets page (t72) (#931)
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) Skipped
CI / Deploy Dashboard (push) Successful in 6m24s
CI / Deploy Agent (push) Successful in 8m43s
2026-11-07 02:50:56 +00:00
78 changed files with 7176 additions and 1709 deletions

No files matched your search

+4 -2
View File
@@ -138,6 +138,8 @@ jobs:
run: cargo clippy -p werkbank-exec --all-targets -- -D warnings
- name: Clippy (control-map)
run: cargo clippy -p control-map --all-targets -- -D warnings
- name: Clippy (graph)
run: cargo clippy -p compliance-graph --all-targets -- -D warnings
# Security audit
- name: Security Audit
@@ -146,8 +148,8 @@ jobs:
RUSTC_WRAPPER: ""
# Tests (reuses compilation artifacts from clippy)
- name: Tests (core + agent + werkbank-exec + control-map)
run: cargo test -p compliance-core -p compliance-agent -p werkbank-exec -p control-map --lib
- name: Tests (core + agent + graph + werkbank-exec + control-map)
run: cargo test -p compliance-core -p compliance-agent -p compliance-graph -p werkbank-exec -p control-map --lib
# compliance-core's integration tests need no services.
- name: Tests (core integration)
run: cargo test -p compliance-core --tests
+58 -26
View File
@@ -51,30 +51,6 @@ jobs:
env:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: example
# The image main deployed. Dev mode (no Keycloak): the harness talks to
# the unauthenticated dev tenant; source_only matches staging.
agent:
image: repo.breakpilot.com/pruefwerk/compliance-agent:latest
credentials:
username: ${{ secrets.REGISTRY_USERNAME }}
password: ${{ secrets.REGISTRY_PASSWORD }}
env:
APP_ENV: dev
MONGODB_URI: mongodb://root:example@mongo:27017/?authSource=admin
MONGODB_DATABASE: nightly
PW_FEATURES: source_only
# No chat model: LLM triage, code review and the control judge are
# off (LlmClient sends nothing without LITELLM_MODEL, #575). Their
# output never gates the run, and with the model on, ~600 calls of
# 11 s on average (p99 147 s) on the gateway prod also uses kept
# every scan past NIGHTLY_TIMEOUT_SECS from 2026-10-30 on (#573).
# Embeddings stay on: the gateway's embedding model.
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
LITELLM_EMBED_MODEL: bge-multilingual-gemma2
# Optional. The CODESYS CVE match queries NVD, which rate-limits
# unauthenticated clients; a key keeps those CVEs from going missing.
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
steps:
- name: Checkout
run: |
@@ -149,10 +125,59 @@ jobs:
env:
RUSTC_WRAPPER: ""
# The image main deployed, started here rather than as a service:
# act_runner 0.6.1 hands a service's registry credentials to the job
# container's own pull (map order decides which service wins), so the
# Harbor login reached docker.io about every other night. mongo, the
# only service left, has no credentials. The agent shares this
# container's network: it reaches mongo by name and listens on
# localhost here. The login lands in this container's ~/.docker, which
# goes with it.
# Dev mode (no Keycloak): the harness talks to the unauthenticated dev
# tenant; source_only matches staging.
- name: Start the agent
run: |
curl -fsSL -o /tmp/docker.tgz \
https://download.docker.com/linux/static/stable/x86_64/docker-27.5.1.tgz
echo "4f798b3ee1e0140eab5bf30b0edc4e84f4cdb53255a429dc3bbae9524845d640 /tmp/docker.tgz" \
| sha256sum -c -
tar xzf /tmp/docker.tgz --strip-components=1 -C /usr/local/bin docker/docker
echo "$REGISTRY_PASSWORD" | docker login repo.breakpilot.com -u "$REGISTRY_USERNAME" --password-stdin
# -e NAME without a value passes this step's variable, so no secret
# appears on the command line. The container runs on the runner's
# daemon, outside the job's own limits, so it has its own; the label
# finds one a cancelled job left behind.
docker run -d --pull always --name "nightly-agent-${GITHUB_RUN_ID}" \
--label pruefwerk-nightly --memory 4g --cpus 2 \
--network "container:$(hostname)" \
-e APP_ENV=dev \
-e MONGODB_URI=mongodb://root:example@mongo:27017/?authSource=admin \
-e MONGODB_DATABASE=nightly \
-e PW_FEATURES=source_only \
-e LITELLM_URL -e LITELLM_API_KEY \
-e LITELLM_EMBED_MODEL=bge-multilingual-gemma2 \
-e NVD_API_KEY \
repo.breakpilot.com/pruefwerk/compliance-agent:latest
env:
RUSTC_WRAPPER: ""
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
# No chat model: LLM triage, code review and the control judge are
# off (LlmClient sends nothing without LITELLM_MODEL, #575). Their
# output never gates the run, and with the model on, ~600 calls of
# 11 s on average (p99 147 s) on the gateway prod also uses kept
# every scan past NIGHTLY_TIMEOUT_SECS from 2026-10-30 on (#573).
# Embeddings stay on: the gateway's embedding model.
LITELLM_URL: ${{ secrets.NIGHTLY_LITELLM_URL }}
LITELLM_API_KEY: ${{ secrets.NIGHTLY_LITELLM_API_KEY }}
# Optional. The CODESYS CVE match queries NVD, which rate-limits
# unauthenticated clients; a key keeps those CVEs from going missing.
NVD_API_KEY: ${{ secrets.NIGHTLY_NVD_API_KEY }}
- name: Wait for the agent
run: |
for i in $(seq 1 90); do
curl -fsS http://agent:3001/api/v1/health && exit 0
curl -fsS http://localhost:3001/api/v1/health && exit 0
sleep 2
done
echo "agent did not become healthy" >&2
@@ -163,13 +188,20 @@ jobs:
- name: Scan the corpus and compare with the baselines
run: cargo test -p compliance-agent --test nightly -- --nocapture
env:
NIGHTLY_AGENT_URL: http://agent:3001
NIGHTLY_AGENT_URL: http://localhost:3001
NIGHTLY_CODESYS_SAMPLE: /tmp/csv-blackbox.projectarchive
NIGHTLY_ZEPHYR_EXAMPLE: /tmp/zephyr-example.zip
NIGHTLY_IOS_SAMPLE: /tmp/ios-sample.zip
NIGHTLY_ANDROID_SAMPLE: /tmp/android-sample.zip
NIGHTLY_BLESS: ${{ inputs.bless && '1' || '0' }}
# The agent is not a service, so the runner does not remove it.
- name: Stop the agent
if: always()
run: docker rm -f "nightly-agent-${GITHUB_RUN_ID}" || true
env:
RUSTC_WRAPPER: ""
# upload-artifact is a Node action and the Rust image has no node.
- name: Install node for the artifact upload
if: always()
Generated
+24
View File
@@ -662,6 +662,7 @@ dependencies = [
"base64 0.22.1",
"bson",
"chrono",
"encoding_rs",
"hex",
"jsonschema",
"jsonwebtoken",
@@ -754,9 +755,12 @@ dependencies = [
"petgraph",
"serde",
"tantivy",
"thiserror 2.0.18",
"tokio",
"tracing",
"tree-sitter",
"tree-sitter-c",
"tree-sitter-c-sharp",
"tree-sitter-javascript",
"tree-sitter-python",
"tree-sitter-rust",
@@ -6502,6 +6506,26 @@ dependencies = [
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-c"
version = "0.23.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "afd2b1bf1585dc2ef6d69e87d01db8adb059006649dd5f96f31aa789ee6e9c71"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-c-sharp"
version = "0.23.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "67f06accca7b45351758663b8215089e643d53bd9a660ce0349314263737fcb0"
dependencies = [
"cc",
"tree-sitter-language",
]
[[package]]
name = "tree-sitter-javascript"
version = "0.23.1"
+2
View File
@@ -28,6 +28,8 @@ chrono = { version = "0.4", features = ["serde"] }
mongodb = { version = "3", features = ["rustls-tls", "compat-3-0-0"] }
reqwest = { version = "0.12", features = ["json", "rustls-tls", "multipart", "cookies", "stream"], default-features = false }
thiserror = "2"
# Source files in UTF-16 or Windows-1252 (code graph, PLC, .NET).
encoding_rs = "0.8"
sha2 = "0.10"
hex = "0.4"
uuid = { version = "1", features = ["v4", "v5", "serde"] }
+106 -26
View File
@@ -10,7 +10,7 @@ use crate::database::DatabasePool;
use crate::llm::LlmClient;
use crate::pipeline::orchestrator::PipelineOrchestrator;
use crate::registry::RegistryClient;
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
use crate::scan_gate::{Admission, HeldTarget, Job, Priority, ScanGate};
use crate::secrets::SecretBox;
/// A target whose billing changed, with its new billing (t72).
@@ -262,11 +262,16 @@ impl ComplianceAgent {
}
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// run at once, and a request for a target that is already being scanned is
/// coalesced — it becomes the one pending follow-up that this task runs next,
/// or it is dropped if a follow-up is already pending. A scheduled scan
/// first waits a random [`crate::scan_gate::start_delay`]. Every trigger
/// (click, webhook, scheduler, demo seed) comes through here.
/// run at once, a person's before scheduled and webhook ones, and a request
/// for a target that is already queued or being scanned is coalesced — it
/// becomes the one pending follow-up that this task runs next, it takes over
/// a queued scan that was not a person's, or it is dropped as covered. A
/// scheduled scan first waits a random [`crate::scan_gate::start_delay`].
/// Every trigger (click, webhook, scheduler, demo seed) comes through here.
///
/// Each request is recorded at once as a `queued` run, which shows that it
/// waits for a slot (t84); a request that will not run has its queued run
/// removed again.
///
/// # Errors
///
@@ -288,15 +293,22 @@ impl ComplianceAgent {
);
tokio::time::sleep(delay).await;
}
let db = self.db_pool.for_tenant_id(tenant_id).await?;
let run_id = queue_run(&db, target_id, &trigger).await;
let key = ScanGate::key(tenant_id, target_id);
match self.scan_gate.admit(&key, trigger.clone()) {
match self
.scan_gate
.admit(&key, Job::new(trigger, run_id.clone()))
{
Admission::Run => {}
Admission::Coalesced => {
Admission::Coalesced { replaced } => {
tracing::info!(
tenant_id,
target_id,
took_over = replaced.is_some(),
"scan already running; follow-up queued"
);
discard_queued_run(&db, replaced.as_deref()).await;
return Ok(());
}
Admission::Dropped => {
@@ -305,41 +317,43 @@ impl ComplianceAgent {
target_id,
"scan and follow-up already queued; dropped"
);
discard_queued_run(&db, run_id.as_deref()).await;
return Ok(());
}
}
// Released on panic or cancellation; a normal finish disarms it.
let held = HeldTarget::new(&self.scan_gate, key.clone());
let mut trigger = trigger;
let result = loop {
let outcome = {
let _slot = self
.scan_gate
.slot()
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
self.run_one_target_scan(tenant_id, target_id, trigger.clone())
.await
};
// The scan to run is the one current when the slot is granted: a
// person's request may have taken it over while it waited.
let (slot, job) = self
.scan_gate
.start(&key)
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let outcome = self.run_one_target_scan(tenant_id, target_id, &job).await;
drop(slot);
if let Err(e) = &outcome {
tracing::error!(tenant_id, target_id, "scan failed: {e}");
fail_queued_run(&db, job.run_id.as_deref(), e).await;
}
match self.scan_gate.finish(&key) {
Some(next) => trigger = next,
None => break outcome,
if !self.scan_gate.finish(&key) {
break outcome;
}
};
held.disarm();
result
}
/// One scan of a target, with no gating: the pipeline plus its usage event.
/// One scan of a target, with no gating: the pipeline plus its usage event,
/// recorded on the run that waited for it and charged as `job` says.
async fn run_one_target_scan(
&self,
tenant_id: &str,
target_id: &str,
trigger: compliance_core::models::ScanTrigger,
job: &Job,
) -> Result<(), crate::error::AgentError> {
let trigger = job.trigger.clone();
let db = self.db_pool.for_tenant_id(tenant_id).await?;
// Whether this target is included or extra decides whether its scan
// counts, and the plan's limits whether a counted one may run (t72).
@@ -353,9 +367,12 @@ impl ComplianceAgent {
.with_nuget_license_cache(self.nuget_license_cache.clone())
.with_exploit_cache(self.exploit_cache.clone())
.with_advisory_index(self.advisory_index.clone())
.with_plan_limits(plan.map(|p| p.limits));
.with_plan_limits(plan.map(|p| p.limits))
.with_charged_as(job.charged_as.clone());
let started = chrono::Utc::now();
let outcome = orchestrator.run_target(target_id, trigger.clone()).await?;
let outcome = orchestrator
.run_target(target_id, trigger.clone(), job.run_id.as_deref())
.await?;
// Support's scans are ours, not the customer's usage; a scheduled scan
// skipped because nothing changed scanned nothing (#465).
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
@@ -424,7 +441,7 @@ impl ComplianceAgent {
// slot too. Each PR is distinct work, so it is not coalesced.
let _slot = self
.scan_gate
.slot()
.slot(Priority::Background)
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let db = self.db_pool.for_tenant_id(tenant_id).await?;
@@ -500,6 +517,69 @@ impl ComplianceAgent {
}
}
/// Record a scan request for `target_id` as a run waiting for a slot (t84),
/// so it shows at once. Returns its id, or `None` when it could not be
/// written: the scan then runs on a run of its own when it starts.
async fn queue_run(
db: &crate::database::Database,
target_id: &str,
trigger: &compliance_core::models::ScanTrigger,
) -> Option<String> {
let run = compliance_core::models::ScanRun::queued(target_id.to_string(), trigger.clone());
match db.scan_runs().insert_one(&run).await {
Ok(insert) => insert.inserted_id.as_object_id().map(|id| id.to_hex()),
Err(e) => {
tracing::warn!(target_id, "queued scan run not recorded: {e}");
None
}
}
}
/// Remove the queued run `run_id` of a request that will not run, because
/// another queued scan covers it or took it over. A run that has started
/// meanwhile is kept.
async fn discard_queued_run(db: &crate::database::Database, run_id: Option<&str>) {
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
return;
};
if let Err(e) = db
.scan_runs()
.delete_one(mongodb::bson::doc! { "_id": oid, "status": "queued" })
.await
{
tracing::warn!(run_id = %oid, "queued scan run not removed: {e}");
}
}
/// Close the queued run `run_id` as failed when its scan ended with `error`
/// before it started (an unknown target, an unreachable database), so it does
/// not stay queued. A run the scan started records its own outcome.
async fn fail_queued_run(
db: &crate::database::Database,
run_id: Option<&str>,
error: &crate::error::AgentError,
) {
let Some(oid) = run_id.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) else {
return;
};
let (code, message) = error.run_failure();
if let Err(e) = db
.scan_runs()
.update_one(
mongodb::bson::doc! { "_id": oid, "status": "queued" },
mongodb::bson::doc! { "$set": {
"status": "failed",
"error_message": message,
"error_code": mongodb::bson::to_bson(&code).unwrap_or_default(),
"completed_at": mongodb::bson::DateTime::now(),
} },
)
.await
{
tracing::warn!(run_id = %oid, "queued scan run not closed: {e}");
}
}
/// Findings of `target_id` first stored since `since`, by severity; `None`
/// when there are none.
async fn new_findings_summary(
@@ -79,9 +79,14 @@ async fn load_inputs(
.map_err(load_err)?,
)
.await,
// A run still waiting for a slot has examined nothing yet (t84).
last_run: db
.scan_runs()
.find_one(by_target)
.find_one({
let mut started = by_target;
started.insert("status", doc! { "$ne": "queued" });
started
})
.sort(doc! { "started_at": -1 })
.await
.map_err(load_err)?,
+114 -4
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,60 @@ 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>,
/// Source files left out because they could not be read as text; 0 when
/// none were, or the build did not count them.
pub unreadable_files: u32,
}
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,
// Not `?`: a build from before this count still shows its card.
unreadable_files: build.unreadable_file_count.unwrap_or(0),
})
}
}
/// 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(
@@ -355,7 +411,9 @@ pub async fn get_file_content(
return Err(StatusCode::FORBIDDEN);
}
let content = std::fs::read_to_string(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
// Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens.
let content =
compliance_core::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
// Cap at 10,000 lines
let truncated: String = content.lines().take(10_000).collect::<Vec<_>>().join("\n");
@@ -434,10 +492,17 @@ pub async fn trigger_build(
}
};
// A PLC target's graph is its POUs, as the scan builds it.
let plc_files = crate::pipeline::plan::build_scan_plan(&repo)
.has(compliance_core::models::ScanType::PlcControlLogic)
.then(|| crate::pipeline::plc::read_tree(&repo_path));
let source = match &plc_files {
Some(files) => crate::pipeline::graph_build::GraphSource::Plc(files),
None => crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
};
let graph_build_id = uuid::Uuid::new_v4().to_string();
let engine = compliance_graph::GraphEngine::new(50_000);
match engine.build_graph(&repo_path, &repo_id, &graph_build_id) {
match crate::pipeline::graph_build::build_graph(source, &repo_id, &graph_build_id) {
Ok((code_graph, build_run)) => {
let store = compliance_graph::graph::persistence::GraphStore::new(db.inner());
let _ = store.delete_repo_graph(&repo_id).await;
@@ -460,3 +525,48 @@ 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());
}
#[test]
fn unreadable_files_are_shown_and_an_uncounted_build_has_none() {
let mut build = completed(10, Some(2), Some(1));
build.unreadable_file_count = Some(3);
assert_eq!(GraphSummary::of(build).expect("shown").unreadable_files, 3);
let uncounted = completed(10, Some(2), Some(1));
assert_eq!(
GraphSummary::of(uncounted).expect("shown").unreadable_files,
0
);
}
}
@@ -0,0 +1,54 @@
//! The tenant's metering this month, for the dashboard's usage view (t72).
use axum::extract::Extension;
use axum::http::StatusCode;
use axum::Json;
use serde::Serialize;
use compliance_core::tenant_ctx::TenantCtx;
use super::dto::{tenant_db, AgentExt};
use crate::metering::{month_summary, MonthSummary};
/// The usage view: what was used this month, and what the plan allows.
#[derive(Debug, Serialize)]
struct UsageView {
/// What was used.
#[serde(flatten)]
used: MonthSummary,
/// Whether the plan could be read; without it the limits are unknown,
/// not unlimited.
plan_known: bool,
/// The plan's included targets; `None` is unlimited.
included_targets: Option<u32>,
/// The monthly quota; `None` is unlimited.
monthly_pruefungen: Option<u32>,
/// The customer's Prüftag cap; `None` is no cap.
prueftag_cap: Option<u32>,
}
/// GET /api/v1/metering/usage — the tenant's Prüfungen, Prüftage and extra
/// targets this month (Europe/Berlin), with the plan's limits.
///
/// # Errors
///
/// `500` when the counters cannot be read.
pub async fn get_usage(
Extension(agent): AgentExt,
tenant: TenantCtx,
) -> Result<Json<serde_json::Value>, StatusCode> {
let db = tenant_db(&agent, &tenant).await?;
let used = month_summary(&db, chrono::Utc::now()).await.map_err(|e| {
tracing::error!(tenant_id = %tenant.0.tenant_id, "usage not read: {e}");
StatusCode::INTERNAL_SERVER_ERROR
})?;
let plan = agent.plan(&tenant.0.tenant_id).await;
let view = UsageView {
used,
plan_known: plan.is_some(),
included_targets: plan.and_then(|p| p.included_targets),
monthly_pruefungen: plan.and_then(|p| p.limits.monthly_pruefungen),
prueftag_cap: plan.and_then(|p| p.limits.prueftag_cap),
};
Ok(Json(serde_json::json!({ "data": view })))
}
+1
View File
@@ -14,6 +14,7 @@ pub mod licenses;
pub mod manual_findings;
pub mod mcp_servers;
pub mod mcp_tokens;
pub mod metering;
pub mod notifications;
pub mod onboarding;
pub mod oscal;
@@ -114,7 +114,7 @@ pub async fn list_targets(
// `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()),
latest_scan_runs(&runs, ids.clone(), true),
findings_counts(&findings, ids),
);
let data = targets
@@ -179,10 +179,13 @@ impl TargetFilter {
}
}
/// The newest scan run of each target in `target_ids`, in one query.
/// The newest scan run of each target in `target_ids`, in one query; with
/// `with_queued`, also a run still waiting for a slot (t84), which the
/// dashboard shows but which has scanned nothing yet.
pub(crate) async fn latest_scan_runs(
runs: &mongodb::Collection<ScanRun>,
target_ids: Vec<String>,
with_queued: bool,
) -> HashMap<String, ScanRun> {
use futures_util::StreamExt;
@@ -190,8 +193,12 @@ pub(crate) async fn latest_scan_runs(
return HashMap::new();
}
// Runs store their target's id as `repo_id`.
let mut matching = doc! { "repo_id": { "$in": target_ids } };
if !with_queued {
matching.insert("status", doc! { "$ne": "queued" });
}
let pipeline = vec![
doc! { "$match": { "repo_id": { "$in": target_ids } } },
doc! { "$match": matching },
doc! { "$sort": { "started_at": -1 } },
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
];
@@ -1023,6 +1030,76 @@ fn requested_trigger(staff: bool, reason: Option<&str>) -> compliance_core::mode
}
}
/// `POST /api/v1/targets/{id}/billing/swap`: the included target to swap
/// the extra target `{id}` with.
#[derive(Debug, Deserialize)]
pub struct SwapRequest {
/// The id of the included target that becomes extra.
pub with: String,
}
/// The JSON `error` of a refused swap, for the dashboard to word.
fn swap_refusal_code(refusal: compliance_core::models::SwapRefusal) -> &'static str {
use compliance_core::models::SwapRefusal;
match refusal {
SwapRefusal::Unlimited => "swap_unlimited",
SwapRefusal::NotExtra => "swap_not_extra",
SwapRefusal::NotIncluded => "swap_not_included",
SwapRefusal::Locked => "swap_locked",
}
}
/// POST /api/v1/targets/{id}/billing/swap — swap the extra target `{id}`
/// with the included target `with` (t72): `{id}` becomes included and stays
/// so until the end of the calendar month, `with` becomes extra at once.
/// The number of extra targets, and so the extra-target line, is the same.
///
/// # Errors
///
/// `404` for a target that is not an active one of the tenant, `409` with
/// the reason when the swap is not allowed, `503` when the plan cannot be
/// read.
pub async fn swap_target_billing(
Extension(agent): AgentExt,
tenant: TenantCtx,
Path(id): Path<String>,
Json(req): Json<SwapRequest>,
) -> Result<Json<serde_json::Value>, (StatusCode, Json<serde_json::Value>)> {
let refuse =
|status: StatusCode, error: &str| (status, Json(serde_json::json!({ "error": error })));
let incoming = parse_oid(&id).map_err(|s| refuse(s, "invalid_id"))?;
let outgoing = parse_oid(&req.with).map_err(|s| refuse(s, "invalid_id"))?;
let db = tenant_db(&agent, &tenant)
.await
.map_err(|s| refuse(s, "database_unavailable"))?;
let tenant_id = tenant.0.tenant_id.as_str();
let plan = agent
.plan(tenant_id)
.await
.ok_or_else(|| refuse(StatusCode::SERVICE_UNAVAILABLE, "plan_unavailable"))?;
let outcome = crate::metering::swap(
&db,
incoming,
outgoing,
plan.included_targets.is_some(),
chrono::Utc::now(),
)
.await
.map_err(|e| {
tracing::error!(tenant_id, "swap failed: {e}");
refuse(StatusCode::INTERNAL_SERVER_ERROR, "swap_failed")
})?;
match outcome {
None => Err(refuse(StatusCode::NOT_FOUND, "target_not_found")),
Some(Err(refusal)) => Err(refuse(StatusCode::CONFLICT, swap_refusal_code(refusal))),
Some(Ok(())) => {
agent.refresh_billing(tenant_id, &db).await;
tracing::info!(tenant_id, incoming = %id, outgoing = %req.with, "targets swapped");
Ok(Json(serde_json::json!({ "data": { "swapped": true } })))
}
}
}
/// POST /api/v1/targets/{id}/scan — trigger a scan for the target.
///
/// Dispatches to the unified pipeline when `UNIFIED_PIPELINE` is set (else the
@@ -560,7 +560,7 @@ pub async fn list_targets(
.collect();
let runs = db.scan_runs();
let (mut last_scans, open, vulns) = tokio::join!(
super::onboarding::latest_scan_runs(&runs, ids.clone()),
super::onboarding::latest_scan_runs(&runs, ids.clone(), false),
open_findings_counts(&db, ids.clone()),
open_vulnerabilities_counts(&db, ids),
);
+9
View File
@@ -15,6 +15,7 @@ pub fn build_router() -> Router {
.route("/api/v1/stats/overview", get(handlers::stats_overview))
// The tenant's projects (owned by the registry), for assigning targets.
.route("/api/v1/projects", get(handlers::projects::list_projects))
.route("/api/v1/metering/usage", get(handlers::metering::get_usage))
// Whether the caller may use Prüfwerk at all: answered by the
// authentication and entitlement layers in front of it (a blocked
// member gets 403 MEMBER_BLOCKED), for the dashboard's sign-in check.
@@ -84,6 +85,10 @@ pub fn build_router() -> Router {
"/api/v1/targets/{id}/scan",
post(handlers::onboarding::trigger_target_scan),
)
.route(
"/api/v1/targets/{id}/billing/swap",
post(handlers::onboarding::swap_target_billing),
)
.route("/api/v1/findings", get(handlers::list_findings))
.route(
"/api/v1/findings/variants",
@@ -194,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),
+1 -1
View File
@@ -215,7 +215,7 @@ pub async fn grounded_surface_findings(
/// Read a window of lines around `line` (1-based) from `repo_path/file`.
fn fetch_region(repo_path: &Path, file: &str, line: u32) -> Option<CandidateRegion> {
let content = std::fs::read_to_string(repo_path.join(file)).ok()?;
let content = compliance_core::encoding::read_source(&repo_path.join(file)).ok()?;
let lines: Vec<&str> = content.lines().collect();
if lines.is_empty() {
return None;
+20 -1
View File
@@ -156,7 +156,8 @@ pub fn retrieve(repo_path: &Path, terms: &[&str], excluded: &[String]) -> Vec<Ca
if !meta.is_file() || meta.len() > MAX_FILE_BYTES {
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
let Ok(content) = compliance_core::encoding::read_source(path) else {
continue;
};
let rel = path
@@ -286,6 +287,24 @@ mod tests {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_windows_1252_file_is_read() {
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
// "Prüfung" as Windows-1252 writes it: 0xFC for "ü".
let path = dir.join("app/Auth.cs");
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
std::fs::write(
&path,
b"// Pr\xFCfung\nbool Login(string u, string p) { }\n",
)
.unwrap();
let regions = retrieve(&dir, terms_for("cra-ai-11"), &[]);
let _ = std::fs::remove_dir_all(&dir);
assert_eq!(regions.len(), 1);
assert!(regions[0].content.contains("Prüfung"));
}
#[test]
fn firmware_update_code_is_read_but_not_the_vendor_hal() {
let dir = std::env::temp_dir().join(format!("surface-{}", uuid::Uuid::new_v4()));
+43 -10
View File
@@ -43,14 +43,15 @@ struct OrphanRule {
}
/// Code scans are what customers see, so they get their own `interrupted`
/// status. The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
/// status, also those still waiting for a slot: the queue lives in the agent's
/// memory and is gone after a restart (t84). The rest close as `failed` with [`INTERRUPTED_MESSAGE`]: DAST and
/// pentest are off in production, and graph and embedding builds are steps of
/// a scan. A paused pentest session can only be resumed through in-memory
/// state, so after a restart it is as dead as a running one.
const ORPHAN_RULES: [OrphanRule; 5] = [
OrphanRule {
collection: "scan_runs",
open: &["running"],
open: &["queued", "running"],
closed_as: "interrupted",
},
OrphanRule {
@@ -218,12 +219,16 @@ async fn targets_to_resume(
.await?;
let mut out = Vec::new();
for id in ids.iter().filter_map(|v| v.as_str()) {
// Only scans that had started count: one interrupted while it still
// waited for a slot cannot be what stopped the agent. It never got a
// start time of its own, so it still starts when it was requested.
let interruptions = db
.scan_runs()
.count_documents(doc! {
"repo_id": id,
"status": "interrupted",
"completed_at": { "$gte": window },
"$expr": { "$ne": ["$started_at", "$queued_at"] },
})
.await?;
if interruptions > MAX_RECENT_INTERRUPTIONS {
@@ -243,12 +248,25 @@ async fn targets_to_resume(
.await?;
if active > 0 {
// Resumed as it was started: a scan a person started runs even when
// nothing changed since the last completed one (#465).
let trigger = db
// nothing changed since the last completed one (#465). Of a running
// scan and its queued follow-up, a person's wins.
let triggers = db
.scan_runs()
.find_one(doc! { "repo_id": id, "status": "interrupted", "completed_at": closed })
.await?
.map_or(ScanTrigger::Scheduled, |run| run.trigger);
.distinct(
"trigger",
doc! { "repo_id": id, "status": "interrupted", "completed_at": closed },
)
.await?;
let triggers: Vec<ScanTrigger> = triggers
.into_iter()
.filter_map(|t| mongodb::bson::from_bson(t).ok())
.collect();
let trigger = triggers
.iter()
.find(|t| t.started_by_person())
.or_else(|| triggers.first())
.cloned()
.unwrap_or(ScanTrigger::Scheduled);
out.push((id.to_string(), trigger));
}
}
@@ -365,10 +383,11 @@ mod tests {
let archived = insert(archived_target).await;
let earlier_only = insert(target("earlier-only")).await;
// Arrange: runs left open, plus one interrupted an hour ago.
// The scan to resume was started by a person.
// Arrange: runs left open, plus one interrupted an hour ago. The
// target to resume has a scheduled scan running and a person's
// follow-up queued (t84): one interruption, resumed as the person's.
for (id, trigger) in [
(&resumes, ScanTrigger::Manual),
(&resumes, ScanTrigger::Scheduled),
(&looping, ScanTrigger::Scheduled),
(&archived, ScanTrigger::Scheduled),
] {
@@ -377,6 +396,10 @@ mod tests {
.await
.unwrap();
}
db.scan_runs()
.insert_one(ScanRun::queued(resumes.clone(), ScanTrigger::Manual))
.await
.unwrap();
for id in [&looping, &earlier_only] {
let mut run = ScanRun::new(id.clone(), ScanTrigger::Scheduled);
run.status = compliance_core::models::ScanRunStatus::Interrupted;
@@ -423,6 +446,16 @@ mod tests {
}
}
#[test]
fn queued_code_scans_are_closed_at_startup_too() {
let scan_rule = ORPHAN_RULES
.iter()
.find(|r| r.collection == "scan_runs")
.expect("scan_runs rule");
assert!(scan_rule.open.contains(&"queued"));
assert!(scan_rule.open.contains(&"running"));
}
#[test]
fn code_scans_are_interrupted_not_failed() {
let scan_rule = ORPHAN_RULES
+1 -1
View File
@@ -861,7 +861,7 @@ fn read_surrounding_context(finding: &Finding) -> Option<String> {
let line = finding.line_number? as usize;
// Try to read the file — this works because the repo is cloned locally
let content = std::fs::read_to_string(file_path).ok()?;
let content = compliance_core::encoding::read_source(std::path::Path::new(file_path)).ok()?;
let lines: Vec<&str> = content.lines().collect();
let start = line.saturating_sub(25);
+156 -4
View File
@@ -20,7 +20,8 @@ use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, Document};
use compliance_core::models::{
split_included, BillableTarget, DayUsage, MonthUsage, PlanLimits, RunCharge, TargetBilling,
check_swap, split_included, BillableTarget, DayUsage, IncludedChoice, MonthUsage, PlanLimits,
RunCharge, SwapRefusal, TargetBilling,
};
use crate::database::Database;
@@ -45,12 +46,12 @@ pub async fn assign_billing(
db: &Database,
included: Option<u32>,
) -> Result<Vec<(ObjectId, TargetBilling)>, AgentError> {
// Only the three fields the split needs: a whole target holds its
// artifacts, and older documents may lack fields the model requires.
// Only the fields the split needs: a whole target holds its artifacts,
// and older documents may lack fields the model requires.
let docs: Vec<Document> = db
.raw_collection("onboarded_targets")
.find(doc! { "archived_at": null })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1 })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1, "included_choice": 1 })
.await?
.try_collect()
.await?;
@@ -90,9 +91,89 @@ fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
.get("billing")
.and_then(|b| mongodb::bson::from_bson(b.clone()).ok())
.unwrap_or_default(),
choice: target
.get("included_choice")
.and_then(|c| mongodb::bson::from_bson(c.clone()).ok()),
})
}
/// The first instant after the calendar month (Europe/Berlin) of `at`: until
/// then a target swapped in at `at` stays included.
pub fn end_of_berlin_month(at: DateTime<Utc>) -> DateTime<Utc> {
use chrono::{Datelike, TimeZone};
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
let (year, month) = if local.month() == 12 {
(local.year() + 1, 1)
} else {
(local.year(), local.month() + 1)
};
// Midnight is never skipped or repeated in Berlin (DST changes at 2–3 h).
chrono_tz::Europe::Berlin
.with_ymd_and_hms(year, month, 1, 0, 0, 0)
.earliest()
.map_or(at, |next| next.with_timezone(&Utc))
}
/// Swap the extra target `incoming` with the included target `outgoing`
/// (t72): the one swapped in stays included until the end of the calendar
/// month, the other becomes extra. It records the customer's choice; the
/// next [`assign_billing`] (which the caller runs) moves the billing.
///
/// # Arguments
///
/// * `limited` - Whether the plan limits the included targets.
///
/// # Returns
///
/// `None` when either target is not an active one of the tenant; else
/// whether the swap was made, or why not.
///
/// # Errors
///
/// Returns an error if the targets cannot be read or updated.
pub async fn swap(
db: &Database,
incoming: ObjectId,
outgoing: ObjectId,
limited: bool,
at: DateTime<Utc>,
) -> Result<Option<Result<(), SwapRefusal>>, AgentError> {
let targets = db.onboarded_targets();
let active = |id: ObjectId| doc! { "_id": id, "archived_at": null };
let (Some(swapped_in), Some(swapped_out)) = (
targets.find_one(active(incoming)).await?,
targets.find_one(active(outgoing)).await?,
) else {
return Ok(None);
};
let locked = swapped_out.included_until.is_some_and(|until| until > at);
if let Err(refusal) = check_swap(limited, swapped_in.billing, swapped_out.billing, locked) {
return Ok(Some(Err(refusal)));
}
let to_bson = |v: IncludedChoice| {
mongodb::bson::to_bson(&v).map_err(|e| AgentError::Other(e.to_string()))
};
targets
.update_one(
doc! { "_id": incoming },
doc! { "$set": {
"included_choice": to_bson(IncludedChoice::Included)?,
"included_until": mongodb::bson::DateTime::from_chrono(end_of_berlin_month(at)),
} },
)
.await?;
targets
.update_one(
doc! { "_id": outgoing },
doc! {
"$set": { "included_choice": to_bson(IncludedChoice::Extra)? },
"$unset": { "included_until": "" },
},
)
.await?;
Ok(Some(Ok(())))
}
/// The tenant's plan as metering reads it from the registry.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Plan {
@@ -316,11 +397,80 @@ pub async fn record_extra_peak(
Ok(Some(peak))
}
/// The tenant's metering this month, for the dashboard (t72).
#[derive(Debug, Clone, Default, PartialEq, Eq, serde::Serialize)]
pub struct MonthSummary {
/// The calendar month in Europe/Berlin, `YYYY-MM`.
pub month: String,
/// Counted Prüfungen charged to the quota.
pub pruefungen: u32,
/// Prüftage booked.
pub prueftage: u32,
/// Active targets that are extra now.
pub extra_targets: u32,
/// The highest number of extra targets at once this month, which the
/// extra-target line bills.
pub extra_peak: u32,
}
/// What the tenant used in the month of `at`.
///
/// # Errors
///
/// Returns an error if the counters or the targets cannot be read.
pub async fn month_summary(db: &Database, at: DateTime<Utc>) -> Result<MonthSummary, AgentError> {
let (month, _) = berlin_period(at);
let stored = db
.raw_collection(MONTHS)
.find_one(doc! { "_id": &month })
.await?;
let extra = mongodb::bson::to_bson(&TargetBilling::Extra)
.map_err(|e| AgentError::Other(e.to_string()))?;
let extra_targets = db
.onboarded_targets()
.count_documents(doc! { "archived_at": null, "billing": extra })
.await?;
let extra_targets = u32::try_from(extra_targets).unwrap_or(u32::MAX);
Ok(MonthSummary {
month,
pruefungen: count(stored.as_ref(), "pruefungen"),
prueftage: count(stored.as_ref(), "prueftage"),
extra_targets,
// The peak is recorded when the billing is refreshed; until then
// it is at least what is extra now.
extra_peak: count(stored.as_ref(), "extra_peak").max(extra_targets),
})
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
#[test]
fn a_swap_holds_until_the_berlin_month_ends() {
let at = |y, m, d, h| {
Utc.with_ymd_and_hms(y, m, d, h, 0, 0)
.single()
.expect("valid")
};
// 1 Dec 00:00 in Berlin (CET) is 30 Nov 23:00 UTC.
assert_eq!(
end_of_berlin_month(at(2026, 11, 6, 9)),
at(2026, 11, 30, 23)
);
// December rolls into January of the next year.
assert_eq!(
end_of_berlin_month(at(2026, 12, 15, 9)),
at(2026, 12, 31, 23)
);
// 1 Aug 00:00 in Berlin (CEST) is 31 Jul 22:00 UTC.
assert_eq!(
end_of_berlin_month(at(2026, 7, 31, 21)),
at(2026, 7, 31, 22)
);
}
#[test]
fn periods_are_calendar_ones_in_berlin() {
let at = |y, m, d, h, min| {
@@ -368,6 +518,7 @@ mod tests {
id,
created_at: at.to_chrono(),
billing: TargetBilling::Extra,
choice: None,
})
);
assert_eq!(
@@ -376,6 +527,7 @@ mod tests {
id,
created_at: DateTime::<Utc>::MIN_UTC,
billing: TargetBilling::Included,
choice: None,
})
);
assert_eq!(billable(&doc! { "name": "no id" }), None);
+3 -21
View File
@@ -145,33 +145,15 @@ pub(crate) fn relative(root: &Path, path: &Path) -> String {
}
/// The text of a file that may start with a byte-order mark (Visual Studio
/// writes UTF-8 with BOM, older tools UTF-16). `None` for a file too large or
/// writes UTF-8 with BOM, older tools UTF-16) or be Windows-1252, decoded by
/// [`compliance_core::encoding::read_source`]. `None` for a file too large or
/// unreadable.
pub(crate) fn read_text(path: &Path) -> Option<String> {
let meta = std::fs::metadata(path).ok()?;
if meta.len() > MAX_FILE_BYTES {
return None;
}
let bytes = std::fs::read(path).ok()?;
let utf16 = |bytes: &[u8], le: bool| {
let units: Vec<u16> = bytes
.chunks_exact(2)
.map(|c| {
if le {
u16::from_le_bytes([c[0], c[1]])
} else {
u16::from_be_bytes([c[0], c[1]])
}
})
.collect();
String::from_utf16(&units).ok()
};
match bytes.as_slice() {
[0xEF, 0xBB, 0xBF, rest @ ..] => String::from_utf8(rest.to_vec()).ok(),
[0xFF, 0xFE, rest @ ..] => utf16(rest, true),
[0xFE, 0xFF, rest @ ..] => utf16(rest, false),
_ => String::from_utf8(bytes).ok(),
}
compliance_core::encoding::read_source(path).ok()
}
/// Parse XML the way project and configuration files need: a DTD is allowed
@@ -147,7 +147,8 @@ pub fn detect(root: &Path, repo_id: &str) -> Vec<SbomEntry> {
}) {
let small = entry.metadata().is_ok_and(|m| m.len() <= MAX_HEADER_BYTES);
let Some(text) = small
.then(|| std::fs::read_to_string(entry.path()).ok())
// Vendor SDK headers are often Windows-1252 (a "©" in the banner).
.then(|| compliance_core::encoding::read_source(entry.path()).ok())
.flatten()
else {
continue;
+22 -1
View File
@@ -973,7 +973,8 @@ fn content_fingerprints(tree: &Path, findings: &mut [Finding]) {
continue;
};
let lines = files.entry(path.clone()).or_insert_with(|| {
std::fs::read_to_string(tree.join(&path))
// Decoded like the scanners read it: UTF-8, UTF-16, Windows-1252.
compliance_core::encoding::read_source(&tree.join(&path))
.ok()
.map(|text| text.lines().map(normalised).collect())
});
@@ -1249,6 +1250,26 @@ mod tests {
assert!(missing[0].legacy_fingerprints.is_empty());
}
#[test]
fn a_windows_1252_file_is_keyed_by_content_as_its_utf8_version_is() {
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
// "größe" as Windows-1252 writes it (0xF6 0xDF), then the same file
// saved again as UTF-8.
std::fs::write(dir.join("a.c"), b"int x;\nint gr\xF6\xDFe = read();\n").unwrap();
let ansi = keyed(&dir, vec![at("a.c", 2)]);
std::fs::write(dir.join("a.c"), "int x;\nint größe = read();\n").unwrap();
let utf8 = keyed(&dir, vec![at("a.c", 2)]);
let _ = std::fs::remove_dir_all(&dir);
// Keyed by content, with the line-based key kept to adopt the row
// stored under it while the file could not be read.
let line_key = crate::pipeline::dedup::compute_fingerprint(&["repo-1", "rule", "a.c", "2"]);
assert_eq!(ansi[0].legacy_fingerprints, std::slice::from_ref(&line_key));
assert_ne!(ansi[0].fingerprint, line_key);
// Re-saving the file in another encoding keeps the key.
assert_eq!(ansi[0].fingerprint, utf8[0].fingerprint);
}
#[test]
fn a_scanners_own_content_and_groups_are_respected() {
let dir = std::env::temp_dir().join(format!("cs-fp-{}", uuid::Uuid::new_v4()));
+46 -1
View File
@@ -495,7 +495,18 @@ impl GitOps {
_ => "",
};
let content = std::str::from_utf8(line.content()).unwrap_or("");
// A diff line is UTF-8 or, from an older tool, Windows-1252
// (single-byte, so a line decodes on its own). UTF-16 files are
// binary to git and have no lines here.
let bytes = line.content();
let decoded;
let content = match std::str::from_utf8(bytes) {
Ok(text) => text,
Err(_) => {
decoded = compliance_core::encoding::decode(bytes.to_vec()).unwrap_or_default();
decoded.as_str()
}
};
diff_file.hunks.push_str(prefix);
diff_file.hunks.push_str(content);
@@ -919,4 +930,38 @@ mod tests {
.expect_err("private origin must be refused");
assert!(err.to_string().contains("10.0.0.5"), "{err}");
}
#[test]
fn a_windows_1252_line_shows_in_the_diff() {
// Arrange: a file committed, then a line with "für" as Windows-1252
// writes it (0xFC) added in a second commit.
let dir = source_repo();
let repo = git2::Repository::open(&dir).unwrap();
let old = repo.head().unwrap().peel_to_commit().unwrap();
std::fs::write(
dir.join("README.md"),
b"pump controller\n// f\xFCr Halle 2\n",
)
.unwrap();
let mut index = repo.index().unwrap();
index.add_path(Path::new("README.md")).unwrap();
index.write().unwrap();
let tree = repo.find_tree(index.write_tree().unwrap()).unwrap();
let sig = git2::Signature::now("t", "t@example.com").unwrap();
let new = repo
.commit(Some("HEAD"), &sig, &sig, "note", &tree, &[&old])
.unwrap();
// Act
let diff = GitOps::get_diff_content(&dir, &old.id().to_string(), &new.to_string()).unwrap();
std::fs::remove_dir_all(&dir).unwrap();
// Assert: the added line is there, decoded.
assert_eq!(diff.len(), 1);
assert!(
diff[0].hunks.contains("+// für Halle 2"),
"{}",
diff[0].hunks
);
}
}
+56 -13
View File
@@ -1,28 +1,71 @@
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::graph::GraphBuildRun;
use compliance_core::models::Finding;
use compliance_graph::graph::engine::CodeGraph;
use super::orchestrator::{GraphContext, PipelineOrchestrator};
use super::plc::PlcFile;
use crate::error::AgentError;
/// The most nodes a graph build parses.
const GRAPH_MAX_NODES: u32 = 50_000;
/// What a code graph is built from.
pub(crate) enum GraphSource<'a> {
/// The source files of a checked-out tree, by the graph crate's parsers.
Tree(&'a Path),
/// The POUs of a PLC target, read from every one of its PLC source trees.
Plc(&'a [PlcFile]),
}
/// Build a code graph and detect its communities.
///
/// # Errors
///
/// Returns the graph engine's error when a tree can't be read or the graph
/// can't be assembled.
pub(crate) fn build_graph(
source: GraphSource<'_>,
repo_id: &str,
graph_build_id: &str,
) -> Result<(CodeGraph, GraphBuildRun), CoreError> {
let engine = compliance_graph::GraphEngine::new(GRAPH_MAX_NODES);
match source {
GraphSource::Tree(path) => engine.build_graph(path, repo_id, graph_build_id),
GraphSource::Plc(files) => engine.assemble(
super::plc::graph::parse_output(files, repo_id, graph_build_id),
repo_id,
),
}
}
impl PipelineOrchestrator {
/// Build the code knowledge graph for a repo and compute impact analyses
/// Build the code knowledge graph for a repo, store it in place of the
/// previous one and compute the impact of each finding.
pub(super) async fn build_code_graph(
&self,
repo_path: &std::path::Path,
source: GraphSource<'_>,
repo_id: &str,
findings: &[Finding],
) -> Result<GraphContext, AgentError> {
let graph_build_id = uuid::Uuid::new_v4().to_string();
let engine = compliance_graph::GraphEngine::new(50_000);
let built = build_graph(source, repo_id, &graph_build_id)
.map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?;
self.store_code_graph(built, repo_id, &graph_build_id, findings)
.await
}
let (mut code_graph, build_run) =
engine
.build_graph(repo_path, repo_id, &graph_build_id)
.map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?;
// Apply community detection
compliance_graph::graph::community::apply_communities(&mut code_graph);
// Store graph in MongoDB
/// Replace the repo's stored graph with `built`, and store the impact of
/// each finding that has a file.
async fn store_code_graph(
&self,
(code_graph, build_run): (CodeGraph, GraphBuildRun),
repo_id: &str,
graph_build_id: &str,
findings: &[Finding],
) -> Result<GraphContext, AgentError> {
let store = compliance_graph::graph::persistence::GraphStore::new(self.db.inner());
store
.delete_repo_graph(repo_id)
@@ -42,7 +85,7 @@ impl PipelineOrchestrator {
let impact = analyzer.analyze(
repo_id,
&finding.fingerprint,
&graph_build_id,
graph_build_id,
file_path,
finding.line_number,
);
+1 -1
View File
@@ -23,7 +23,7 @@ pub mod git;
pub mod git_retry;
pub mod git_submodules;
pub mod gitleaks;
mod graph_build;
pub(crate) mod graph_build;
pub mod grouping;
pub mod ios_config;
mod issue_catchup;
+179 -32
View File
@@ -82,6 +82,10 @@ pub struct PipelineOrchestrator {
/// The tenant's plan limits for metering (t72); `None` when not known,
/// and then counted Prüfungen are neither checked nor charged.
pub(super) plan_limits: Option<PlanLimits>,
/// Set when this person's scan took over a waiting scheduled, webhook or
/// new-content scan (t84): the trigger it is charged as. Change detection
/// then decides whether it counts, as for that scan.
pub(super) charged_as: Option<ScanTrigger>,
}
impl PipelineOrchestrator {
@@ -99,9 +103,17 @@ impl PipelineOrchestrator {
exploit_cache: None,
advisory_index: None,
plan_limits: None,
charged_as: None,
}
}
/// Charge this run as a scan started by `trigger` would be, when a
/// person's request took that waiting scan over (t84).
pub(crate) fn with_charged_as(mut self, trigger: Option<ScanTrigger>) -> Self {
self.charged_as = trigger;
self
}
/// Check and charge counted Prüfungen against `limits` (t72).
pub(crate) fn with_plan_limits(mut self, limits: Option<PlanLimits>) -> Self {
self.plan_limits = limits;
@@ -227,6 +239,16 @@ impl PipelineOrchestrator {
repo.billing,
)
.await?;
} else if let Some(original) = &self.charged_as {
let new_commits =
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
self.charge_as_taken_over(
scan_run_id,
&repo_id,
ScanAttribution::detected(original, new_commits || repo.changed_besides_commits),
repo.billing,
)
.await?;
}
// Submodules are part of what the product ships (a HAL, an RTOS).
@@ -938,8 +960,12 @@ impl PipelineOrchestrator {
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
.await;
let graph_context = match async {
self.build_code_graph(&repo_path, &repo_id, &all_findings)
.await
self.build_code_graph(
crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
&repo_id,
&all_findings,
)
.await
}
.instrument(tracing::info_span!("stage_graph_building"))
.await
@@ -1155,7 +1181,9 @@ impl PipelineOrchestrator {
/// `OnboardedTarget`. Mirrors [`Self::run`] but sources the target from
/// `onboarded_targets` and dispatches by the scan plan.
#[tracing::instrument(skip_all, fields(target_id = %target_id, trigger = ?trigger))]
/// Run one scan of the target `target_id`.
/// Run one scan of the target `target_id`, recorded on the run `queued`
/// that waited for this scan's slot (t84), or on a new run when there is
/// none.
///
/// # Returns
///
@@ -1170,6 +1198,7 @@ impl PipelineOrchestrator {
&self,
target_id: &str,
trigger: ScanTrigger,
queued: Option<&str>,
) -> Result<TargetScanOutcome, AgentError> {
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
.map_err(|e| AgentError::Other(e.to_string()))?;
@@ -1185,14 +1214,15 @@ impl PipelineOrchestrator {
// detection attributes the others (t72).
if let Some(attribution) = ScanAttribution::of_person(&trigger) {
scan_run.attribution = Some(attribution);
scan_run.chargeable = attribution.chargeable(target.billing);
// One that took over a waiting scan counts only as that scan
// would have; change detection decides below (t84).
scan_run.chargeable =
self.charged_as.is_none() && attribution.chargeable(target.billing);
}
let insert = self.db.scan_runs().insert_one(&scan_run).await?;
let scan_run_id = insert
.inserted_id
.as_object_id()
.map(|id| id.to_hex())
.unwrap_or_default();
scan_run.charged_as = self.charged_as.clone();
let run_oid = self.start_run(&scan_run, queued).await?;
let scan_run_id = run_oid.to_hex();
let run_id = mongodb::bson::Bson::ObjectId(run_oid);
// A counted Prüfung a person started is checked against the plan
// before anything runs (t72).
@@ -1226,10 +1256,7 @@ impl PipelineOrchestrator {
}
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "$set": completed },
)
.update_one(doc! { "_id": &run_id }, doc! { "$set": completed })
.await?;
// Refresh the target's cached findings count. The shared pipeline
// (Stage 7) increments `repositories`, which the unified path does
@@ -1266,7 +1293,7 @@ impl PipelineOrchestrator {
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "_id": &run_id },
doc! { "$set": {
"status": "completed",
"current_phase": "completed",
@@ -1281,7 +1308,7 @@ impl PipelineOrchestrator {
self.db
.scan_runs()
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "_id": &run_id },
doc! { "$set": {
"status": "failed",
"error_message": message,
@@ -1301,7 +1328,7 @@ impl PipelineOrchestrator {
let run = self
.db
.scan_runs()
.find_one(doc! { "_id": &insert.inserted_id })
.find_one(doc! { "_id": &run_id })
.await
.ok()
.flatten();
@@ -1315,7 +1342,7 @@ impl PipelineOrchestrator {
// A counted Prüfung is charged when it completed, or when it failed on
// the customer's input; a failure of ours never is (t72).
let charged = if chargeable && ((result.is_ok() && !unchanged) || invalid_input) {
self.charge_run(&insert.inserted_id, target_id).await
self.charge_run(&run_id, target_id).await
} else {
None
};
@@ -1330,6 +1357,59 @@ impl PipelineOrchestrator {
})
}
/// Record that `run` starts now: on the run `queued` that waited for the
/// slot, which moves from `queued` to `running`, or as a new run when
/// there is none or it is gone. Returns the run's id.
///
/// # Errors
///
/// The run could not be written.
async fn start_run(
&self,
run: &ScanRun,
queued: Option<&str>,
) -> Result<mongodb::bson::oid::ObjectId, AgentError> {
if let Some(oid) = queued.and_then(|id| mongodb::bson::oid::ObjectId::parse_str(id).ok()) {
let mut started = doc! {
"status": "running",
"trigger": mongodb::bson::to_bson(&run.trigger)
.map_err(|e| AgentError::Other(e.to_string()))?,
"started_at": mongodb::bson::DateTime::from_chrono(run.started_at),
"chargeable": run.chargeable,
};
if let Some(charged_as) = &run.charged_as {
started.insert(
"charged_as",
mongodb::bson::to_bson(charged_as)
.map_err(|e| AgentError::Other(e.to_string()))?,
);
}
if let Some(attribution) = run.attribution {
started.insert(
"attribution",
mongodb::bson::to_bson(&attribution)
.map_err(|e| AgentError::Other(e.to_string()))?,
);
}
let updated = self
.db
.scan_runs()
.update_one(
doc! { "_id": oid, "status": "queued" },
doc! { "$set": started },
)
.await?;
if updated.matched_count == 1 {
return Ok(oid);
}
}
let insert = self.db.scan_runs().insert_one(run).await?;
insert
.inserted_id
.as_object_id()
.ok_or_else(|| AgentError::Other("the scan run got no id".into()))
}
/// Check a counted Prüfung against the plan before it scans (t72):
/// the quota, today's Prüftag on the target, the customer's cap. It runs
/// when the plan's limits or the usage are not known.
@@ -1428,6 +1508,40 @@ impl PipelineOrchestrator {
Ok(())
}
/// Count the run `scan_run_id`, a person's request that took over a
/// waiting scan, only when `detected` (that scan's attribution from change
/// detection) counts on a target billed as `billing`, and then check it
/// against the plan (t84). The run keeps the person's attribution, so its
/// history shows that a person asked. Several code artifacts: a change in
/// any of them counts it, as in [`Self::attribute_run`].
///
/// # Errors
///
/// [`AgentError::NotAdmitted`] when the plan does not allow a counted
/// Prüfung now.
async fn charge_as_taken_over(
&self,
scan_run_id: &str,
target_id: &str,
detected: ScanAttribution,
billing: TargetBilling,
) -> Result<(), AgentError> {
if !detected.chargeable(billing) {
return Ok(());
}
if let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) {
if let Err(e) = self
.db
.scan_runs()
.update_one(doc! { "_id": oid }, doc! { "$set": { "chargeable": true } })
.await
{
tracing::warn!(scan_run_id, "scan run not marked as counted: {e}");
}
}
self.admit_run(scan_run_id, target_id).await
}
/// Store `attribution` and `chargeable` on the run, unless it already
/// reads as a change.
async fn record_attribution(
@@ -1502,17 +1616,25 @@ impl PipelineOrchestrator {
return Ok(0);
}
// A git target is attributed where its commits are compared.
if !trigger.started_by_person() && !has_git {
self.attribute_run(
scan_run_id,
&target_id,
ScanAttribution::detected(
trigger,
crate::pipeline::change::content_changed(target),
),
target.billing,
)
.await?;
if !has_git {
let changed = crate::pipeline::change::content_changed(target);
if !trigger.started_by_person() {
self.attribute_run(
scan_run_id,
&target_id,
ScanAttribution::detected(trigger, changed),
target.billing,
)
.await?;
} else if let Some(original) = &self.charged_as {
self.charge_as_taken_over(
scan_run_id,
&target_id,
ScanAttribution::detected(original, changed),
target.billing,
)
.await?;
}
}
let plan = build_scan_plan(target);
// An attached artifact nothing analyses is recorded, never passed over:
@@ -1723,6 +1845,8 @@ impl PipelineOrchestrator {
// Each source's findings next to the tree they were found in: the
// control mapping below reads the flagged regions from it.
let mut analysed = Vec::with_capacity(sources.len());
// Every tree's POUs, for the code graph.
let mut plc_files = Vec::new();
let mut all_sbom: Vec<SbomEntry> = Vec::new();
let mut sbom_seen = std::collections::BTreeSet::new();
// CODESYS projects in their native format: their control logic is not
@@ -1741,10 +1865,12 @@ impl PipelineOrchestrator {
left_out.excluded.extend(pruned.excluded);
left_out.test_data.extend(pruned.test_data);
native.extend(crate::pipeline::plc::native_projects(&path));
let files = crate::pipeline::plc::read_tree(&path);
analysed.push((
path.clone(),
crate::pipeline::plc::analyze_tree(&path, target_id),
crate::pipeline::plc::findings(&files, target_id),
));
plc_files.extend(files);
// Control-application SBOM: CODESYS libraries + runtime from a
// `.projectarchive` (uploaded, or committed in the working tree).
let archive = a
@@ -1806,6 +1932,21 @@ impl PipelineOrchestrator {
"PLC control-logic analysis complete"
);
// The POUs and how they use each other, as for a code scan; a stale
// graph is replaced even when no POU was read.
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
.await;
if let Err(e) = self
.build_code_graph(
crate::pipeline::graph_build::GraphSource::Plc(&plc_files),
target_id,
&all_findings,
)
.await
{
tracing::warn!(target_id, error = %e, "PLC graph building failed");
}
let mut new_count = 0u32;
let mut refreshed_count = 0u32;
for mut finding in all_findings {
@@ -3258,6 +3399,7 @@ fn planned_phases(
if config.breakpilot.semantic_mapping {
phases.push(ScanPhase::SemanticControlMapping);
}
phases.push(ScanPhase::GraphBuilding);
if config.plc_runtime.enabled && target.live_url().is_none() {
phases.push(ScanPhase::PlcProvision);
}
@@ -3411,7 +3553,11 @@ mod tests {
assert_eq!(
planned_phases(&target, &plan, &config),
[ScanPhase::Classification, ScanPhase::PlcAnalysis]
[
ScanPhase::Classification,
ScanPhase::PlcAnalysis,
ScanPhase::GraphBuilding
]
);
// The LLM control mapping is a phase of its own, so a long one shows.
@@ -3421,7 +3567,8 @@ mod tests {
[
ScanPhase::Classification,
ScanPhase::PlcAnalysis,
ScanPhase::SemanticControlMapping
ScanPhase::SemanticControlMapping,
ScanPhase::GraphBuilding
]
);
}
+37 -3
View File
@@ -186,9 +186,17 @@ fn scan_with_patterns(
.unwrap_or("")
.to_string();
let content = match std::fs::read_to_string(path) {
Ok(c) => c,
Err(_) => continue, // skip binary files
// Only files a pattern looks at are read at all.
if !patterns.iter().any(|p| p.file_extensions.contains(&ext)) {
continue;
}
// UTF-8, UTF-16 with a BOM, or Windows-1252; a binary is skipped.
let content = match compliance_core::encoding::read_source(path) {
Ok(text) => text,
Err(error) => {
tracing::debug!(file = %path.display(), %error, "pattern scan: file not readable");
continue;
}
};
let relative_path = path
@@ -417,4 +425,30 @@ mod tests {
assert!(!pattern.file_extensions.contains(&"rs".to_string()));
assert!(!pattern.file_extensions.contains(&"py".to_string()));
}
// --- file decoding ---
#[test]
fn a_windows_1252_file_is_scanned_not_skipped() {
// Arrange: a C# file written by an older tool, "Größe" as 0xF6 0xDF.
let dir = std::env::temp_dir().join(format!("cs-pat-{}", uuid::Uuid::new_v4()));
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("Log.cs"), b"// Gr\xF6\xDFe\nLog(email);\n").unwrap();
let rule = PatternRule {
id: "pii".into(),
title: "t".into(),
description: "d".into(),
pattern: compile_regex(r"Log\(email\)"),
severity: Severity::Medium,
file_extensions: vec!["cs".into()],
};
// Act
let findings = scan_with_patterns(&dir, "repo", &[rule], ScanType::Gdpr, "t").unwrap();
let _ = std::fs::remove_dir_all(&dir);
// Assert: found on its line.
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].line_number, Some(2));
}
}
+118 -1
View File
@@ -14,8 +14,96 @@ pub struct Pou {
pub vars: Vec<VarDecl>,
/// The statement body.
pub body: Vec<Stmt>,
/// 1-based line where the POU header appears (in the source that was parsed).
/// 1-based line where the POU header appears. For a PLCopen POU it is
/// the `<pou>` element's line in the XML; its statements keep the lines
/// of the Structured Text reconstructed from it.
pub line: u32,
/// 1-based line of its `END_*` keyword (the last line when it is
/// missing); for a PLCopen POU, the `</pou>` line.
pub end_line: u32,
}
impl Pou {
/// Call `visit` with the callee and line of every call in the body, bare
/// (`TON1(IN := x);`) or inside an expression (`LIMIT(0, x, 10)`), in
/// source order.
pub fn for_each_call(&self, mut visit: impl FnMut(&str, u32)) {
for stmt in &self.body {
stmt.for_each_call(&mut visit);
}
}
}
impl Stmt {
/// See [`Pou::for_each_call`]. `visit` is `&mut dyn` so the recursion
/// through nested blocks doesn't instantiate a new closure type per level.
fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) {
let block = |body: &[Stmt], visit: &mut dyn FnMut(&str, u32)| {
for stmt in body {
stmt.for_each_call(visit);
}
};
match self {
Stmt::Assign { target, value, .. } => {
target.for_each_call(visit);
value.for_each_call(visit);
}
Stmt::If {
branches,
else_body,
..
} => {
for (cond, body) in branches {
cond.for_each_call(visit);
block(body, visit);
}
if let Some(body) = else_body {
block(body, visit);
}
}
Stmt::Case {
selector,
arms,
else_body,
..
} => {
selector.for_each_call(visit);
for (labels, body) in arms {
for label in labels {
label.for_each_call(visit);
}
block(body, visit);
}
if let Some(body) = else_body {
block(body, visit);
}
}
Stmt::For {
from, to, by, body, ..
} => {
from.for_each_call(visit);
to.for_each_call(visit);
if let Some(by) = by {
by.for_each_call(visit);
}
block(body, visit);
}
Stmt::While { cond, body, .. }
| Stmt::Repeat {
body, until: cond, ..
} => {
cond.for_each_call(visit);
block(body, visit);
}
Stmt::Call { callee, args, line } => {
visit(callee, *line);
for arg in args {
arg.value.for_each_call(visit);
}
}
Stmt::Return { .. } | Stmt::Exit { .. } | Stmt::Jump { .. } | Stmt::Label { .. } => {}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -191,6 +279,35 @@ impl Expr {
}
}
/// See [`Pou::for_each_call`].
fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) {
match self {
Expr::Int(..)
| Expr::Real(..)
| Expr::Bool(..)
| Expr::Str(..)
| Expr::Time(..)
| Expr::Ident(..) => {}
Expr::Index { base, index, .. } => {
base.for_each_call(visit);
index.for_each_call(visit);
}
Expr::Member { base, .. } | Expr::Unary { expr: base, .. } => {
base.for_each_call(visit);
}
Expr::Binary { lhs, rhs, .. } => {
lhs.for_each_call(visit);
rhs.for_each_call(visit);
}
Expr::Call { callee, args, line } => {
visit(callee, *line);
for arg in args {
arg.value.for_each_call(visit);
}
}
}
}
/// If this expression is a plain identifier, its name.
pub fn as_ident(&self) -> Option<&str> {
match self {
+295
View File
@@ -0,0 +1,295 @@
//! The POUs of a PLC project as code-graph nodes and edges, for
//! [`compliance_graph::GraphEngine::assemble`].
//!
//! - A `PROGRAM` is a module and an entry point: the PLC's tasks run it.
//! - A `FUNCTION_BLOCK` is a class, since each instance keeps its own state.
//! - A `FUNCTION` is a function.
//!
//! A variable whose type is a function block is a dependency on it (a type
//! reference). A call through an instance (`Pump1(Start := x)`) is a call to
//! its type. Standard blocks such as `TON` or `CTU` have no node, so their
//! edges stay unresolved and the engine drops them.
use std::collections::HashMap;
use std::path::Path;
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
use compliance_core::traits::graph_builder::ParseOutput;
use compliance_graph::parsers::FileGraph;
use super::ast::{Pou, PouKind};
use super::PlcFile;
/// The nodes and edges of every POU in `files`.
///
/// # Arguments
///
/// * `files` - the PLC source files read from one or more trees
/// * `repo_id`, `graph_build_id` - stamped on every node and edge
pub(crate) fn parse_output(files: &[PlcFile], repo_id: &str, graph_build_id: &str) -> ParseOutput {
let mut output = ParseOutput::default();
for file in files {
let language = if file.plcopen {
"plcopen"
} else {
"structured_text"
};
let mut graph = FileGraph::new(
Path::new(&file.rel),
file.line_count,
repo_id,
graph_build_id,
language,
);
for pou in &file.pous {
add_pou(&mut graph, pou);
}
let part = graph.finish();
output.nodes.extend(part.nodes);
output.edges.extend(part.edges);
}
output
}
/// Add `pou`'s node, its type references and its calls.
fn add_pou(graph: &mut FileGraph<'_>, pou: &Pou) {
let qualified = graph.top_level(&pou.name);
let kind = match pou.kind {
PouKind::Program => CodeNodeKind::Module,
PouKind::FunctionBlock => CodeNodeKind::Class,
PouKind::Function => CodeNodeKind::Function,
};
graph.node_at(
qualified.clone(),
pou.name.clone(),
kind,
(pou.line, pou.end_line),
pou.kind == PouKind::Program,
);
// IEC 61131-3 identifiers are case-insensitive, so the instances are
// looked up by their lowercased name.
let mut instances: HashMap<String, &str> = HashMap::with_capacity(pou.vars.len());
for var in &pou.vars {
if !is_identifier(&var.type_name) {
continue; // ARRAY[..] OF, POINTER TO, STRING(80): not a block type
}
graph.edge_at(&qualified, &var.type_name, CodeEdgeKind::TypeRef, var.line);
instances.insert(var.name.to_ascii_lowercase(), var.type_name.as_str());
}
pou.for_each_call(|callee, line| {
let target = instances
.get(&callee.to_ascii_lowercase())
.copied()
.unwrap_or(callee);
graph.edge_at(&qualified, target, CodeEdgeKind::Calls, line);
});
}
/// Whether a declared type is a plain name (`FB_Pump`, `TON`, `INT`).
fn is_identifier(type_name: &str) -> bool {
!type_name.is_empty()
&& type_name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_')
}
#[cfg(test)]
mod tests {
use super::*;
use crate::pipeline::plc::{parser, plcopen};
fn st_file(rel: &str, source: &str) -> PlcFile {
PlcFile {
rel: rel.to_string(),
plcopen: false,
line_count: source.lines().count() as u32,
pous: parser::parse(source),
}
}
const LINE: &str = "\
FUNCTION_BLOCK FB_Pump
VAR_INPUT
Start : BOOL;
END_VAR
VAR
Delay : TON;
END_VAR
Delay(IN := Start, PT := T#2s);
END_FUNCTION_BLOCK
FUNCTION Clamp : INT
VAR_INPUT
x : INT;
END_VAR
Clamp := LIMIT(0, x, 100);
END_FUNCTION
PROGRAM Main
VAR
pump1 : FB_Pump;
level : INT;
END_VAR
PUMP1(Start := TRUE);
IF Clamp(level) > 50 THEN
level := 0;
END_IF;
END_PROGRAM
";
#[test]
fn pous_become_nodes_and_programs_entry_points() {
let output = parse_output(&[st_file("src/line.st", LINE)], "r", "b");
let node = |name: &str| {
output
.nodes
.iter()
.find(|n| n.name == name)
.unwrap_or_else(|| panic!("no node {name}"))
};
assert_eq!(node("line.st").kind, CodeNodeKind::File);
let pump = node("FB_Pump");
assert_eq!(pump.kind, CodeNodeKind::Class);
assert_eq!(pump.qualified_name, "src/line.st::FB_Pump");
assert_eq!((pump.start_line, pump.end_line), (1, 9));
assert!(!pump.is_entry_point);
assert_eq!(node("Clamp").kind, CodeNodeKind::Function);
let main = node("Main");
assert_eq!(main.kind, CodeNodeKind::Module);
assert_eq!((main.start_line, main.end_line), (18, 27));
assert!(main.is_entry_point);
assert!(output.nodes.iter().all(|n| n.language == "structured_text"));
}
#[test]
fn instances_lead_to_their_type_and_calls_to_the_callee() {
let output = parse_output(&[st_file("line.st", LINE)], "r", "b");
let edges: Vec<(&str, CodeEdgeKind)> = output
.edges
.iter()
.filter(|e| e.source == "line.st::Main")
.map(|e| (e.target.as_str(), e.kind.clone()))
.collect();
// The instance declaration and the call through it (in another case)
// lead to FB_Pump; the function is called by name.
let to = |target: &str, kind: CodeEdgeKind| {
edges
.iter()
.filter(|(t, k)| *t == target && *k == kind)
.count()
};
assert_eq!(to("FB_Pump", CodeEdgeKind::TypeRef), 1);
assert_eq!(to("FB_Pump", CodeEdgeKind::Calls), 1);
assert_eq!(to("Clamp", CodeEdgeKind::Calls), 1);
// A standard block keeps its own name and resolves to nothing.
assert!(output
.edges
.iter()
.any(|e| e.source == "line.st::FB_Pump" && e.target == "TON"));
}
#[test]
fn plcopen_pous_span_their_xml_element() {
let xml = r#"<?xml version="1.0" encoding="utf-8"?>
<project>
<types>
<pous>
<pou name="Main" pouType="program">
<interface>
<localVars>
<variable name="pump1"><type><derived name="FB_Pump"/></type></variable>
</localVars>
</interface>
<body>
<ST><xhtml xmlns="http://www.w3.org/1999/xhtml">pump1(Start := TRUE);</xhtml></ST>
</body>
</pou>
</pous>
</types>
</project>
"#;
let file = PlcFile {
rel: "export.xml".to_string(),
plcopen: true,
line_count: xml.lines().count() as u32,
pous: plcopen::parse_plcopen(xml),
};
let output = parse_output(&[file], "r", "b");
let main = output
.nodes
.iter()
.find(|n| n.name == "Main")
.expect("Main is a node");
assert_eq!((main.start_line, main.end_line), (5, 14));
assert_eq!(main.language, "plcopen");
assert!(output
.edges
.iter()
.any(|e| e.target == "FB_Pump" && e.kind == CodeEdgeKind::Calls));
}
#[test]
fn the_engine_links_instances_and_drops_standard_blocks() {
let output = parse_output(&[st_file("line.st", LINE)], "r", "b");
let (graph, run) = compliance_graph::GraphEngine::new(1_000)
.assemble(output, "r")
.expect("assembles");
let linked = |source: &str, target: &str| {
graph
.edges
.iter()
.any(|e| e.source == source && e.target == target)
};
assert!(linked("line.st::Main", "line.st::FB_Pump"));
assert!(linked("line.st::Main", "line.st::Clamp"));
assert!(!graph.edges.iter().any(|e| e.target == "TON"));
assert_eq!(run.languages_parsed, ["structured_text"]);
}
#[test]
fn every_pou_of_the_demo_project_is_a_node() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/plc-demo");
let mut files = crate::pipeline::plc::read_tree(&root);
files.sort_by(|a, b| a.rel.cmp(&b.rel));
let output = parse_output(&files, "r", "b");
let mut pous: Vec<(&str, bool)> = output
.nodes
.iter()
.filter(|n| n.kind != CodeNodeKind::File)
.map(|n| (n.name.as_str(), n.is_entry_point))
.collect();
pous.sort();
assert_eq!(
pous,
[
("ConveyorCtrl", true),
("PumpFbdCtrl", false),
("PumpStationCtrl", false),
("TrafficLight", true),
]
);
assert_eq!(
output
.nodes
.iter()
.filter(|n| n.kind == CodeNodeKind::File)
.count(),
4
);
}
#[test]
fn only_plain_type_names_are_references() {
assert!(is_identifier("FB_Pump"));
assert!(!is_identifier("ARRAY[0..9] OF INT"));
assert!(!is_identifier("STRING(80)"));
assert!(!is_identifier(""));
}
}
+111 -18
View File
@@ -9,6 +9,7 @@
//! scan says so instead of finding nothing in silence (#165).
pub mod ast;
pub(crate) mod graph;
pub mod lexer;
pub mod parser;
pub mod plcopen;
@@ -45,9 +46,26 @@ impl Scanner for PlcControlLogicScanner {
}
}
/// Walk a PLC project tree and produce findings.
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
let mut findings = Vec::new();
/// A PLC source file and the POUs read from it.
pub(crate) struct PlcFile {
/// The path relative to the tree it was found in.
pub(crate) rel: String,
/// Whether it is a PLCopen XML export rather than Structured Text.
pub(crate) plcopen: bool,
/// Its number of lines.
pub(crate) line_count: u32,
pub(crate) pous: Vec<ast::Pou>,
}
/// Read every PLC source file under `root` (Structured Text, and PLCopen XML
/// exports) into its POUs. Files with no POU are left out.
///
/// Each file is decoded by [`compliance_core::encoding::read_source`]:
/// CODESYS and TIA exports are often Windows-1252 or UTF-16. Files still not
/// readable as text are logged as one warning per tree.
pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
let mut files = Vec::new();
let mut unreadable: u32 = 0;
for entry in walkdir::WalkDir::new(root)
.into_iter()
.filter_map(|e| e.ok())
@@ -66,8 +84,17 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
if !is_st && !is_xml {
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
continue;
let content = match compliance_core::encoding::read_source(path) {
Ok(text) => text,
Err(error) => {
// A binary `.project` is CODESYS's native format, which
// [`native_projects`] reports; anything else is a loss.
if ext != "project" {
tracing::debug!(file = %path.display(), %error, "PLC source file not readable");
unreadable += 1;
}
continue;
}
};
// A `.project` is read only as a PLCopen export; CODESYS's native one
// is binary ([`native_projects`] reports it).
@@ -82,16 +109,41 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
if pous.is_empty() {
continue;
}
let rel = path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string();
for pou in &pous {
files.push(PlcFile {
rel: path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string(),
plcopen: is_xml,
line_count: content.lines().count() as u32,
pous,
});
}
// One line per tree; the paths are logged at debug level only.
if unreadable > 0 {
tracing::warn!(
unreadable_files = unreadable,
"PLC source files left out: not readable as text"
);
}
files
}
/// Run the control-logic rules over the POUs of `files`.
pub(crate) fn findings(files: &[PlcFile], repo_id: &str) -> Vec<Finding> {
let mut findings = Vec::new();
for file in files {
for pou in &file.pous {
for hit in rules::analyze(pou) {
let line_s = hit.line.to_string();
let fingerprint =
dedup::compute_fingerprint(&[repo_id, &rel, hit.rule_id, &pou.name, &line_s]);
let fingerprint = dedup::compute_fingerprint(&[
repo_id,
&file.rel,
hit.rule_id,
&pou.name,
&line_s,
]);
let mut f = Finding::new(
repo_id.to_string(),
fingerprint,
@@ -101,7 +153,7 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
hit.description,
hit.severity,
);
f.file_path = Some(rel.clone());
f.file_path = Some(file.rel.clone());
f.line_number = Some(hit.line);
f.rule_id = Some(hit.rule_id.to_string());
f.cwe = hit.cwe.map(String::from);
@@ -113,6 +165,11 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
findings
}
/// Walk a PLC project tree and produce findings.
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
findings(&read_tree(root), repo_id)
}
/// Whether `content` starts as an XML document (after a byte-order mark and
/// white space).
fn looks_like_xml(content: &str) -> bool {
@@ -152,10 +209,9 @@ pub fn native_projects(root: &Path) -> Vec<String> {
.unwrap_or("")
.to_ascii_lowercase();
let native = match ext.as_str() {
"project" => !std::fs::read(path)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.is_some_and(|text| looks_like_xml(&text)),
// Decoded as [`read_tree`] reads it: a UTF-16 export is no native one.
"project" => !compliance_core::encoding::read_source(path)
.is_ok_and(|text| looks_like_xml(&text)),
"projectarchive" => sbom::check_archive(path).is_ok(),
_ => false,
};
@@ -349,4 +405,41 @@ mod tests {
// The binary project yields no POUs and no error.
assert!(analyze_tree(&root.0, "t").is_empty());
}
#[test]
fn windows_1252_and_utf16_sources_are_read() {
// Arrange: Structured Text as older CODESYS saves it (Windows-1252:
// "Größe" is F6 DF, "€" is 80), and a PLCopen export in UTF-16 LE.
let root =
Scratch(std::env::temp_dir().join(format!("cs-plc-enc-{}", uuid::Uuid::new_v4())));
std::fs::create_dir_all(&root.0).expect("mkdir");
std::fs::write(
root.0.join("legacy.st"),
b"PROGRAM Legacy\nVAR\n s : STRING := 'Gr\xF6\xDFe in \x80';\nEND_VAR\n\
s := 'x'; (* Gr\xF6\xDFe *)\nEND_PROGRAM\n",
)
.expect("write st");
let xml = "<?xml version=\"1.0\" encoding=\"UTF-16\"?>\
<project xmlns=\"http://www.plcopen.org/xml/tc6_0201\"><types><pous>\
<pou name=\"Wide\" pouType=\"program\"><interface><localVars>\
<variable name=\"Größe\"><type><INT/></type></variable></localVars></interface>\
<body><ST><xhtml xmlns=\"http://www.w3.org/1999/xhtml\">x := 1;</xhtml></ST></body>\
</pou></pous></types></project>";
let utf16: Vec<u8> = [0xFF, 0xFE]
.into_iter()
.chain(xml.encode_utf16().flat_map(u16::to_le_bytes))
.collect();
std::fs::write(root.0.join("wide.xml"), utf16).expect("write xml");
// Act
let files = read_tree(&root.0);
// Assert
let mut pous: Vec<&str> = files
.iter()
.flat_map(|f| f.pous.iter().map(|p| p.name.as_str()))
.collect();
pous.sort_unstable();
assert_eq!(pous, ["Legacy", "Wide"]);
}
}
@@ -119,6 +119,7 @@ impl Parser {
body.push(s);
}
}
let end_line = self.line();
self.eat_kw(end);
Some(Pou {
@@ -127,6 +128,7 @@ impl Parser {
vars,
body,
line,
end_line,
})
}
+10 -1
View File
@@ -49,7 +49,16 @@ pub fn parse_plcopen(xml: &str) -> Vec<Pou> {
_ => "PROGRAM",
};
let synthetic = format!("{kw} {name}\n{var_block}{body}\nEND_{kw}\n");
pous.extend(parser::parse(&synthetic));
// Statement lines stay those of the synthetic source (the findings'
// lines and fingerprints use them); the POU itself spans its
// `<pou>` element in the XML, which is what the code graph shows.
let start = doc.text_pos_at(pou.range().start).row;
let end = doc.text_pos_at(pou.range().end).row;
pous.extend(parser::parse(&synthetic).into_iter().map(|mut parsed| {
parsed.line = start;
parsed.end_line = end;
parsed
}));
}
pous
}
+6 -4
View File
@@ -19,9 +19,10 @@ pub fn relative_path(root: &Path, path: &str) -> String {
rel.to_string_lossy().replace('\\', "/")
}
/// The whole text of `root/rel`. `None` when the file is unreadable or the
/// path would leave `root`: scanner output is not trusted to stay inside the
/// tree.
/// The whole text of `root/rel`, decoded by
/// [`compliance_core::encoding::read_source`]. `None` when the file is
/// unreadable or the path would leave `root`: scanner output is not trusted
/// to stay inside the tree.
pub fn read_text(root: &Path, rel: &str) -> Option<String> {
let rel_path = Path::new(rel);
if rel_path.is_absolute()
@@ -31,7 +32,8 @@ pub fn read_text(root: &Path, rel: &str) -> Option<String> {
{
return None;
}
std::fs::read_to_string(root.join(rel_path)).ok()
// UTF-16 with a BOM and Windows-1252 too, as the code graph reads them.
compliance_core::encoding::read_source(&root.join(rel_path)).ok()
}
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
+688 -87
View File
@@ -1,37 +1,55 @@
//! How many scans run at once, and what happens to a scan requested while the
//! same target is already being scanned.
//! How many scans run at once, in which order they get a slot, and what
//! happens to a scan requested while the same target is already queued or
//! being scanned.
//!
//! Every scan used to be a bare `tokio::spawn` with no limit. A burst of pushes,
//! a scheduler tick and a few clicks could start any number of scans side by
//! side — each one a clone plus semgrep plus syft — on an 8 GB node, and two
//! scans of the same target shared one checkout directory and corrupted each
//! other. Two rules now apply to every trigger (click, webhook, scheduler):
//! other. These rules now apply to every trigger (click, webhook, scheduler):
//!
//! * **Global:** at most `SCAN_CONCURRENCY` scans run at a time; the rest wait
//! for a slot.
//! * **Per target — coalesce:** one scan runs and at most one more is pending.
//! A request that arrives while one is pending is dropped, because the pending
//! scan will pick up the latest code anyway. Ten pushes during a long scan
//! therefore cost two scans, not ten. Dropped requests are never billed: only
//! a scan that actually ran emits usage.
//! * **Order:** a scan a person started ([`Priority::Person`]) gets a free slot
//! before scheduled, webhook and new-content scans ([`Priority::Background`]);
//! within a class the first to ask is the first served. So that a stream of
//! clicks never starves the scheduler, a waiting background scan gets the
//! slot after [`PERSON_GRANTS_IN_A_ROW`] person scans in a row (t84).
//! * **Per target — coalesce:** one scan of a target waits or runs, and while
//! it runs at most one more is pending. A request while the scan still waits
//! for its slot is covered by it (it reads the latest code once it starts);
//! a request while one is pending is covered by that one. Ten pushes during
//! a long scan therefore cost two scans, not ten. A person's request takes
//! over a waiting or pending scan that was not a person's, so it runs at
//! person priority and always scans. Requests that do not run are never
//! billed: only a scan that actually ran emits usage.
//!
//! Each admitted request carries the id of the run recorded for it while it
//! waits (status `queued`); the gate tells the caller which of those runs will
//! not happen, so no queued run is left behind.
//!
//! A scheduled scan also starts after a random delay of up to
//! [`SCHEDULED_SCAN_JITTER`], so the scans of a tenant's repositories (often
//! all on one git host) do not start in the same second.
use std::sync::Arc;
use std::collections::VecDeque;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::time::Duration;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use rand::Rng;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
use tokio::sync::oneshot;
use compliance_core::models::ScanTrigger;
/// The longest a scheduled scan waits before it starts.
pub const SCHEDULED_SCAN_JITTER: Duration = Duration::from_secs(30);
/// How many slots in a row go to person-started scans while a background scan
/// waits; the next one goes to the background scan.
pub const PERSON_GRANTS_IN_A_ROW: u32 = 3;
/// How long a scan with `trigger` waits before it starts: a random delay of
/// up to [`SCHEDULED_SCAN_JITTER`] for a scheduled scan, none for a scan a
/// webhook or a person started.
@@ -45,33 +63,108 @@ pub fn start_delay(trigger: &ScanTrigger) -> Duration {
}
}
/// Which queue a scan waits in for a slot.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Priority {
/// Started by a person (the customer or support): served first.
Person,
/// Scheduled, webhook and new-content scans, and PR reviews.
Background,
}
impl Priority {
/// The queue a scan with `trigger` waits in.
pub fn of(trigger: &ScanTrigger) -> Self {
if trigger.started_by_person() {
Self::Person
} else {
Self::Background
}
}
}
/// One scan to run: what started it and the run recorded for it while it
/// waits (`None` when that record could not be written).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Job {
pub trigger: ScanTrigger,
pub run_id: Option<String>,
/// Set when a person's request took over a waiting scan that was not a
/// person's: that scan's trigger, which the run is charged as (t84).
pub charged_as: Option<ScanTrigger>,
}
impl Job {
/// A scan started by `trigger`, recorded as the run `run_id`.
pub fn new(trigger: ScanTrigger, run_id: Option<String>) -> Self {
Self {
trigger,
run_id,
charged_as: None,
}
}
fn priority(&self) -> Priority {
Priority::of(&self.trigger)
}
}
/// What happened to a scan request.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Admission {
/// Nothing was running for this target: the caller runs the scan now.
/// Nothing was queued or running for this target: the caller now holds
/// it and runs its scans through [`ScanGate::start`].
Run,
/// A scan is running; this request becomes the single pending follow-up,
/// run by the task that holds the target once it finishes.
Coalesced,
/// A scan is running and a follow-up is already pending: nothing to do.
/// The request will run: as the target's pending follow-up, or in place
/// of the target's waiting scan. `replaced` is the run of the request it
/// took over, which will not happen.
Coalesced { replaced: Option<String> },
/// A scan already queued for this target covers the request: its own run
/// will not happen.
Dropped,
}
/// The scan queue is gone, or the target is no longer held.
#[derive(Debug, thiserror::Error)]
pub enum GateError {
#[error("the scan queue was closed")]
Closed,
#[error("the target is not held")]
NotHeld,
}
/// Global scan slots plus the per-target coalescing state.
#[derive(Debug)]
pub struct ScanGate {
slots: Arc<Semaphore>,
/// Present while a scan of the key is running; the value is the pending
/// follow-up's trigger, if one was requested meanwhile.
running: DashMap<String, Option<ScanTrigger>>,
slots: Arc<Slots>,
/// Present while a scan of the key waits or runs.
targets: DashMap<String, Held>,
}
/// The scans of one target that are queued or running.
#[derive(Debug)]
struct Held {
/// The scan that waits for a slot or runs now.
current: Job,
/// Whether `current` has its slot.
running: bool,
/// The follow-up requested while `current` runs.
pending: Option<Job>,
}
impl ScanGate {
/// A gate allowing `concurrency` scans at once (at least one).
pub fn new(concurrency: usize) -> Self {
Self {
slots: Arc::new(Semaphore::new(concurrency.max(1))),
running: DashMap::new(),
slots: Arc::new(Slots {
queue: Mutex::new(Queue {
free: concurrency.max(1),
person: VecDeque::new(),
background: VecDeque::new(),
person_grants: 0,
}),
}),
targets: DashMap::new(),
}
}
@@ -83,60 +176,253 @@ impl ScanGate {
/// Decide what to do with a scan request for `key`. Atomic per key, so two
/// simultaneous requests can never both be told to [`Admission::Run`].
pub fn admit(&self, key: &str, trigger: ScanTrigger) -> Admission {
match self.running.entry(key.to_string()) {
pub fn admit(&self, key: &str, job: Job) -> Admission {
// Lock order: a target's entry, then the slot queue (in `promote`).
// `start` keeps the same order and `Permit::drop` takes only the queue.
match self.targets.entry(key.to_string()) {
Entry::Vacant(v) => {
v.insert(None);
v.insert(Held {
current: job,
running: false,
pending: None,
});
Admission::Run
}
Entry::Occupied(mut o) if o.get().is_none() => {
o.insert(Some(trigger));
Admission::Coalesced
Entry::Occupied(mut o) => {
let held = o.get_mut();
let person = job.trigger.started_by_person();
// A person's request takes over a queued scan that is not a
// person's: that one might skip as unchanged (#465), theirs
// always scans, e.g. right after they uploaded new files.
let takes_over = |queued: &Job| person && !queued.trigger.started_by_person();
if !held.running {
// The waiting scan reads the latest code once it starts,
// so it covers the request, or the person's takes its
// place, at person priority. It would have run anyway,
// so it is charged as the scan it replaces.
if !takes_over(&held.current) {
return Admission::Dropped;
}
let job = Job {
charged_as: Some(held.current.trigger.clone()),
..job
};
let replaced = std::mem::replace(&mut held.current, job).run_id;
self.slots.promote(key);
return Admission::Coalesced { replaced };
}
match held.pending.as_ref().map(takes_over) {
None => {
held.pending = Some(job);
Admission::Coalesced { replaced: None }
}
Some(true) => {
let replaced = held.pending.replace(job).and_then(|p| p.run_id);
Admission::Coalesced { replaced }
}
Some(false) => Admission::Dropped,
}
}
// A person's request takes over a pending scheduled or webhook
// follow-up: that one may skip as unchanged (#465), theirs always
// scans, e.g. right after they uploaded new files.
Entry::Occupied(mut o)
if trigger.started_by_person()
&& o.get().as_ref().is_some_and(|p| !p.started_by_person()) =>
{
o.insert(Some(trigger));
Admission::Coalesced
}
Entry::Occupied(_) => Admission::Dropped,
}
}
/// Called by the task holding `key` after each scan. Returns the pending
/// follow-up to run next (the target stays held), or `None` once there is
/// nothing left, releasing the target.
pub fn finish(&self, key: &str) -> Option<ScanTrigger> {
match self.running.entry(key.to_string()) {
Entry::Occupied(mut o) => match o.get_mut().take() {
Some(next) => Some(next),
None => {
o.remove();
None
/// Wait for a slot for the held target `key`'s next scan, in the queue of
/// its priority, and return the slot with the scan to run. The scan is the
/// one current when the slot is granted: a person's request may have taken
/// it over meanwhile.
///
/// # Errors
///
/// [`GateError::NotHeld`] if `key` was released meanwhile, and
/// [`GateError::Closed`] if the queue is gone, which this gate never does.
pub async fn start(&self, key: &str) -> Result<(Permit, Job), GateError> {
let waiting = {
let held = self.targets.get(key).ok_or(GateError::NotHeld)?;
self.slots.enqueue(Some(key), held.current.priority())
// The entry's guard is dropped here, before waiting.
};
let permit = waiting.wait().await?;
let mut held = self.targets.get_mut(key).ok_or(GateError::NotHeld)?;
held.running = true;
Ok((permit, held.current.clone()))
}
/// Called by the task holding `key` after each scan. Returns whether a
/// follow-up is pending, to run next through [`Self::start`] (the target
/// stays held), or `false` once there is nothing left, releasing it.
pub fn finish(&self, key: &str) -> bool {
match self.targets.entry(key.to_string()) {
Entry::Occupied(mut o) => {
let held = o.get_mut();
match held.pending.take() {
Some(next) => {
held.current = next;
held.running = false;
true
}
None => {
o.remove();
false
}
}
},
Entry::Vacant(_) => None,
}
Entry::Vacant(_) => false,
}
}
/// Release `key` unconditionally, dropping any pending follow-up. Used when
/// the holding task dies, so the target does not stay "running" forever.
pub fn release(&self, key: &str) {
self.running.remove(key);
self.targets.remove(key);
}
/// Wait for one of the global scan slots. The slot is freed when the
/// returned permit is dropped.
/// Wait for a slot for work that is not a target's scan (a PR review).
/// The slot is freed when the returned permit is dropped.
///
/// # Errors
///
/// Only if the semaphore was closed, which this gate never does.
pub async fn slot(&self) -> Result<OwnedSemaphorePermit, tokio::sync::AcquireError> {
self.slots.clone().acquire_owned().await
/// Only if the queue is gone, which this gate never does.
pub async fn slot(&self, priority: Priority) -> Result<Permit, GateError> {
self.slots.enqueue(None, priority).wait().await
}
}
/// The slots and the two queues waiting for them.
#[derive(Debug)]
struct Slots {
queue: Mutex<Queue>,
}
#[derive(Debug)]
struct Queue {
/// Slots nobody holds. Only above zero while nobody waits.
free: usize,
person: VecDeque<Waiter>,
background: VecDeque<Waiter>,
/// Person scans granted in a row while a background scan waited.
person_grants: u32,
}
/// One request waiting for a slot; the slot is handed over through `grant`.
#[derive(Debug)]
struct Waiter {
/// The target it is for, so a person's request can move it forward.
key: Option<String>,
grant: oneshot::Sender<Permit>,
}
/// A request in a queue, or a slot already granted.
enum Waiting {
Granted(Permit),
Queued(oneshot::Receiver<Permit>),
}
impl Waiting {
async fn wait(self) -> Result<Permit, GateError> {
match self {
Self::Granted(permit) => Ok(permit),
// The sender only goes away unsent with the gate itself.
Self::Queued(grant) => grant.await.map_err(|_| GateError::Closed),
}
}
}
impl Slots {
/// The queue, also after a thread panicked while holding it: every change
/// to it is a single push or pop, so it is never left half-changed.
fn lock(&self) -> MutexGuard<'_, Queue> {
self.queue.lock().unwrap_or_else(PoisonError::into_inner)
}
/// Take a free slot, or join the queue of `priority`.
fn enqueue(self: &Arc<Self>, key: Option<&str>, priority: Priority) -> Waiting {
let mut queue = self.lock();
if queue.free > 0 {
queue.free -= 1;
return Waiting::Granted(Permit::new(self));
}
let (grant, granted) = oneshot::channel();
let waiter = Waiter {
key: key.map(str::to_string),
grant,
};
match priority {
Priority::Person => queue.person.push_back(waiter),
Priority::Background => queue.background.push_back(waiter),
}
Waiting::Queued(granted)
}
/// Move the background request for `key`, if one waits, to the back of
/// the person queue.
fn promote(&self, key: &str) {
let mut queue = self.lock();
let found = queue
.background
.iter()
.position(|w| w.key.as_deref() == Some(key));
if let Some(waiter) = found.and_then(|i| queue.background.remove(i)) {
queue.person.push_back(waiter);
}
}
/// Hand a freed slot to the next request, or keep it free.
fn release(self: &Arc<Self>) {
let mut queue = self.lock();
while let Some(waiter) = queue.next() {
match waiter.grant.send(Permit::new(self)) {
Ok(()) => return,
// The request was given up (its task ended): the permit comes
// back unused, and the slot goes to the next one.
Err(mut unused) => unused.slots = None,
}
}
queue.free += 1;
}
}
impl Queue {
/// The next request to serve: person scans first, except that a waiting
/// background scan gets the slot after [`PERSON_GRANTS_IN_A_ROW`] person
/// scans in a row.
fn next(&mut self) -> Option<Waiter> {
let background_due = self.person.is_empty() || self.person_grants >= PERSON_GRANTS_IN_A_ROW;
if background_due {
if let Some(waiter) = self.background.pop_front() {
self.person_grants = 0;
return Some(waiter);
}
}
let waiter = self.person.pop_front()?;
self.person_grants = if self.background.is_empty() {
0
} else {
self.person_grants + 1
};
Some(waiter)
}
}
/// One scan slot; freed, and handed to the next request, when dropped.
#[derive(Debug)]
pub struct Permit {
/// `None` once the permit was given back unused.
slots: Option<Arc<Slots>>,
}
impl Permit {
fn new(slots: &Arc<Slots>) -> Self {
Self {
slots: Some(Arc::clone(slots)),
}
}
}
impl Drop for Permit {
fn drop(&mut self) {
if let Some(slots) = self.slots.take() {
slots.release();
}
}
}
@@ -175,10 +461,20 @@ impl Drop for HeldTarget<'_> {
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::{start_delay, Admission, HeldTarget, ScanGate, SCHEDULED_SCAN_JITTER};
use super::{
start_delay, Admission, HeldTarget, Job, Priority, ScanGate, PERSON_GRANTS_IN_A_ROW,
SCHEDULED_SCAN_JITTER,
};
use compliance_core::models::ScanTrigger;
use std::sync::{Arc, Mutex};
use std::time::Duration;
type Log = Arc<Mutex<Vec<(String, ScanTrigger)>>>;
fn job(trigger: ScanTrigger, run: &str) -> Job {
Job::new(trigger, Some(run.to_string()))
}
#[test]
fn a_scheduled_scan_waits_within_the_jitter() {
let delays: Vec<Duration> = (0..1000)
@@ -202,52 +498,163 @@ mod tests {
}
#[test]
fn a_burst_coalesces_into_one_run_and_one_follow_up() {
fn only_a_persons_scan_has_person_priority() {
assert_eq!(Priority::of(&ScanTrigger::Manual), Priority::Person);
assert_eq!(Priority::of(&ScanTrigger::Support), Priority::Person);
for trigger in [
ScanTrigger::Scheduled,
ScanTrigger::Webhook,
ScanTrigger::NewContent,
] {
assert_eq!(Priority::of(&trigger), Priority::Background);
}
}
#[tokio::test]
async fn a_burst_coalesces_into_one_run_and_one_follow_up() {
let gate = ScanGate::new(2);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
for _ in 0..8 {
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
let (_slot, running) = gate.start(&key).await.unwrap();
assert_eq!(running, job(ScanTrigger::Manual, "r1"));
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Coalesced { replaced: None }
);
for i in 0..8 {
let run = format!("drop{i}");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, &run)),
Admission::Dropped
);
}
// The holder runs the one follow-up, then releases the target.
assert!(gate.finish(&key).is_some());
assert!(gate.finish(&key).is_none());
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert!(gate.finish(&key));
let (_next, follow_up) = gate.start(&key).await.unwrap();
assert_eq!(follow_up, job(ScanTrigger::Webhook, "r2"));
assert!(!gate.finish(&key));
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Run
);
}
#[test]
fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
fn a_scan_still_waiting_covers_requests_that_are_not_a_persons() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Scheduled), Admission::Run);
assert_eq!(
gate.admit(&key, ScanTrigger::Scheduled),
Admission::Coalesced
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
// Not started yet, so it will read the push's code anyway.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Dropped
);
}
#[tokio::test]
async fn a_waiting_scan_taken_over_is_charged_as_the_scan_it_replaces() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r1")),
Admission::Run
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
Admission::Coalesced {
replaced: Some("r1".into())
}
);
let (_slot, run) = gate.start(&key).await.unwrap();
assert_eq!(run.trigger, ScanTrigger::Manual);
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
}
#[tokio::test]
async fn a_persons_follow_up_after_a_running_scan_is_charged_as_theirs() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
let (running, _) = gate.start(&key).await.unwrap();
// Pending behind the running scan, replacing a scheduled follow-up.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
Admission::Coalesced { replaced: None }
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Coalesced {
replaced: Some("r2".into())
}
);
drop(running);
assert!(gate.finish(&key));
let (_slot, follow_up) = gate.start(&key).await.unwrap();
assert_eq!(follow_up, job(ScanTrigger::Manual, "r3"));
assert_eq!(follow_up.charged_as, None);
}
#[tokio::test]
async fn a_persons_request_takes_over_a_pending_scheduled_follow_up() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r1")),
Admission::Run
);
let _slot = gate.start(&key).await.unwrap();
assert_eq!(
gate.admit(&key, job(ScanTrigger::Scheduled, "r2")),
Admission::Coalesced { replaced: None }
);
// Clicked after uploading new files: the follow-up scans in full.
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Coalesced);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Dropped);
assert_eq!(gate.admit(&key, ScanTrigger::Support), Admission::Dropped);
// Clicked after uploading new files: the follow-up scans in full, and
// the scheduled follow-up's queued run will not happen.
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r3")),
Admission::Coalesced {
replaced: Some("r2".into())
}
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r4")),
Admission::Dropped
);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Support, "r5")),
Admission::Dropped
);
assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual));
assert!(gate.finish(&key));
}
#[test]
fn targets_and_tenants_are_independent() {
let gate = ScanGate::new(2);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")),
Admission::Run
);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
gate.admit(&ScanGate::key("acme", "t2"), job(ScanTrigger::Manual, "b")),
Admission::Run
);
// Same target id in another tenant is another target.
assert_eq!(
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
gate.admit(
&ScanGate::key("globex", "t1"),
job(ScanTrigger::Manual, "c")
),
Admission::Run
);
}
@@ -256,34 +663,228 @@ mod tests {
fn a_dead_holder_does_not_leave_the_target_locked() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
{
// The holding task ends without calling finish (panic / shutdown).
let _held = HeldTarget::new(&gate, key.clone());
}
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
Admission::Run
);
}
#[test]
fn a_disarmed_holder_leaves_the_state_to_finish() {
#[tokio::test]
async fn a_disarmed_holder_leaves_the_state_to_finish() {
let gate = ScanGate::new(1);
let key = ScanGate::key("acme", "t1");
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
let _slot = gate.start(&key).await.unwrap();
HeldTarget::new(&gate, key.clone()).disarm();
// Still held: disarm does not release, finish does.
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
assert_eq!(
gate.admit(&key, job(ScanTrigger::Webhook, "r2")),
Admission::Coalesced { replaced: None }
);
}
/// What `ComplianceAgent::run_target_scan` does once admitted: take a
/// slot, scan (here: log), and run the pending follow-up, if any.
async fn hold_and_scan(gate: Arc<ScanGate>, key: String, log: Log) {
loop {
{
let (_slot, job) = gate.start(&key).await.unwrap();
log.lock().unwrap().push((key.clone(), job.trigger));
}
if !gate.finish(&key) {
break;
}
}
}
/// Admit `trigger` for each of `targets` of tenant `acme`, each with a
/// task that scans it, queued in that order behind a slot held elsewhere.
async fn queue_targets(
gate: &Arc<ScanGate>,
targets: &[&str],
trigger: ScanTrigger,
log: &Log,
) -> Vec<tokio::task::JoinHandle<()>> {
let mut tasks = Vec::new();
for target in targets {
let key = ScanGate::key("acme", target);
assert_eq!(
gate.admit(&key, job(trigger.clone(), target)),
Admission::Run
);
tasks.push(tokio::spawn(hold_and_scan(gate.clone(), key, log.clone())));
// Let it queue for the slot before the next one does.
tokio::task::yield_now().await;
}
tasks
}
fn triggers(log: &Log) -> Vec<ScanTrigger> {
log.lock().unwrap().iter().map(|(_, t)| t.clone()).collect()
}
#[tokio::test]
async fn a_persons_scan_gets_the_next_slot_before_scheduled_scans() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
// Another tenant's scan has the only slot.
let busy = gate.slot(Priority::Background).await.unwrap();
let mut tasks = queue_targets(&gate, &["t1", "t2"], ScanTrigger::Scheduled, &log).await;
tasks.extend(queue_targets(&gate, &["t3"], ScanTrigger::Manual, &log).await);
drop(busy);
for task in tasks {
task.await.unwrap();
}
assert_eq!(
triggers(&log),
[
ScanTrigger::Manual,
ScanTrigger::Scheduled,
ScanTrigger::Scheduled
]
);
}
#[tokio::test]
async fn a_persons_request_takes_over_a_scheduled_scan_still_waiting() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
// Another tenant's scan has the only slot.
let busy = gate.slot(Priority::Background).await.unwrap();
// A scheduler tick admits three targets; all wait for the slot.
let tasks = queue_targets(&gate, &["t1", "t2", "t3"], ScanTrigger::Scheduled, &log).await;
// A person asks for t3 while its scheduled scan still waits, last.
let t3 = ScanGate::key("acme", "t3");
assert_eq!(
gate.admit(&t3, job(ScanTrigger::Manual, "click")),
Admission::Coalesced {
replaced: Some("t3".into())
}
);
drop(busy);
for task in tasks {
task.await.unwrap();
}
// Their scan runs first, once, in place of the scheduled one, and
// is charged as the scheduled one (asserted on the job below).
let order: Vec<(String, ScanTrigger)> = log.lock().unwrap().clone();
assert_eq!(
order,
[
(t3, ScanTrigger::Manual),
(ScanGate::key("acme", "t1"), ScanTrigger::Scheduled),
(ScanGate::key("acme", "t2"), ScanTrigger::Scheduled),
]
);
}
#[tokio::test]
async fn a_persons_follow_up_waits_only_for_the_running_scan() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
let t1 = ScanGate::key("acme", "t1");
assert_eq!(
gate.admit(&t1, job(ScanTrigger::Scheduled, "t1")),
Admission::Run
);
// t1's scheduled scan runs; two more targets queue behind it.
let (running, _) = gate.start(&t1).await.unwrap();
let tasks = queue_targets(&gate, &["t2", "t3"], ScanTrigger::Scheduled, &log).await;
assert_eq!(
gate.admit(&t1, job(ScanTrigger::Manual, "click")),
Admission::Coalesced { replaced: None }
);
// t1's scan ends; its follow-up queues as a person's.
assert!(gate.finish(&t1));
let follow_up = tokio::spawn(hold_and_scan(gate.clone(), t1.clone(), log.clone()));
tokio::task::yield_now().await;
drop(running);
follow_up.await.unwrap();
for task in tasks {
task.await.unwrap();
}
assert_eq!(
triggers(&log),
[
ScanTrigger::Manual,
ScanTrigger::Scheduled,
ScanTrigger::Scheduled
]
);
}
#[tokio::test]
async fn a_stream_of_clicks_does_not_starve_scheduled_scans() {
let gate = Arc::new(ScanGate::new(1));
let log = Log::default();
let busy = gate.slot(Priority::Background).await.unwrap();
let mut tasks = queue_targets(&gate, &["s1"], ScanTrigger::Scheduled, &log).await;
let clicks: Vec<String> = (0..10).map(|i| format!("p{i}")).collect();
let clicks: Vec<&str> = clicks.iter().map(String::as_str).collect();
tasks.extend(queue_targets(&gate, &clicks, ScanTrigger::Manual, &log).await);
drop(busy);
for task in tasks {
task.await.unwrap();
}
let scheduled_at = triggers(&log)
.iter()
.position(|t| *t == ScanTrigger::Scheduled)
.unwrap();
assert_eq!(scheduled_at, PERSON_GRANTS_IN_A_ROW as usize);
}
#[tokio::test]
async fn a_given_up_request_passes_its_slot_on() {
let gate = Arc::new(ScanGate::new(1));
let busy = gate.slot(Priority::Background).await.unwrap();
// A request that waits and is then given up (its task ends).
let gone = tokio::spawn({
let gate = gate.clone();
async move { gate.slot(Priority::Person).await.map(drop) }
});
tokio::task::yield_now().await;
gone.abort();
let _ = gone.await;
drop(busy);
let next = tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Background));
assert!(
next.await.is_ok(),
"the slot is not lost to the given-up request"
);
}
#[tokio::test]
async fn slots_bound_how_many_scans_run_at_once() {
let gate = ScanGate::new(2);
let a = gate.slot().await.unwrap();
let _b = gate.slot().await.unwrap();
let a = gate.slot(Priority::Background).await.unwrap();
let _b = gate.slot(Priority::Background).await.unwrap();
// A third slot is not available until one is freed.
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
let third =
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
assert!(third.is_err(), "a third concurrent scan must wait");
drop(a);
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
let third =
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
assert!(third.is_ok(), "a freed slot is reused");
}
}
+7 -1
View File
@@ -7,7 +7,7 @@
use chrono::{TimeZone, Utc};
use compliance_agent::database::DatabasePool;
use compliance_agent::metering::{charge, usage};
use compliance_agent::metering::{charge, month_summary, usage};
use compliance_core::models::{
admit, Admission, PlanLimits, Refusal, RunCharge, PRUEFUNGEN_PER_PRUEFTAG,
};
@@ -79,5 +79,11 @@ async fn the_quota_then_a_prueftag_of_six_then_nothing() {
assert_eq!(month.prueftage, 1);
assert_eq!(month.pruefungen, 2);
// The usage view reads the same month.
let summary = month_summary(&db, at).await.unwrap();
assert_eq!(summary.month, "2026-11");
assert_eq!((summary.pruefungen, summary.prueftage), (2, 1));
assert_eq!((summary.extra_targets, summary.extra_peak), (0, 0));
pool.drop_tenant(TENANT).await.ok();
}
+250
View File
@@ -0,0 +1,250 @@
//! A scan request shows at once as a run waiting for a slot (t84): the run is
//! recorded `queued` before the scan gets one of the agent's slots, a person's
//! request takes over a waiting webhook scan without leaving its queued run
//! behind, a request covered by the waiting scan leaves none, and the run
//! leaves `queued` once its scan had its turn. Runs against a live Mongo
//! (`TEST_MONGODB_URI`) and skips cleanly without one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
mod common;
use std::sync::Arc;
use std::time::Duration;
use futures_util::TryStreamExt;
use mongodb::bson::doc;
use compliance_agent::agent::ComplianceAgent;
use compliance_agent::database::Database;
use compliance_agent::scan_gate::Priority;
use compliance_core::models::{ScanRun, ScanRunStatus, ScanTrigger};
use common::dev_config;
const TENANT: &str = "scanqueue";
async fn runs(db: &Database, target_id: &str) -> Vec<ScanRun> {
db.scan_runs()
.find(doc! { "repo_id": target_id })
.await
.unwrap()
.try_collect()
.await
.unwrap()
}
/// Wait until the runs of `target_id` satisfy `done`, and return them.
async fn until(db: &Database, target_id: &str, done: impl Fn(&[ScanRun]) -> bool) -> Vec<ScanRun> {
for _ in 0..200 {
let found = runs(db, target_id).await;
if done(&found) {
return found;
}
tokio::time::sleep(Duration::from_millis(25)).await;
}
panic!(
"runs never reached the expected state: {:?}",
runs(db, target_id).await
);
}
#[tokio::test]
async fn a_request_shows_as_queued_until_its_scan_has_a_slot() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
// No such target, so its scan ends at once when it gets the slot.
let target = mongodb::bson::oid::ObjectId::new().to_hex();
// Arrange: another scan has the only slot.
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
// Act 1: a push asks for a scan; it waits, recorded as queued.
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.clone());
async move {
agent
.run_target_scan(TENANT, &target, ScanTrigger::Webhook)
.await
}
});
let queued = until(&db, &target, |r| r.len() == 1).await;
assert_eq!(queued[0].status, ScanRunStatus::Queued);
assert_eq!(queued[0].trigger, ScanTrigger::Webhook);
assert!(queued[0].queued_at.is_some());
// Act 2: a person asks while it waits: theirs takes its place, and only
// their queued run is left. Another push is covered and leaves none.
agent
.run_target_scan(TENANT, &target, ScanTrigger::Manual)
.await
.unwrap();
agent
.run_target_scan(TENANT, &target, ScanTrigger::Webhook)
.await
.unwrap();
let waiting = runs(&db, &target).await;
assert_eq!(waiting.len(), 1, "one queued run: {waiting:?}");
assert_eq!(waiting[0].status, ScanRunStatus::Queued);
assert_eq!(waiting[0].trigger, ScanTrigger::Manual);
// Act 3: the slot frees; the person's scan has its turn.
drop(busy);
assert!(holder.await.unwrap().is_err(), "the unknown target fails");
// Assert: the same run, no longer queued.
let done = runs(&db, &target).await;
assert_eq!(done.len(), 1);
assert_eq!(done[0].id, waiting[0].id);
assert_eq!(done[0].status, ScanRunStatus::Failed);
assert!(done[0].completed_at.is_some());
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn the_scan_runs_on_the_run_that_waited() {
use compliance_core::models::{OnboardedTarget, TargetType};
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
// A target with nothing attached yet: its scan has nothing to read.
let target = db
.onboarded_targets()
.insert_one(OnboardedTarget::new(
"empty".into(),
TargetType::BackendService,
))
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex();
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.clone());
async move {
agent
.run_target_scan(TENANT, &target, ScanTrigger::Manual)
.await
}
});
let queued = until(&db, &target, |r| r.len() == 1).await;
assert_eq!(queued[0].status, ScanRunStatus::Queued);
tokio::time::sleep(Duration::from_millis(20)).await;
drop(busy);
holder.await.unwrap().ok();
// The scan used the queued run: one run, started after it was requested.
let done = runs(&db, &target).await;
assert_eq!(done.len(), 1, "{done:?}");
assert_eq!(done[0].id, queued[0].id);
assert_ne!(done[0].status, ScanRunStatus::Queued);
assert!(done[0].started_at > done[0].queued_at.unwrap());
pool.drop_tenant(TENANT).await.ok();
}
/// The run of `target`'s scan by `trigger`, started while another scan has the
/// only slot; with `takes_over`, a webhook scan waits first and the person's
/// request takes it over.
async fn scan_with_slot_busy(
agent: &Arc<ComplianceAgent>,
db: &Database,
target: &str,
takes_over: bool,
) -> ScanRun {
let busy = agent.scan_gate.slot(Priority::Background).await.unwrap();
let first = if takes_over {
ScanTrigger::Webhook
} else {
ScanTrigger::Manual
};
let holder = tokio::spawn({
let (agent, target) = (agent.clone(), target.to_string());
async move { agent.run_target_scan(TENANT, &target, first).await }
});
until(db, target, |r| r.len() == 1).await;
if takes_over {
agent
.run_target_scan(TENANT, target, ScanTrigger::Manual)
.await
.unwrap();
}
drop(busy);
holder.await.unwrap().ok();
let mut done = runs(db, target).await;
assert_eq!(done.len(), 1, "{done:?}");
done.remove(0)
}
#[tokio::test]
async fn a_taken_over_scan_is_charged_as_the_scan_it_replaces() {
use compliance_core::models::{OnboardedTarget, ScanAttribution, TargetType};
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let db_name = format!("sq_{}", &uuid::Uuid::new_v4().simple().to_string()[..12]);
let Ok(pool) = compliance_agent::database::DatabasePool::connect(&uri, &db_name).await else {
eprintln!("SKIP scan_queue: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
let mut config = dev_config(uri, db_name);
config.scan_concurrency = 1;
let agent = Arc::new(ComplianceAgent::new(config, pool.clone()));
let new_target = || {
let db = db.clone();
async move {
let target = OnboardedTarget::new("t".into(), TargetType::BackendService);
db.onboarded_targets()
.insert_one(target)
.await
.unwrap()
.inserted_id
.as_object_id()
.unwrap()
.to_hex()
}
};
// A person's request that took over a waiting webhook scan of an
// included target: their priority and attribution, but not counted, as
// the webhook scan would not have been.
let included = new_target().await;
let run = scan_with_slot_busy(&agent, &db, &included, true).await;
assert_eq!(run.trigger, ScanTrigger::Manual);
assert_eq!(run.attribution, Some(ScanAttribution::Request));
assert_eq!(run.charged_as, Some(ScanTrigger::Webhook));
assert!(!run.chargeable, "it would have run anyway: {run:?}");
// A person's own scan, not taking any over, counts as their request.
let asked = new_target().await;
let run = scan_with_slot_busy(&agent, &db, &asked, false).await;
assert_eq!(run.attribution, Some(ScanAttribution::Request));
assert_eq!(run.charged_as, None);
assert!(run.chargeable);
pool.drop_tenant(TENANT).await.ok();
}
+68
View File
@@ -80,3 +80,71 @@ async fn the_oldest_targets_are_included_and_an_extra_one_moves_up() {
pool.drop_tenant(TENANT).await.ok();
}
#[tokio::test]
async fn a_swap_moves_both_and_holds_the_one_swapped_in_until_month_end() {
use compliance_agent::metering::swap;
use compliance_core::models::SwapRefusal;
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!("swap_{}", &uuid::Uuid::new_v4().simple().to_string()[..10]);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP target_billing swap: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: three targets on a plan with two included: the newest is extra.
let mut ids = Vec::new();
for days in [3, 2, 1] {
let mut target = OnboardedTarget::new(format!("t{days}"), TargetType::FirmwareRtos);
target.created_at = Utc::now() - Duration::days(days);
let res = db.onboarded_targets().insert_one(&target).await.unwrap();
ids.push(res.inserted_id.as_object_id().unwrap());
}
let (oldest, middle, newest) = (ids[0], ids[1], ids[2]);
assign_billing(&db, Some(2)).await.unwrap();
let nov6 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 11, 6, 9, 0, 0)
.single()
.unwrap();
// Act: swap the newest in for the oldest.
let swapped = swap(&db, newest, oldest, true, nov6).await.unwrap();
assign_billing(&db, Some(2)).await.unwrap();
// Assert: they changed places; the count of extra targets is the same.
assert_eq!(swapped, Some(Ok(())));
assert_eq!(billing(&db, newest).await, TargetBilling::Included);
assert_eq!(billing(&db, oldest).await, TargetBilling::Extra);
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
// The one swapped in stays included this month; another may go out.
assert_eq!(
swap(&db, oldest, newest, true, nov6).await.unwrap(),
Some(Err(SwapRefusal::Locked))
);
assert_eq!(
swap(&db, oldest, middle, true, nov6).await.unwrap(),
Some(Ok(()))
);
assign_billing(&db, Some(2)).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Extra);
// From December, the target swapped in on 6 Nov may go out again.
let dec1 = chrono::TimeZone::with_ymd_and_hms(&Utc, 2026, 12, 1, 9, 0, 0)
.single()
.unwrap();
assert_eq!(
swap(&db, middle, newest, true, dec1).await.unwrap(),
Some(Ok(()))
);
assert_eq!(
swap(&db, middle, ObjectId::new(), true, dec1)
.await
.unwrap(),
None,
"an unknown target"
);
pool.drop_tenant(TENANT).await.ok();
}
+2
View File
@@ -45,6 +45,8 @@ serde = { workspace = true }
serde_json = { workspace = true }
chrono = { workspace = true }
thiserror = { workspace = true }
# Decoding source files: BOM sniffing, UTF-16, Windows-1252
encoding_rs = { workspace = true }
sha2 = { workspace = true }
hex = { workspace = true }
uuid = { workspace = true }
+186
View File
@@ -0,0 +1,186 @@
//! Source files as text, whatever encoding the tool that wrote them chose.
//!
//! Visual Studio writes UTF-8 with a byte-order mark (BOM) or UTF-16, older
//! .NET and PLC tools write Windows-1252. `std::fs::read_to_string` accepts
//! only UTF-8 (and keeps a UTF-8 BOM as a leading `U+FEFF`), so every reader
//! of source files decodes through [`read_source`] instead:
//!
//! 1. a BOM (UTF-8 `EF BB BF`, UTF-16 LE `FF FE`, UTF-16 BE `FE FF`) names the
//! encoding; the BOM itself is dropped;
//! 2. without one, the bytes are UTF-8 if they are valid UTF-8;
//! 3. otherwise they are Windows-1252, unless they contain a NUL byte: no
//! 1252 text does, but binaries and UTF-16 without a BOM do.
use std::path::Path;
use encoding_rs::{Encoding, UTF_8, WINDOWS_1252};
/// Why a file could not be read as text.
#[derive(Debug, thiserror::Error)]
pub enum SourceTextError {
/// The file could not be read at all (missing, no permission, ...).
#[error("cannot read the file: {0}")]
Io(#[from] std::io::Error),
/// The file's BOM names an encoding its bytes don't follow, e.g. UTF-16
/// with an odd byte count or an unpaired surrogate.
#[error("the file is not valid {0} although its byte-order mark says so")]
Malformed(&'static str),
/// The file has no BOM, is not UTF-8 and contains a NUL byte: a binary
/// file, or UTF-16 we can't tell the byte order of.
#[error("the file is binary or of an unknown encoding")]
Binary,
}
/// Read the file at `path` as text, decoded as the module docs describe.
///
/// # Arguments
///
/// * `path` - the file to read
///
/// # Returns
///
/// The file's text, without a byte-order mark.
///
/// # Errors
///
/// Returns [`SourceTextError::Io`] when the file can't be read, and the
/// errors of [`decode`] when its bytes aren't text.
pub fn read_source(path: &Path) -> Result<String, SourceTextError> {
decode(std::fs::read(path)?)
}
/// Decode a source file's bytes, as the module docs describe.
///
/// Takes the bytes by value so that the common case, UTF-8 without a BOM,
/// becomes the `String` without copying: a Rust `String` is a UTF-8 byte
/// buffer, so `String::from_utf8` only validates and reuses the `Vec`.
///
/// # Arguments
///
/// * `bytes` - the whole file
///
/// # Returns
///
/// The text, without a byte-order mark.
///
/// # Errors
///
/// Returns [`SourceTextError::Malformed`] when a BOM names an encoding the
/// bytes don't follow, and [`SourceTextError::Binary`] for non-UTF-8 bytes
/// that contain a NUL.
///
/// # Examples
///
/// ```
/// use compliance_core::encoding::decode;
///
/// // "€" is 0x80 in Windows-1252.
/// assert_eq!(decode(b"// 5 \x80".to_vec()).ok().as_deref(), Some("// 5 €"));
/// ```
pub fn decode(mut bytes: Vec<u8>) -> Result<String, SourceTextError> {
if let Some((encoding, bom_len)) = Encoding::for_bom(&bytes) {
if encoding == UTF_8 {
// Drop the BOM in place, then validate without another copy.
bytes.drain(..bom_len);
return String::from_utf8(bytes).map_err(|_| SourceTextError::Malformed("UTF-8"));
}
// UTF-16 LE or BE: `None` on an odd byte count or unpaired surrogate.
return encoding
.decode_without_bom_handling_and_without_replacement(&bytes[bom_len..])
.map(|text| text.into_owned())
.ok_or(SourceTextError::Malformed(encoding.name()));
}
match String::from_utf8(bytes) {
Ok(text) => Ok(text),
Err(not_utf8) => {
// Hand the buffer back; `from_utf8` gave up ownership on failure.
let bytes = not_utf8.into_bytes();
if bytes.contains(&0) {
return Err(SourceTextError::Binary);
}
// Windows-1252 maps every byte, so this decoding can't fail.
let (text, _had_errors) = WINDOWS_1252.decode_without_bom_handling(&bytes);
Ok(text.into_owned())
}
}
}
#[cfg(test)]
mod tests {
use super::*;
/// `text` as UTF-16 with its BOM, in the byte order asked for.
fn utf16(text: &str, little_endian: bool) -> Vec<u8> {
let bom: [u8; 2] = if little_endian {
[0xFF, 0xFE]
} else {
[0xFE, 0xFF]
};
let units = text.encode_utf16().flat_map(|unit| {
if little_endian {
unit.to_le_bytes()
} else {
unit.to_be_bytes()
}
});
bom.into_iter().chain(units).collect()
}
#[test]
fn utf8_without_a_bom_is_kept_as_it_is() {
let text = decode("int größe = 1; // €".as_bytes().to_vec());
assert_eq!(text.ok().as_deref(), Some("int größe = 1; // €"));
}
#[test]
fn a_utf8_bom_is_dropped() {
let mut bytes = vec![0xEF, 0xBB, 0xBF];
bytes.extend_from_slice(b"class A {}");
assert_eq!(decode(bytes).ok().as_deref(), Some("class A {}"));
}
#[test]
fn utf16_with_a_bom_is_decoded_in_both_byte_orders() {
for little_endian in [true, false] {
let text = decode(utf16("class Größe {}", little_endian));
assert_eq!(text.ok().as_deref(), Some("class Größe {}"));
}
}
#[test]
fn windows_1252_is_the_fallback() {
// "Größe" and "€" as Windows-1252 writes them: 0xF6 0xDF and 0x80.
let text = decode(b"// Gr\xF6\xDFe in \x80".to_vec());
assert_eq!(text.ok().as_deref(), Some("// Größe in €"));
}
#[test]
fn malformed_utf16_and_binaries_are_not_text() {
// An odd byte count after a UTF-16 LE BOM.
assert!(matches!(
decode(vec![0xFF, 0xFE, 0x41]),
Err(SourceTextError::Malformed("UTF-16LE"))
));
// An unpaired high surrogate (D800) in UTF-16 BE.
assert!(matches!(
decode(vec![0xFE, 0xFF, 0xD8, 0x00, 0x00, 0x41]),
Err(SourceTextError::Malformed("UTF-16BE"))
));
// Invalid UTF-8 after a UTF-8 BOM.
assert!(matches!(
decode(vec![0xEF, 0xBB, 0xBF, 0xFF]),
Err(SourceTextError::Malformed("UTF-8"))
));
// Not UTF-8 and a NUL: a binary.
assert!(matches!(
decode(vec![0x7F, b'E', b'L', b'F', 0x00, 0xFF]),
Err(SourceTextError::Binary)
));
}
#[test]
fn a_missing_file_is_an_io_error() {
let missing = std::env::temp_dir().join("compliance-core-no-such-file.cs");
assert!(matches!(read_source(&missing), Err(SourceTextError::Io(_))));
}
}
+1
View File
@@ -4,6 +4,7 @@ pub mod control_check;
pub mod csaf_docs;
pub mod csaf_ingest;
pub mod db;
pub mod encoding;
pub mod enisa_docs;
pub mod error;
pub mod exec_policy;
+39
View File
@@ -121,6 +121,20 @@ 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>,
/// Source files left out because they could not be read as text (not
/// UTF-8, UTF-16 with a byte-order mark or Windows-1252, or an I/O
/// error). `None` on a build stored before it was counted, and on a PLC
/// build, whose files are read by the PLC stage.
#[serde(default)]
pub unreadable_file_count: Option<u32>,
pub error_message: Option<String>,
#[serde(with = "super::serde_helpers::bson_datetime")]
pub started_at: DateTime<Utc>,
@@ -139,6 +153,9 @@ impl GraphBuildRun {
edge_count: 0,
community_count: 0,
languages_parsed: Vec::new(),
file_count: None,
entry_point_count: None,
unreadable_file_count: None,
error_message: None,
started_at: Utc::now(),
completed_at: None,
@@ -187,3 +204,25 @@ impl ImpactAnalysis {
}
}
}
#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
use super::*;
#[test]
fn a_build_stored_before_the_counts_still_reads() {
// Arrange: a stored build as t82 and earlier wrote it.
let mut stored = bson::to_document(&GraphBuildRun::new("r".to_string())).expect("bson");
for field in ["file_count", "entry_point_count", "unreadable_file_count"] {
stored.remove(field);
}
// Act
let build: GraphBuildRun = bson::from_document(stored).expect("old build reads");
// Assert
assert_eq!(build.file_count, None);
assert_eq!(build.unreadable_file_count, None);
}
}
+128 -2
View File
@@ -186,6 +186,79 @@ pub fn admit(limits: PlanLimits, month: MonthUsage, day: DayUsage) -> Admission
}
}
/// The customer's choice for a target's billing, from a swap (t72): the
/// target swapped in is wanted included, the one swapped out extra.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum IncludedChoice {
/// Swapped in: included before the oldest targets.
Included,
/// Swapped out: extra before the newest targets.
Extra,
}
impl IncludedChoice {
/// Where a target with `choice` comes in the split: swapped in first,
/// swapped out last, every other target by age in between.
fn rank(choice: Option<Self>) -> u8 {
match choice {
Some(Self::Included) => 0,
None => 1,
Some(Self::Extra) => 2,
}
}
}
/// Why a swap of an extra target with an included one is not made (t72).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SwapRefusal {
/// The plan includes every target, so there is nothing to swap.
Unlimited,
/// The target to swap in is not extra.
NotExtra,
/// The target to swap out is not included.
NotIncluded,
/// The target to swap out was swapped in this month and stays included
/// until the month's end.
Locked,
}
/// Whether an extra target may be swapped with an included one, by the
/// contract: at any time, except that a target swapped in stays included
/// until the end of its calendar month.
///
/// # Arguments
///
/// * `limited` - Whether the plan limits the included targets.
/// * `incoming` - How the target to swap in is billed now.
/// * `outgoing` - How the target to swap out is billed now.
/// * `outgoing_locked` - Whether the target to swap out is still within
/// the month it was swapped in.
///
/// # Errors
///
/// The [`SwapRefusal`] that stops the swap.
pub fn check_swap(
limited: bool,
incoming: TargetBilling,
outgoing: TargetBilling,
outgoing_locked: bool,
) -> Result<(), SwapRefusal> {
if !limited {
return Err(SwapRefusal::Unlimited);
}
if incoming != TargetBilling::Extra {
return Err(SwapRefusal::NotExtra);
}
if outgoing != TargetBilling::Included {
return Err(SwapRefusal::NotIncluded);
}
if outgoing_locked {
return Err(SwapRefusal::Locked);
}
Ok(())
}
/// One active target as [`split_included`] sees it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BillableTarget<Id> {
@@ -195,10 +268,14 @@ pub struct BillableTarget<Id> {
pub created_at: DateTime<Utc>,
/// How it is billed now.
pub billing: TargetBilling,
/// The customer's choice from a swap, if any.
pub choice: Option<IncludedChoice>,
}
/// The targets whose billing has to change so that the `included` oldest
/// active targets are included and the rest are extra.
/// active targets are included and the rest are extra; a target the
/// customer swapped in comes before the oldest, one swapped out after the
/// newest.
///
/// # Arguments
///
@@ -215,7 +292,12 @@ pub fn split_included<Id: Ord + Clone>(
included: Option<u32>,
) -> Vec<(Id, TargetBilling)> {
let mut ordered: Vec<&BillableTarget<Id>> = targets.iter().collect();
ordered.sort_unstable_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
ordered.sort_unstable_by(|a, b| {
IncludedChoice::rank(a.choice)
.cmp(&IncludedChoice::rank(b.choice))
.then(a.created_at.cmp(&b.created_at))
.then(a.id.cmp(&b.id))
});
// `usize::MAX` stands for "no limit"; a u32 always fits a usize here.
let limit = included.map_or(usize::MAX, |n| n as usize);
ordered
@@ -245,9 +327,53 @@ mod tests {
.single()
.expect("valid date"),
billing,
choice: None,
}
}
#[test]
fn a_swap_moves_one_in_and_one_out() {
// Arrange: two included (days 1, 2) and one extra (day 3); the
// customer swaps 3 in for 1.
let mut incoming = target(3, 3, TargetBilling::Extra);
incoming.choice = Some(IncludedChoice::Included);
let mut outgoing = target(1, 1, TargetBilling::Included);
outgoing.choice = Some(IncludedChoice::Extra);
let targets = [outgoing, target(2, 2, TargetBilling::Included), incoming];
// Act
let mut changes = split_included(&targets, Some(2));
changes.sort_unstable_by_key(|(id, _)| *id);
// Assert: the count of extra targets is the same.
assert_eq!(
changes,
vec![(1, TargetBilling::Extra), (3, TargetBilling::Included)]
);
}
#[test]
fn a_target_swapped_in_this_month_cannot_go_out() {
use TargetBilling::{Extra, Included};
assert_eq!(check_swap(true, Extra, Included, false), Ok(()));
assert_eq!(
check_swap(true, Extra, Included, true),
Err(SwapRefusal::Locked)
);
assert_eq!(
check_swap(true, Included, Included, false),
Err(SwapRefusal::NotExtra)
);
assert_eq!(
check_swap(true, Extra, Extra, false),
Err(SwapRefusal::NotIncluded)
);
assert_eq!(
check_swap(false, Extra, Included, false),
Err(SwapRefusal::Unlimited)
);
}
#[test]
fn the_oldest_targets_are_included_and_the_rest_extra() {
// Arrange: three included targets, created on days 3, 1 and 2.
+3 -2
View File
@@ -59,8 +59,9 @@ pub use license_policy::{
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
pub use mcp_token::{McpToken, McpTokenView};
pub use metering::{
admit, split_included, Admission, BillableTarget, DayUsage, MonthUsage, PlanLimits, Refusal,
RunCharge, ScanAttribution, TargetBilling, PRUEFUNGEN_PER_PRUEFTAG,
admit, check_swap, split_included, Admission, BillableTarget, DayUsage, IncludedChoice,
MonthUsage, PlanLimits, Refusal, RunCharge, ScanAttribution, SwapRefusal, TargetBilling,
PRUEFUNGEN_PER_PRUEFTAG,
};
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
pub use onboarding::{
+14
View File
@@ -665,6 +665,18 @@ pub struct OnboardedTarget {
/// unseen.
#[serde(default)]
pub billing: super::metering::TargetBilling,
/// The customer's choice from a swap of an extra target with an
/// included one (t72); `None` until one is made.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub included_choice: Option<super::metering::IncludedChoice>,
/// Until when a target swapped in stays included: the end of the
/// calendar month (Europe/Berlin) it was swapped in.
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "super::serde_helpers::opt_bson_datetime"
)]
pub included_until: Option<DateTime<Utc>>,
/// Creation timestamp.
#[serde(
default = "chrono::Utc::now",
@@ -706,6 +718,8 @@ impl OnboardedTarget {
last_scan: None,
layer_pins: None,
billing: super::metering::TargetBilling::default(),
included_choice: None,
included_until: None,
created_at: now,
updated_at: now,
}
+41
View File
@@ -70,6 +70,9 @@ impl std::fmt::Display for ScanType {
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanRunStatus {
/// Requested and waiting for one of the agent's scan slots (t84). Moves
/// to `running` when it gets one.
Queued,
Running,
Completed,
/// The scan itself hit an error on the target (clone, tool, pipeline).
@@ -80,6 +83,16 @@ pub enum ScanRunStatus {
Interrupted,
}
impl ScanRunStatus {
/// Whether the run has not ended yet: it waits for a slot or runs.
pub fn is_open(&self) -> bool {
match self {
Self::Queued | Self::Running => true,
Self::Completed | Self::Failed | Self::Interrupted => false,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanPhase {
@@ -154,8 +167,18 @@ pub struct ScanRun {
/// absent on runs recorded before it existed.
#[serde(default)]
pub error_code: Option<RunErrorCode>,
/// When the run started; for a queued run, when it was requested, until
/// it starts.
#[serde(with = "super::serde_helpers::bson_datetime")]
pub started_at: DateTime<Utc>,
/// When a run that waited for a slot was requested (t84); `None` for a
/// run that started at once, and in runs from before it was recorded.
#[serde(
default,
skip_serializing_if = "Option::is_none",
with = "super::serde_helpers::opt_bson_datetime"
)]
pub queued_at: Option<DateTime<Utc>>,
#[serde(default, with = "super::serde_helpers::opt_bson_datetime")]
pub completed_at: Option<DateTime<Utc>>,
/// Stages the pipeline deliberately did not run (e.g. a deployment
@@ -194,6 +217,12 @@ pub struct ScanRun {
/// billing when it was attributed).
#[serde(default)]
pub chargeable: bool,
/// For a person's request that took over a scheduled, webhook or
/// new-content scan still waiting for a slot (t84): that scan's trigger.
/// The run has the person's priority and attribution, but it counts only
/// as that scan would have: it would have run anyway, just later.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub charged_as: Option<ScanTrigger>,
/// What the run was charged to once it counted; `None` while it runs,
/// and for a run that did not count.
#[serde(default, skip_serializing_if = "Option::is_none")]
@@ -426,6 +455,7 @@ impl ScanRun {
error_message: None,
error_code: None,
started_at: Utc::now(),
queued_at: None,
completed_at: None,
skipped_stages: Vec::new(),
notes: Vec::new(),
@@ -434,9 +464,20 @@ impl ScanRun {
sbom_quality: None,
attribution: None,
chargeable: false,
charged_as: None,
charge: None,
}
}
/// A run requested by `trigger` that waits for a scan slot (t84).
pub fn queued(repo_id: String, trigger: ScanTrigger) -> Self {
let run = Self::new(repo_id, trigger);
Self {
status: ScanRunStatus::Queued,
queued_at: Some(run.started_at),
..run
}
}
}
impl ScanRun {
+189 -264
View File
@@ -1,231 +1,241 @@
// ═══════════════════════════════════════════════════════════════
// Graph Visualization — vis-network wrapper for Code Knowledge Graph
// Obsidian Control theme
// ═══════════════════════════════════════════════════════════════
// Code graph drawing: a thin vis-network wrapper.
//
// The dashboard's Rust code decides what is drawn (the whole graph, the
// community overview or one community, see pages/graph_view.rs) and passes
// the nodes, edges and the UI texts in the reader's language. This file only
// draws them, in the colours of the current theme.
(function () {
"use strict";
// Color palette matching Obsidian Control
const NODE_COLORS = {
function: { bg: "#00c8ff", border: "#00a0cc", font: "#060a13" },
method: { bg: "#00c8ff", border: "#00a0cc", font: "#060a13" },
struct: { bg: "#e040fb", border: "#b030d0", font: "#060a13" },
class: { bg: "#e040fb", border: "#b030d0", font: "#060a13" },
enum: { bg: "#ffb020", border: "#cc8c18", font: "#060a13" },
interface: { bg: "#7c4dff", border: "#5c38c0", font: "#ffffff" },
trait: { bg: "#7c4dff", border: "#5c38c0", font: "#ffffff" },
module: { bg: "#ff8a3d", border: "#cc6e30", font: "#060a13" },
file: { bg: "#00e676", border: "#00b85e", font: "#060a13" },
// CSS custom properties per node kind, defined in main.css from the theme
// tokens, so the graph follows the light and dark theme.
var KIND_TOKEN = {
function: "--graph-function",
method: "--graph-function",
class: "--graph-type",
struct: "--graph-type",
enum: "--graph-enum",
interface: "--graph-interface",
trait: "--graph-interface",
module: "--graph-module",
file: "--graph-file",
community: "--graph-community",
folder: "--graph-community",
};
var EDGE_TOKEN = {
calls: "--graph-function",
imports: "--graph-enum",
inherits: "--graph-type",
implements: "--graph-interface",
bundle: "--graph-community",
};
const EDGE_COLORS = {
calls: "#00c8ff",
imports: "#ffb020",
inherits: "#e040fb",
implements: "#7c4dff",
contains: "rgba(94, 114, 145, 0.6)",
type_ref: "rgba(94, 114, 145, 0.5)",
};
var SHAPE = { file: "diamond", module: "square", folder: "hexagon" };
const DEFAULT_NODE_COLOR = { bg: "#5e7291", border: "#3d506b", font: "#e4eaf4" };
const DEFAULT_EDGE_COLOR = "rgba(94, 114, 145, 0.3)";
// Above this many nodes the layout runs a short while and then stops,
// so a large drawing does not keep the CPU busy.
var LARGE = 400;
let network = null;
let nodesDataset = null;
let edgesDataset = null;
let rawNodes = [];
let rawEdges = [];
var network = null;
var nodesDataset = null;
var edgesDataset = null;
var rawNodes = [];
var rawEdges = [];
var texts = { kinds: {}, edges: {}, program: "", plc: [], layout: "", entry: "", file: "" };
function getNodeColor(kind) {
return NODE_COLORS[kind] || DEFAULT_NODE_COLOR;
function token(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
}
function getEdgeColor(kind) {
return EDGE_COLORS[kind] || DEFAULT_EDGE_COLOR;
function palette() {
var kinds = {};
Object.keys(KIND_TOKEN).forEach(function (k) {
kinds[k] = token(KIND_TOKEN[k]);
});
var edges = {};
Object.keys(EDGE_TOKEN).forEach(function (k) {
edges[k] = token(EDGE_TOKEN[k]);
});
return {
kinds: kinds,
edges: edges,
quiet: token("--border-strong"),
text: token("--text-primary"),
halo: token("--bg-primary"),
ring: token("--text-primary"),
fallback: token("--text-tertiary"),
font: token("--font-body"),
};
}
// Build a vis-network node from raw graph data
function toVisNode(node, edgeCounts) {
const color = getNodeColor(node.kind);
const connections = edgeCounts[node.qualified_name] || 0;
const size = Math.max(8, Math.min(35, 8 + connections * 2));
function edgeCounts(edges) {
var counts = {};
edges.forEach(function (e) {
counts[e.source] = (counts[e.source] || 0) + 1;
counts[e.target] = (counts[e.target] || 0) + 1;
});
return counts;
}
function toVisNode(node, counts, colors) {
var color = colors.kinds[node.kind] || colors.fallback;
var isGroup = node.kind === "community" || node.kind === "folder";
// A PLC PROGRAM is kept as a module; it is named a program.
var kindName = node.kind === "module" && texts.plc.indexOf(node.language) >= 0
? texts.program
: texts.kinds[node.kind] || node.kind;
// A group is sized by its members through `value`, which also scales its
// label, so the large groups stay legible when the overview is zoomed out.
var size = Math.max(8, Math.min(30, 8 + (counts[node.qualified_name] || 0) * 1.5));
var title = isGroup
? kindName + " " + node.name + ": " + node.member_count
: kindName + ": " + node.qualified_name +
"\n" + texts.file + ": " + node.file_path + ":" + node.start_line +
(node.is_entry_point ? "\n" + texts.entry : "");
return {
id: node.qualified_name,
label: node.name,
title: `${node.kind}: ${node.qualified_name}\nFile: ${node.file_path}:${node.start_line}`,
size: size,
label: isGroup ? node.name + "\n" + node.member_count : node.name,
title: title,
size: isGroup ? undefined : size,
value: isGroup ? node.member_count : undefined,
color: {
background: color.bg,
border: color.border,
highlight: { background: color.bg, border: "#ffffff" },
hover: { background: color.bg, border: "#ffffff" },
background: color,
border: node.is_entry_point ? colors.ring : color,
highlight: { background: color, border: colors.ring },
hover: { background: color, border: colors.ring },
},
font: {
color: color.font,
size: 10,
face: "'JetBrains Mono', monospace",
strokeWidth: 2,
strokeColor: "#060a13",
color: colors.text,
size: isGroup ? 13 : 11,
face: colors.font,
strokeWidth: 3,
strokeColor: colors.halo,
},
borderWidth: 1,
borderWidth: node.is_entry_point ? 3 : 1,
borderWidthSelected: 3,
shape: node.kind === "file" ? "diamond" : node.kind === "module" ? "square" : "dot",
// Store raw data for click handler
shape: SHAPE[node.kind] || "dot",
_raw: node,
};
}
function toVisEdge(edge) {
const color = getEdgeColor(edge.kind);
const isDim = edge.kind === "contains" || edge.kind === "type_ref";
function toVisEdge(edge, colors) {
var color = colors.edges[edge.kind] || colors.quiet;
var count = edge.count || 1;
var label = edge.kind === "bundle" ? String(count) : texts.edges[edge.kind] || edge.kind;
return {
id: edge.source + "|" + edge.target + "|" + edge.kind,
from: edge.source,
to: edge.target,
color: {
color: color,
highlight: "#ffffff",
highlight: colors.ring,
hover: color,
opacity: edge.kind === "bundle" ? 0.35 : 0.7,
},
width: isDim ? 1 : 2,
arrows: {
to: {
enabled: edge.kind !== "contains",
scaleFactor: 0.5,
},
},
smooth: {
enabled: true,
type: "continuous",
roundness: 0.3,
},
title: `${edge.kind}: ${edge.source} → ${edge.target}`,
_raw: edge,
width: edge.kind === "bundle" ? Math.min(8, 1 + Math.log2(count)) : 1,
arrows: { to: { enabled: edge.kind !== "contains", scaleFactor: 0.4 } },
smooth: { enabled: true, type: "continuous", roundness: 0.3 },
title: label,
};
}
// Recolour everything after a theme change, without a new layout.
function recolor() {
if (!network) return;
var colors = palette();
var counts = edgeCounts(rawEdges);
nodesDataset.update(rawNodes.map(function (n) {
return toVisNode(n, counts, colors);
}));
edgesDataset.update(rawEdges.map(function (e) {
return toVisEdge(e, colors);
}));
}
new MutationObserver(recolor).observe(document.documentElement, {
attributes: true,
attributeFilter: ["data-theme"],
});
window.matchMedia("(prefers-color-scheme: dark)").addEventListener("change", recolor);
function uniqueBy(items, key) {
var seen = {};
return items.filter(function (item) {
var k = key(item);
if (seen[k]) return false;
seen[k] = true;
return true;
});
}
/**
* Initialize or reload the graph visualization.
* Called from Rust via eval().
* Draw `nodes` and `edges`, then select and show the nodes named in
* `focus` (may be empty). `labels` holds the UI texts. Called from Rust.
*/
window.__loadGraph = function (nodes, edges) {
window.__loadGraph = function (nodes, edges, labels, focus) {
var container = document.getElementById("graph-canvas");
if (!container) {
console.error("[graph-viz] #graph-canvas not found");
return;
}
if (!container) return;
texts = labels;
// Count edges per node for sizing
const edgeCounts = {};
edges.forEach(function (e) {
edgeCounts[e.source] = (edgeCounts[e.source] || 0) + 1;
edgeCounts[e.target] = (edgeCounts[e.target] || 0) + 1;
});
rawNodes = uniqueBy(nodes, function (n) { return n.qualified_name; });
rawEdges = uniqueBy(edges, function (e) { return e.source + "|" + e.target + "|" + e.kind; });
// Deduplicate nodes by qualified_name (keep first occurrence)
var seenNodes = {};
var uniqueNodes = [];
nodes.forEach(function (n) {
if (!seenNodes[n.qualified_name]) {
seenNodes[n.qualified_name] = true;
uniqueNodes.push(n);
}
});
var colors = palette();
var counts = edgeCounts(rawEdges);
nodesDataset = new vis.DataSet(rawNodes.map(function (n) {
return toVisNode(n, counts, colors);
}));
edgesDataset = new vis.DataSet(rawEdges.map(function (e) {
return toVisEdge(e, colors);
}));
// Deduplicate edges by source+target+kind
var seenEdges = {};
var uniqueEdges = [];
edges.forEach(function (e) {
var key = e.source + "|" + e.target + "|" + e.kind;
if (!seenEdges[key]) {
seenEdges[key] = true;
uniqueEdges.push(e);
}
});
rawNodes = uniqueNodes;
rawEdges = uniqueEdges;
var visNodes = uniqueNodes.map(function (n) {
return toVisNode(n, edgeCounts);
});
var visEdges = uniqueEdges.map(toVisEdge);
nodesDataset = new vis.DataSet(visNodes);
edgesDataset = new vis.DataSet(visEdges);
const options = {
var large = rawNodes.length > LARGE;
var options = {
nodes: {
font: { color: "#e4eaf4", size: 10 },
scaling: { min: 8, max: 35 },
},
edges: {
font: { color: "#5e7291", size: 9, strokeWidth: 0 },
selectionWidth: 3,
scaling: {
min: 12,
max: 56,
label: { enabled: true, min: 22, max: 48, drawThreshold: 5, maxVisible: 30 },
},
},
physics: {
enabled: true,
solver: "forceAtlas2Based",
forceAtlas2Based: {
gravitationalConstant: -80,
centralGravity: 0.005,
springLength: 120,
gravitationalConstant: -60,
centralGravity: 0.008,
springLength: 110,
springConstant: 0.04,
damping: 0.5,
avoidOverlap: 0.6,
damping: 0.6,
avoidOverlap: 0.5,
},
stabilization: {
enabled: true,
iterations: 1500,
updateInterval: 25,
},
maxVelocity: 50,
stabilization: { enabled: true, iterations: large ? 300 : 1000, updateInterval: 25 },
maxVelocity: 40,
minVelocity: 0.75,
},
interaction: {
hover: true,
tooltipDelay: 200,
hideEdgesOnDrag: false,
hideEdgesOnZoom: false,
multiselect: false,
navigationButtons: false,
keyboard: { enabled: true },
},
layout: {
improvedLayout: uniqueNodes.length < 300,
hideEdgesOnDrag: large,
hideEdgesOnZoom: large,
keyboard: { enabled: true, bindToWindow: false },
},
layout: { improvedLayout: rawNodes.length < 300 },
};
// Destroy previous instance
if (network) {
network.destroy();
}
if (network) network.destroy();
network = new vis.Network(container, { nodes: nodesDataset, edges: edgesDataset }, options);
network = new vis.Network(
container,
{ nodes: nodesDataset, edges: edgesDataset },
options
);
// Click handler — sends data to Rust
network.on("click", function (params) {
if (params.nodes.length > 0) {
const nodeId = params.nodes[0];
const visNode = nodesDataset.get(nodeId);
if (visNode && visNode._raw && window.__onNodeClick) {
window.__onNodeClick(JSON.stringify(visNode._raw));
}
}
if (params.nodes.length === 0) return;
var raw = rawNodes.find(function (n) { return n.qualified_name === params.nodes[0]; });
if (raw && window.__onNodeClick) window.__onNodeClick(JSON.stringify(raw));
});
// Stabilization overlay
var overlay = document.getElementById("graph-stabilization-overlay");
var progressFill = document.getElementById("graph-stab-progress-fill");
var pctLabel = document.getElementById("graph-stab-pct");
// Show the overlay
if (overlay) {
overlay.classList.remove("graph-stab-fade-out");
overlay.style.display = "flex";
@@ -233,120 +243,35 @@
network.on("stabilizationProgress", function (params) {
var pct = Math.round((params.iterations / params.total) * 100);
if (progressFill) {
progressFill.style.width = pct + "%";
}
if (pctLabel) {
pctLabel.textContent = pct + "% — computing layout";
}
if (progressFill) progressFill.style.width = pct + "%";
if (pctLabel) pctLabel.textContent = texts.layout + " · " + pct + " %";
});
network.on("stabilizationIterationsDone", function () {
network.once("stabilizationIterationsDone", function () {
if (progressFill) progressFill.style.width = "100%";
if (pctLabel) pctLabel.textContent = "Complete";
// Fade out overlay
if (overlay) {
overlay.classList.add("graph-stab-fade-out");
setTimeout(function () {
overlay.style.display = "none";
}, 900);
setTimeout(function () { overlay.style.display = "none"; }, 600);
}
// Keep physics running so nodes float and respond to dragging,
// but reduce forces for a calm, settled feel
network.setOptions({
physics: {
enabled: true,
solver: "forceAtlas2Based",
forceAtlas2Based: {
gravitationalConstant: -40,
centralGravity: 0.003,
springLength: 120,
springConstant: 0.03,
damping: 0.7,
avoidOverlap: 0.6,
},
maxVelocity: 20,
minVelocity: 0.75,
},
});
// A large drawing stops moving; a small one keeps settling gently
// and answers to dragging.
network.setOptions({ physics: large ? { enabled: false } : { maxVelocity: 15 } });
window.__highlightNodes(focus || []);
});
console.log(
"[graph-viz] Loaded " + nodes.length + " nodes, " + edges.length + " edges"
);
};
/**
* Highlight a node by qualified name. Focuses + selects it.
*/
window.__highlightNode = function (qualifiedName) {
if (!network || !nodesDataset) return;
const node = nodesDataset.get(qualifiedName);
if (!node) return;
network.selectNodes([qualifiedName]);
network.focus(qualifiedName, {
scale: 1.5,
animation: { duration: 500, easingFunction: "easeInOutQuad" },
});
// Trigger click callback too
if (node._raw && window.__onNodeClick) {
window.__onNodeClick(JSON.stringify(node._raw));
}
};
/**
* Highlight multiple nodes (e.g., search results or file nodes).
*/
/** Select the named nodes that are drawn and show them. */
window.__highlightNodes = function (qualifiedNames) {
if (!network || !nodesDataset) return;
network.selectNodes(qualifiedNames);
if (qualifiedNames.length > 0) {
network.fit({
nodes: qualifiedNames,
animation: { duration: 500, easingFunction: "easeInOutQuad" },
});
}
var drawn = qualifiedNames.filter(function (id) { return nodesDataset.get(id); });
if (drawn.length === 0) return;
network.selectNodes(drawn);
network.fit({ nodes: drawn, animation: { duration: 500, easingFunction: "easeInOutQuad" } });
};
/**
* Highlight all nodes belonging to a specific file path.
*/
window.__highlightFileNodes = function (filePath) {
if (!network || !nodesDataset) return;
var matching = [];
rawNodes.forEach(function (n) {
if (n.file_path === filePath) {
matching.push(n.qualified_name);
}
});
if (matching.length > 0) {
network.selectNodes(matching);
network.fit({
nodes: matching,
animation: { duration: 500, easingFunction: "easeInOutQuad" },
});
}
};
/**
* Clear selection.
*/
window.__clearGraphSelection = function () {
if (!network) return;
network.unselectAll();
};
/**
* Fit entire graph in view.
*/
/** Fit the whole drawing in view. */
window.__fitGraph = function () {
if (!network) return;
network.fit({
animation: { duration: 400, easingFunction: "easeInOutQuad" },
});
network.fit({ animation: { duration: 400, easingFunction: "easeInOutQuad" } });
};
})();
+160 -155
View File
@@ -101,6 +101,18 @@
color-scheme: light;
}
/* Code graph colours (graph-viz.js reads them), from the theme tokens, so
they follow the light and dark theme. */
:root {
--graph-function: var(--accent);
--graph-type: var(--success);
--graph-enum: var(--warning);
--graph-interface: var(--info);
--graph-module: var(--orange);
--graph-file: var(--text-faint);
--graph-community: var(--text-tertiary);
}
/* ── Dark ("Nacht") ──
When chosen explicitly (`data-theme="dark"`), or when the OS prefers dark
and no choice was made. */
@@ -1762,85 +1774,6 @@ tbody tr:last-child td {
gap: 24px;
}
/* Orbital rings */
.graph-stab-rings {
position: relative;
width: 120px;
height: 120px;
}
.graph-stab-ring {
position: absolute;
inset: 0;
border-radius: 50%;
border: 1px solid transparent;
}
.graph-stab-ring-1 {
border-top-color: var(--accent);
border-right-color: var(--accent-muted);
animation: stab-orbit 2.4s linear infinite;
}
.graph-stab-ring-2 {
inset: 14px;
border-bottom-color: rgba(224, 64, 251, 0.5);
border-left-color: rgba(224, 64, 251, 0.1);
animation: stab-orbit 1.8s linear infinite reverse;
filter: drop-shadow(0 0 6px rgba(224, 64, 251, 0.25));
}
.graph-stab-ring-3 {
inset: 30px;
border-top-color: var(--success);
border-right-color: var(--success-bg);
animation: stab-orbit 3.2s linear infinite;
}
.graph-stab-core {
position: absolute;
top: 50%;
left: 50%;
width: 10px;
height: 10px;
transform: translate(-50%, -50%);
background: var(--accent);
border-radius: 50%;
box-shadow: 0 0 0 3px var(--border-accent);
animation: stab-pulse 1.6s ease-in-out infinite;
}
@keyframes stab-orbit {
to { transform: rotate(360deg); }
}
@keyframes stab-pulse {
0%, 100% { transform: translate(-50%, -50%) scale(1); opacity: 1; }
50% { transform: translate(-50%, -50%) scale(1.6); opacity: 0.6; }
}
/* Text */
.graph-stab-text {
text-align: center;
}
.graph-stab-title {
font-family: var(--font-display);
font-size: 16px;
font-weight: 700;
letter-spacing: 0.08em;
text-transform: uppercase;
color: var(--text-primary);
margin-bottom: 4px;
}
.graph-stab-subtitle {
font-family: var(--font-mono);
font-size: 12px;
color: var(--text-secondary);
letter-spacing: 0.03em;
}
/* Progress bar */
.graph-stab-progress {
width: 200px;
@@ -1854,23 +1787,9 @@ tbody tr:last-child td {
.graph-stab-progress-fill {
height: 100%;
width: 0%;
background: linear-gradient(90deg, var(--accent), #e040fb);
background: var(--accent);
border-radius: 2px;
transition: width 0.3s ease-out;
box-shadow: none;
position: relative;
}
.graph-stab-progress-fill::after {
content: '';
position: absolute;
right: 0;
top: -2px;
width: 7px;
height: 7px;
background: #fff;
border-radius: 50%;
box-shadow: none;
}
.graph-stab-pct {
@@ -1885,16 +1804,11 @@ tbody tr:last-child td {
flex-direction: column;
align-items: center;
justify-content: center;
height: 100%;
min-height: 240px;
color: var(--text-tertiary);
gap: 8px;
}
.graph-empty-icon {
font-size: 48px;
opacity: 0.3;
}
.graph-empty-state h3 {
font-family: var(--font-display);
font-size: 16px;
@@ -1905,37 +1819,6 @@ tbody tr:last-child td {
font-size: 13px;
}
/* Stats Bar */
.graph-stats-bar {
display: flex;
align-items: center;
gap: 12px;
padding: 8px 16px;
background: var(--bg-secondary);
border-top: 1px solid var(--border);
font-family: var(--font-mono);
font-size: 11px;
flex-shrink: 0;
}
.graph-stat {
display: inline-flex;
align-items: center;
}
.graph-stat-value {
color: var(--accent);
font-weight: 600;
}
.graph-stat-label {
color: var(--text-tertiary);
}
.graph-stat-divider {
color: var(--border-bright);
}
/* Node Kind Badges */
.node-label-badge {
display: inline-flex;
@@ -1949,40 +1832,96 @@ tbody tr:last-child td {
letter-spacing: 0.04em;
}
.node-kind-function, .node-kind-method {
background: var(--accent-muted);
color: var(--accent);
border: 1px solid var(--border-accent);
/* Node kinds: the badge in the inspector and the legend's dots, in the
colours graph-viz.js draws them with. */
.node-label-badge[class*="graph-kind-"] {
background: color-mix(in oklch, var(--kind) 12%, transparent);
color: var(--kind);
border: 1px solid color-mix(in oklch, var(--kind) 30%, transparent);
}
.node-kind-struct, .node-kind-class {
background: rgba(224, 64, 251, 0.12);
color: #e040fb;
border: 1px solid rgba(224, 64, 251, 0.2);
.graph-kind-function, .graph-kind-method { --kind: var(--graph-function); }
.graph-kind-class, .graph-kind-struct { --kind: var(--graph-type); }
.graph-kind-enum { --kind: var(--graph-enum); }
.graph-kind-interface, .graph-kind-trait { --kind: var(--graph-interface); }
.graph-kind-module { --kind: var(--graph-module); }
.graph-kind-file { --kind: var(--graph-file); }
.graph-kind-community, .graph-kind-folder { --kind: var(--graph-community); }
.graph-legend-dot.graph-kind-folder { border-radius: 2px; }
.graph-legend {
position: absolute;
left: 12px;
bottom: 12px;
z-index: 10;
display: flex;
flex-wrap: wrap;
gap: 4px 12px;
max-width: calc(100% - 24px);
margin: 0;
padding: 6px 10px;
list-style: none;
font-size: 11.5px;
color: var(--text-secondary);
background: color-mix(in oklch, var(--bg-card) 90%, transparent);
border: 1px solid var(--border);
border-radius: var(--radius);
}
.node-kind-enum {
background: rgba(255, 176, 32, 0.12);
color: #ffb020;
border: 1px solid rgba(255, 176, 32, 0.2);
.graph-legend li {
display: inline-flex;
align-items: center;
gap: 6px;
}
.node-kind-interface, .node-kind-trait {
background: rgba(124, 77, 255, 0.12);
color: #7c4dff;
border: 1px solid rgba(124, 77, 255, 0.2);
.graph-legend-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--kind);
}
.node-kind-module {
background: rgba(255, 138, 61, 0.12);
color: #ff8a3d;
border: 1px solid rgba(255, 138, 61, 0.2);
.graph-legend-entry {
background: transparent;
border: 2px solid var(--text-primary);
}
.node-kind-file {
background: var(--success-bg);
color: var(--success);
border: 1px solid color-mix(in oklch, var(--success) 30%, transparent);
.graph-note {
margin: 0 0 12px;
font-size: 12.5px;
color: var(--text-tertiary);
}
/* A finding's impact: its call chains and the names around it. */
.impact-summary {
grid-template-columns: 1fr;
}
.impact-chains,
.impact-names {
display: grid;
gap: 8px;
margin: 0;
padding: 0;
list-style: none;
}
.impact-chains li {
display: flex;
flex-wrap: wrap;
align-items: center;
gap: 6px;
}
.impact-chains code,
.impact-names code {
font-family: var(--font-mono);
font-size: 12px;
overflow-wrap: anywhere;
}
.impact-chain-arrow {
color: var(--text-faint);
}
/* Code Inspector Panel */
@@ -2243,12 +2182,23 @@ tbody tr:last-child td {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
padding: 8px 12px;
cursor: pointer;
font: inherit;
color: inherit;
text-align: left;
background: none;
border: none;
border-bottom: 1px solid var(--border);
transition: background 0.15s;
}
.search-suggestion-item:focus-visible {
outline: 2px solid var(--accent);
outline-offset: -2px;
}
.search-suggestion-item:last-child {
border-bottom: none;
}
@@ -4782,6 +4732,21 @@ tbody tr:last-child td {
color: var(--accent);
}
.usage-summary {
display: flex;
flex-wrap: wrap;
align-items: baseline;
gap: 6px 16px;
margin: 0 0 16px;
font-size: 13px;
color: var(--text-secondary);
}
.usage-summary-title {
font-weight: 600;
color: var(--text-primary);
}
.targets-type,
.targets-ago {
display: block;
@@ -4797,6 +4762,21 @@ tbody tr:last-child td {
margin-top: 4px;
}
.target-billing {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 8px;
margin-bottom: 16px;
}
.billing-swap-row {
display: flex;
flex-wrap: wrap;
gap: 8px;
align-items: center;
}
.targets-cra {
min-width: 220px;
}
@@ -4916,6 +4896,30 @@ 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);
}
/* Files the graph left out: a fact to notice, not an alarm. */
.target-graph-unreadable {
margin: 0 0 4px;
font-size: 13px;
color: var(--warning);
}
.target-graph-note {
margin: 0;
font-size: 12px;
color: var(--text-tertiary);
}
.target-figures {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
@@ -5174,6 +5178,7 @@ tbody tr:last-child td {
@media (max-width: 1000px) {
.target-summary,
.target-summary:has(.target-graph),
.target-columns {
grid-template-columns: 1fr;
}
+2 -2
View File
@@ -28,8 +28,8 @@ pub enum Route {
SbomPage { target: String },
#[route("/issues")]
IssuesPage {},
#[route("/graph")]
GraphIndexPage {},
// The code graph opens from its card on the target page.
#[redirect("/graph", || Route::TargetsPage {})]
#[route("/graph/:repo_id")]
GraphExplorerPage { repo_id: String },
#[route("/graph/:repo_id/impact/:finding_id")]
@@ -0,0 +1,121 @@
//! On an extra target's page: swap it with an included target (t72). The
//! target swapped in stays included until the end of the month; the one
//! swapped out becomes extra at once.
use dioxus::prelude::*;
use crate::components::toast::{ToastType, Toasts};
use crate::i18n::texts::targets as tx;
use crate::i18n::use_lang;
use crate::infrastructure::onboarding::{fetch_targets_page, swap_target_billing};
/// The included targets one could swap out, as (id, name), from the
/// targets list: included, not archived, and not `target_id` itself.
fn swappable(targets: &[serde_json::Value], target_id: &str) -> Vec<(String, String)> {
targets
.iter()
.filter(|t| {
t.get("billing")
.and_then(|b| b.as_str())
.unwrap_or("included")
== "included"
})
.filter(|t| t.get("archived_at").is_none_or(serde_json::Value::is_null))
.filter_map(|t| {
let id = t
.get("_id")
.and_then(|i| i.get("$oid").or(Some(i)))
.and_then(|i| i.as_str())?
.to_string();
let name = t
.get("name")
.and_then(|n| n.as_str())
.unwrap_or("")
.to_string();
(id != target_id).then_some((id, name))
})
.collect()
}
/// The swap control for the extra target `target_id`; `on_swapped` runs
/// once the swap is made.
#[component]
pub fn BillingSwap(target_id: String, on_swapped: EventHandler<()>) -> Element {
let lang = use_lang()();
let mut toasts = use_context::<Toasts>();
let targets = use_resource(move || async move { fetch_targets_page(None, 1, 100).await });
let mut chosen = use_signal(String::new);
let mut busy = use_signal(|| false);
let options = match &*targets.read() {
Some(Ok(resp)) => swappable(&resp.data, &target_id),
_ => Vec::new(),
};
if options.is_empty() {
return rsx! {};
}
rsx! {
div { class: "billing-swap",
h4 { class: "target-subhead", {tx::SWAP_TITLE.get(lang)} }
p { class: "target-muted", {tx::SWAP_HINT.get(lang)} }
div { class: "billing-swap-row",
select {
onchange: move |e| chosen.set(e.value()),
option { value: "", {tx::SWAP_CHOOSE.get(lang)} }
for (id, name) in options {
option { value: "{id}", selected: chosen() == id, "{name}" }
}
}
button {
class: "btn btn-secondary",
disabled: chosen().is_empty() || busy(),
onclick: {
let target_id = target_id.clone();
move |_| {
let (id, with) = (target_id.clone(), chosen());
busy.set(true);
spawn(async move {
match swap_target_billing(id, with).await {
Ok(()) => {
toasts.push(ToastType::Success, tx::SWAPPED.get(lang));
on_swapped.call(());
}
Err(e) => toasts.push(
ToastType::Error,
tx::swap_refused(&e.to_string(), lang),
),
}
busy.set(false);
});
}
},
{tx::SWAP.get(lang)}
}
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn only_other_included_active_targets_can_be_swapped_out() {
let targets = serde_json::json!([
{ "_id": { "$oid": "a" }, "name": "Pumpe", "billing": "included" },
{ "_id": { "$oid": "b" }, "name": "Ventil", "billing": "extra" },
{ "_id": { "$oid": "c" }, "name": "Alt" },
{ "_id": { "$oid": "d" }, "name": "Archiv", "billing": "included",
"archived_at": { "$date": { "$numberLong": "1" } } },
{ "_id": { "$oid": "e" }, "name": "Selbst", "billing": "included" },
]);
let list = targets.as_array().cloned().unwrap_or_default();
assert_eq!(
swappable(&list, "e"),
[
("a".to_string(), "Pumpe".to_string()),
("c".to_string(), "Alt".to_string())
]
);
}
}
@@ -1,17 +1,22 @@
use dioxus::prelude::*;
use crate::i18n::texts::graph as tx;
use crate::i18n::use_lang;
use crate::infrastructure::graph::fetch_file_content;
/// A file of the code graph, with the selected code unit's lines marked.
#[component]
pub fn CodeInspector(
repo_id: String,
file_path: String,
node_name: String,
node_kind: String,
node_language: String,
start_line: u32,
end_line: u32,
on_close: EventHandler<()>,
) -> Element {
let lang = use_lang()();
let file_path_clone = file_path.clone();
let repo_id_clone = repo_id.clone();
let file_content = use_resource(move || {
@@ -30,18 +35,20 @@ pub fn CodeInspector(
// Header
div { class: "code-inspector-header",
div { class: "code-inspector-title",
span { class: "badge badge-info", "SELECTED" }
span { class: "code-inspector-file-name", "{file_path}" }
}
div { class: "code-inspector-meta",
span { class: "node-label-badge node-kind-{node_kind}", "{node_kind}" }
span { class: "node-label-badge graph-kind-{node_kind}", {tx::node_kind(&node_kind, &node_language).get(lang)} }
span { class: "code-inspector-node-name", "{node_name}" }
if start_line > 0 && end_line > 0 {
span { class: "code-inspector-lines", "L{start_line}–L{end_line}" }
span { class: "code-inspector-lines", "{tx::LINES.get(lang)} {start_line}–{end_line}" }
}
}
button {
class: "btn-sm code-inspector-close",
class: "btn btn-ghost btn-sm code-inspector-close",
r#type: "button",
title: tx::CLOSE.get(lang),
"aria-label": tx::CLOSE.get(lang),
onclick: move |_| on_close.call(()),
"\u{2715}"
}
@@ -79,12 +86,10 @@ pub fn CodeInspector(
}
},
Some(None) => rsx! {
div { class: "code-inspector-empty",
"Could not load file content."
}
div { class: "code-inspector-empty", {tx::FILE_FAILED.get(lang)} }
},
None => rsx! {
div { class: "loading", "Loading file..." }
div { class: "loading", {tx::FILE_LOADING.get(lang)} }
},
}
}
@@ -1,6 +1,7 @@
pub mod app_shell;
pub mod artifact_upload;
pub mod attack_chain;
pub mod billing_swap;
pub mod code_inspector;
pub mod code_snippet;
pub mod copy_button;
@@ -28,5 +29,6 @@ pub mod sidebar;
pub mod support;
pub mod theme_toggle;
pub mod toast;
pub mod usage_summary;
pub mod vex_panel;
pub mod webhook_deliveries;
@@ -108,9 +108,7 @@ pub fn ScanRunList(
.peek()
.as_ref()
.and_then(|r| r.as_ref())
.is_some_and(|list| {
list.is_empty() || list.iter().any(|r| r.status == ScanRunStatus::Running)
});
.is_some_and(|list| list.is_empty() || list.iter().any(|r| r.status.is_open()));
if waiting {
runs.restart();
}
@@ -161,7 +159,8 @@ fn run_transitions(
let mut finished = Vec::new();
for run in runs {
let id = run.id.map(|id| id.to_hex()).unwrap_or_default();
if run.status == ScanRunStatus::Running {
// A queued run counts: it may finish before it is ever seen running.
if run.status.is_open() {
running.push(id);
} else if seen_running.contains(&id) && !finished_here.contains(&id) {
finished.push(id);
@@ -176,13 +175,20 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
let started = format_time(&run.started_at, lang);
let finished = run.completed_at.as_ref().map(|t| format_time(t, lang));
let running = run.status == ScanRunStatus::Running;
// A queued run's time is when it was asked for: it has not started.
let queued = run.status == ScanRunStatus::Queued;
let started_label = if queued {
scans::REQUESTED
} else {
scans::STARTED
};
rsx! {
div { style: "border-left: 3px solid var(--border); padding: 6px 10px; margin: 6px 0;",
div { style: "display: flex; gap: 12px; align-items: center; flex-wrap: wrap;",
span { class: "{badge}", {status.get(lang)} }
span { style: "font-size: 0.9em;",
{scans::STARTED.get(lang)} ": {started}"
{started_label.get(lang)} ": {started}"
}
if let Some(finished) = finished {
span { style: "font-size: 0.9em;",
@@ -213,6 +219,11 @@ fn scan_run_card(run: &ScanRun, lang: Lang) -> Element {
run_id: run.id.map(|id| id.to_hex()).unwrap_or_default(),
}
}
if queued {
div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;",
{scans::QUEUED_HINT.get(lang)}
}
}
if run.status == ScanRunStatus::Interrupted {
div { style: "font-size: 0.85em; opacity: 0.8; margin-top: 4px;",
{scans::INTERRUPTED_HINT.get(lang)}
@@ -450,6 +461,7 @@ fn RunReveal(target_id: String, run_id: String, count: u32) -> Element {
/// The badge class and label for a run status.
pub fn status_badge(status: &ScanRunStatus) -> (&'static str, Text) {
match status {
ScanRunStatus::Queued => ("badge badge-neutral", scans::QUEUED),
ScanRunStatus::Running => ("badge badge-info", scans::RUNNING),
ScanRunStatus::Completed => ("badge badge-success", scans::COMPLETED),
ScanRunStatus::Failed => ("badge badge-danger", scans::FAILED),
@@ -542,6 +554,24 @@ mod tests {
assert!(finished.is_empty());
}
#[test]
fn a_queued_run_reads_as_waiting_for_a_slot_and_is_followed_to_its_end() {
let mut run = ScanRun::queued("t".into(), compliance_core::models::ScanTrigger::Manual);
let (_, label) = status_badge(&run.status);
assert_eq!(label.get(Lang::De), "Wartet auf einen Platz");
assert_eq!(label.get(Lang::En), "Waiting for a slot");
// Seen while it waits, so its end is revealed even if it is never
// seen running.
let none = HashSet::new();
let (seen, _) = run_transitions(std::slice::from_ref(&run), &none, &none);
assert_eq!(seen, vec![String::new()]);
run.status = ScanRunStatus::Completed;
let seen = HashSet::from([String::new()]);
let (_, finished) = run_transitions(std::slice::from_ref(&run), &seen, &none);
assert_eq!(finished, vec![String::new()]);
}
#[test]
fn the_stepper_marks_done_current_and_pending_phases() {
let mut run = ScanRun::new("t".into(), compliance_core::models::ScanTrigger::Manual);
@@ -0,0 +1,87 @@
//! The usage view on the targets page (t72): this month's Prüfungen against
//! the quota, Prüftage against the cap, and the extra targets.
use dioxus::prelude::*;
use crate::i18n::texts::metering as tx;
use crate::i18n::use_lang;
use crate::infrastructure::metering::{fetch_usage, Usage};
/// The lines of the usage view: only the count when the plan is not known,
/// Prüftage only where there is a quota, extra targets only where the plan
/// limits the included ones.
fn lines(u: &Usage, lang: crate::i18n::Lang) -> Vec<String> {
if !u.plan_known {
return vec![tx::counted(u.pruefungen, lang)];
}
let mut lines = vec![tx::pruefungen(u.pruefungen, u.monthly_pruefungen, lang)];
if u.monthly_pruefungen.is_some() {
lines.push(tx::prueftage(u.prueftage, u.prueftag_cap, lang));
}
if u.included_targets.is_some() {
lines.push(tx::extra_targets(u.extra_targets, lang));
}
lines
}
/// This month's usage in one row. Shows nothing while it loads or when it
/// cannot be read.
#[component]
pub fn UsageSummary() -> Element {
let lang = use_lang()();
let usage = use_resource(move || async move { fetch_usage().await });
let Some(Ok(resp)) = usage.read().clone() else {
return rsx! {};
};
rsx! {
div { class: "usage-summary", title: tx::HINT.get(lang),
span { class: "usage-summary-title", {tx::TITLE.get(lang)} }
for line in lines(&resp.data, lang) {
span { class: "usage-summary-item", "{line}" }
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::i18n::Lang;
#[test]
fn a_standard_plan_shows_quota_prueftage_and_extra_targets() {
let u = Usage {
pruefungen: 37,
prueftage: 1,
extra_targets: 2,
plan_known: true,
included_targets: Some(5),
monthly_pruefungen: Some(100),
prueftag_cap: None,
..Usage::default()
};
assert_eq!(
lines(&u, Lang::De),
[
"37 von 100 Prüfungen",
"1 Prüftag",
"2 zusätzliche Prüfobjekte"
]
);
}
#[test]
fn enterprise_and_an_unknown_plan_show_only_the_count() {
let enterprise = Usage {
pruefungen: 12,
plan_known: true,
..Usage::default()
};
assert_eq!(lines(&enterprise, Lang::En), ["12 scans, unlimited"]);
let unknown = Usage {
pruefungen: 12,
..Usage::default()
};
assert_eq!(lines(&unknown, Lang::En), ["12 counted scans"]);
}
}
+28
View File
@@ -93,6 +93,24 @@ pub fn format_bytes(bytes: u64, lang: Lang) -> String {
}
}
/// A count with thousands separators: `12.345` in German, `12,345` in English.
pub fn format_count(count: u64, lang: Lang) -> String {
let separator = match lang {
Lang::De => '.',
Lang::En => ',',
};
let digits = count.to_string();
let mut grouped = String::with_capacity(digits.len() + digits.len() / 3);
for (i, digit) in digits.chars().enumerate() {
// A separator before every digit that starts a group of three from the right.
if i > 0 && (digits.len() - i).is_multiple_of(3) {
grouped.push(separator);
}
grouped.push(digit);
}
grouped
}
/// A moment in the reader's date convention, in UTC: `30.09.2026 08:05 UTC`
/// in German, `2026-09-30 08:05 UTC` in English.
pub fn format_time(time: &chrono::DateTime<chrono::Utc>, lang: Lang) -> String {
@@ -195,6 +213,16 @@ fn set_document_lang(lang: Lang) {
#[cfg(test)]
mod tests {
#[test]
fn a_count_has_the_languages_thousands_separator() {
use super::{format_count, Lang};
assert_eq!(format_count(0, Lang::De), "0");
assert_eq!(format_count(999, Lang::De), "999");
assert_eq!(format_count(1_000, Lang::De), "1.000");
assert_eq!(format_count(12_345_678, Lang::De), "12.345.678");
assert_eq!(format_count(10_000, Lang::En), "10,000");
}
#[test]
fn a_moment_reads_as_how_long_ago_it_was() {
use chrono::{Duration, TimeZone, Utc};
+513
View File
@@ -367,6 +367,19 @@ pub mod scans {
de: "Noch nicht geprüft",
en: "Not scanned yet",
};
pub const QUEUED: Text = Text {
de: "Wartet auf einen Platz",
en: "Waiting for a slot",
};
pub const QUEUED_HINT: Text = Text {
de: "Alle Prüfplätze sind gerade belegt. Die Prüfung startet, sobald einer \
frei wird.",
en: "All scan slots are busy right now. The scan starts as soon as one is free.",
};
pub const REQUESTED: Text = Text {
de: "Angefordert",
en: "Requested",
};
pub const RUNNING: Text = Text {
de: "Läuft",
en: "Running",
@@ -870,6 +883,56 @@ pub mod targets {
de: "Zusätzliches Prüfobjekt",
en: "Extra target",
};
pub const SWAP_TITLE: Text = Text {
de: "Gegen ein enthaltenes Prüfobjekt tauschen",
en: "Swap with an included target",
};
pub const SWAP_HINT: Text = Text {
de: "Dieses Prüfobjekt wird enthalten und bleibt es bis Monatsende; das gewählte wird \
sofort zusätzlich. Die Zahl der zusätzlichen Prüfobjekte bleibt gleich.",
en: "This target becomes included and stays so until the end of the month; the one \
you choose becomes extra at once. The number of extra targets stays the same.",
};
pub const SWAP_CHOOSE: Text = Text {
de: "Enthaltenes Prüfobjekt wählen",
en: "Choose an included target",
};
pub const SWAP: Text = Text {
de: "Tauschen",
en: "Swap",
};
pub const SWAPPED: Text = Text {
de: "Getauscht. Dieses Prüfobjekt ist jetzt bis Monatsende enthalten.",
en: "Swapped. This target is now included until the end of the month.",
};
/// The words for a refused swap, from the agent's `error`.
pub fn swap_refused(error: &str, lang: super::super::Lang) -> String {
use super::super::Lang;
let text = if error.contains("swap_locked") {
Text {
de: "Das gewählte Prüfobjekt wurde in diesem Monat eingetauscht und bleibt bis \
Monatsende enthalten. Wählen Sie ein anderes.",
en: "The chosen target was swapped in this month and stays included until the \
end of the month. Choose another one.",
}
} else if error.contains("swap_not_extra") || error.contains("swap_not_included") {
Text {
de: "Die Zuordnung hat sich inzwischen geändert. Laden Sie die Seite neu.",
en: "The included targets changed in the meantime. Reload the page.",
}
} else if error.contains("swap_unlimited") {
Text {
de: "Ihr Tarif enthält alle Prüfobjekte; es gibt nichts zu tauschen.",
en: "Your plan includes every target; there is nothing to swap.",
}
} else {
return match lang {
Lang::De => format!("Nicht getauscht: {error}"),
Lang::En => format!("Not swapped: {error}"),
};
};
text.get(lang).to_string()
}
pub const EXTRA_HINT: Text = Text {
de: "Über die in Ihrem Tarif enthaltenen Prüfobjekte hinaus: wird monatlich \
zusätzlich berechnet, und jede seiner Prüfungen zählt zu Ihrem Kontingent.",
@@ -1078,6 +1141,36 @@ 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_SHOW: Text = Text {
de: "Anzeigen",
en: "Show",
};
/// The code graph's source files it could not read as text:
/// "1 Datei nicht lesbar", "3 files unreadable".
pub fn unreadable_files(count: u32, lang: super::super::Lang) -> String {
match (lang, count) {
(super::super::Lang::De, 1) => "1 Datei nicht lesbar".to_string(),
(super::super::Lang::De, n) => format!("{n} Dateien nicht lesbar"),
(super::super::Lang::En, 1) => "1 file unreadable".to_string(),
(super::super::Lang::En, n) => format!("{n} files unreadable"),
}
}
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",
@@ -1203,6 +1296,14 @@ pub mod targets {
assert_eq!(count(1, Lang::En), "1 target");
assert_eq!(count(0, Lang::En), "0 targets");
}
#[test]
fn the_unreadable_files_line_reads_like_the_language() {
assert_eq!(unreadable_files(1, Lang::De), "1 Datei nicht lesbar");
assert_eq!(unreadable_files(4, Lang::De), "4 Dateien nicht lesbar");
assert_eq!(unreadable_files(1, Lang::En), "1 file unreadable");
assert_eq!(unreadable_files(4, Lang::En), "4 files unreadable");
}
}
}
@@ -3071,6 +3172,8 @@ pub mod compliance {
"rust" => "Rust",
"csharp" => "C#",
"swift" => "Swift",
"structured_text" => "Structured Text",
"plcopen" => "PLCopen XML",
other => other,
}
}
@@ -4433,3 +4536,413 @@ pub mod license_review {
}
}
}
/// The usage view on the targets page (t72): Prüfungen against the quota,
/// Prüftage against the cap, extra targets.
pub mod metering {
use super::Text;
use crate::i18n::Lang;
pub const TITLE: Text = Text {
de: "Nutzung in diesem Monat",
en: "Usage this month",
};
pub const HINT: Text = Text {
de: "Gezählt werden Prüfungen, die Sie starten, und jede Prüfung eines zusätzlichen \
Prüfobjekts. Prüfungen nach einer Änderung an enthaltenen Prüfobjekten zählen \
nicht.",
en: "Counted are the scans you start, and every scan of an extra target. Scans after \
a change to an included target are not counted.",
};
/// "37 von 100 Prüfungen", or "37 Prüfungen, unbegrenzt" without a quota.
pub fn pruefungen(used: u32, quota: Option<u32>, lang: Lang) -> String {
match (lang, quota) {
(Lang::De, Some(q)) => format!("{used} von {q} Prüfungen"),
(Lang::De, None) => format!("{used} Prüfungen, unbegrenzt"),
(Lang::En, Some(q)) => format!("{used} of {q} scans"),
(Lang::En, None) => format!("{used} scans, unlimited"),
}
}
/// "37 gezählte Prüfungen", when the plan's limits are not known.
pub fn counted(used: u32, lang: Lang) -> String {
match lang {
Lang::De => format!("{used} gezählte Prüfungen"),
Lang::En => format!("{used} counted scans"),
}
}
/// "2 Prüftage (Limit 5)", "1 Prüftag", or that none are allowed.
pub fn prueftage(booked: u32, cap: Option<u32>, lang: Lang) -> String {
let days = match (lang, booked) {
(Lang::De, 1) => "1 Prüftag".to_string(),
(Lang::De, n) => format!("{n} Prüftage"),
(Lang::En, 1) => "1 Prüftag".to_string(),
(Lang::En, n) => format!("{n} Prüftage"),
};
match (lang, cap) {
(Lang::De, Some(0)) => "Keine Prüftage erlaubt".to_string(),
(Lang::En, Some(0)) => "No Prüftage allowed".to_string(),
(_, Some(c)) => format!("{days} (Limit {c})"),
(_, None) => days,
}
}
/// "1 zusätzliches Prüfobjekt", or that every target is included.
pub fn extra_targets(extra: u32, lang: Lang) -> String {
match (lang, extra) {
(Lang::De, 0) => "Alle Prüfobjekte im Tarif enthalten".to_string(),
(Lang::De, 1) => "1 zusätzliches Prüfobjekt".to_string(),
(Lang::De, n) => format!("{n} zusätzliche Prüfobjekte"),
(Lang::En, 0) => "All targets included in your plan".to_string(),
(Lang::En, 1) => "1 extra target".to_string(),
(Lang::En, n) => format!("{n} extra targets"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_quota_line_says_what_is_left_or_that_there_is_no_limit() {
assert_eq!(pruefungen(37, Some(100), Lang::De), "37 von 100 Prüfungen");
assert_eq!(pruefungen(37, None, Lang::En), "37 scans, unlimited");
assert_eq!(counted(37, Lang::De), "37 gezählte Prüfungen");
}
#[test]
fn the_prueftag_line_names_the_cap() {
assert_eq!(prueftage(2, Some(5), Lang::De), "2 Prüftage (Limit 5)");
assert_eq!(prueftage(1, None, Lang::De), "1 Prüftag");
assert_eq!(prueftage(0, Some(0), Lang::De), "Keine Prüftage erlaubt");
}
#[test]
fn extra_targets_read_naturally() {
assert_eq!(
extra_targets(0, Lang::De),
"Alle Prüfobjekte im Tarif enthalten"
);
assert_eq!(extra_targets(1, Lang::De), "1 zusätzliches Prüfobjekt");
assert_eq!(extra_targets(3, Lang::En), "3 extra targets");
}
}
}
/// The code graph's explorer and a finding's impact in it (t82).
pub mod graph {
use super::super::{format_count, Lang};
use super::Text;
pub const TITLE: Text = Text {
de: "Codegraph",
en: "Code graph",
};
pub const BACK: Text = Text {
de: "Zurück",
en: "Back",
};
pub const OVERVIEW: Text = Text {
de: "Übersicht",
en: "Overview",
};
pub const SEARCH: Text = Text {
de: "Baustein suchen …",
en: "Search code units …",
};
pub const FIT: Text = Text {
de: "Alles zeigen",
en: "Fit view",
};
pub const REBUILD: Text = Text {
de: "Neu aufbauen",
en: "Rebuild",
};
pub const BUILDING: Text = Text {
de: "Wird aufgebaut …",
en: "Building …",
};
pub const BUILD_STARTED: Text = Text {
de: "Der Codegraph wird neu aufgebaut.",
en: "The code graph is being rebuilt.",
};
pub const FILES: Text = Text {
de: "Dateien",
en: "Files",
};
pub const FILTER_FILES: Text = Text {
de: "Dateien filtern …",
en: "Filter files …",
};
pub const LOADING: Text = Text {
de: "Codegraph wird geladen …",
en: "Loading the code graph …",
};
pub const LOAD_FAILED: Text = Text {
de: "Der Codegraph konnte nicht geladen werden.",
en: "The code graph could not be loaded.",
};
pub const EMPTY_TITLE: Text = Text {
de: "Noch kein Codegraph",
en: "No code graph yet",
};
pub const EMPTY_BODY: Text = Text {
de: "Er entsteht mit der nächsten Prüfung dieses Prüfobjekts.",
en: "It is built with this target's next scan.",
};
pub const LAYOUT: Text = Text {
de: "Anordnung wird berechnet",
en: "Computing the layout",
};
pub const CODE_UNITS: Text = Text {
de: "Bausteine",
en: "code units",
};
pub const EDGES: Text = Text {
de: "Beziehungen",
en: "relations",
};
pub const GROUPS: Text = Text {
de: "Gruppen",
en: "groups",
};
pub const ENTRY_POINT: Text = Text {
de: "Einstiegspunkt",
en: "Entry point",
};
pub const FILE: Text = Text {
de: "Datei",
en: "File",
};
pub const LINES: Text = Text {
de: "Zeilen",
en: "lines",
};
pub const CLOSE: Text = Text {
de: "Schließen",
en: "Close",
};
pub const FILE_FAILED: Text = Text {
de: "Die Datei konnte nicht geladen werden.",
en: "The file could not be loaded.",
};
pub const FILE_LOADING: Text = Text {
de: "Datei wird geladen …",
en: "Loading the file …",
};
pub const OVERVIEW_NOTE: Text = Text {
de: "Der Graph ist groß: jeder Kreis ist eine Gruppe eng verbundener Bausteine, jedes Sechseck die übrigen Bausteine eines Ordners. Ein Klick öffnet sie.",
en: "The graph is large: each circle is a group of closely connected code units, each hexagon a folder's other code units. Click one to open it.",
};
/// "Ausschnitt: die ersten 10.000 von 23.456 Beziehungen".
pub fn truncated(shown: usize, total: u64, lang: Lang) -> String {
match lang {
Lang::De => format!(
"Ausschnitt: die ersten {} von {} Beziehungen",
format_count(shown as u64, lang),
format_count(total, lang)
),
Lang::En => format!(
"Excerpt: the first {} of {} relations",
format_count(shown as u64, lang),
format_count(total, lang)
),
}
}
/// "Die 1.200 meistverbundenen von 3.400 Bausteinen dieser Gruppe".
pub fn capped(shown: usize, total: usize, lang: Lang) -> String {
let (shown, total) = (
format_count(shown as u64, lang),
format_count(total as u64, lang),
);
match lang {
Lang::De => {
format!("Die {shown} meistverbundenen von {total} Bausteinen dieser Gruppe")
}
Lang::En => format!("The {shown} most connected of this group's {total} code units"),
}
}
/// A PLC PROGRAM, which the graph keeps as a module ("Modul" names a
/// bookable product, so it is not used for PLC code).
pub const PROGRAM: Text = Text {
de: "Programm",
en: "Program",
};
/// The languages a PLC project is parsed as; their modules are programs.
pub const PLC_LANGUAGES: [&str; 2] = ["structured_text", "plcopen"];
/// A node's kind name, given its language: a PLC PROGRAM is a "Programm".
pub fn node_kind(kind: &str, language: &str) -> Text {
if kind == "module" && PLC_LANGUAGES.contains(&language) {
PROGRAM
} else {
self::kind(kind)
}
}
/// A node kind's name, for the legend, the tooltip and the inspector.
pub fn kind(kind: &str) -> Text {
match kind {
"function" => Text {
de: "Funktion",
en: "Function",
},
"method" => Text {
de: "Methode",
en: "Method",
},
"class" => Text {
de: "Klasse",
en: "Class",
},
"struct" => Text {
de: "Struktur",
en: "Struct",
},
"enum" => Text {
de: "Aufzählung",
en: "Enum",
},
"interface" => Text {
de: "Schnittstelle",
en: "Interface",
},
"trait" => Text {
de: "Trait",
en: "Trait",
},
"module" => Text {
de: "Modul",
en: "Module",
},
"file" => Text {
de: "Datei",
en: "File",
},
"community" => Text {
de: "Gruppe",
en: "Group",
},
"folder" => Text {
de: "Ordner",
en: "Folder",
},
_ => Text {
de: "Baustein",
en: "Code unit",
},
}
}
/// An edge kind's name, for the tooltip.
pub fn edge_kind(kind: &str) -> Text {
match kind {
"calls" => Text {
de: "ruft auf",
en: "calls",
},
"imports" => Text {
de: "importiert",
en: "imports",
},
"inherits" => Text {
de: "erbt von",
en: "inherits from",
},
"implements" => Text {
de: "implementiert",
en: "implements",
},
"contains" => Text {
de: "enthält",
en: "contains",
},
"type_ref" => Text {
de: "verwendet Typ",
en: "uses type",
},
_ => Text {
de: "Beziehungen",
en: "relations",
},
}
}
// ── Impact of one finding ──
pub const IMPACT_TITLE: Text = Text {
de: "Auswirkung im Codegraph",
en: "Impact in the code graph",
};
pub const IMPACT_SUBTITLE: Text = Text {
de: "Welche Einstiegspunkte die Stelle des Befunds erreichen und was von ihr aus erreichbar ist.",
en: "Which entry points reach the finding's location and what it reaches in turn.",
};
pub const IMPACT_NONE: Text = Text {
de: "Für diesen Befund gibt es im Codegraph keine Stelle.",
en: "The code graph has no location for this finding.",
};
pub const IMPACT_LOADING: Text = Text {
de: "Auswirkung wird geladen …",
en: "Loading the impact …",
};
pub const REACHED_BY: Text = Text {
de: "Einstiegspunkte erreichen die Stelle",
en: "entry points reach the location",
};
pub const BLAST_RADIUS: Text = Text {
de: "Bausteine von der Stelle aus erreichbar",
en: "code units reachable from the location",
};
pub const ENTRY_POINTS: Text = Text {
de: "Einstiegspunkte",
en: "Entry points",
};
pub const CALL_CHAINS: Text = Text {
de: "Aufrufketten",
en: "Call chains",
};
pub const CALL_CHAINS_HINT: Text = Text {
de: "Vom Einstiegspunkt bis zur Stelle des Befunds.",
en: "From the entry point to the finding's location.",
};
pub const CALLERS: Text = Text {
de: "Direkte Aufrufer",
en: "Direct callers",
};
pub const CALLEES: Text = Text {
de: "Direkt aufgerufen",
en: "Directly called",
};
pub const NONE: Text = Text {
de: "Keine.",
en: "None.",
};
pub const SHOW_IMPACT: Text = Text {
de: "Auswirkung anzeigen",
en: "Show the impact",
};
pub const OPEN_GRAPH: Text = Text {
de: "Im Codegraph öffnen",
en: "Open in the code graph",
};
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_plc_program_is_named_a_program_not_a_module() {
assert_eq!(node_kind("module", "structured_text").de, "Programm");
assert_eq!(node_kind("module", "plcopen").de, "Programm");
assert_eq!(node_kind("module", "python").de, "Modul");
assert_eq!(node_kind("class", "structured_text").de, "Klasse");
}
}
}
@@ -11,6 +11,16 @@ pub struct GraphData {
pub build: Option<serde_json::Value>,
pub nodes: Vec<serde_json::Value>,
pub edges: Vec<serde_json::Value>,
/// The agent sent only the first of the graph's edges (and the nodes they
/// connect).
#[serde(default)]
pub truncated: bool,
/// Edges in the whole graph.
#[serde(default)]
pub total_edges: u64,
/// Nodes in the whole graph.
#[serde(default)]
pub total_nodes: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -18,12 +28,6 @@ pub struct ImpactResponse {
pub data: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CommunitiesResponse {
pub data: Vec<serde_json::Value>,
pub total: Option<u64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct NodesResponse {
pub data: Vec<serde_json::Value>,
@@ -48,6 +52,42 @@ 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, its languages and the
/// source files it could not read.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
pub struct GraphSummary {
pub units: u32,
pub entry_points: u32,
pub languages: Vec<String>,
/// Source files left out as not readable as text; 0 from an agent that
/// does not send the count yet.
#[serde(default)]
pub unreadable_files: u32,
}
/// 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}"))
@@ -80,32 +120,19 @@ pub async fn fetch_impact(
Ok(body)
}
#[server]
pub async fn fetch_communities(repo_id: String) -> Result<CommunitiesResponse, ServerFnError> {
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/communities"))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: CommunitiesResponse = resp
.json()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
Ok(body)
}
#[server]
pub async fn fetch_file_content(
repo_id: String,
file_path: String,
) -> Result<FileContentResponse, ServerFnError> {
let resp = super::agent_client::agent_get(&format!(
"/api/v1/graph/{repo_id}/file-content?path={file_path}"
))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
// The path as a query parameter, encoded: file names can hold spaces,
// `#` or `&`.
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/file-content"))
.await?
.query(&[("path", file_path.as_str())])
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: FileContentResponse = resp
.json()
.await
@@ -115,13 +142,12 @@ pub async fn fetch_file_content(
#[server]
pub async fn search_nodes(repo_id: String, query: String) -> Result<SearchResponse, ServerFnError> {
let resp = super::agent_client::agent_get(&format!(
"/api/v1/graph/{repo_id}/search?q={query}&limit=50"
))
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let resp = super::agent_client::agent_get(&format!("/api/v1/graph/{repo_id}/search"))
.await?
.query(&[("q", query.as_str()), ("limit", "50")])
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
let body: SearchResponse = resp
.json()
.await
@@ -0,0 +1,51 @@
//! Server function for the usage view (t72): proxies the agent's
//! `/api/v1/metering/usage`.
use dioxus::prelude::*;
use serde::{Deserialize, Serialize};
/// The tenant's metering this month, as the agent reports it.
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Usage {
/// The calendar month in Europe/Berlin, `YYYY-MM`.
#[serde(default)]
pub month: String,
/// Counted Prüfungen charged to the quota.
#[serde(default)]
pub pruefungen: u32,
/// Prüftage booked.
#[serde(default)]
pub prueftage: u32,
/// Active targets that are extra now.
#[serde(default)]
pub extra_targets: u32,
/// Whether the plan could be read; without it the limits are unknown.
#[serde(default)]
pub plan_known: bool,
/// The plan's included targets; `None` is unlimited.
#[serde(default)]
pub included_targets: Option<u32>,
/// The monthly quota; `None` is unlimited.
#[serde(default)]
pub monthly_pruefungen: Option<u32>,
/// The customer's Prüftag cap; `None` is no cap.
#[serde(default)]
pub prueftag_cap: Option<u32>,
}
/// The agent's answer.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct UsageResponse {
pub data: Usage,
}
/// The tenant's Prüfungen, Prüftage and extra targets this month.
#[server]
pub async fn fetch_usage() -> Result<UsageResponse, ServerFnError> {
let resp = super::agent_client::agent_get("/api/v1/metering/usage")
.await?
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::json_or_error(resp).await
}
@@ -12,6 +12,7 @@ pub mod issues;
pub mod manual_findings;
pub mod mcp;
pub mod mcp_tokens;
pub mod metering;
pub mod notifications;
pub mod onboarding;
pub mod pentest;
@@ -113,11 +113,15 @@ pub async fn set_archive_password(
}
/// Whether any of `targets` (as the list endpoint returns them) has a scan
/// running, so a page showing them should keep refreshing.
/// running or waiting for a slot, so a page showing them should keep
/// refreshing.
pub fn any_scan_running(targets: &[serde_json::Value]) -> bool {
targets
.iter()
.any(|t| t["last_scan"]["status"].as_str() == Some("running"))
targets.iter().any(|t| {
matches!(
t["last_scan"]["status"].as_str(),
Some("running" | "queued")
)
})
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -545,6 +549,22 @@ pub async fn fetch_target(id: String) -> Result<TargetResponse, ServerFnError> {
super::agent_client::json_or_error(resp).await
}
/// Swap the extra target `id` with the included target `with` (t72):
/// `id` becomes included until the end of the month, `with` extra.
#[server]
pub async fn swap_target_billing(id: String, with: String) -> Result<(), ServerFnError> {
let resp = super::agent_client::agent_request(
reqwest::Method::POST,
&format!("/api/v1/targets/{id}/billing/swap"),
)
.await?
.json(&serde_json::json!({ "with": with }))
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
super::agent_client::ok_or_error(resp).await
}
/// Run kind-based classification on a target.
#[server]
pub async fn detect_target(id: String) -> Result<TargetResponse, ServerFnError> {
@@ -697,8 +717,10 @@ mod tests {
let idle = serde_json::json!({ "last_scan": { "status": "completed" } });
let fresh = serde_json::json!({ "last_scan": null });
let busy = serde_json::json!({ "last_scan": { "status": "running" } });
let queued = serde_json::json!({ "last_scan": { "status": "queued" } });
assert!(!any_scan_running(&[idle.clone(), fresh.clone()]));
assert!(any_scan_running(&[idle, fresh, busy]));
assert!(any_scan_running(&[idle.clone(), fresh, busy]));
assert!(any_scan_running(&[idle, queued]));
}
#[test]
@@ -7,11 +7,13 @@ use crate::components::code_snippet::CodeSnippet;
use crate::components::markdown::render_markdown;
use crate::components::page_header::PageHeader;
use crate::components::severity_badge::SeverityBadge;
use crate::i18n::texts::{common, findings as tx};
use crate::i18n::{format_time, use_lang};
use crate::i18n::texts::{common, findings as tx, graph as graph_tx};
use crate::i18n::{format_count, format_time, use_lang};
use crate::infrastructure::evidence::{fetch_catalog_controls, CatalogControl};
use crate::infrastructure::findings::{location, mask_secrets, wire_name};
use crate::infrastructure::graph::fetch_impact;
use crate::pages::findings::status_icon;
use crate::pages::graph_view::impact_has_content;
use compliance_core::models::{FindingStatus, ScanType};
/// What happened to the last save on this page, shown next to what was saved.
@@ -57,6 +59,24 @@ pub fn FindingDetailPage(id: String) -> Element {
.ok()
});
// The finding's place in the code graph, when the graph has its location.
// Impact analyses are stored under the finding's fingerprint.
let impact = use_resource(move || async move {
let (repo_id, fingerprint) = finding
.read()
.as_ref()
.and_then(|f| f.as_ref())
.map(|f| (f.repo_id.clone(), f.fingerprint.clone()))?;
let data = fetch_impact(repo_id, fingerprint.clone())
.await
.ok()?
.data?;
impact_has_content(&data).then(|| {
let reached_by = data["affected_entry_points"].as_array().map_or(0, Vec::len);
(fingerprint, reached_by as u64)
})
});
let snapshot = finding.read().clone();
match snapshot {
@@ -194,6 +214,21 @@ pub fn FindingDetailPage(id: String) -> Element {
}
}
if let Some((fingerprint, reached_by)) = impact.read().clone().flatten() {
div { class: "card",
div { class: "target-card-head",
div { class: "card-header", {graph_tx::TITLE.get(lang)} }
Link {
to: Route::ImpactAnalysisPage { repo_id: f.repo_id.clone(), finding_id: fingerprint },
class: "target-card-link",
{graph_tx::SHOW_IMPACT.get(lang)}
Icon { icon: BsArrowRight, width: 14, height: 14 }
}
}
p { "{format_count(reached_by, lang)} {graph_tx::REACHED_BY.get(lang)}" }
}
}
if let Some(rationale) = &f.triage_rationale {
div { class: "card",
div { class: "card-header", {tx::TRIAGE.get(lang)} }
+391 -344
View File
@@ -1,253 +1,350 @@
//! One target's code graph, drawn: its files, its code units and how they
//! call and use each other. Opened from the code graph card on the target
//! page. A large graph opens as its groups (see [`super::graph_view`]).
use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;
use serde_json::{json, Value};
use super::graph_view::{draw, node_id, GraphView, Group, Grouping};
use crate::app::Route;
use crate::components::code_inspector::CodeInspector;
use crate::components::file_tree::{build_file_tree, FileTree};
use crate::components::page_header::PageHeader;
use crate::components::toast::{ToastType, Toasts};
use crate::infrastructure::graph::{fetch_graph, search_nodes, trigger_graph_build};
use crate::i18n::texts::{compliance::language_name, graph as tx};
use crate::i18n::{format_count, use_lang, Lang};
use crate::infrastructure::graph::{fetch_graph, search_nodes, trigger_graph_build, GraphData};
use crate::infrastructure::onboarding::fetch_target;
/// The node kinds in the legend, in the order shown.
const LEGEND_KINDS: [&str; 6] = ["function", "class", "interface", "enum", "module", "file"];
/// What stands for a group in the legend, outside the whole view.
const LEGEND_GROUPS: [&str; 2] = ["community", "folder"];
/// The texts `graph-viz.js` shows, in `lang`.
fn viz_labels(lang: Lang) -> Value {
let kinds: serde_json::Map<String, Value> = [
"function",
"method",
"class",
"struct",
"enum",
"interface",
"trait",
"module",
"file",
"community",
"folder",
]
.into_iter()
.map(|k| (k.to_string(), tx::kind(k).get(lang).into()))
.collect();
let edges: serde_json::Map<String, Value> = [
"calls",
"imports",
"inherits",
"implements",
"contains",
"type_ref",
]
.into_iter()
.map(|k| (k.to_string(), tx::edge_kind(k).get(lang).into()))
.collect();
json!({
"kinds": kinds,
"program": tx::PROGRAM.get(lang),
"plc": tx::PLC_LANGUAGES,
"edges": edges,
"layout": tx::LAYOUT.get(lang),
"entry": tx::ENTRY_POINT.get(lang),
"file": tx::FILE.get(lang),
})
}
/// What the page's header and notes say about the loaded graph.
#[derive(Debug, Clone, PartialEq)]
struct GraphFacts {
/// Nodes the agent sent, so the ones that can be drawn.
drawable: usize,
/// Code units, relations and groups in the whole graph.
units: u64,
relations: u64,
groups: u64,
/// The languages parsed, by name.
languages: Vec<String>,
/// Whether the graph has PLC code, and code in other languages: which
/// names its modules get in the legend.
has_plc: bool,
has_other: bool,
/// `(edges sent, edges in the graph)` when the agent sent only part.
truncated: Option<(usize, u64)>,
}
impl GraphFacts {
fn of(data: &GraphData) -> Self {
let build = data.build.as_ref();
let count = |key: &str| build.and_then(|b| b[key].as_u64()).unwrap_or(0);
let codes: Vec<&str> = build
.and_then(|b| b["languages_parsed"].as_array())
.map(|codes| codes.iter().filter_map(Value::as_str).collect())
.unwrap_or_default();
let is_plc = |code: &&str| tx::PLC_LANGUAGES.contains(code);
Self {
drawable: data.nodes.len(),
units: data.total_nodes.max(count("node_count")),
relations: data.total_edges.max(count("edge_count")),
groups: count("community_count"),
languages: codes
.iter()
.map(|code| language_name(code).to_string())
.collect(),
has_plc: codes.iter().any(is_plc),
has_other: !codes.iter().all(is_plc),
truncated: data
.truncated
.then_some((data.edges.len(), data.total_edges)),
}
}
}
#[component]
pub fn GraphExplorerPage(repo_id: String) -> Element {
rsx! {
div { class: "back-nav",
button {
class: "btn btn-ghost btn-back",
onclick: move |_| { navigator().go_back(); },
Icon { icon: BsArrowLeft, width: 16, height: 16 }
"Back"
}
}
PageHeader {
title: "Code Knowledge Graph",
description: "Interactive visualization of code structure and relationships",
}
GraphExplorerBody { repo_id: repo_id }
}
}
/// Inline variant without back button and page header — for embedding in other pages.
#[component]
pub fn GraphExplorerInline(repo_id: String) -> Element {
rsx! {
GraphExplorerBody { repo_id: repo_id }
}
}
/// Shared graph explorer body used by both the full page and inline variants.
#[component]
fn GraphExplorerBody(repo_id: String) -> Element {
let lang = use_lang()();
let can_write = crate::components::no_access::use_can_write();
let repo_id_clone = repo_id.clone();
let mut graph_data = use_resource(move || {
let rid = repo_id_clone.clone();
async move {
if rid.is_empty() {
return None;
}
fetch_graph(rid).await.ok()
}
let mut toasts = use_context::<Toasts>();
let rid = repo_id.clone();
let target = use_resource(move || {
let rid = rid.clone();
async move { fetch_target(rid).await.ok() }
});
let rid = repo_id.clone();
let mut graph = use_resource(move || {
let rid = rid.clone();
async move { fetch_graph(rid).await.ok() }
});
// The view chosen by a click; `None` is the one the graph opens with.
let mut view = use_signal(|| Option::<GraphView>::None);
// Nodes to select once the next drawing has its layout.
let mut pending_focus = use_signal(Vec::<String>::new);
let mut building = use_signal(|| false);
let mut toasts = use_context::<Toasts>();
let mut selected_node = use_signal(|| Option::<serde_json::Value>::None);
let mut inspector_open = use_signal(|| false);
let mut selected = use_signal(|| Option::<Value>::None);
let mut search_query = use_signal(String::new);
let mut search_results = use_signal(Vec::<serde_json::Value>::new);
let mut search_results = use_signal(Vec::<Value>::new);
let mut file_filter = use_signal(String::new);
let mut nodes_json = use_signal(String::new);
let mut edges_json = use_signal(String::new);
let mut graph_ready = use_signal(|| false);
let graph_data_read = graph_data.read();
if let Some(Some(data)) = &*graph_data_read {
if !data.data.nodes.is_empty() && !graph_ready() {
let nj = serde_json::to_string(&data.data.nodes).unwrap_or_else(|_| "[]".into());
let ej = serde_json::to_string(&data.data.edges).unwrap_or_else(|_| "[]".into());
nodes_json.set(nj);
edges_json.set(ej);
graph_ready.set(true);
}
}
let (node_count, edge_count, community_count, languages, file_tree_data) =
if let Some(Some(data)) = &*graph_data_read {
let build = data.data.build.clone().unwrap_or_default();
let nc = build
.get("node_count")
.and_then(|n| n.as_u64())
.unwrap_or(0);
let ec = build
.get("edge_count")
.and_then(|n| n.as_u64())
.unwrap_or(0);
let cc = build
.get("community_count")
.and_then(|n| n.as_u64())
.unwrap_or(0);
let langs: Vec<String> = build
.get("languages_parsed")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default();
let tree = build_file_tree(&data.data.nodes);
(nc, ec, cc, langs, tree)
} else {
(0, 0, 0, Vec::new(), Vec::new())
};
let has_graph_data = matches!(&*graph_data_read, Some(Some(d)) if !d.data.nodes.is_empty());
drop(graph_data_read);
// Each node's group, the view drawn, and what is drawn: recomputed only
// when the graph or the chosen view changes.
let grouping = use_memo(move || {
let graph = graph.read();
Some(Grouping::new(&graph.as_ref()?.as_ref()?.data.nodes))
});
let shown_view = use_memo(move || {
let graph = graph.read();
let count = graph.as_ref()?.as_ref()?.data.nodes.len();
Some(view().unwrap_or_else(|| GraphView::initial(count)))
});
// The header's figures and the file tree, so a render (a keystroke in the
// search box) doesn't copy or walk the graph.
let facts = use_memo(move || Some(GraphFacts::of(&graph.read().as_ref()?.as_ref()?.data)));
let file_tree = use_memo(move || {
let graph = graph.read();
graph
.as_ref()
.and_then(|g| g.as_ref())
.map(|g| build_file_tree(&g.data.nodes))
.unwrap_or_default()
});
let drawn = use_memo(move || {
let graph = graph.read();
let d = &graph.as_ref()?.as_ref()?.data;
Some(draw(
&d.nodes,
&d.edges,
grouping.read().as_ref()?,
shown_view.read().as_ref()?,
))
});
use_effect(move || {
let ready = graph_ready();
if !ready {
let drawn = drawn.read();
let Some(drawn) = drawn.as_ref().filter(|d| !d.nodes.is_empty()) else {
return;
}
let nj = nodes_json();
let ej = edges_json();
if nj.is_empty() {
return;
}
spawn(async move {
let js = format!(
r#"
window.__onNodeClick = function(nodeJson) {{
var el = document.getElementById('graph-node-click-data');
if (el) {{
el.value = nodeJson;
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
}}
}};
setTimeout(function() {{
if (window.__loadGraph) {{
window.__loadGraph({nj}, {ej});
}}
}}, 300);
"#
);
let _ = document::eval(&js);
});
};
let nodes = serde_json::to_string(&drawn.nodes).unwrap_or_else(|_| "[]".into());
let edges = serde_json::to_string(&drawn.edges).unwrap_or_else(|_| "[]".into());
let focus = serde_json::to_string(&*pending_focus.peek()).unwrap_or_else(|_| "[]".into());
let labels = viz_labels(lang);
// The canvas is in the DOM once this render is committed; the timeout
// lets vis-network measure it.
let js = format!(
r#"
window.__onNodeClick = function (nodeJson) {{
var el = document.getElementById('graph-node-click-data');
if (el) {{
el.value = nodeJson;
el.dispatchEvent(new Event('input', {{ bubbles: true }}));
}}
}};
setTimeout(function () {{
if (window.__loadGraph) window.__loadGraph({nodes}, {edges}, {labels}, {focus});
}}, 50);
"#
);
let _ = document::eval(&js);
});
let sel = selected_node();
let sel_file = sel
// Show the nodes named `names`: open their group first when its members
// aren't drawn. The group is the first name's.
let mut reveal = move |names: Vec<String>| {
let Some(group) = names
.first()
.and_then(|first| grouping.read().as_ref()?.of(first).cloned())
else {
return;
};
if shown_view().is_some_and(|v| v.shows_members_of(&group)) {
let names = serde_json::to_string(&names).unwrap_or_else(|_| "[]".into());
let _ = document::eval(&format!(
"window.__highlightNodes && window.__highlightNodes({names});"
));
} else {
pending_focus.set(names);
view.set(Some(GraphView::Group(group)));
}
};
let target_name = target
.read()
.as_ref()
.and_then(|n| n.get("file_path").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
let sel_name = sel
.as_ref()
.and_then(|n| n.get("name").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
let sel_kind = sel
.as_ref()
.and_then(|n| n.get("kind").and_then(|v| v.as_str()))
.unwrap_or("")
.to_string();
let sel_start = sel
.as_ref()
.and_then(|n| n.get("start_line").and_then(|v| v.as_u64()))
.unwrap_or(0) as u32;
let sel_end = sel
.as_ref()
.and_then(|n| n.get("end_line").and_then(|v| v.as_u64()))
.unwrap_or(0) as u32;
.and_then(|t| t.as_ref()?.data["name"].as_str().map(String::from));
let Some(facts) = facts() else {
return rsx! {
GraphBack { repo_id: repo_id.clone() }
match graph.read().as_ref() {
Some(None) => rsx! { div { class: "card", p { {tx::LOAD_FAILED.get(lang)} } } },
_ => rsx! { div { class: "loading", {tx::LOADING.get(lang)} } },
}
};
};
let opens_as_overview = GraphView::initial(facts.drawable) == GraphView::Overview;
let current = shown_view().unwrap_or(GraphView::All);
let units = format_count(facts.units, lang);
let relations = format_count(facts.relations, lang);
let groups = format_count(facts.groups, lang);
let capped = drawn.read().as_ref().and_then(|d| d.capped);
// A module is a "Programm" in PLC code; a graph with both shows both.
let legend: Vec<(&str, &str)> = LEGEND_KINDS
.into_iter()
.flat_map(|kind| match kind {
"module" => [
facts.has_other.then(|| (kind, tx::kind(kind).get(lang))),
facts.has_plc.then(|| (kind, tx::PROGRAM.get(lang))),
],
_ => [Some((kind, tx::kind(kind).get(lang))), None],
})
.flatten()
.collect();
let sel = selected();
let layout_class = if sel.is_some() {
"graph-explorer-layout inspector-open"
} else {
"graph-explorer-layout"
};
rsx! {
if repo_id.is_empty() {
div { class: "card",
p { "Select a repository to view its code graph." }
GraphBack { repo_id: repo_id.clone() }
header { class: "target-head",
div { class: "target-head-text",
h2 { {tx::TITLE.get(lang)} }
p { class: "target-head-meta",
if let Some(name) = target_name {
span { "{name}" }
}
span { "{units} {tx::CODE_UNITS.get(lang)}" }
span { "{relations} {tx::EDGES.get(lang)}" }
span { "{groups} {tx::GROUPS.get(lang)}" }
if !facts.languages.is_empty() {
span { {facts.languages.join(", ")} }
}
}
}
} else {
// Toolbar
div { class: "graph-toolbar",
if can_write {
if can_write {
div { class: "target-head-actions",
button {
class: "btn btn-primary",
class: "btn btn-secondary",
disabled: building(),
onclick: {
let rid = repo_id.clone();
move |_| {
let rid = rid.clone();
building.set(true);
graph_ready.set(false);
nodes_json.set(String::new());
edges_json.set(String::new());
spawn(async move {
match trigger_graph_build(rid).await {
Ok(_) => toasts.push(ToastType::Success, "Graph build triggered"),
Ok(()) => toasts.push(ToastType::Success, tx::BUILD_STARTED.get(lang)),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
building.set(false);
graph_data.restart();
view.set(None);
graph.restart();
});
}
},
if building() { "Building..." } else { "Build Graph" }
Icon { icon: BsArrowRepeat, width: 14, height: 14 }
if building() { {tx::BUILDING.get(lang)} } else { {tx::REBUILD.get(lang)} }
}
}
}
}
if facts.drawable == 0 {
div { class: "card graph-empty-state",
h3 { {tx::EMPTY_TITLE.get(lang)} }
p { {tx::EMPTY_BODY.get(lang)} }
}
} else {
div { class: "graph-toolbar",
if opens_as_overview && current != GraphView::Overview {
button {
class: "btn btn-secondary btn-sm",
onclick: move |_| {
pending_focus.set(Vec::new());
view.set(Some(GraphView::Overview));
},
Icon { icon: BsArrowLeft, width: 14, height: 14 }
{tx::OVERVIEW.get(lang)}
}
}
div { class: "graph-search-bar",
input {
r#type: "text",
placeholder: "Search nodes...",
r#type: "search",
placeholder: tx::SEARCH.get(lang),
"aria-label": tx::SEARCH.get(lang),
value: "{search_query}",
oninput: {
let rid = repo_id.clone();
move |e: FormEvent| {
let val = e.value();
search_query.set(val.clone());
if val.len() >= 2 {
let rid = rid.clone();
spawn(async move {
if let Ok(resp) = search_nodes(rid, val).await {
let q = e.value();
search_query.set(q.clone());
if q.chars().count() < 2 {
search_results.set(Vec::new());
return;
}
let rid = rid.clone();
spawn(async move {
// A stale answer for an older query is dropped.
if let Ok(resp) = search_nodes(rid, q.clone()).await {
if search_query() == q {
search_results.set(resp.data);
}
});
} else {
search_results.set(Vec::new());
}
}
},
onkeypress: {
let rid = repo_id.clone();
move |e: KeyboardEvent| {
if e.key() == Key::Enter {
search_results.set(Vec::new());
let q = search_query();
let rid = rid.clone();
if !q.is_empty() {
spawn(async move {
match search_nodes(rid, q).await {
Ok(resp) => {
let names: Vec<String> = resp.data.iter()
.filter_map(|n| n.get("qualified_name").and_then(|v| v.as_str()).map(String::from))
.collect();
let names_json = serde_json::to_string(&names).unwrap_or_else(|_| "[]".into());
let js = format!("if (window.__highlightNodes) {{ window.__highlightNodes({names_json}); }}");
let _ = document::eval(&js);
},
Err(e) => {
toasts.push(ToastType::Error, e.to_string());
}
}
});
} else {
spawn(async move {
let _ = document::eval("if (window.__clearGraphSelection) { window.__clearGraphSelection(); }");
});
}
}
});
}
},
}
@@ -255,29 +352,22 @@ fn GraphExplorerBody(repo_id: String) -> Element {
div { class: "search-suggestions",
for node in search_results() {
{
let name = node.get("name").and_then(|v| v.as_str()).unwrap_or("").to_string();
let kind = node.get("kind").and_then(|v| v.as_str()).unwrap_or("").to_string();
let file_path = node.get("file_path").and_then(|v| v.as_str()).unwrap_or("").to_string();
let node_clone = node.clone();
let qname = node.get("qualified_name").and_then(|v| v.as_str()).unwrap_or("").to_string();
let kind = node["kind"].as_str().unwrap_or_default().to_string();
let language = node["language"].as_str().unwrap_or_default().to_string();
let name = node["name"].as_str().unwrap_or_default().to_string();
let path = node["file_path"].as_str().unwrap_or_default().to_string();
rsx! {
div {
button {
class: "search-suggestion-item",
r#type: "button",
onclick: move |_| {
let nc = node_clone.clone();
let qn = qname.clone();
selected_node.set(Some(nc));
inspector_open.set(true);
reveal(vec![node_id(&node).to_string()]);
selected.set(Some(node.clone()));
search_results.set(Vec::new());
spawn(async move {
let names_json = serde_json::to_string(&vec![&qn]).unwrap_or_else(|_| "[]".into());
let js = format!("if (window.__highlightNodes) {{ window.__highlightNodes({names_json}); }}");
let _ = document::eval(&js);
});
},
span { class: "search-suggestion-name", "{name}" }
span { class: "search-suggestion-kind", "{kind}" }
span { class: "search-suggestion-path", "{file_path}" }
span { class: "search-suggestion-kind", {tx::node_kind(&kind, &language).get(lang)} }
span { class: "search-suggestion-path", "{path}" }
}
}
}
@@ -285,177 +375,134 @@ fn GraphExplorerBody(repo_id: String) -> Element {
}
}
}
button {
class: "btn-sm",
class: "btn btn-secondary btn-sm",
onclick: move |_| {
spawn(async move {
let _ = document::eval("if (window.__fitGraph) { window.__fitGraph(); }");
});
let _ = document::eval("window.__fitGraph && window.__fitGraph();");
},
"Fit View"
Icon { icon: BsArrowsFullscreen, width: 14, height: 14 }
{tx::FIT.get(lang)}
}
}
// Hidden input for JS → Rust node click communication
if current == GraphView::Overview {
p { class: "graph-note", {tx::OVERVIEW_NOTE.get(lang)} }
}
if let Some((shown, total)) = capped {
p { class: "graph-note", {tx::capped(shown, total, lang)} }
}
if let Some((shown, total)) = facts.truncated {
p { class: "graph-note", {tx::truncated(shown, total, lang)} }
}
// graph-viz.js reports a clicked node here.
input {
id: "graph-node-click-data",
r#type: "hidden",
value: "",
oninput: move |e| {
let val = e.value();
if !val.is_empty() {
if let Ok(node) = serde_json::from_str::<serde_json::Value>(&val) {
selected_node.set(Some(node));
inspector_open.set(true);
let Ok(node) = serde_json::from_str::<Value>(&e.value()) else { return };
// A group's node opens the group; any other node is shown
// in the inspector.
match serde_json::from_value::<Group>(node["group"].clone()) {
Ok(group) => {
pending_focus.set(Vec::new());
view.set(Some(GraphView::Group(group)));
}
Err(_) => selected.set(Some(node)),
}
},
}
// 3-panel layout: file-tree | [code-inspector] | graph-canvas
div { class: if inspector_open() { "graph-explorer-layout inspector-open" } else { "graph-explorer-layout" },
// Left: File Tree
div { class: layout_class,
div { class: "file-tree-panel",
div { class: "file-tree-header",
h4 { "Files" }
}
div { class: "file-tree-header", h4 { {tx::FILES.get(lang)} } }
div { class: "file-tree-search",
input {
r#type: "text",
placeholder: "Filter files...",
r#type: "search",
placeholder: tx::FILTER_FILES.get(lang),
"aria-label": tx::FILTER_FILES.get(lang),
value: "{file_filter}",
oninput: move |e| file_filter.set(e.value()),
}
}
div { class: "file-tree-content",
if file_tree_data.is_empty() {
div { class: "file-tree-empty", "No files. Build the graph first." }
} else {
FileTree {
tree: file_tree_data,
filter: file_filter(),
on_file_click: move |path: String| {
// Open code inspector for this file
let file_node = serde_json::json!({
"file_path": &path,
"name": path.rsplit('/').next().unwrap_or(&path),
"kind": "file",
"start_line": 1,
"end_line": 0,
});
selected_node.set(Some(file_node));
inspector_open.set(true);
// Also highlight in graph
spawn(async move {
let js = format!(
"if (window.__highlightFileNodes) {{ window.__highlightFileNodes('{path}'); }}"
);
let _ = document::eval(&js);
});
},
}
FileTree {
tree: file_tree(),
filter: file_filter(),
on_file_click: move |path: String| {
let in_file = graph
.read()
.as_ref()
.and_then(|g| g.as_ref())
.map(|g| {
g.data
.nodes
.iter()
.filter(|n| n["file_path"] == path.as_str())
.map(|n| node_id(n).to_string())
.collect()
})
.unwrap_or_default();
reveal(in_file);
selected.set(Some(json!({
"file_path": &path,
"name": path.rsplit('/').next().unwrap_or(&path),
"kind": "file",
})));
},
}
}
}
// Left-center: Code Inspector (between file tree and graph)
if inspector_open() && selected_node().is_some() {
if let Some(node) = sel {
CodeInspector {
repo_id: repo_id.clone(),
file_path: sel_file,
node_name: sel_name,
node_kind: sel_kind,
start_line: sel_start,
end_line: sel_end,
on_close: move |_| {
inspector_open.set(false);
selected_node.set(None);
},
file_path: node["file_path"].as_str().unwrap_or_default().to_string(),
node_name: node["name"].as_str().unwrap_or_default().to_string(),
node_kind: node["kind"].as_str().unwrap_or_default().to_string(),
node_language: node["language"].as_str().unwrap_or_default().to_string(),
start_line: node["start_line"].as_u64().unwrap_or(0) as u32,
end_line: node["end_line"].as_u64().unwrap_or(0) as u32,
on_close: move |_| selected.set(None),
}
}
// Right: Graph Canvas
div { class: "graph-canvas-panel",
if has_graph_data {
div {
id: "graph-canvas",
class: "graph-canvas",
}
// Stabilization overlay
div {
id: "graph-stabilization-overlay",
class: "graph-stab-overlay",
div { class: "graph-stab-content",
// Orbital rings
div { class: "graph-stab-rings",
div { class: "graph-stab-ring graph-stab-ring-1" }
div { class: "graph-stab-ring graph-stab-ring-2" }
div { class: "graph-stab-ring graph-stab-ring-3" }
div { class: "graph-stab-core" }
}
div { class: "graph-stab-text",
div { class: "graph-stab-title", "Rendering Graph" }
div { class: "graph-stab-subtitle",
id: "graph-stab-node-info",
"{node_count} nodes \u{00B7} {edge_count} edges"
}
}
// Progress bar
div { class: "graph-stab-progress",
div {
class: "graph-stab-progress-fill",
id: "graph-stab-progress-fill",
}
}
div {
class: "graph-stab-pct",
id: "graph-stab-pct",
"Initializing\u{2026}"
}
div { id: "graph-canvas", class: "graph-canvas" }
div { id: "graph-stabilization-overlay", class: "graph-stab-overlay",
div { class: "graph-stab-content",
div { class: "graph-stab-progress",
div { class: "graph-stab-progress-fill", id: "graph-stab-progress-fill" }
}
}
} else if node_count > 0 {
// Data exists but nodes array was empty (shouldn't happen)
div { class: "loading", "Loading graph visualization..." }
} else if (*graph_data.read()).is_none() {
div { class: "loading", "Loading graph data..." }
} else {
div { class: "graph-empty-state",
div { class: "graph-empty-icon", "\u{29BB}" }
h3 { "No Graph Data" }
p { "Click \"Build Graph\" to analyze the repository's code structure." }
div { class: "graph-stab-pct", id: "graph-stab-pct", {tx::LAYOUT.get(lang)} }
}
}
// Stats bar
if node_count > 0 {
div { class: "graph-stats-bar",
span { class: "graph-stat",
span { class: "graph-stat-value", "{node_count}" }
span { class: "graph-stat-label", " nodes" }
}
span { class: "graph-stat-divider", "|" }
span { class: "graph-stat",
span { class: "graph-stat-value", "{edge_count}" }
span { class: "graph-stat-label", " edges" }
}
span { class: "graph-stat-divider", "|" }
span { class: "graph-stat",
span { class: "graph-stat-value", "{community_count}" }
span { class: "graph-stat-label", " communities" }
}
if !languages.is_empty() {
span { class: "graph-stat-divider", "|" }
span { class: "graph-stat",
span { class: "graph-stat-label", "{languages.join(\", \")}" }
}
ul { class: "graph-legend",
for (kind, name) in legend {
li { span { class: "graph-legend-dot graph-kind-{kind}" } {name} }
}
li { span { class: "graph-legend-dot graph-legend-entry" } {tx::ENTRY_POINT.get(lang)} }
if current != GraphView::All {
for kind in LEGEND_GROUPS {
li { span { class: "graph-legend-dot graph-kind-{kind}" } {tx::kind(kind).get(lang)} }
}
}
}
}
}
}
}
}
/// Back to the target the graph belongs to.
#[component]
fn GraphBack(repo_id: String) -> Element {
let lang = use_lang()();
rsx! {
div { class: "back-nav",
Link { to: Route::TargetPage { id: repo_id }, class: "btn btn-ghost btn-back",
Icon { icon: BsArrowLeft, width: 16, height: 16 }
{tx::BACK.get(lang)}
}
}
}
@@ -1,94 +0,0 @@
use dioxus::prelude::*;
use crate::app::Route;
use crate::components::page_header::PageHeader;
use crate::infrastructure::onboarding::fetch_targets;
#[component]
pub fn GraphIndexPage() -> Element {
let repos = use_resource(|| async { fetch_targets().await.ok() });
rsx! {
PageHeader {
title: "Code Knowledge Graph",
description: "Select a repository to explore its code graph",
}
match &*repos.read() {
Some(Some(data)) => {
let repo_list = &data.data;
if repo_list.is_empty() {
rsx! {
div { class: "card",
p { "No repositories found. Add a repository first." }
}
}
} else {
rsx! {
div { class: "graph-index-grid",
for repo in repo_list {
{
let repo_id = repo.get("_id").and_then(|o| o.get("$oid")).and_then(|s| s.as_str()).unwrap_or_default().to_string();
let name = repo.get("name").and_then(|n| n.as_str()).unwrap_or_default().to_string();
let url = repo
.get("artifacts")
.and_then(|a| a.as_array())
.and_then(|arr| {
arr.iter().find(|a| {
a.get("kind").and_then(|k| k.as_str()) == Some("git_repo")
})
})
.and_then(|a| a.get("source_ref"))
.and_then(|s| s.as_str())
.unwrap_or_default()
.to_string();
let branch = repo
.get("artifacts")
.and_then(|a| a.as_array())
.and_then(|arr| {
arr.iter().find_map(|a| {
a.get("git")
.and_then(|g| g.get("default_branch"))
.and_then(|b| b.as_str())
})
})
.unwrap_or("main")
.to_string();
let findings = repo.get("findings_count").and_then(|n| n.as_u64()).unwrap_or(0);
let findings_label = if findings != 1 { format!("{findings} findings") } else { "1 finding".to_string() };
rsx! {
Link {
to: Route::GraphExplorerPage { repo_id },
class: "graph-repo-card",
div { class: "graph-repo-card-header",
div { class: "graph-repo-card-icon", "\u{29BB}" }
h3 { class: "graph-repo-card-name", "{name}" }
}
if !url.is_empty() {
p { class: "graph-repo-card-url", "{url}" }
}
div { class: "graph-repo-card-meta",
span { class: "graph-repo-card-tag",
"\u{E0A0} {branch}"
}
span { class: "graph-repo-card-tag graph-repo-card-tag-findings",
"{findings_label}"
}
}
}
}
}
}
}
}
}
},
Some(None) => rsx! {
div { class: "card", p { "Failed to load repositories." } }
},
None => rsx! {
div { class: "loading", "Loading repositories..." }
},
}
}
}
@@ -0,0 +1,479 @@
//! What the code graph explorer draws.
//!
//! A force-directed layout stays readable up to about a thousand nodes, and a
//! repository's graph can have tens of thousands. So a small graph is drawn
//! whole. A larger one is first drawn as one node per group, and a click opens
//! one group with its members, while its links to other groups stay visible as
//! those groups' nodes. A group is a community the graph build computed
//! (closely connected code units); communities too small to be worth a node
//! of their own are pooled by folder.
//!
//! The functions here are pure and run in the browser's WASM, not in
//! JavaScript; `graph-viz.js` only draws what they return.
use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
/// The most code units drawn at once.
pub const VIEW_NODE_LIMIT: usize = 1_200;
/// Communities with fewer members are pooled by folder: the build makes many
/// of two to ten (a file and its few functions), which would crowd the
/// overview. On this repository's agent (4,356 nodes) that is 839
/// communities, but about 150 groups.
pub const MIN_COMMUNITY: usize = 10;
/// A group of nodes drawn as one node until it is opened.
///
/// Serialized into the group's drawn node, so a click on it names the group.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(tag = "by", content = "key", rename_all = "snake_case")]
pub enum Group {
/// A community of the graph build.
Community(u32),
/// The nodes of one folder that are in no community of their own size.
Folder(String),
}
impl Group {
/// The group's node id in the drawing.
fn id(&self) -> String {
match self {
Self::Community(id) => format!("group:community:{id}"),
Self::Folder(dir) => format!("group:folder:{dir}"),
}
}
/// The kind its node is drawn as.
fn kind(&self) -> &'static str {
match self {
Self::Community(_) => "community",
Self::Folder(_) => "folder",
}
}
}
/// Which part of the graph is drawn.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum GraphView {
/// Every node: the graph is small enough.
All,
/// One node per group.
Overview,
/// One group's members and the groups linked to them.
Group(Group),
}
impl GraphView {
/// The view a graph with `node_count` nodes opens with.
pub fn initial(node_count: usize) -> Self {
if node_count <= VIEW_NODE_LIMIT {
Self::All
} else {
Self::Overview
}
}
/// Whether `group`'s members are drawn as themselves in this view.
pub fn shows_members_of(&self, group: &Group) -> bool {
match self {
Self::All => true,
Self::Overview => false,
Self::Group(shown) => shown == group,
}
}
}
/// The group of every node, by `qualified_name`.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Grouping(HashMap<String, Group>);
impl Grouping {
/// Groups `nodes`: by community when it has at least [`MIN_COMMUNITY`]
/// members, else by folder.
pub fn new(nodes: &[Value]) -> Self {
let mut sizes: HashMap<u32, usize> = HashMap::new();
for id in nodes.iter().filter_map(community) {
*sizes.entry(id).or_default() += 1;
}
Self(
nodes
.iter()
.map(|node| {
let group = match community(node) {
Some(id) if sizes[&id] >= MIN_COMMUNITY => Group::Community(id),
_ => Group::Folder(folder(node).to_string()),
};
(node_id(node).to_string(), group)
})
.collect(),
)
}
/// The group of the node named `id`, if the graph has it.
pub fn of(&self, id: &str) -> Option<&Group> {
self.0.get(id)
}
}
/// The nodes and edges to draw, in the JSON shape `graph-viz.js` reads.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Drawn {
pub nodes: Vec<Value>,
pub edges: Vec<Value>,
/// When the opened group has more members than [`VIEW_NODE_LIMIT`]:
/// `(shown, total)`.
pub capped: Option<(usize, usize)>,
}
/// A node's `qualified_name`, its id in the drawing.
pub fn node_id(node: &Value) -> &str {
node["qualified_name"].as_str().unwrap_or_default()
}
/// A node's community, if the build put it in one.
fn community(node: &Value) -> Option<u32> {
node["community_id"]
.as_u64()
.and_then(|id| u32::try_from(id).ok())
}
/// The folder of a node's file; empty at the repository's root.
fn folder(node: &Value) -> &str {
let path = node["file_path"].as_str().unwrap_or_default();
path.rsplit_once('/').map_or("", |(dir, _)| dir)
}
/// What to draw of `nodes` and `edges` in `view`, with `grouping` made from
/// the same nodes.
///
/// Linear in the number of nodes and edges. Edges that end in a group drawn
/// as one node become one edge per pair of ends, carrying how many it stands
/// for in `count`.
pub fn draw(nodes: &[Value], edges: &[Value], grouping: &Grouping, view: &GraphView) -> Drawn {
let opened = match view {
GraphView::All => {
return Drawn {
nodes: nodes.to_vec(),
edges: edges.to_vec(),
capped: None,
}
}
GraphView::Overview => None,
GraphView::Group(group) => Some(group),
};
// The opened group's members, the most connected first when there are
// more than the limit.
let mut members: Vec<&Value> = nodes
.iter()
.filter(|n| opened.is_some() && grouping.of(node_id(n)) == opened)
.collect();
let member_total = members.len();
if member_total > VIEW_NODE_LIMIT {
let mut degree: HashMap<&str, usize> = HashMap::with_capacity(member_total);
for end in edges.iter().flat_map(|e| [&e["source"], &e["target"]]) {
if let Some(id) = end.as_str() {
*degree.entry(id).or_default() += 1;
}
}
// Ties broken by name so the same graph always shows the same members.
members.sort_by(|a, b| {
let (da, db) = (degree.get(node_id(a)), degree.get(node_id(b)));
db.cmp(&da).then_with(|| node_id(a).cmp(node_id(b)))
});
members.truncate(VIEW_NODE_LIMIT);
}
let shown: HashSet<&str> = members.iter().map(|n| node_id(n)).collect();
// Where an edge end is drawn: the member itself, or its group's node.
// `None` drops the edge: a member left out by the cap, or a name the
// graph has no node for.
let endpoint = |id: &str| -> Option<String> {
let group = grouping.of(id)?;
if opened == Some(group) {
shown.contains(id).then(|| id.to_string())
} else {
Some(group.id())
}
};
let mut drawn_edges = Vec::new();
let mut bundled: HashMap<(String, String), usize> = HashMap::new();
for edge in edges {
let (Some(source), Some(target)) = (
edge["source"].as_str().and_then(endpoint),
edge["target"].as_str().and_then(endpoint),
) else {
continue;
};
let (source_shown, target_shown) = (
shown.contains(source.as_str()),
shown.contains(target.as_str()),
);
if source_shown && target_shown {
drawn_edges.push(edge.clone());
} else if source != target && (opened.is_none() || source_shown || target_shown) {
// With a group opened, only edges that touch one of its members.
*bundled.entry((source, target)).or_default() += 1;
}
}
// With a group opened, only the groups linked to it are drawn.
let linked: HashSet<&str> = bundled
.keys()
.flat_map(|(s, t)| [s.as_str(), t.as_str()])
.collect();
// Each other group with its size and the folder most of its members are
// in, as its label.
let mut stats: HashMap<&Group, (usize, HashMap<&str, usize>)> = HashMap::new();
for node in nodes {
let Some(group) = grouping.of(node_id(node)) else {
continue;
};
if opened == Some(group) {
continue;
}
let (size, folders) = stats.entry(group).or_default();
*size += 1;
*folders.entry(folder(node)).or_default() += 1;
}
let mut groups: Vec<(&Group, usize, &str)> = stats
.into_iter()
.map(|(group, (size, folders))| {
let label = match group {
Group::Folder(dir) => dir.as_str(),
// The most common folder, the first by name on a tie.
Group::Community(_) => folders
.into_iter()
.max_by(|(fa, ca), (fb, cb)| ca.cmp(cb).then_with(|| fb.cmp(fa)))
.map_or("", |(dir, _)| dir),
};
(group, size, label)
})
.filter(|(group, _, _)| opened.is_none() || linked.contains(group.id().as_str()))
.collect();
groups.sort_by(|a, b| a.0.cmp(b.0));
drawn_edges.extend(bundled.into_iter().map(|((source, target), count)| {
json!({ "source": source, "target": target, "kind": "bundle", "count": count })
}));
let mut drawn_nodes: Vec<Value> = members.into_iter().cloned().collect();
drawn_nodes.extend(groups.into_iter().map(|(group, size, label)| {
json!({
"qualified_name": group.id(),
"name": if label.is_empty() { "/" } else { label },
"kind": group.kind(),
"group": group,
"member_count": size,
"file_path": "",
})
}));
Drawn {
nodes: drawn_nodes,
edges: drawn_edges,
capped: (member_total > VIEW_NODE_LIMIT).then_some((VIEW_NODE_LIMIT, member_total)),
}
}
/// Whether a stored impact analysis has anything to show: the analysis is
/// stored for every finding with a file, also when the graph has no node at
/// the finding's location.
pub fn impact_has_content(impact: &Value) -> bool {
let non_empty = |key: &str| impact[key].as_array().is_some_and(|a| !a.is_empty());
impact["blast_radius"].as_u64().unwrap_or(0) > 0
|| [
"affected_entry_points",
"call_chains",
"direct_callers",
"direct_callees",
]
.into_iter()
.any(non_empty)
}
#[cfg(test)]
mod tests {
use super::*;
fn node(name: &str, community: Option<u32>, file: &str) -> Value {
json!({ "qualified_name": name, "name": name, "kind": "function",
"community_id": community, "file_path": file })
}
fn edge(source: &str, target: &str) -> Value {
json!({ "source": source, "target": target, "kind": "calls" })
}
fn ids(values: &[Value]) -> Vec<&str> {
values.iter().map(node_id).collect()
}
/// `(source, target, count)` of the bundled edges, sorted.
fn bundles(drawn: &Drawn) -> Vec<(String, String, u64)> {
let mut bundles: Vec<_> = drawn
.edges
.iter()
.filter(|e| e["kind"] == "bundle")
.map(|e| {
(
e["source"].as_str().unwrap().to_string(),
e["target"].as_str().unwrap().to_string(),
e["count"].as_u64().unwrap(),
)
})
.collect();
bundles.sort();
bundles
}
/// Community 0 with `MIN_COMMUNITY` members in src/net, community 1 with
/// two members in src/ui (pooled), and a node in no community at the root.
fn sample() -> (Vec<Value>, Vec<Value>) {
let mut nodes: Vec<Value> = (0..MIN_COMMUNITY)
.map(|i| node(&format!("a{i}"), Some(0), "src/net/a.c"))
.collect();
nodes.push(node("b0", Some(1), "src/ui/b.c"));
nodes.push(node("b1", Some(1), "src/ui/c.c"));
nodes.push(node("x", None, "main.c"));
let edges = vec![
edge("a0", "b0"),
edge("a1", "b0"),
edge("a0", "a1"),
edge("x", "a0"),
];
(nodes, edges)
}
#[test]
fn a_small_graph_opens_whole_and_a_large_one_as_the_overview() {
assert_eq!(GraphView::initial(VIEW_NODE_LIMIT), GraphView::All);
assert_eq!(GraphView::initial(VIEW_NODE_LIMIT + 1), GraphView::Overview);
}
#[test]
fn small_communities_and_nodes_in_none_are_pooled_by_folder() {
let (nodes, _) = sample();
let grouping = Grouping::new(&nodes);
assert_eq!(grouping.of("a0"), Some(&Group::Community(0)));
assert_eq!(grouping.of("b1"), Some(&Group::Folder("src/ui".into())));
assert_eq!(grouping.of("x"), Some(&Group::Folder(String::new())));
assert_eq!(grouping.of("missing"), None);
}
#[test]
fn the_overview_has_one_node_per_group_and_bundled_edges() {
let (nodes, edges) = sample();
let drawn = draw(&nodes, &edges, &Grouping::new(&nodes), &GraphView::Overview);
assert_eq!(
ids(&drawn.nodes),
["group:community:0", "group:folder:", "group:folder:src/ui"]
);
assert_eq!(drawn.nodes[0]["name"], "src/net");
assert_eq!(drawn.nodes[0]["member_count"], MIN_COMMUNITY);
assert_eq!(drawn.nodes[0]["kind"], "community");
// The root folder is named "/".
assert_eq!(drawn.nodes[1]["name"], "/");
assert_eq!(drawn.nodes[2]["kind"], "folder");
// A click on a group's node names the group.
let clicked: Group = serde_json::from_value(drawn.nodes[2]["group"].clone()).unwrap();
assert_eq!(clicked, Group::Folder("src/ui".into()));
// The edge inside community 0 is not drawn in the overview.
assert_eq!(
bundles(&drawn),
[
("group:community:0".into(), "group:folder:src/ui".into(), 2),
("group:folder:".into(), "group:community:0".into(), 1),
]
);
assert_eq!(drawn.capped, None);
}
#[test]
fn an_opened_group_shows_its_members_and_only_the_groups_linked_to_it() {
let (mut nodes, mut edges) = sample();
// Another community with no link to the folder src/ui.
nodes.extend((0..MIN_COMMUNITY).map(|i| node(&format!("c{i}"), Some(2), "lib/c.c")));
edges.push(edge("c0", "a0"));
let ui = Group::Folder("src/ui".into());
let drawn = draw(
&nodes,
&edges,
&Grouping::new(&nodes),
&GraphView::Group(ui),
);
assert_eq!(ids(&drawn.nodes), ["b0", "b1", "group:community:0"]);
assert_eq!(
bundles(&drawn),
[("group:community:0".into(), "b0".into(), 2)]
);
}
#[test]
fn edges_between_members_are_drawn_as_they_are() {
let (nodes, edges) = sample();
let drawn = draw(
&nodes,
&edges,
&Grouping::new(&nodes),
&GraphView::Group(Group::Community(0)),
);
assert!(drawn.edges.contains(&edges[2]));
assert_eq!(drawn.nodes.len(), MIN_COMMUNITY + 2);
}
#[test]
fn a_group_above_the_limit_keeps_its_most_connected_members() {
let mut nodes: Vec<Value> = (0..VIEW_NODE_LIMIT + 10)
.map(|i| node(&format!("n{i:05}"), Some(3), "src/big.c"))
.collect();
nodes.push(node("hub", Some(3), "src/big.c"));
let edges: Vec<Value> = (0..20).map(|i| edge("hub", &format!("n{i:05}"))).collect();
let drawn = draw(
&nodes,
&edges,
&Grouping::new(&nodes),
&GraphView::Group(Group::Community(3)),
);
assert_eq!(drawn.nodes.len(), VIEW_NODE_LIMIT);
assert_eq!(node_id(&drawn.nodes[0]), "hub");
assert_eq!(drawn.capped, Some((VIEW_NODE_LIMIT, VIEW_NODE_LIMIT + 11)));
// Only edges between drawn members remain.
assert!(drawn.edges.iter().all(|e| e["kind"] == "calls"));
}
#[test]
fn the_whole_view_draws_the_graph_as_it_is() {
let (nodes, edges) = sample();
let community = Group::Community(0);
let drawn = draw(&nodes, &edges, &Grouping::new(&nodes), &GraphView::All);
assert_eq!(drawn.nodes, nodes);
assert_eq!(drawn.edges, edges);
assert!(GraphView::All.shows_members_of(&community));
assert!(!GraphView::Overview.shows_members_of(&community));
assert!(GraphView::Group(community.clone()).shows_members_of(&community));
}
#[test]
fn an_impact_without_a_location_in_the_graph_has_nothing_to_show() {
let empty = json!({ "blast_radius": 0, "affected_entry_points": [],
"call_chains": [], "direct_callers": [], "direct_callees": [] });
assert!(!impact_has_content(&empty));
assert!(impact_has_content(&json!({ "blast_radius": 3 })));
assert!(impact_has_content(&json!({ "direct_callers": ["main"] })));
}
}
+121 -84
View File
@@ -1,107 +1,144 @@
//! One finding's place in the code graph: the entry points that reach it,
//! the call chains from them, and what it reaches in turn. Opened from the
//! finding's page when the graph has its location.
use dioxus::prelude::*;
use dioxus_free_icons::icons::bs_icons::*;
use dioxus_free_icons::Icon;
use serde_json::Value;
use crate::components::page_header::PageHeader;
use super::graph_view::impact_has_content;
use crate::app::Route;
use crate::i18n::texts::graph as tx;
use crate::i18n::{format_count, use_lang};
use crate::infrastructure::graph::fetch_impact;
/// `finding_id` is the finding's fingerprint, the key impact analyses are
/// stored under.
#[component]
pub fn ImpactAnalysisPage(repo_id: String, finding_id: String) -> Element {
let impact_data = use_resource(move || {
let rid = repo_id.clone();
let fid = finding_id.clone();
async move { fetch_impact(rid, fid).await.ok() }
let lang = use_lang()();
let rid = repo_id.clone();
let impact = use_resource(move || {
let (rid, fid) = (rid.clone(), finding_id.clone());
async move { fetch_impact(rid, fid).await.ok().map(|r| r.data) }
});
rsx! {
div { class: "back-nav",
button {
class: "btn btn-ghost btn-back",
onclick: move |_| { navigator().go_back(); },
Icon { icon: BsArrowLeft, width: 16, height: 16 }
"Back"
}
}
let names = |impact: &Value, key: &str| -> Vec<String> {
impact[key]
.as_array()
.map(|a| {
a.iter()
.filter_map(Value::as_str)
.map(String::from)
.collect()
})
.unwrap_or_default()
};
PageHeader {
title: "Impact Analysis",
description: "Blast radius and affected entry points for a security finding",
}
div { class: "card",
match &*impact_data.read() {
Some(Some(resp)) => {
let impact = resp.data.clone().unwrap_or_default();
rsx! {
div { class: "grid grid-cols-2 gap-4 mb-4",
div { class: "stat-card",
div { class: "stat-value",
"{impact.get(\"blast_radius\").and_then(|v| v.as_u64()).unwrap_or(0)}"
}
div { class: "stat-label", "Blast Radius (nodes affected)" }
let body = match impact.read().clone() {
None => rsx! { div { class: "loading", {tx::IMPACT_LOADING.get(lang)} } },
Some(Some(Some(data))) if impact_has_content(&data) => {
let entry_points = names(&data, "affected_entry_points");
let chains: Vec<Vec<String>> = data["call_chains"]
.as_array()
.map(|a| {
a.iter()
.filter_map(Value::as_array)
.map(|c| {
c.iter()
.filter_map(Value::as_str)
.map(String::from)
.collect()
})
.collect()
})
.unwrap_or_default();
let blast_radius = format_count(data["blast_radius"].as_u64().unwrap_or(0), lang);
let reached_by = format_count(entry_points.len() as u64, lang);
rsx! {
div { class: "target-summary impact-summary",
section { class: "card",
div { class: "target-figures",
div {
span { class: "target-figure", "{reached_by}" }
span { class: "target-figure-label", {tx::REACHED_BY.get(lang)} }
}
div { class: "stat-card",
div { class: "stat-value",
"{impact.get(\"affected_entry_points\").and_then(|v| v.as_array()).map(|a| a.len()).unwrap_or(0)}"
}
div { class: "stat-label", "Entry Points Affected" }
div {
span { class: "target-figure", "{blast_radius}" }
span { class: "target-figure-label", {tx::BLAST_RADIUS.get(lang)} }
}
}
h3 { "Affected Entry Points" }
if let Some(entries) = impact.get("affected_entry_points").and_then(|v| v.as_array()) {
if entries.is_empty() {
p { class: "text-muted", "No entry points affected." }
} else {
ul { class: "list",
for entry in entries {
li { "{entry.as_str().unwrap_or(\"-\")}" }
}
}
}
}
h3 { class: "mt-4", "Call Chains" }
if let Some(chains) = impact.get("call_chains").and_then(|v| v.as_array()) {
if chains.is_empty() {
p { class: "text-muted", "No call chains found." }
} else {
for (i, chain) in chains.iter().enumerate() {
div { class: "card mb-2",
strong { "Chain {i + 1}: " }
if let Some(steps) = chain.as_array() {
for (j, step) in steps.iter().enumerate() {
span { "{step.as_str().unwrap_or(\"-\")}" }
if j < steps.len() - 1 {
span { class: "text-muted", " → " }
}
}
}
}
section { class: "card",
div { class: "card-header", {tx::CALL_CHAINS.get(lang)} }
p { class: "graph-note", {tx::CALL_CHAINS_HINT.get(lang)} }
if chains.is_empty() {
p { class: "text-muted", {tx::NONE.get(lang)} }
} else {
ol { class: "impact-chains",
for chain in chains {
li {
for (i, step) in chain.iter().enumerate() {
if i > 0 {
span { class: "impact-chain-arrow", "aria-hidden": "true", "\u{2192}" }
}
}
}
}
}
h3 { class: "mt-4", "Direct Callers" }
if let Some(callers) = impact.get("direct_callers").and_then(|v| v.as_array()) {
if callers.is_empty() {
p { class: "text-muted", "No direct callers." }
} else {
ul { class: "list",
for caller in callers {
li { code { "{caller.as_str().unwrap_or(\"-\")}" } }
code { "{step}" }
}
}
}
}
}
},
Some(None) => rsx! {
p { "No impact analysis data available for this finding." }
},
None => rsx! {
p { "Loading impact analysis..." }
},
}
NameList { title: tx::ENTRY_POINTS.get(lang), names: entry_points }
NameList { title: tx::CALLERS.get(lang), names: names(&data, "direct_callers") }
NameList { title: tx::CALLEES.get(lang), names: names(&data, "direct_callees") }
}
}
Some(_) => rsx! { div { class: "card", p { {tx::IMPACT_NONE.get(lang)} } } },
};
rsx! {
div { class: "back-nav",
button {
class: "btn btn-ghost btn-back",
onclick: move |_| navigator().go_back(),
Icon { icon: BsArrowLeft, width: 16, height: 16 }
{tx::BACK.get(lang)}
}
}
header { class: "target-head",
div { class: "target-head-text",
h2 { {tx::IMPACT_TITLE.get(lang)} }
p { class: "target-head-meta", {tx::IMPACT_SUBTITLE.get(lang)} }
}
div { class: "target-head-actions",
Link { to: Route::GraphExplorerPage { repo_id }, class: "btn btn-secondary",
{tx::OPEN_GRAPH.get(lang)}
Icon { icon: BsArrowRight, width: 14, height: 14 }
}
}
}
{body}
}
}
/// A titled list of qualified names.
#[component]
fn NameList(title: &'static str, names: Vec<String>) -> Element {
let lang = use_lang()();
rsx! {
section { class: "card",
div { class: "card-header", "{title}" }
if names.is_empty() {
p { class: "text-muted", {tx::NONE.get(lang)} }
} else {
ul { class: "impact-names",
for name in names {
li { code { "{name}" } }
}
}
}
}
}
+1 -2
View File
@@ -8,7 +8,7 @@ pub mod dast_targets;
pub mod finding_detail;
pub mod findings;
pub mod graph_explorer;
pub mod graph_index;
pub(crate) mod graph_view;
pub mod impact_analysis;
pub mod issues;
pub mod mcp_servers;
@@ -31,7 +31,6 @@ pub use dast_targets::DastTargetsPage;
pub use finding_detail::FindingDetailPage;
pub use findings::FindingsPage;
pub use graph_explorer::GraphExplorerPage;
pub use graph_index::GraphIndexPage;
pub use impact_analysis::ImpactAnalysisPage;
pub use issues::IssuesPage;
pub use mcp_servers::McpServersPage;
+48 -1
View File
@@ -8,6 +8,7 @@ use dioxus_free_icons::Icon;
use crate::app::Route;
use crate::components::artifact_upload::ArtifactUpload;
use crate::components::billing_swap::BillingSwap;
use crate::components::cra_bar::CraBar;
use crate::components::evidence_button::EvidencePackButton;
use crate::components::layer_pins::LayerPinsCard;
@@ -20,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,
@@ -111,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);
@@ -154,6 +158,9 @@ pub fn TargetPage(id: String) -> Element {
.as_ref()
.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 {}
@@ -222,6 +229,16 @@ pub fn TargetPage(id: String) -> Element {
}
}
// An extra target can be swapped with an included one (t72).
if is_extra {
div { class: "card target-billing",
span { class: "badge badge-neutral", title: tx::EXTRA_HINT.get(lang), {tx::EXTRA.get(lang)} }
if can_write {
BillingSwap { target_id: id.clone(), on_swapped: move |_| target.restart() }
}
}
}
div { class: "target-summary",
section { class: "card target-cra",
div { class: "target-card-head",
@@ -254,6 +271,36 @@ 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)} }
Link { to: Route::GraphExplorerPage { repo_id: id.clone() }, class: "target-card-link",
{tx::GRAPH_SHOW.get(lang)}
Icon { icon: BsArrowRight, width: 14, height: 14 }
}
}
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(", ")}
}
if graph.unreadable_files > 0 {
p { class: "target-graph-unreadable",
{tx::unreadable_files(graph.unreadable_files, lang)}
}
}
p { class: "target-graph-note", {tx::GRAPH_NOTE.get(lang)} }
}
}
}
section { class: "card target-open",
@@ -15,6 +15,7 @@ use crate::components::pagination::Pagination;
use crate::components::projects::ProjectChips;
use crate::components::scan_runs::status_badge;
use crate::components::toast::{ToastType, Toasts};
use crate::components::usage_summary::UsageSummary;
use crate::i18n::texts::{common, kinds, scans as scan_texts, targets as tx};
use crate::i18n::{format_ago, use_lang, Lang};
use crate::infrastructure::auth_check::{go_to_login, is_session_expired};
@@ -132,6 +133,7 @@ pub fn TargetsPage() -> Element {
title: tx::TITLE.get(lang),
description: tx::SUBTITLE.get(lang),
}
UsageSummary {}
div { class: "page-actions",
if can_write {
+4
View File
@@ -13,6 +13,8 @@ chrono = { workspace = true }
tracing = { workspace = true }
tokio = { workspace = true }
mongodb = { workspace = true }
thiserror = { workspace = true }
# Tree-sitter parsing
tree-sitter = "0.24"
@@ -20,6 +22,8 @@ tree-sitter-rust = "0.23"
tree-sitter-python = "0.23"
tree-sitter-javascript = "0.23"
tree-sitter-typescript = "0.23"
tree-sitter-c = "0.23"
tree-sitter-c-sharp = "=0.23.1"
# Graph algorithms
petgraph = "0.7"
+2 -1
View File
@@ -29,7 +29,8 @@ pub fn extract_chunks(
for node in nodes {
let file = repo_path.join(&node.file_path);
let source = match std::fs::read_to_string(&file) {
// Decoded as the graph's parser read it, so every node has its lines.
let source = match compliance_core::encoding::read_source(&file) {
Ok(s) => s,
Err(_) => continue,
};
+128 -241
View File
@@ -1,257 +1,143 @@
use std::collections::HashMap;
use petgraph::graph::NodeIndex;
use petgraph::visit::EdgeRef;
use petgraph::Direction;
use tracing::info;
use super::engine::CodeGraph;
/// Louvain's local-move phase over the graph, read as undirected: each node
/// starts in its own community and moves to the neighbouring community with
/// the best modularity gain until no move helps (at most 50 passes).
///
/// The community degree totals are kept up to date on every move instead of
/// being summed again for every node, and a node's edges per neighbouring
/// community are counted in a scratch array, so one pass costs
/// O(nodes + edges). Communities are numbered 0.. in node order, so the
/// same graph always gets the same numbers.
///
/// # Returns
///
/// The community of every node, indexed by node index.
fn louvain(code_graph: &CodeGraph) -> Vec<u32> {
let graph = &code_graph.graph;
let node_count = graph.node_count();
let mut community: Vec<u32> = (0..node_count as u32).collect();
if graph.edge_count() == 0 {
return community;
}
let m2 = 2.0 * graph.edge_count() as f64;
// Neighbours in both directions, once, as plain indices.
let neighbours: Vec<Vec<usize>> = graph
.node_indices()
.map(|idx| {
graph
.edges_directed(idx, Direction::Outgoing)
.map(|e| e.target().index())
.chain(
graph
.edges_directed(idx, Direction::Incoming)
.map(|e| e.source().index()),
)
.collect()
})
.collect();
let degree: Vec<f64> = neighbours.iter().map(|n| n.len() as f64).collect();
let mut totals = degree.clone();
// Edges from the current node into each community; `touched` lists the
// communities set, so only those are reset.
let mut edges_to = vec![0.0_f64; node_count];
let mut touched: Vec<u32> = Vec::new();
for _ in 0..50 {
let mut improved = false;
for node in 0..node_count {
let current = community[node];
let node_degree = degree[node];
for &neighbour in &neighbours[node] {
let c = community[neighbour];
if edges_to[c as usize] == 0.0 {
touched.push(c);
}
edges_to[c as usize] += 1.0;
}
let remove_cost = edges_to[current as usize]
- (totals[current as usize] - node_degree) * node_degree / m2;
let mut best = current;
let mut best_gain = 0.0;
for &candidate in &touched {
if candidate == current {
continue;
}
let gain = edges_to[candidate as usize]
- totals[candidate as usize] * node_degree / m2
- remove_cost;
if gain > best_gain {
best_gain = gain;
best = candidate;
}
}
for &c in &touched {
edges_to[c as usize] = 0.0;
}
touched.clear();
if best != current {
totals[current as usize] -= node_degree;
totals[best as usize] += node_degree;
community[node] = best;
improved = true;
}
}
if !improved {
break;
}
}
// Renumber 0.. in order of first appearance.
let mut renumbered = vec![u32::MAX; node_count];
let mut next = 0;
for c in &mut community {
let slot = &mut renumbered[*c as usize];
if *slot == u32::MAX {
*slot = next;
next += 1;
}
*c = *slot;
}
community
}
/// The number of communities in a node assignment numbered 0...
fn count(communities: &[u32]) -> u32 {
communities.iter().max().map_or(0, |max| max + 1)
}
/// Run Louvain community detection on the code graph.
/// Returns the number of communities detected.
/// Mutates node community_id in place.
///
/// # Returns
///
/// The number of communities detected.
pub fn detect_communities(code_graph: &CodeGraph) -> u32 {
let graph = &code_graph.graph;
let node_count = graph.node_count();
if node_count == 0 {
return 0;
}
// Initialize: each node in its own community
let mut community: HashMap<NodeIndex, u32> = HashMap::new();
for idx in graph.node_indices() {
community.insert(idx, idx.index() as u32);
}
// Compute total edge weight (all edges weight 1.0)
let total_edges = graph.edge_count() as f64;
if total_edges == 0.0 {
// All nodes are isolated, each is its own community
return node_count as u32;
}
let m2 = 2.0 * total_edges;
// Pre-compute node degrees
let mut degree: HashMap<NodeIndex, f64> = HashMap::new();
for idx in graph.node_indices() {
let d = graph.edges(idx).count() as f64;
degree.insert(idx, d);
}
// Louvain phase 1: local moves
let mut improved = true;
let mut iterations = 0;
let max_iterations = 50;
while improved && iterations < max_iterations {
improved = false;
iterations += 1;
for node in graph.node_indices() {
let current_comm = community[&node];
let node_deg = degree[&node];
// Compute edges to each neighboring community
let mut comm_edges: HashMap<u32, f64> = HashMap::new();
for edge in graph.edges(node) {
let neighbor = edge.target();
let neighbor_comm = community[&neighbor];
*comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0;
}
// Also check incoming edges (undirected treatment)
for edge in graph.edges_directed(node, petgraph::Direction::Incoming) {
let neighbor = edge.source();
let neighbor_comm = community[&neighbor];
*comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0;
}
// Compute community totals (sum of degrees in each community)
let mut comm_totals: HashMap<u32, f64> = HashMap::new();
for (n, &c) in &community {
*comm_totals.entry(c).or_insert(0.0) += degree[n];
}
// Find best community
let current_total = comm_totals.get(&current_comm).copied().unwrap_or(0.0);
let edges_to_current = comm_edges.get(&current_comm).copied().unwrap_or(0.0);
// Modularity gain from removing node from current community
let remove_cost = edges_to_current - (current_total - node_deg) * node_deg / m2;
let mut best_comm = current_comm;
let mut best_gain = 0.0;
for (&candidate_comm, &edges_to_candidate) in &comm_edges {
if candidate_comm == current_comm {
continue;
}
let candidate_total = comm_totals.get(&candidate_comm).copied().unwrap_or(0.0);
// Modularity gain from adding node to candidate community
let add_gain = edges_to_candidate - candidate_total * node_deg / m2;
let gain = add_gain - remove_cost;
if gain > best_gain {
best_gain = gain;
best_comm = candidate_comm;
}
}
if best_comm != current_comm {
community.insert(node, best_comm);
improved = true;
}
}
}
// Renumber communities to be contiguous
let mut comm_remap: HashMap<u32, u32> = HashMap::new();
let mut next_id: u32 = 0;
for &c in community.values() {
if let std::collections::hash_map::Entry::Vacant(e) = comm_remap.entry(c) {
e.insert(next_id);
next_id += 1;
}
}
// Apply to community map
for c in community.values_mut() {
if let Some(&new_id) = comm_remap.get(c) {
*c = new_id;
}
}
let num_communities = next_id;
info!(
communities = num_communities,
iterations, "Community detection complete"
);
// NOTE: community IDs are stored in the HashMap but need to be applied
// back to the CodeGraph nodes by the caller (engine) if needed for persistence.
// For now we return the count; the full assignment is available via the map.
num_communities
count(&louvain(code_graph))
}
/// Apply community assignments back to code nodes
/// Detect communities and write each node's community into `community_id`.
///
/// # Returns
///
/// The number of communities detected.
pub fn apply_communities(code_graph: &mut CodeGraph) -> u32 {
detect_communities_with_assignment(code_graph)
}
/// Detect communities and write assignments into the nodes
fn detect_communities_with_assignment(code_graph: &mut CodeGraph) -> u32 {
let graph = &code_graph.graph;
let node_count = graph.node_count();
if node_count == 0 {
return 0;
}
let mut community: HashMap<NodeIndex, u32> = HashMap::new();
for idx in graph.node_indices() {
community.insert(idx, idx.index() as u32);
}
let total_edges = graph.edge_count() as f64;
if total_edges == 0.0 {
for node in &mut code_graph.nodes {
if let Some(gi) = node.graph_index {
node.community_id = Some(gi);
}
}
return node_count as u32;
}
let m2 = 2.0 * total_edges;
let mut degree: HashMap<NodeIndex, f64> = HashMap::new();
for idx in graph.node_indices() {
let d = (graph.edges(idx).count()
+ graph
.edges_directed(idx, petgraph::Direction::Incoming)
.count()) as f64;
degree.insert(idx, d);
}
let mut improved = true;
let mut iterations = 0;
let max_iterations = 50;
while improved && iterations < max_iterations {
improved = false;
iterations += 1;
for node in graph.node_indices() {
let current_comm = community[&node];
let node_deg = degree[&node];
let mut comm_edges: HashMap<u32, f64> = HashMap::new();
for edge in graph.edges(node) {
let neighbor_comm = community[&edge.target()];
*comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0;
}
for edge in graph.edges_directed(node, petgraph::Direction::Incoming) {
let neighbor_comm = community[&edge.source()];
*comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0;
}
let mut comm_totals: HashMap<u32, f64> = HashMap::new();
for (n, &c) in &community {
*comm_totals.entry(c).or_insert(0.0) += degree[n];
}
let current_total = comm_totals.get(&current_comm).copied().unwrap_or(0.0);
let edges_to_current = comm_edges.get(&current_comm).copied().unwrap_or(0.0);
let remove_cost = edges_to_current - (current_total - node_deg) * node_deg / m2;
let mut best_comm = current_comm;
let mut best_gain = 0.0;
for (&candidate_comm, &edges_to_candidate) in &comm_edges {
if candidate_comm == current_comm {
continue;
}
let candidate_total = comm_totals.get(&candidate_comm).copied().unwrap_or(0.0);
let add_gain = edges_to_candidate - candidate_total * node_deg / m2;
let gain = add_gain - remove_cost;
if gain > best_gain {
best_gain = gain;
best_comm = candidate_comm;
}
}
if best_comm != current_comm {
community.insert(node, best_comm);
improved = true;
}
}
}
// Renumber
let mut comm_remap: HashMap<u32, u32> = HashMap::new();
let mut next_id: u32 = 0;
for &c in community.values() {
if let std::collections::hash_map::Entry::Vacant(e) = comm_remap.entry(c) {
e.insert(next_id);
next_id += 1;
}
}
// Apply to nodes
let communities = louvain(code_graph);
for node in &mut code_graph.nodes {
if let Some(gi) = node.graph_index {
let idx = NodeIndex::new(gi as usize);
if let Some(&comm) = community.get(&idx) {
let remapped = comm_remap.get(&comm).copied().unwrap_or(comm);
node.community_id = Some(remapped);
}
if let Some(&community) = node.graph_index.and_then(|gi| communities.get(gi as usize)) {
node.community_id = Some(community);
}
}
next_id
let communities = count(&communities);
info!(communities, "Community detection complete");
communities
}
#[cfg(test)]
@@ -259,6 +145,7 @@ mod tests {
use super::*;
use compliance_core::models::graph::{CodeEdgeKind, CodeNode, CodeNodeKind};
use petgraph::graph::DiGraph;
use std::collections::HashMap;
fn make_node(qualified_name: &str, graph_index: u32) -> CodeNode {
CodeNode {
+367 -122
View File
@@ -4,7 +4,7 @@ use std::path::Path;
use chrono::Utc;
use compliance_core::error::CoreError;
use compliance_core::models::graph::{
CodeEdge, CodeEdgeKind, CodeNode, GraphBuildRun, GraphBuildStatus,
CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus,
};
use compliance_core::traits::graph_builder::ParseOutput;
use petgraph::graph::{DiGraph, NodeIndex};
@@ -12,7 +12,7 @@ use tracing::info;
use crate::parsers::registry::ParserRegistry;
use super::community::detect_communities;
use super::community::apply_communities;
use super::impact::ImpactAnalyzer;
/// Walk up the qualified-name hierarchy to find the closest ancestor
@@ -39,6 +39,141 @@ fn find_parent_qname(qname: &str, node_map: &HashMap<String, NodeIndex>) -> Opti
}
}
/// The last segment of a qualified name or edge target, after the last
/// `::` and then the last `.`: `src/a.py::Cls.run` and `self.run` both end
/// in `run`. Every name a target can match by suffix shares the target's
/// last segment, so it is the key the candidates are found by.
fn last_segment(name: &str) -> &str {
let after_path = name.rsplit("::").next().unwrap_or(name);
after_path.rsplit('.').next().unwrap_or(after_path)
}
/// One node an edge target may resolve to.
struct Candidate<'a> {
qualified: &'a str,
file_path: &'a str,
idx: NodeIndex,
}
/// Resolves edge targets to nodes. Candidates are found by the target's
/// last segment instead of scanning every node per edge, and when several
/// match, the one in the edge's own file wins (C's `static` functions,
/// same-named helpers), then the first by qualified name, so a rebuild
/// links the same way every time.
struct NameIndex<'a> {
exact: &'a HashMap<String, NodeIndex>,
by_last: HashMap<&'a str, Vec<Candidate<'a>>>,
/// File nodes by file name, for `#include "uart.h"` and other targets
/// that are paths.
files_by_name: HashMap<&'a str, Vec<Candidate<'a>>>,
}
impl<'a> NameIndex<'a> {
fn new(nodes: &'a [CodeNode], exact: &'a HashMap<String, NodeIndex>) -> Self {
let mut by_last: HashMap<&str, Vec<Candidate<'_>>> = HashMap::new();
let mut files_by_name: HashMap<&str, Vec<Candidate<'_>>> = HashMap::new();
for node in nodes {
let Some(&idx) = exact.get(&node.qualified_name) else {
continue;
};
let candidate = || Candidate {
qualified: &node.qualified_name,
file_path: &node.file_path,
idx,
};
by_last
.entry(last_segment(&node.qualified_name))
.or_default()
.push(candidate());
if matches!(node.kind, CodeNodeKind::File) {
let name = node.qualified_name.rsplit('/').next().unwrap_or_default();
files_by_name.entry(name).or_default().push(candidate());
}
}
for list in by_last.values_mut().chain(files_by_name.values_mut()) {
list.sort_unstable_by(|a, b| a.qualified.cmp(b.qualified));
}
Self {
exact,
by_last,
files_by_name,
}
}
/// The node `target` names, seen from an edge in `from_file`.
///
/// Resolution strategies (in order):
/// 1. Direct qualified-name match
/// 2. Suffix match: "foo" matches "src/main.rs::mod::foo" and "src/app.js.foo"
/// 3. Module-path match: "crate::config::load" matches "src/config.rs::load"
/// 4. Self-method: "self.method" matches "::method"
/// 5. File path: "uart.h" and "./lib/uart.h" match the file "src/lib/uart.h"
fn resolve(&self, target: &str, from_file: &str) -> Option<NodeIndex> {
if let Some(&idx) = self.exact.get(target) {
return Some(idx);
}
let candidates = self.by_last.get(last_segment(target));
// 2. Suffix match
let colon = format!("::{target}");
let dot = format!(".{target}");
if let Some(idx) = pick(candidates, from_file, |q| {
q.ends_with(&colon) || q.ends_with(&dot)
}) {
return Some(idx);
}
// 3. Module path: match progressively shorter suffixes of the path,
// without Rust's relative prefixes.
if target.contains("::") {
let stripped = target
.strip_prefix("crate::")
.or_else(|| target.strip_prefix("super::"))
.or_else(|| target.strip_prefix("self::"))
.unwrap_or(target);
let segments: Vec<&str> = stripped.split("::").collect();
for start in 0..segments.len() {
let pattern = format!("::{}", segments[start..].join("::"));
if let Some(idx) = pick(candidates, from_file, |q| q.ends_with(&pattern)) {
return Some(idx);
}
}
}
// 4. Self-method
if let Some(method) = target.strip_prefix("self.") {
let pattern = format!("::{method}");
if let Some(idx) = pick(candidates, from_file, |q| q.ends_with(&pattern)) {
return Some(idx);
}
}
// 5. File path
let path = target.trim_start_matches("./");
let file_name = path.rsplit('/').next().unwrap_or(path);
let in_dir = format!("/{path}");
pick(self.files_by_name.get(file_name), from_file, |q| {
q == path || q.ends_with(&in_dir)
})
}
}
/// The first candidate that `matches`, preferring one in `from_file`.
fn pick(
candidates: Option<&Vec<Candidate<'_>>>,
from_file: &str,
matches: impl Fn(&str) -> bool,
) -> Option<NodeIndex> {
let mut first = None;
for candidate in candidates?.iter().filter(|c| matches(c.qualified)) {
if candidate.file_path == from_file {
return Some(candidate.idx);
}
first.get_or_insert(candidate.idx);
}
first
}
/// The main graph engine that builds and manages code knowledge graphs
pub struct GraphEngine {
parser_registry: ParserRegistry,
@@ -68,38 +203,56 @@ impl GraphEngine {
repo_id: &str,
graph_build_id: &str,
) -> Result<(CodeGraph, GraphBuildRun), CoreError> {
let mut build_run = GraphBuildRun::new(repo_id.to_string());
info!(repo_id, path = %repo_path.display(), "Starting graph build");
// Phase 1: Parse all files
let parse_output = self.parser_registry.parse_directory(
let parsed = self.parser_registry.parse_directory(
repo_path,
repo_id,
graph_build_id,
self.max_nodes,
)?;
let (code_graph, mut build_run) = self.assemble(parsed.output, repo_id)?;
build_run.unreadable_file_count = Some(parsed.unreadable_files);
Ok((code_graph, build_run))
}
// Phase 2: Build petgraph
let code_graph = self.build_petgraph(parse_output)?;
/// Build a code graph from nodes and edges parsed elsewhere, e.g. by a
/// parser outside this crate through [`crate::parsers::FileGraph`]: link
/// the edges, detect communities and count what was built.
///
/// # Arguments
///
/// * `parse_output` - every file's nodes and edges, kept within the
/// engine's node limit by the caller
/// * `repo_id` - the repository the build run belongs to
///
/// # Errors
///
/// Returns `CoreError::Graph` when the graph can't be assembled.
pub fn assemble(
&self,
parse_output: ParseOutput,
repo_id: &str,
) -> Result<(CodeGraph, GraphBuildRun), CoreError> {
let mut build_run = GraphBuildRun::new(repo_id.to_string());
let mut code_graph = self.build_petgraph(parse_output)?;
// Phase 3: Run community detection
let community_count = detect_communities(&code_graph);
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());
@@ -132,19 +285,15 @@ impl GraphEngine {
}
// Resolve and add explicit edges from parsers
let index = NameIndex::new(&nodes, &node_map);
let mut resolved_edges = Vec::new();
for mut edge in parse_output.edges {
let source_idx = node_map.get(&edge.source);
let resolved = self.resolve_edge_target(&edge.target, &node_map);
let resolved = index.resolve(&edge.target, &edge.file_path);
if let (Some(&src), Some(tgt)) = (source_idx, resolved) {
let resolved_name = node_map
.iter()
.find(|(_, &idx)| idx == tgt)
.map(|(name, _)| name.clone());
if let Some(name) = resolved_name {
edge.target = name;
}
// A node's weight is its qualified name.
edge.target = graph[tgt].clone();
graph.add_edge(src, tgt, edge.kind.clone());
resolved_edges.push(edge);
}
@@ -200,70 +349,6 @@ impl GraphEngine {
})
}
/// Try to resolve an edge target to a known node.
///
/// Resolution strategies (in order):
/// 1. Direct qualified-name match
/// 2. Suffix match: "foo" matches "src/main.rs::mod::foo"
/// 3. Module-path match: "config::load" matches "src/config.rs::load"
/// 4. Self-method: "self.method" matches "::method"
fn resolve_edge_target(
&self,
target: &str,
node_map: &HashMap<String, NodeIndex>,
) -> Option<NodeIndex> {
// 1. Direct match
if let Some(idx) = node_map.get(target) {
return Some(*idx);
}
// 2. Suffix match: "foo" → "path/file.rs::foo"
let suffix_pattern = format!("::{target}");
let dot_pattern = format!(".{target}");
for (qualified, idx) in node_map {
if qualified.ends_with(&suffix_pattern) || qualified.ends_with(&dot_pattern) {
return Some(*idx);
}
}
// 3. Module-path match: "config::load" → try matching the last N
// segments of the target against node qualified names.
// This handles cross-file calls like `crate::config::load` or
// `super::handlers::process` where the prefix differs.
if target.contains("::") {
// Strip common Rust path prefixes
let stripped = target
.strip_prefix("crate::")
.or_else(|| target.strip_prefix("super::"))
.or_else(|| target.strip_prefix("self::"))
.unwrap_or(target);
let segments: Vec<&str> = stripped.split("::").collect();
// Try matching progressively shorter suffixes
for start in 0..segments.len() {
let suffix = segments[start..].join("::");
let pattern = format!("::{suffix}");
for (qualified, idx) in node_map {
if qualified.ends_with(&pattern) {
return Some(*idx);
}
}
}
}
// 4. Self-method: "self.method" → "::method"
if let Some(method_name) = target.strip_prefix("self.") {
let pattern = format!("::{method_name}");
for (qualified, idx) in node_map {
if qualified.ends_with(&pattern) {
return Some(*idx);
}
}
}
None
}
/// Get the impact analyzer for a built graph
pub fn impact_analyzer(code_graph: &CodeGraph) -> ImpactAnalyzer<'_> {
ImpactAnalyzer::new(code_graph)
@@ -307,61 +392,62 @@ mod tests {
map
}
/// Resolve `target` from `src/main.rs` against nodes named `names`,
/// returning the qualified name it resolved to.
fn resolve(names: &[&str], target: &str) -> Option<String> {
resolve_from(names, target, "src/main.rs")
}
fn resolve_from(names: &[&str], target: &str, from_file: &str) -> Option<String> {
let nodes: Vec<CodeNode> = names.iter().map(|n| make_node(n)).collect();
let node_map = build_test_node_map(names);
NameIndex::new(&nodes, &node_map)
.resolve(target, from_file)
.map(|idx| names[idx.index()].to_string())
}
#[test]
fn test_resolve_edge_target_direct_match() {
let engine = GraphEngine::new(1000);
let node_map = build_test_node_map(&["src/main.rs::foo", "src/main.rs::bar"]);
let result = engine.resolve_edge_target("src/main.rs::foo", &node_map);
assert!(result.is_some());
assert_eq!(result.unwrap(), node_map["src/main.rs::foo"]);
let result = resolve(
&["src/main.rs::foo", "src/main.rs::bar"],
"src/main.rs::foo",
);
assert_eq!(result.as_deref(), Some("src/main.rs::foo"));
}
#[test]
fn test_resolve_edge_target_short_name_match() {
let engine = GraphEngine::new(1000);
let node_map = build_test_node_map(&["src/main.rs::foo", "src/main.rs::bar"]);
let result = engine.resolve_edge_target("foo", &node_map);
assert!(result.is_some());
assert_eq!(result.unwrap(), node_map["src/main.rs::foo"]);
let result = resolve(&["src/main.rs::foo", "src/main.rs::bar"], "foo");
assert_eq!(result.as_deref(), Some("src/main.rs::foo"));
}
#[test]
fn test_resolve_edge_target_method_match() {
let engine = GraphEngine::new(1000);
let node_map = build_test_node_map(&["src/main.rs::MyStruct::do_thing"]);
let result = engine.resolve_edge_target("do_thing", &node_map);
let result = resolve(&["src/main.rs::MyStruct::do_thing"], "do_thing");
assert!(result.is_some());
}
#[test]
fn test_resolve_edge_target_self_method() {
let engine = GraphEngine::new(1000);
let node_map = build_test_node_map(&["src/main.rs::MyStruct::process"]);
let result = engine.resolve_edge_target("self.process", &node_map);
let result = resolve(&["src/main.rs::MyStruct::process"], "self.process");
assert!(result.is_some());
}
#[test]
fn test_resolve_edge_target_no_match() {
let engine = GraphEngine::new(1000);
let node_map = build_test_node_map(&["src/main.rs::foo"]);
let result = engine.resolve_edge_target("nonexistent", &node_map);
let result = resolve(&["src/main.rs::foo"], "nonexistent");
assert!(result.is_none());
}
#[test]
fn test_resolve_edge_target_empty_map() {
let engine = GraphEngine::new(1000);
let node_map = HashMap::new();
let result = engine.resolve_edge_target("anything", &node_map);
let result = resolve(&[], "anything");
assert!(result.is_none());
}
#[test]
fn test_resolve_edge_target_dot_notation() {
let engine = GraphEngine::new(1000);
let node_map = build_test_node_map(&["src/app.js.handler"]);
let result = engine.resolve_edge_target("handler", &node_map);
let result = resolve(&["src/app.js.handler"], "handler");
assert!(result.is_some());
}
@@ -504,13 +590,127 @@ mod tests {
#[test]
fn test_cross_file_resolution_with_module_path() {
let engine = GraphEngine::new(1000);
let node_map = build_test_node_map(&["src/config.rs::load_config", "src/main.rs::main"]);
// "crate::config::load_config" should resolve to "src/config.rs::load_config"
let result = engine.resolve_edge_target("crate::config::load_config", &node_map);
let result = resolve(
&["src/config.rs::load_config", "src/main.rs::main"],
"crate::config::load_config",
);
assert!(result.is_some(), "cross-file crate:: path should resolve");
}
fn node_in(qualified_name: &str, file_path: &str, kind: CodeNodeKind) -> CodeNode {
CodeNode {
file_path: file_path.to_string(),
kind,
..make_node(qualified_name)
}
}
fn edge_in(source: &str, target: &str, file_path: &str, kind: CodeEdgeKind) -> CodeEdge {
CodeEdge {
id: None,
repo_id: "test".to_string(),
graph_build_id: "build1".to_string(),
source: source.to_string(),
target: target.to_string(),
kind,
file_path: file_path.to_string(),
line_number: Some(1),
}
}
#[test]
fn same_named_functions_resolve_within_the_calling_file() {
let engine = GraphEngine::new(1000);
let mut output = ParseOutput::default();
for (name, file) in [
("b.c::helper", "b.c"),
("a.c::helper", "a.c"),
("a.c::main", "a.c"),
("b.c::run", "b.c"),
] {
output
.nodes
.push(node_in(name, file, CodeNodeKind::Function));
}
output
.edges
.push(edge_in("a.c::main", "helper", "a.c", CodeEdgeKind::Calls));
output
.edges
.push(edge_in("b.c::run", "helper", "b.c", CodeEdgeKind::Calls));
let code_graph = engine.build_petgraph(output).unwrap();
let targets: Vec<(&str, &str)> = code_graph
.edges
.iter()
.filter(|e| matches!(e.kind, CodeEdgeKind::Calls))
.map(|e| (e.source.as_str(), e.target.as_str()))
.collect();
assert_eq!(
targets,
[("a.c::main", "a.c::helper"), ("b.c::run", "b.c::helper")]
);
}
#[test]
fn ambiguous_names_resolve_the_same_way_every_time() {
let names = ["src/z.rs::helper", "src/b.rs::helper", "src/m.rs::helper"];
for _ in 0..20 {
assert_eq!(
resolve_from(&names, "helper", "src/other.rs").as_deref(),
Some("src/b.rs::helper")
);
}
}
#[test]
fn includes_resolve_to_the_header_file() {
let engine = GraphEngine::new(1000);
let mut output = ParseOutput::default();
output
.nodes
.push(node_in("src/main.c", "src/main.c", CodeNodeKind::File));
output.nodes.push(node_in(
"src/lib/uart.h",
"src/lib/uart.h",
CodeNodeKind::File,
));
for target in [
"uart.h",
"lib/uart.h",
"./lib/uart.h",
"stdio.h",
"b/uart.h",
] {
output.edges.push(edge_in(
"src/main.c",
target,
"src/main.c",
CodeEdgeKind::Imports,
));
}
let code_graph = engine.build_petgraph(output).unwrap();
let imports: Vec<&str> = code_graph
.edges
.iter()
.filter(|e| matches!(e.kind, CodeEdgeKind::Imports))
.map(|e| e.target.as_str())
.collect();
assert_eq!(
imports,
["src/lib/uart.h", "src/lib/uart.h", "src/lib/uart.h"]
);
}
#[test]
fn last_segment_splits_paths_then_members() {
assert_eq!(last_segment("src/a.py::Cls.run"), "run");
assert_eq!(last_segment("self.run"), "run");
assert_eq!(last_segment("crate::config::load"), "load");
assert_eq!(last_segment("main"), "main");
}
#[test]
fn test_find_parent_qname() {
let node_map = build_test_node_map(&[
@@ -529,4 +729,49 @@ 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"]);
// Assembled from nodes parsed elsewhere: nothing was read here.
assert_eq!(run.unreadable_file_count, None);
}
#[test]
fn a_tree_build_records_its_unreadable_files() {
let tree = crate::test_tree::TempTree::in_every_encoding("engine");
let (_, run) = GraphEngine::new(1000)
.build_graph(tree.path(), "test", "build")
.expect("builds");
// Five readable files, the broken UTF-16 one and the binary not.
assert_eq!(run.file_count, Some(5));
assert_eq!(run.unreadable_file_count, Some(2));
}
}
+3
View File
@@ -4,6 +4,9 @@
pub mod graph;
pub mod parsers;
pub mod search;
#[cfg(test)]
#[allow(clippy::expect_used)]
mod test_tree;
pub use graph::engine::GraphEngine;
pub use parsers::registry::ParserRegistry;
+389
View File
@@ -0,0 +1,389 @@
//! C, as in embedded firmware: functions, structs, unions and enums, calls
//! and `#include`s. Interrupt handlers count as entry points, in the
//! spellings of the compilers our customers use: avr-gcc's `ISR(vector)`,
//! CodeVision's `interrupt [vector]`, SDCC's `__interrupt(n)`, IAR's
//! `__interrupt` and GCC's `__attribute__((interrupt))` / `((signal))`.
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
use tree_sitter::Node;
use super::common::{parse, text, walk, FileGraph};
/// avr-gcc's interrupt macros, which tree-sitter reads as a function whose
/// return type is the macro and whose name is the vector: `ISR(TIMER1_vect)`.
const ISR_MACROS: [&str; 3] = ["ISR", "SIGNAL", "INTERRUPT"];
/// Parses C sources and headers.
#[derive(Debug, Default)]
pub struct CParser;
impl CParser {
/// A C parser.
pub fn new() -> Self {
Self
}
/// Visit the declarations of a translation unit, including those inside
/// `#if`/`#ifdef` blocks, without descending into function bodies.
fn walk_declarations(root: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
walk(root, |node| match node.kind() {
"function_definition" => {
Self::function(node, source, graph);
false
}
"type_definition" => {
Self::typedef(node, source, graph);
false
}
"struct_specifier" | "union_specifier" | "enum_specifier" => {
Self::record(node, None, source, graph);
false
}
_ => true,
});
}
fn function(node: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
let Some(declarator) = node.child_by_field_name("declarator") else {
return;
};
let Some(name_node) = declarator_name(declarator) else {
return;
};
let raw_name = text(name_node, source);
let return_type = node
.child_by_field_name("type")
.map(|t| text(t, source))
.unwrap_or("");
// `ISR(TIMER1_vect)` is named after its vector.
let isr_macro = ISR_MACROS.contains(&return_type);
let name = if isr_macro {
format!("{return_type}({raw_name})")
} else {
raw_name.to_string()
};
let is_entry = name == "main" || isr_macro || is_interrupt_handler(node, name_node, source);
let qualified = graph.top_level(&name);
graph.node(
qualified.clone(),
&name,
CodeNodeKind::Function,
node,
is_entry,
);
if let Some(body) = node.child_by_field_name("body") {
Self::calls(body, &qualified, source, graph);
}
}
/// `typedef struct { … } name_t;` declares the struct under the typedef's
/// name when the struct itself has none.
fn typedef(node: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
let Some(ty) = node.child_by_field_name("type") else {
return;
};
if !matches!(
ty.kind(),
"struct_specifier" | "union_specifier" | "enum_specifier"
) {
return;
}
let alias = node
.child_by_field_name("declarator")
.filter(|d| d.kind() == "type_identifier")
.map(|d| text(d, source));
Self::record(ty, alias, source, graph);
}
/// A struct, union or enum with a body; a bare reference such as
/// `struct point p;` declares nothing.
fn record(node: Node<'_>, alias: Option<&str>, source: &str, graph: &mut FileGraph<'_>) {
if node.child_by_field_name("body").is_none() {
return;
}
let Some(name) = node
.child_by_field_name("name")
.map(|n| text(n, source))
.or(alias)
else {
return;
};
let kind = if node.kind() == "enum_specifier" {
CodeNodeKind::Enum
} else {
CodeNodeKind::Struct
};
let qualified = graph.top_level(name);
graph.node(qualified, name, kind, node, false);
}
/// Calls by name inside a function body. Calls through a function pointer
/// (`s->cb()`) are left out: their target can't be known from the source.
fn calls(body: Node<'_>, caller: &str, source: &str, graph: &mut FileGraph<'_>) {
walk(body, |node| {
if node.kind() == "call_expression" {
if let Some(callee) = node
.child_by_field_name("function")
.filter(|f| f.kind() == "identifier")
{
graph.edge(caller, text(callee, source), CodeEdgeKind::Calls, node);
}
}
true
});
}
fn includes(root: Node<'_>, source: &str, graph: &mut FileGraph<'_>) {
let file = graph.file_path().to_string();
walk(root, |node| {
if node.kind() == "preproc_include" {
if let Some(path) = node.child_by_field_name("path") {
let target = text(path, source).trim_matches(['"', '<', '>']);
graph.edge(&file, target, CodeEdgeKind::Imports, node);
}
return false;
}
// Includes sit at file level or inside preprocessor blocks.
node.kind() == "translation_unit" || node.kind().starts_with("preproc_")
});
}
}
/// The identifier a declarator names, through pointers, parentheses and
/// attributes: `*make(void)` names `make`.
fn declarator_name(declarator: Node<'_>) -> Option<Node<'_>> {
let mut current = declarator;
loop {
if current.kind() == "identifier" {
return Some(current);
}
current = current
.child_by_field_name("declarator")
.or_else(|| current.named_child(0))?;
}
}
/// Header tokens that mark an interrupt handler: IAR's and CodeVision's
/// `interrupt`, SDCC's `__interrupt(n)`, GCC's `__attribute__((interrupt))`
/// and avr-gcc's `__attribute__((signal))`.
const INTERRUPT_TOKENS: [&str; 5] = [
"interrupt",
"__interrupt",
"__interrupt__",
"signal",
"__signal__",
];
/// Whether the function header marks an interrupt handler. The header is
/// everything before the body except the name and the parameter list, so
/// neither `interrupt_flag_clear` nor a parameter named `signal` counts.
/// CodeVision's `interrupt [vector]` stands right before the function, and
/// tree-sitter reads it as a separate statement.
fn is_interrupt_handler(function: Node<'_>, name: Node<'_>, source: &str) -> bool {
let header_end = function
.child_by_field_name("body")
.map_or(function.end_byte(), |b| b.start_byte());
let after_name = parameter_list(function)
.map_or(name.end_byte(), |p| p.end_byte())
.min(header_end);
let header = [
&source[function.start_byte()..name.start_byte()],
&source[after_name..header_end],
];
let marked = header.iter().any(|part| {
part.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
.any(|token| INTERRUPT_TOKENS.contains(&token))
});
marked
|| function
.prev_named_sibling()
.filter(|prev| prev.kind() == "expression_statement")
.is_some_and(|prev| text(prev, source).trim_start().starts_with("interrupt"))
}
/// The parameter list of a function definition, found through the same
/// declarator chain as its name.
fn parameter_list(function: Node<'_>) -> Option<Node<'_>> {
let mut current = function.child_by_field_name("declarator")?;
loop {
if current.kind() == "function_declarator" {
return current.child_by_field_name("parameters");
}
current = current
.child_by_field_name("declarator")
.or_else(|| current.named_child(0))?;
}
}
impl LanguageParser for CParser {
fn language(&self) -> &str {
"c"
}
fn extensions(&self) -> &[&str] {
&["c", "h"]
}
fn parse_file(
&self,
file_path: &Path,
source: &str,
repo_id: &str,
graph_build_id: &str,
) -> Result<ParseOutput, CoreError> {
let tree = parse(tree_sitter_c::LANGUAGE.into(), source, "C")?;
let mut graph = FileGraph::new(
file_path,
source.lines().count() as u32,
repo_id,
graph_build_id,
"c",
);
Self::walk_declarations(tree.root_node(), source, &mut graph);
Self::includes(tree.root_node(), source, &mut graph);
Ok(graph.finish())
}
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::graph::CodeNode;
const FIRMWARE: &str = r#"
#include "uart.h"
#include <avr/io.h>
static int helper(int a) { return a + 1; }
int *make(void) { return 0; }
struct point { int x; int y; };
struct point origin;
typedef struct { int a; } cfg_t;
enum mode { A, B };
#ifdef DEBUG
void trace(void) { helper(0); }
#endif
interrupt [TIM0_OVF] void timer0_ovf_isr(void) { helper(2); }
void ext_isr(void) __interrupt(1) { helper(3); }
__attribute__((__interrupt__)) static void avr32_isr(void) { helper(4); }
ISR(TIMER1_vect) { helper(5); }
void interrupt_flag_clear(void) { }
void on_event(int signal) { }
interrupt_state_t save_state(void) { return 0; }
int main(void) { uart_init(); helper(1); s->cb(2); return 0; }
"#;
fn parsed() -> ParseOutput {
CParser::new()
.parse_file(Path::new("src/main.c"), FIRMWARE, "repo", "build")
.expect("C parses")
}
fn node<'a>(out: &'a ParseOutput, name: &str) -> &'a CodeNode {
out.nodes
.iter()
.find(|n| n.name == name)
.unwrap_or_else(|| panic!("no node {name}"))
}
#[test]
fn functions_records_and_the_file_become_nodes() {
let out = parsed();
assert!(matches!(node(&out, "main.c").kind, CodeNodeKind::File));
for function in ["helper", "make", "trace", "main"] {
assert!(matches!(node(&out, function).kind, CodeNodeKind::Function));
}
assert!(matches!(node(&out, "point").kind, CodeNodeKind::Struct));
assert!(matches!(node(&out, "cfg_t").kind, CodeNodeKind::Struct));
assert!(matches!(node(&out, "mode").kind, CodeNodeKind::Enum));
assert_eq!(node(&out, "helper").qualified_name, "src/main.c::helper");
assert_eq!(node(&out, "helper").start_line, 4);
// `struct point origin;` only uses the struct.
assert_eq!(out.nodes.iter().filter(|n| n.name == "point").count(), 1);
}
#[test]
fn main_and_every_interrupt_spelling_are_entry_points() {
let out = parsed();
for entry in [
"main",
"timer0_ovf_isr",
"ext_isr",
"avr32_isr",
"ISR(TIMER1_vect)",
] {
assert!(
node(&out, entry).is_entry_point,
"{entry} is an entry point"
);
}
for plain in [
"helper",
"make",
"trace",
"interrupt_flag_clear",
"on_event",
"save_state",
] {
assert!(!node(&out, plain).is_entry_point, "{plain} is not");
}
}
#[test]
fn calls_by_name_and_includes_become_edges() {
let out = parsed();
let calls: Vec<(&str, &str)> = out
.edges
.iter()
.filter(|e| matches!(e.kind, CodeEdgeKind::Calls))
.map(|e| (e.source.as_str(), e.target.as_str()))
.collect();
assert!(calls.contains(&("src/main.c::main", "uart_init")));
assert!(calls.contains(&("src/main.c::main", "helper")));
assert!(calls.contains(&("src/main.c::ISR(TIMER1_vect)", "helper")));
// A call through a function pointer has no target we can name.
assert!(!calls.iter().any(|(_, target)| target.contains("cb")));
let includes: Vec<&str> = out
.edges
.iter()
.filter(|e| matches!(e.kind, CodeEdgeKind::Imports))
.map(|e| e.target.as_str())
.collect();
assert_eq!(includes, ["uart.h", "avr/io.h"]);
}
#[test]
fn ifdef_alternatives_share_one_node() {
let source = "#ifdef FAST\nvoid init(void) { fast(); }\n#else\nvoid init(void) { slow(); }\n#endif\n";
let out = CParser::new()
.parse_file(Path::new("i.c"), source, "r", "b")
.expect("C parses");
assert_eq!(out.nodes.iter().filter(|n| n.name == "init").count(), 1);
let callees: Vec<&str> = out
.edges
.iter()
.filter(|e| matches!(e.kind, CodeEdgeKind::Calls))
.map(|e| e.target.as_str())
.collect();
assert_eq!(callees, ["fast", "slow"]);
}
#[test]
fn broken_code_still_yields_what_parses() {
let out = CParser::new()
.parse_file(
Path::new("bad.c"),
"void ok(void) {}\nint broken( {\n",
"r",
"b",
)
.expect("a syntax error is not a failure");
assert!(out.nodes.iter().any(|n| n.name == "ok"));
}
}
+208
View File
@@ -0,0 +1,208 @@
//! Shared building blocks for the tree-sitter parsers: parsing a file with a
//! grammar, collecting its nodes and edges, and walking a subtree without
//! recursion.
use std::collections::HashMap;
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::graph::{CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind};
use compliance_core::traits::graph_builder::ParseOutput;
use tree_sitter::{Language, Node, Parser, Tree};
/// Parse `source` with `language`.
///
/// # Errors
///
/// Returns `CoreError::Graph` when the grammar can't be loaded (an ABI the
/// tree-sitter core doesn't support) or the parser gives up.
pub(crate) fn parse(language: Language, source: &str, name: &str) -> Result<Tree, CoreError> {
let mut parser = Parser::new();
parser
.set_language(&language)
.map_err(|e| CoreError::Graph(format!("Failed to set {name} language: {e}")))?;
parser
.parse(source, None)
.ok_or_else(|| CoreError::Graph(format!("Failed to parse {name} file")))
}
/// The source text a syntax node covers.
pub(crate) fn text<'s>(node: Node<'_>, source: &'s str) -> &'s str {
&source[node.byte_range()]
}
/// The 1-based line a syntax node starts on.
pub(crate) fn line(node: Node<'_>) -> u32 {
node.start_position().row as u32 + 1
}
/// Call `visit` on `root` and every node below it, depth first, with a
/// cursor instead of recursion, so deeply nested generated code can't
/// overflow the stack. `visit` returns whether to descend into that node.
pub(crate) fn walk(root: Node<'_>, mut visit: impl FnMut(Node<'_>) -> bool) {
let mut cursor = root.walk();
loop {
if visit(cursor.node()) && cursor.goto_first_child() {
continue;
}
// No (wanted) children: move to the next sibling, climbing up until
// one exists or we are back at `root`.
loop {
if cursor.node() == root {
return;
}
if cursor.goto_next_sibling() {
break;
}
if !cursor.goto_parent() {
return;
}
}
}
}
/// The nodes and edges of one file, with the identifiers every one of them
/// carries filled in once. The tree-sitter parsers use it, and so can a
/// parser outside this crate (the agent's IEC 61131-3 one), which hands the
/// result to [`crate::GraphEngine::assemble`].
pub struct FileGraph<'a> {
repo_id: &'a str,
graph_build_id: &'a str,
file_path: String,
language: &'static str,
output: ParseOutput,
/// Qualified names already added: overloads (`Get(int)`, `Get(string)`)
/// and `#ifdef`/`#else` alternatives share one, and the graph keys nodes
/// by it.
seen: HashMap<String, usize>,
}
impl<'a> FileGraph<'a> {
/// Start a file's graph with its `File` node.
///
/// # Arguments
///
/// * `file_path` - the file's path relative to the scanned tree
/// * `line_count` - the file's number of lines, the `File` node's end line
/// * `repo_id`, `graph_build_id` - stamped on every node and edge
/// * `language` - the language name the nodes carry, e.g. `"c"`
pub fn new(
file_path: &Path,
line_count: u32,
repo_id: &'a str,
graph_build_id: &'a str,
language: &'static str,
) -> Self {
let file_path_str = file_path.to_string_lossy().into_owned();
let mut graph = Self {
repo_id,
graph_build_id,
file_path: file_path_str.clone(),
language,
output: ParseOutput::default(),
seen: HashMap::new(),
};
let name = file_path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
graph.node_at(
file_path_str,
name,
CodeNodeKind::File,
(1, line_count),
false,
);
graph
}
/// The file's path, which is also its `File` node's qualified name.
pub fn file_path(&self) -> &str {
&self.file_path
}
/// The qualified name of a top-level declaration named `name`.
pub fn top_level(&self, name: &str) -> String {
format!("{}::{name}", self.file_path)
}
/// Add a declaration spanning the syntax node `node`; see [`Self::node_at`].
pub(crate) fn node(
&mut self,
qualified_name: String,
name: &str,
kind: CodeNodeKind,
node: Node<'_>,
is_entry_point: bool,
) {
let end_line = node.end_position().row as u32 + 1;
self.node_at(
qualified_name,
name.to_string(),
kind,
(line(node), end_line),
is_entry_point,
);
}
/// Add a declaration spanning `lines` (1-based start and end, inclusive).
/// A second declaration under the same qualified name (an overload, an
/// `#else` alternative) adds no node; edges from its body still count,
/// from the first one's node, and an entry point makes it one.
pub fn node_at(
&mut self,
qualified_name: String,
name: String,
kind: CodeNodeKind,
(start_line, end_line): (u32, u32),
is_entry_point: bool,
) {
if let Some(&first) = self.seen.get(&qualified_name) {
self.output.nodes[first].is_entry_point |= is_entry_point;
return;
}
self.seen
.insert(qualified_name.clone(), self.output.nodes.len());
self.output.nodes.push(CodeNode {
id: None,
repo_id: self.repo_id.to_string(),
graph_build_id: self.graph_build_id.to_string(),
qualified_name,
name,
kind,
file_path: self.file_path.clone(),
start_line,
end_line,
language: self.language.to_string(),
community_id: None,
is_entry_point,
graph_index: None,
});
}
/// Add an edge found at the syntax node `at`; see [`Self::edge_at`].
pub(crate) fn edge(&mut self, source: &str, target: &str, kind: CodeEdgeKind, at: Node<'_>) {
self.edge_at(source, target, kind, line(at));
}
/// Add an edge from `source` to `target`, found on `line`. The engine
/// resolves `target` later, so a bare name is fine; one that matches no
/// node is dropped.
pub fn edge_at(&mut self, source: &str, target: &str, kind: CodeEdgeKind, line: u32) {
self.output.edges.push(CodeEdge {
id: None,
repo_id: self.repo_id.to_string(),
graph_build_id: self.graph_build_id.to_string(),
source: source.to_string(),
target: target.to_string(),
kind,
file_path: self.file_path.clone(),
line_number: Some(line),
});
}
/// The finished nodes and edges.
pub fn finish(self) -> ParseOutput {
self.output
}
}
+461
View File
@@ -0,0 +1,461 @@
//! C#: classes, structs, interfaces, records and enums, their methods and
//! constructors, base types, and calls. Entry points are `Main` and what a
//! web framework calls from outside: ASP.NET controller actions, Razor page
//! handlers, Web Forms pages and controls, ASMX web methods and HTTP
//! handlers.
//!
//! `using` directives are left out: the graph has no namespace nodes they
//! could point to.
use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind};
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
use tree_sitter::Node;
use super::common::{parse, text, walk, FileGraph};
/// Base types whose methods a web framework calls: MVC and API
/// controllers, Razor pages, SignalR hubs, Web Forms pages, controls and
/// master pages, and ASMX services.
const WEB_BASES: [&str; 9] = [
"Controller",
"ControllerBase",
"ApiController",
"PageModel",
"Hub",
"Page",
"UserControl",
"MasterPage",
"WebService",
];
/// Attributes that expose a method over HTTP.
const ENDPOINT_ATTRIBUTES: [&str; 10] = [
"HttpGet",
"HttpPost",
"HttpPut",
"HttpDelete",
"HttpPatch",
"HttpHead",
"HttpOptions",
"AcceptVerbs",
"Route",
"WebMethod",
];
/// Parses C# sources.
#[derive(Debug, Default)]
pub struct CSharpParser;
/// What a method's entry-point rule needs to know about its type.
#[derive(Clone, Copy)]
struct TypeContext<'a> {
qualified: &'a str,
/// The type derives from a web framework base or is an `[ApiController]`.
web: bool,
/// The type implements `IHttpHandler`, whose `ProcessRequest` the server calls.
http_handler: bool,
}
impl CSharpParser {
/// A C# parser.
pub fn new() -> Self {
Self
}
/// Visit type declarations at file level, in namespaces (block and
/// file-scoped alike), and nested in other types.
fn declarations(
root: Node<'_>,
parent: Option<TypeContext<'_>>,
source: &str,
graph: &mut FileGraph<'_>,
) {
walk(root, |node| {
if node == root {
return true;
}
match node.kind() {
"class_declaration"
| "struct_declaration"
| "interface_declaration"
| "record_declaration"
| "enum_declaration" => {
Self::type_declaration(node, parent, source, graph);
false
}
"method_declaration" | "constructor_declaration" => {
if let Some(ty) = parent {
Self::method(node, ty, source, graph);
}
false
}
"compilation_unit" | "namespace_declaration" | "declaration_list" => true,
_ => false,
}
});
}
fn type_declaration(
node: Node<'_>,
parent: Option<TypeContext<'_>>,
source: &str,
graph: &mut FileGraph<'_>,
) {
let Some(name) = node.child_by_field_name("name").map(|n| text(n, source)) else {
return;
};
let qualified = match parent {
Some(p) => format!("{}.{name}", p.qualified),
None => graph.top_level(name),
};
let kind = match node.kind() {
"struct_declaration" => CodeNodeKind::Struct,
"interface_declaration" => CodeNodeKind::Interface,
"enum_declaration" => CodeNodeKind::Enum,
_ => CodeNodeKind::Class,
};
graph.node(qualified.clone(), name, kind, node, false);
let bases = base_types(node, source);
for (base, at) in &bases {
let edge = if is_interface_name(base) {
CodeEdgeKind::Implements
} else {
CodeEdgeKind::Inherits
};
graph.edge(&qualified, base, edge, *at);
}
let context = TypeContext {
qualified: &qualified,
web: bases.iter().any(|(b, _)| WEB_BASES.contains(b))
|| attributes(node, source).any(|a| a == "ApiController"),
http_handler: bases.iter().any(|(b, _)| *b == "IHttpHandler"),
};
if let Some(body) = node.child_by_field_name("body") {
Self::declarations(body, Some(context), source, graph);
}
}
fn method(node: Node<'_>, ty: TypeContext<'_>, source: &str, graph: &mut FileGraph<'_>) {
let Some(name) = node.child_by_field_name("name").map(|n| text(n, source)) else {
return;
};
let qualified = format!("{}.{name}", ty.qualified);
let is_entry =
node.kind() == "method_declaration" && is_entry_point(node, name, ty, source);
graph.node(
qualified.clone(),
name,
CodeNodeKind::Method,
node,
is_entry,
);
if let Some(body) = node.child_by_field_name("body") {
Self::calls(body, &qualified, source, graph);
}
}
/// Calls by method name (`repo.Find(id)` calls `Find`) and constructions
/// (`new OrderDto(o)` calls `OrderDto`).
fn calls(body: Node<'_>, caller: &str, source: &str, graph: &mut FileGraph<'_>) {
walk(body, |node| {
let callee = match node.kind() {
"invocation_expression" => {
node.child_by_field_name("function").and_then(simple_name)
}
"object_creation_expression" => {
node.child_by_field_name("type").and_then(simple_name)
}
_ => None,
};
if let Some(callee) = callee {
graph.edge(caller, text(callee, source), CodeEdgeKind::Calls, node);
}
true
});
}
}
/// Whether the framework, not our own code, calls this method.
fn is_entry_point(method: Node<'_>, name: &str, ty: TypeContext<'_>, source: &str) -> bool {
let mut cursor = method.walk();
let modifiers: Vec<&str> = method
.children(&mut cursor)
.filter(|c| c.kind() == "modifier")
.map(|c| text(c, source))
.collect();
let has_modifier = |wanted: &str| modifiers.contains(&wanted);
if name == "Main" && has_modifier("static") {
return true;
}
if attributes(method, source).any(|a| ENDPOINT_ATTRIBUTES.contains(&a)) {
return true;
}
if ty.http_handler && name == "ProcessRequest" {
return true;
}
// Controller actions are public. Web Forms event handlers such as
// `Page_Load` or `BtnSave_Click` are usually protected; the markup
// wires them up.
ty.web && (has_modifier("public") || has_modifier("protected"))
}
/// The simple names of a declaration's attributes, without namespace or
/// the `Attribute` suffix: `[System.Web.Services.WebMethodAttribute]` is
/// `WebMethod`.
fn attributes<'s>(declaration: Node<'_>, source: &'s str) -> impl Iterator<Item = &'s str> {
let mut names = Vec::new();
let mut cursor = declaration.walk();
for list in declaration
.children(&mut cursor)
.filter(|c| c.kind() == "attribute_list")
{
let mut inner = list.walk();
for attribute in list.named_children(&mut inner) {
if let Some(name) = attribute.child_by_field_name("name").and_then(simple_name) {
let name = text(name, source);
names.push(name.strip_suffix("Attribute").unwrap_or(name));
}
}
}
names.into_iter()
}
/// The simple names of the types in a declaration's base list, with the
/// node each one was named at.
fn base_types<'t, 's>(declaration: Node<'t>, source: &'s str) -> Vec<(&'s str, Node<'t>)> {
let mut cursor = declaration.walk();
let Some(list) = declaration
.children(&mut cursor)
.find(|c| c.kind() == "base_list")
else {
return Vec::new();
};
let mut inner = list.walk();
list.named_children(&mut inner)
.filter_map(|ty| simple_name(ty).map(|n| (text(n, source), ty)))
.collect()
}
/// The last identifier of a name: `System.Web.UI.Page` is `Page`,
/// `List<int>` is `List`, `repo.Find` is `Find`.
fn simple_name(node: Node<'_>) -> Option<Node<'_>> {
match node.kind() {
"identifier" => Some(node),
"qualified_name" | "member_access_expression" => {
node.child_by_field_name("name").and_then(simple_name)
}
"generic_name" => node.named_child(0).filter(|n| n.kind() == "identifier"),
_ => None,
}
}
/// .NET names interfaces `IName`; the base list doesn't say which base is
/// the class and which are interfaces, so the convention decides.
fn is_interface_name(name: &str) -> bool {
let mut chars = name.chars();
chars.next() == Some('I') && chars.next().is_some_and(|c| c.is_ascii_uppercase())
}
impl LanguageParser for CSharpParser {
fn language(&self) -> &str {
"csharp"
}
fn extensions(&self) -> &[&str] {
&["cs"]
}
fn parse_file(
&self,
file_path: &Path,
source: &str,
repo_id: &str,
graph_build_id: &str,
) -> Result<ParseOutput, CoreError> {
let tree = parse(tree_sitter_c_sharp::LANGUAGE.into(), source, "C#")?;
let mut graph = FileGraph::new(
file_path,
source.lines().count() as u32,
repo_id,
graph_build_id,
"csharp",
);
Self::declarations(tree.root_node(), None, source, &mut graph);
Ok(graph.finish())
}
}
#[cfg(test)]
mod tests {
use super::*;
use compliance_core::models::graph::CodeNode;
const WEB_APP: &str = r#"
using System;
using Microsoft.AspNetCore.Mvc;
namespace Plant.Web.Controllers {
[ApiController]
[Route("api/[controller]")]
public class OrdersController : ControllerBase, IDisposable {
private readonly IRepo _repo;
public OrdersController(IRepo repo) { _repo = repo; }
[HttpGet("{id}")]
public IActionResult Get(int id) { var o = _repo.Find(id); Log(o); return Ok(new OrderDto(o)); }
private void Log(object o) { Console.WriteLine(o); }
public void Dispose() {}
public class Nested { public void Inner() {} }
}
public interface IRepo { Order Find(int id); }
public struct Pt { public int X; }
public enum Kind { A, B }
public record OrderDto(Order O);
public class Repo : IRepo { public Order Find(int id) { return null; } }
}
namespace Other;
public partial class Default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) { Bind(); }
private void Bind() { }
[System.Web.Services.WebMethodAttribute] public static string Ping() => "pong";
}
public class Download : IHttpHandler { public void ProcessRequest(HttpContext c) { } }
public static class Program { static async Task Main(string[] args) { await Run(); } }
"#;
fn parsed() -> ParseOutput {
CSharpParser::new()
.parse_file(Path::new("Web/Orders.cs"), WEB_APP, "repo", "build")
.expect("C# parses")
}
fn node<'a>(out: &'a ParseOutput, qualified: &str) -> &'a CodeNode {
let qualified = format!("Web/Orders.cs::{qualified}");
out.nodes
.iter()
.find(|n| n.qualified_name == qualified)
.unwrap_or_else(|| panic!("no node {qualified}"))
}
#[test]
fn types_and_methods_become_nodes_in_every_namespace_form() {
let out = parsed();
assert!(matches!(
node(&out, "OrdersController").kind,
CodeNodeKind::Class
));
assert!(matches!(node(&out, "IRepo").kind, CodeNodeKind::Interface));
assert!(matches!(node(&out, "Pt").kind, CodeNodeKind::Struct));
assert!(matches!(node(&out, "Kind").kind, CodeNodeKind::Enum));
assert!(matches!(node(&out, "OrderDto").kind, CodeNodeKind::Class));
// A file-scoped namespace's types are siblings of its declaration.
assert!(matches!(node(&out, "Default").kind, CodeNodeKind::Class));
for method in [
"OrdersController.OrdersController",
"OrdersController.Get",
"OrdersController.Log",
"OrdersController.Nested.Inner",
"IRepo.Find",
"Default.Page_Load",
] {
assert!(
matches!(node(&out, method).kind, CodeNodeKind::Method),
"{method}"
);
}
}
#[test]
fn framework_called_methods_are_entry_points() {
let out = parsed();
for entry in [
"OrdersController.Get",
"OrdersController.Dispose",
"Default.Page_Load",
"Default.Ping",
"Download.ProcessRequest",
"Program.Main",
] {
assert!(
node(&out, entry).is_entry_point,
"{entry} is an entry point"
);
}
for internal in [
"OrdersController.Log",
"OrdersController.OrdersController",
"OrdersController.Nested.Inner",
"Default.Bind",
"Repo.Find",
] {
assert!(!node(&out, internal).is_entry_point, "{internal} is not");
}
}
#[test]
fn bases_and_calls_become_edges() {
let out = parsed();
let edges: Vec<(&str, &str, &str)> = out
.edges
.iter()
.map(|e| {
let kind = match e.kind {
CodeEdgeKind::Calls => "calls",
CodeEdgeKind::Inherits => "inherits",
CodeEdgeKind::Implements => "implements",
_ => "other",
};
(kind, e.source.as_str(), e.target.as_str())
})
.collect();
let controller = "Web/Orders.cs::OrdersController";
assert!(edges.contains(&("inherits", controller, "ControllerBase")));
assert!(edges.contains(&("implements", controller, "IDisposable")));
assert!(edges.contains(&("inherits", "Web/Orders.cs::Default", "Page")));
let get = "Web/Orders.cs::OrdersController.Get";
for callee in ["Find", "Log", "Ok", "OrderDto"] {
assert!(
edges.contains(&("calls", get, callee)),
"Get calls {callee}"
);
}
assert!(edges.contains(&("calls", "Web/Orders.cs::Program.Main", "Run")));
}
#[test]
fn overloads_share_one_node_and_keep_all_their_calls() {
let source = r#"
public class Orders : ControllerBase {
private void Find(int id) { ById(id); }
[HttpGet] public void Find(string name) { ByName(name); }
}
"#;
let out = CSharpParser::new()
.parse_file(Path::new("O.cs"), source, "r", "b")
.expect("C# parses");
let finds: Vec<&CodeNode> = out
.nodes
.iter()
.filter(|n| n.qualified_name == "O.cs::Orders.Find")
.collect();
assert_eq!(finds.len(), 1);
assert!(finds[0].is_entry_point, "one overload is an endpoint");
let callees: Vec<&str> = out
.edges
.iter()
.filter(|e| e.source == "O.cs::Orders.Find")
.map(|e| e.target.as_str())
.collect();
assert_eq!(callees, ["ById", "ByName"]);
}
#[test]
fn interface_names_follow_the_dotnet_convention() {
assert!(is_interface_name("IRepo"));
assert!(!is_interface_name("Item"));
assert!(!is_interface_name("I"));
}
}
+5
View File
@@ -1,5 +1,10 @@
pub mod c;
mod common;
pub mod csharp;
pub mod javascript;
pub mod python;
pub mod registry;
pub mod rust_parser;
pub mod typescript;
pub use common::FileGraph;
+94 -12
View File
@@ -3,13 +3,25 @@ use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
use tracing::{debug, info};
use tracing::{debug, info, warn};
use super::c::CParser;
use super::csharp::CSharpParser;
use super::javascript::JavaScriptParser;
use super::python::PythonParser;
use super::rust_parser::RustParser;
use super::typescript::TypeScriptParser;
/// What [`ParserRegistry::parse_directory`] made of a tree.
#[derive(Debug, Default)]
pub struct DirectoryParse {
/// Every parsed file's nodes and edges.
pub output: ParseOutput,
/// Source files of a supported language that could not be read as text
/// (I/O error, malformed UTF-16, binary): left out of `output`.
pub unreadable_files: u32,
}
/// Registry of language parsers, indexed by file extension
pub struct ParserRegistry {
parsers: Vec<Box<dyn LanguageParser>>,
@@ -24,6 +36,8 @@ impl ParserRegistry {
Box::new(PythonParser::new()),
Box::new(JavaScriptParser::new()),
Box::new(TypeScriptParser::new()),
Box::new(CParser::new()),
Box::new(CSharpParser::new()),
];
let mut extension_map = HashMap::new();
@@ -75,15 +89,36 @@ impl ParserRegistry {
Ok(Some(output))
}
/// Parse all supported files in a directory tree
/// Parse all supported files in a directory tree.
///
/// Each file is decoded by [`compliance_core::encoding::read_source`] (UTF-8,
/// UTF-16 with a BOM, Windows-1252); a file still not readable as text
/// is counted, not parsed.
///
/// # Arguments
///
/// * `dir` - the tree's root; node paths are relative to it
/// * `repo_id` - the repository the nodes belong to
/// * `graph_build_id` - the build the nodes belong to
/// * `max_nodes` - parsing stops once this many nodes are collected
///
/// # Returns
///
/// The nodes and edges of every parsed file, and how many files could
/// not be read.
///
/// # Errors
///
/// Returns `CoreError::Graph` when a directory can't be listed, and a
/// parser's error.
pub fn parse_directory(
&self,
dir: &Path,
repo_id: &str,
graph_build_id: &str,
max_nodes: u32,
) -> Result<ParseOutput, CoreError> {
let mut combined = ParseOutput::default();
) -> Result<DirectoryParse, CoreError> {
let mut combined = DirectoryParse::default();
let mut node_count: u32 = 0;
self.walk_directory(
@@ -96,9 +131,17 @@ impl ParserRegistry {
&mut combined,
)?;
// One line per build; the paths are logged at debug level only.
if combined.unreadable_files > 0 {
warn!(
unreadable_files = combined.unreadable_files,
"Source files left out of the code graph: not readable as text"
);
}
info!(
nodes = combined.nodes.len(),
edges = combined.edges.len(),
nodes = combined.output.nodes.len(),
edges = combined.output.edges.len(),
unreadable_files = combined.unreadable_files,
"Directory parsing complete"
);
@@ -113,7 +156,7 @@ impl ParserRegistry {
graph_build_id: &str,
max_nodes: u32,
node_count: &mut u32,
combined: &mut ParseOutput,
combined: &mut DirectoryParse,
) -> Result<(), CoreError> {
let entries = std::fs::read_dir(dir).map_err(|e| {
CoreError::Graph(format!("Failed to read directory {}: {e}", dir.display()))
@@ -162,15 +205,19 @@ impl ParserRegistry {
// Use relative path from base
let rel_path = path.strip_prefix(base).unwrap_or(&path);
let source = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(_) => continue, // Skip binary/unreadable files
let source = match compliance_core::encoding::read_source(&path) {
Ok(text) => text,
Err(error) => {
debug!(file = %rel_path.display(), %error, "Source file not readable");
combined.unreadable_files += 1;
continue;
}
};
if let Some(output) = self.parse_file(rel_path, &source, repo_id, graph_build_id)? {
*node_count += output.nodes.len() as u32;
combined.nodes.extend(output.nodes);
combined.edges.extend(output.edges);
combined.output.nodes.extend(output.nodes);
combined.output.edges.extend(output.edges);
}
}
}
@@ -290,6 +337,41 @@ mod tests {
assert!(!output.nodes.is_empty());
}
#[test]
fn files_in_every_encoding_parse_and_unreadable_ones_are_counted() {
// Arrange
let tree = crate::test_tree::TempTree::in_every_encoding("registry");
// Act
let parsed = ParserRegistry::new()
.parse_directory(tree.path(), "repo1", "build1", 1000)
.expect("tree parses");
// Assert: each file's declaration is a node, under the file's path.
let has = |file: &str, name: &str| {
parsed
.output
.nodes
.iter()
.any(|n| n.file_path == file && n.name == name)
};
for (file, class) in [
("Plain.cs", "Utf8Plain"),
("Bom.cs", "Utf8Bom"),
("Le.cs", "Utf16Le"),
("Be.cs", "Utf16Be"),
] {
assert!(has(file, class), "no class {class} in {file}");
assert!(has(file, "Run"), "no method Run in {file}");
}
assert!(
has("legacy.c", "unit"),
"no function in the Windows-1252 file"
);
// The broken UTF-16 file and the binary; not the PNG.
assert_eq!(parsed.unreadable_files, 2);
}
#[test]
fn test_default_trait() {
let registry = ParserRegistry::default();
+63 -63
View File
@@ -363,6 +363,69 @@ impl RustParser {
}
}
impl LanguageParser for RustParser {
fn language(&self) -> &str {
"rust"
}
fn extensions(&self) -> &[&str] {
&["rs"]
}
fn parse_file(
&self,
file_path: &Path,
source: &str,
repo_id: &str,
graph_build_id: &str,
) -> Result<ParseOutput, CoreError> {
let mut parser = Parser::new();
let language = tree_sitter_rust::LANGUAGE;
parser
.set_language(&language.into())
.map_err(|e| CoreError::Graph(format!("Failed to set Rust language: {e}")))?;
let tree = parser
.parse(source, None)
.ok_or_else(|| CoreError::Graph("Failed to parse Rust file".to_string()))?;
let file_path_str = file_path.to_string_lossy().to_string();
let mut output = ParseOutput::default();
// Add file node
output.nodes.push(CodeNode {
id: None,
repo_id: repo_id.to_string(),
graph_build_id: graph_build_id.to_string(),
qualified_name: file_path_str.clone(),
name: file_path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default(),
kind: CodeNodeKind::File,
file_path: file_path_str.clone(),
start_line: 1,
end_line: source.lines().count() as u32,
language: "rust".to_string(),
community_id: None,
is_entry_point: false,
graph_index: None,
});
self.walk_tree(
tree.root_node(),
source,
&file_path_str,
repo_id,
graph_build_id,
None,
&mut output,
);
Ok(output)
}
}
#[cfg(test)]
mod tests {
use super::*;
@@ -570,66 +633,3 @@ mod tests {
assert_eq!(parser.extensions(), &["rs"]);
}
}
impl LanguageParser for RustParser {
fn language(&self) -> &str {
"rust"
}
fn extensions(&self) -> &[&str] {
&["rs"]
}
fn parse_file(
&self,
file_path: &Path,
source: &str,
repo_id: &str,
graph_build_id: &str,
) -> Result<ParseOutput, CoreError> {
let mut parser = Parser::new();
let language = tree_sitter_rust::LANGUAGE;
parser
.set_language(&language.into())
.map_err(|e| CoreError::Graph(format!("Failed to set Rust language: {e}")))?;
let tree = parser
.parse(source, None)
.ok_or_else(|| CoreError::Graph("Failed to parse Rust file".to_string()))?;
let file_path_str = file_path.to_string_lossy().to_string();
let mut output = ParseOutput::default();
// Add file node
output.nodes.push(CodeNode {
id: None,
repo_id: repo_id.to_string(),
graph_build_id: graph_build_id.to_string(),
qualified_name: file_path_str.clone(),
name: file_path
.file_name()
.map(|n| n.to_string_lossy().to_string())
.unwrap_or_default(),
kind: CodeNodeKind::File,
file_path: file_path_str.clone(),
start_line: 1,
end_line: source.lines().count() as u32,
language: "rust".to_string(),
community_id: None,
is_entry_point: false,
graph_index: None,
});
self.walk_tree(
tree.root_node(),
source,
&file_path_str,
repo_id,
graph_build_id,
None,
&mut output,
);
Ok(output)
}
}
+73
View File
@@ -0,0 +1,73 @@
//! A source tree on disk for tests, in every encoding the registry reads.
use std::path::{Path, PathBuf};
/// A directory under the system temp dir, removed when dropped (Rust runs
/// `Drop::drop` when the value goes out of scope, like a `with` block's exit).
pub(crate) struct TempTree(PathBuf);
impl TempTree {
/// An empty directory named after the test and this process.
pub(crate) fn new(test: &str) -> Self {
let dir =
std::env::temp_dir().join(format!("compliance-graph-{test}-{}", std::process::id()));
// A leftover from an aborted run would add files.
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).expect("temp dir");
Self(dir)
}
/// The directory.
pub(crate) fn path(&self) -> &Path {
&self.0
}
/// Write `bytes` to `rel` in the tree.
pub(crate) fn write(&self, rel: &str, bytes: &[u8]) {
std::fs::write(self.0.join(rel), bytes).expect("write");
}
/// A tree with one C# class or C function in each encoding the registry
/// reads, and two files it can't read (plus a binary it doesn't try to).
pub(crate) fn in_every_encoding(test: &str) -> Self {
let tree = Self::new(test);
tree.write("Plain.cs", b"class Utf8Plain { void Run() { } }\n");
tree.write("Bom.cs", b"\xEF\xBB\xBFclass Utf8Bom { void Run() { } }\n");
tree.write("Le.cs", &utf16("class Utf16Le { void Run() { } }\n", true));
tree.write("Be.cs", &utf16("class Utf16Be { void Run() { } }\n", false));
// "Größe" and "€" as Windows-1252 writes them.
tree.write(
"legacy.c",
b"/* Gr\xF6\xDFe */\nconst char *unit(void) { return \"\x80\"; }\n",
);
// An odd byte count after a UTF-16 BOM, and a binary with a C name.
tree.write("Broken.cs", b"\xFF\xFE\x41");
tree.write("blob.c", b"\x7FELF\x00\xFF\xFE");
// Not a source file: neither parsed nor counted.
tree.write("logo.png", b"\x89PNG\x00\xFF");
tree
}
}
impl Drop for TempTree {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// `text` as UTF-16 with its byte-order mark.
pub(crate) fn utf16(text: &str, little_endian: bool) -> Vec<u8> {
let bom: [u8; 2] = if little_endian {
[0xFF, 0xFE]
} else {
[0xFE, 0xFF]
};
let units = text.encode_utf16().flat_map(|unit| {
if little_endian {
unit.to_le_bytes()
} else {
unit.to_be_bytes()
}
});
bom.into_iter().chain(units).collect()
}
+16 -1
View File
@@ -96,7 +96,8 @@ pub fn extract_program(root: &Path) -> Option<PlcProgram> {
if !is_st && !is_xml {
continue;
}
let Ok(content) = std::fs::read_to_string(path) else {
// UTF-8, UTF-16 with a BOM, or Windows-1252, as PLC tools write them.
let Ok(content) = compliance_core::encoding::read_source(path) else {
continue;
};
let name = path
@@ -334,6 +335,20 @@ mod tests {
assert_eq!(prog2.file_name, "proj.xml");
}
#[test]
fn extract_reads_a_windows_1252_st_program() {
let s = Scratch::new();
// A comment with "Pumpe für" as Windows-1252 writes it: 0xFC for "ü".
std::fs::write(
s.0.join("main.st"),
b"(* Pumpe f\xFCr Halle 2 *)\nPROGRAM Main\nEND_PROGRAM\nCONFIGURATION C\nEND_CONFIGURATION\n",
)
.expect("w");
let prog = extract_program(&s.0).expect("program");
assert_eq!(prog.file_name, "main.st");
assert!(prog.source.contains("Pumpe für"));
}
#[test]
fn extract_returns_none_without_control_logic() {
let s = Scratch::new();