Compare commits

..
Author SHA1 Message Date
Sharang ParnerkarandClaude Opus 5.5 2e45dcab5c docs(design): t83 Testtag charged unless all its runs failed through our fault
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 3m49s
CI / Check (pull_request) Successful in 17m42s
The user's decision (2026-11-07): a run that fails on the customer's
input counts and makes the Testtag chargeable; only a Testtag whose runs
all failed through Breakpilot's fault is free. The charging table, the
usage event, the test plan, the decisions and the LB wording say so.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 10:55:16 +01:00
Sharang ParnerkarandClaude Opus 5.5 deaa4e9f4e docs(design): t83 review: build network, Testtag billing, ERP codes, data protection
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m13s
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Check (pull_request) Successful in 17m22s
- The build runs customer code and fetches packages: same VM sandbox,
  egress only through a package mirror, test phase internal-only.
  Private feeds unsupported in phase 1, or a separately stored
  write-only feed token used only in the build.
- ERP items CRA-CSA-CLD-TST (LIV/LRN reserved); the Probelauf is only a
  count.
- Billed per Testtag: our failures don't use one of the 3 runs, a
  Testtag with no successful run is not charged; booked only when the
  customer starts a run; a monthly cap in the portal.
- Testtage in the plans as a decision.
- Runner host in Germany, AVV and TOM; where logs and artifacts live
  and when they are deleted.
- Live testing out of phase 1; the L1-L7 analysis stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 09:14:39 +01:00
Sharang ParnerkarandClaude Opus 5.5 61953e2659 docs(design): active testing, a throwaway copy first (t83)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m46s
CI / Check (pull_request) Successful in 19m7s
Proposed design for the user to decide. Active tests run by default against a
copy of the customer's application, built from the repository in a short-lived
sandbox (the Prüfumgebung). The code graph steers them: routes from code, and
static findings confirmed against the copy. Live testing is an optional add-on
with written authorisation. Covers what exists today (checked against the
code), which targets qualify, build failures and charging, limits, the
entitlement, cost and a Testtag price, a stage test plan, and the SKU and LB
wording. Nothing is enabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-06 23:09:51 +01:00
72 changed files with 2162 additions and 6999 deletions

No files matched your search

+2 -4
View File
@@ -138,8 +138,6 @@ 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
@@ -148,8 +146,8 @@ jobs:
RUSTC_WRAPPER: ""
# Tests (reuses compilation artifacts from clippy)
- 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
- name: Tests (core + agent + werkbank-exec + control-map)
run: cargo test -p compliance-core -p compliance-agent -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
+26 -58
View File
@@ -51,6 +51,30 @@ 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: |
@@ -125,59 +149,10 @@ 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://localhost:3001/api/v1/health && exit 0
curl -fsS http://agent:3001/api/v1/health && exit 0
sleep 2
done
echo "agent did not become healthy" >&2
@@ -188,20 +163,13 @@ jobs:
- name: Scan the corpus and compare with the baselines
run: cargo test -p compliance-agent --test nightly -- --nocapture
env:
NIGHTLY_AGENT_URL: http://localhost:3001
NIGHTLY_AGENT_URL: http://agent: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
@@ -749,18 +749,14 @@ dependencies = [
"bson",
"chrono",
"compliance-core",
"encoding_rs",
"futures-util",
"mongodb",
"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",
@@ -6506,26 +6502,6 @@ 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,8 +28,6 @@ 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"] }
+26 -106
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, Job, Priority, ScanGate};
use crate::scan_gate::{Admission, HeldTarget, ScanGate};
use crate::secrets::SecretBox;
/// A target whose billing changed, with its new billing (t72).
@@ -262,16 +262,11 @@ impl ComplianceAgent {
}
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// 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.
/// 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.
///
/// # Errors
///
@@ -293,22 +288,15 @@ 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, Job::new(trigger, run_id.clone()))
{
match self.scan_gate.admit(&key, trigger.clone()) {
Admission::Run => {}
Admission::Coalesced { replaced } => {
Admission::Coalesced => {
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 => {
@@ -317,43 +305,41 @@ 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 {
// 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);
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
};
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;
}
if !self.scan_gate.finish(&key) {
break outcome;
match self.scan_gate.finish(&key) {
Some(next) => trigger = next,
None => break outcome,
}
};
held.disarm();
result
}
/// 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.
/// One scan of a target, with no gating: the pipeline plus its usage event.
async fn run_one_target_scan(
&self,
tenant_id: &str,
target_id: &str,
job: &Job,
trigger: compliance_core::models::ScanTrigger,
) -> 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).
@@ -367,12 +353,9 @@ 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_charged_as(job.charged_as.clone());
.with_plan_limits(plan.map(|p| p.limits));
let started = chrono::Utc::now();
let outcome = orchestrator
.run_target(target_id, trigger.clone(), job.run_id.as_deref())
.await?;
let outcome = orchestrator.run_target(target_id, trigger.clone()).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 {
@@ -441,7 +424,7 @@ impl ComplianceAgent {
// slot too. Each PR is distinct work, so it is not coalesced.
let _slot = self
.scan_gate
.slot(Priority::Background)
.slot()
.await
.map_err(|e| crate::error::AgentError::Other(format!("scan slot: {e}")))?;
let db = self.db_pool.for_tenant_id(tenant_id).await?;
@@ -517,69 +500,6 @@ 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,14 +79,9 @@ 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({
let mut started = by_target;
started.insert("status", doc! { "$ne": "queued" });
started
})
.find_one(by_target)
.sort(doc! { "started_at": -1 })
.await
.map_err(load_err)?,
+4 -114
View File
@@ -6,9 +6,7 @@ use axum::Json;
use mongodb::bson::doc;
use serde::{Deserialize, Serialize};
use compliance_core::models::graph::{
CodeEdge, CodeNode, GraphBuildRun, GraphBuildStatus, ImpactAnalysis,
};
use compliance_core::models::graph::{CodeEdge, CodeNode, GraphBuildRun, ImpactAnalysis};
use compliance_core::tenant_ctx::TenantCtx;
use crate::agent::ComplianceAgent;
@@ -190,60 +188,6 @@ 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(
@@ -411,9 +355,7 @@ pub async fn get_file_content(
return Err(StatusCode::FORBIDDEN);
}
// Decoded as the graph read it, so a UTF-16 or Windows-1252 file opens.
let content =
compliance_graph::encoding::read_source(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
let content = std::fs::read_to_string(&canonical).map_err(|_| StatusCode::NOT_FOUND)?;
// Cap at 10,000 lines
let truncated: String = content.lines().take(10_000).collect::<Vec<_>>().join("\n");
@@ -492,17 +434,10 @@ 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 crate::pipeline::graph_build::build_graph(source, &repo_id, &graph_build_id) {
match engine.build_graph(&repo_path, &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;
@@ -525,48 +460,3 @@ 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
);
}
}
@@ -1,54 +0,0 @@
//! 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,7 +14,6 @@ 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(), true),
latest_scan_runs(&runs, ids.clone()),
findings_counts(&findings, ids),
);
let data = targets
@@ -179,13 +179,10 @@ impl TargetFilter {
}
}
/// 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.
/// The newest scan run of each target in `target_ids`, in one query.
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;
@@ -193,12 +190,8 @@ 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": matching },
doc! { "$match": { "repo_id": { "$in": target_ids } } },
doc! { "$sort": { "started_at": -1 } },
doc! { "$group": { "_id": "$repo_id", "run": { "$first": "$$ROOT" } } },
];
@@ -1030,76 +1023,6 @@ 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(), false),
super::onboarding::latest_scan_runs(&runs, ids.clone()),
open_findings_counts(&db, ids.clone()),
open_vulnerabilities_counts(&db, ids),
);
-9
View File
@@ -15,7 +15,6 @@ 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.
@@ -85,10 +84,6 @@ 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",
@@ -199,10 +194,6 @@ 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 = compliance_graph::encoding::read_source(&repo_path.join(file)).ok()?;
let content = std::fs::read_to_string(repo_path.join(file)).ok()?;
let lines: Vec<&str> = content.lines().collect();
if lines.is_empty() {
return None;
+10 -43
View File
@@ -43,15 +43,14 @@ struct OrphanRule {
}
/// Code scans are what customers see, so they get their own `interrupted`
/// 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
/// status. 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: &["queued", "running"],
open: &["running"],
closed_as: "interrupted",
},
OrphanRule {
@@ -219,16 +218,12 @@ 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 {
@@ -248,25 +243,12 @@ 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). Of a running
// scan and its queued follow-up, a person's wins.
let triggers = db
// nothing changed since the last completed one (#465).
let trigger = db
.scan_runs()
.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);
.find_one(doc! { "repo_id": id, "status": "interrupted", "completed_at": closed })
.await?
.map_or(ScanTrigger::Scheduled, |run| run.trigger);
out.push((id.to_string(), trigger));
}
}
@@ -383,11 +365,10 @@ 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
// target to resume has a scheduled scan running and a person's
// follow-up queued (t84): one interruption, resumed as the person's.
// Arrange: runs left open, plus one interrupted an hour ago.
// The scan to resume was started by a person.
for (id, trigger) in [
(&resumes, ScanTrigger::Scheduled),
(&resumes, ScanTrigger::Manual),
(&looping, ScanTrigger::Scheduled),
(&archived, ScanTrigger::Scheduled),
] {
@@ -396,10 +377,6 @@ 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;
@@ -446,16 +423,6 @@ 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 = compliance_graph::encoding::read_source(std::path::Path::new(file_path)).ok()?;
let content = std::fs::read_to_string(file_path).ok()?;
let lines: Vec<&str> = content.lines().collect();
let start = line.saturating_sub(25);
+4 -156
View File
@@ -20,8 +20,7 @@ use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, Document};
use compliance_core::models::{
check_swap, split_included, BillableTarget, DayUsage, IncludedChoice, MonthUsage, PlanLimits,
RunCharge, SwapRefusal, TargetBilling,
split_included, BillableTarget, DayUsage, MonthUsage, PlanLimits, RunCharge, TargetBilling,
};
use crate::database::Database;
@@ -46,12 +45,12 @@ pub async fn assign_billing(
db: &Database,
included: Option<u32>,
) -> Result<Vec<(ObjectId, TargetBilling)>, AgentError> {
// Only the fields the split needs: a whole target holds its artifacts,
// and older documents may lack fields the model requires.
// Only the three 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, "included_choice": 1 })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1 })
.await?
.try_collect()
.await?;
@@ -91,89 +90,9 @@ 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 {
@@ -397,80 +316,11 @@ 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| {
@@ -518,7 +368,6 @@ mod tests {
id,
created_at: at.to_chrono(),
billing: TargetBilling::Extra,
choice: None,
})
);
assert_eq!(
@@ -527,7 +376,6 @@ mod tests {
id,
created_at: DateTime::<Utc>::MIN_UTC,
billing: TargetBilling::Included,
choice: None,
})
);
assert_eq!(billable(&doc! { "name": "no id" }), None);
+21 -3
View File
@@ -145,15 +145,33 @@ 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) or be Windows-1252, decoded by
/// [`compliance_graph::encoding::read_source`]. `None` for a file too large or
/// writes UTF-8 with BOM, older tools UTF-16). `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;
}
compliance_graph::encoding::read_source(path).ok()
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(),
}
}
/// Parse XML the way project and configuration files need: a DTD is allowed
@@ -147,8 +147,7 @@ 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
// Vendor SDK headers are often Windows-1252 (a "©" in the banner).
.then(|| compliance_graph::encoding::read_source(entry.path()).ok())
.then(|| std::fs::read_to_string(entry.path()).ok())
.flatten()
else {
continue;
+13 -56
View File
@@ -1,71 +1,28 @@
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, store it in place of the
/// previous one and compute the impact of each finding.
/// Build the code knowledge graph for a repo and compute impact analyses
pub(super) async fn build_code_graph(
&self,
source: GraphSource<'_>,
repo_path: &std::path::Path,
repo_id: &str,
findings: &[Finding],
) -> Result<GraphContext, AgentError> {
let graph_build_id = uuid::Uuid::new_v4().to_string();
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 engine = compliance_graph::GraphEngine::new(50_000);
/// 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 (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
let store = compliance_graph::graph::persistence::GraphStore::new(self.db.inner());
store
.delete_repo_graph(repo_id)
@@ -85,7 +42,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;
pub(crate) mod graph_build;
mod graph_build;
pub mod grouping;
pub mod ios_config;
mod issue_catchup;
+32 -179
View File
@@ -82,10 +82,6 @@ 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 {
@@ -103,17 +99,9 @@ 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;
@@ -239,16 +227,6 @@ 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).
@@ -960,12 +938,8 @@ impl PipelineOrchestrator {
self.update_phase(scan_run_id, ScanPhase::GraphBuilding)
.await;
let graph_context = match async {
self.build_code_graph(
crate::pipeline::graph_build::GraphSource::Tree(&repo_path),
&repo_id,
&all_findings,
)
.await
self.build_code_graph(&repo_path, &repo_id, &all_findings)
.await
}
.instrument(tracing::info_span!("stage_graph_building"))
.await
@@ -1181,9 +1155,7 @@ 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`, recorded on the run `queued`
/// that waited for this scan's slot (t84), or on a new run when there is
/// none.
/// Run one scan of the target `target_id`.
///
/// # Returns
///
@@ -1198,7 +1170,6 @@ 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()))?;
@@ -1214,15 +1185,14 @@ impl PipelineOrchestrator {
// detection attributes the others (t72).
if let Some(attribution) = ScanAttribution::of_person(&trigger) {
scan_run.attribution = Some(attribution);
// 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);
scan_run.chargeable = attribution.chargeable(target.billing);
}
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);
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();
// A counted Prüfung a person started is checked against the plan
// before anything runs (t72).
@@ -1256,7 +1226,10 @@ impl PipelineOrchestrator {
}
self.db
.scan_runs()
.update_one(doc! { "_id": &run_id }, doc! { "$set": completed })
.update_one(
doc! { "_id": &insert.inserted_id },
doc! { "$set": completed },
)
.await?;
// Refresh the target's cached findings count. The shared pipeline
// (Stage 7) increments `repositories`, which the unified path does
@@ -1293,7 +1266,7 @@ impl PipelineOrchestrator {
self.db
.scan_runs()
.update_one(
doc! { "_id": &run_id },
doc! { "_id": &insert.inserted_id },
doc! { "$set": {
"status": "completed",
"current_phase": "completed",
@@ -1308,7 +1281,7 @@ impl PipelineOrchestrator {
self.db
.scan_runs()
.update_one(
doc! { "_id": &run_id },
doc! { "_id": &insert.inserted_id },
doc! { "$set": {
"status": "failed",
"error_message": message,
@@ -1328,7 +1301,7 @@ impl PipelineOrchestrator {
let run = self
.db
.scan_runs()
.find_one(doc! { "_id": &run_id })
.find_one(doc! { "_id": &insert.inserted_id })
.await
.ok()
.flatten();
@@ -1342,7 +1315,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(&run_id, target_id).await
self.charge_run(&insert.inserted_id, target_id).await
} else {
None
};
@@ -1357,59 +1330,6 @@ 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.
@@ -1508,40 +1428,6 @@ 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(
@@ -1616,25 +1502,17 @@ impl PipelineOrchestrator {
return Ok(0);
}
// A git target is attributed where its commits are compared.
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?;
}
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?;
}
let plan = build_scan_plan(target);
// An attached artifact nothing analyses is recorded, never passed over:
@@ -1845,8 +1723,6 @@ 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
@@ -1865,12 +1741,10 @@ 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::findings(&files, target_id),
crate::pipeline::plc::analyze_tree(&path, 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
@@ -1932,21 +1806,6 @@ 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 {
@@ -3399,7 +3258,6 @@ 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);
}
@@ -3553,11 +3411,7 @@ mod tests {
assert_eq!(
planned_phases(&target, &plan, &config),
[
ScanPhase::Classification,
ScanPhase::PlcAnalysis,
ScanPhase::GraphBuilding
]
[ScanPhase::Classification, ScanPhase::PlcAnalysis]
);
// The LLM control mapping is a phase of its own, so a long one shows.
@@ -3567,8 +3421,7 @@ mod tests {
[
ScanPhase::Classification,
ScanPhase::PlcAnalysis,
ScanPhase::SemanticControlMapping,
ScanPhase::GraphBuilding
ScanPhase::SemanticControlMapping
]
);
}
+1 -118
View File
@@ -14,96 +14,8 @@ pub struct Pou {
pub vars: Vec<VarDecl>,
/// The statement body.
pub body: Vec<Stmt>,
/// 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.
/// 1-based line where the POU header appears (in the source that was parsed).
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)]
@@ -279,35 +191,6 @@ 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
@@ -1,295 +0,0 @@
//! 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(""));
}
}
+18 -111
View File
@@ -9,7 +9,6 @@
//! 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;
@@ -46,26 +45,9 @@ impl Scanner for PlcControlLogicScanner {
}
}
/// 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_graph::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;
/// 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();
for entry in walkdir::WalkDir::new(root)
.into_iter()
.filter_map(|e| e.ok())
@@ -84,17 +66,8 @@ pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
if !is_st && !is_xml {
continue;
}
let content = match compliance_graph::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;
}
let Ok(content) = std::fs::read_to_string(path) else {
continue;
};
// A `.project` is read only as a PLCopen export; CODESYS's native one
// is binary ([`native_projects`] reports it).
@@ -109,41 +82,16 @@ pub(crate) fn read_tree(root: &Path) -> Vec<PlcFile> {
if pous.is_empty() {
continue;
}
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 {
let rel = path
.strip_prefix(root)
.unwrap_or(path)
.to_string_lossy()
.to_string();
for pou in &pous {
for hit in rules::analyze(pou) {
let line_s = hit.line.to_string();
let fingerprint = dedup::compute_fingerprint(&[
repo_id,
&file.rel,
hit.rule_id,
&pou.name,
&line_s,
]);
let fingerprint =
dedup::compute_fingerprint(&[repo_id, &rel, hit.rule_id, &pou.name, &line_s]);
let mut f = Finding::new(
repo_id.to_string(),
fingerprint,
@@ -153,7 +101,7 @@ pub(crate) fn findings(files: &[PlcFile], repo_id: &str) -> Vec<Finding> {
hit.description,
hit.severity,
);
f.file_path = Some(file.rel.clone());
f.file_path = Some(rel.clone());
f.line_number = Some(hit.line);
f.rule_id = Some(hit.rule_id.to_string());
f.cwe = hit.cwe.map(String::from);
@@ -165,11 +113,6 @@ pub(crate) fn findings(files: &[PlcFile], 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 {
@@ -209,9 +152,10 @@ pub fn native_projects(root: &Path) -> Vec<String> {
.unwrap_or("")
.to_ascii_lowercase();
let native = match ext.as_str() {
// Decoded as [`read_tree`] reads it: a UTF-16 export is no native one.
"project" => !compliance_graph::encoding::read_source(path)
.is_ok_and(|text| looks_like_xml(&text)),
"project" => !std::fs::read(path)
.ok()
.and_then(|bytes| String::from_utf8(bytes).ok())
.is_some_and(|text| looks_like_xml(&text)),
"projectarchive" => sbom::check_archive(path).is_ok(),
_ => false,
};
@@ -405,41 +349,4 @@ 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,7 +119,6 @@ impl Parser {
body.push(s);
}
}
let end_line = self.line();
self.eat_kw(end);
Some(Pou {
@@ -128,7 +127,6 @@ impl Parser {
vars,
body,
line,
end_line,
})
}
+1 -10
View File
@@ -49,16 +49,7 @@ pub fn parse_plcopen(xml: &str) -> Vec<Pou> {
_ => "PROGRAM",
};
let synthetic = format!("{kw} {name}\n{var_block}{body}\nEND_{kw}\n");
// 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.extend(parser::parse(&synthetic));
}
pous
}
+4 -6
View File
@@ -19,10 +19,9 @@ pub fn relative_path(root: &Path, path: &str) -> String {
rel.to_string_lossy().replace('\\', "/")
}
/// The whole text of `root/rel`, decoded by
/// [`compliance_graph::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.
/// 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.
pub fn read_text(root: &Path, rel: &str) -> Option<String> {
let rel_path = Path::new(rel);
if rel_path.is_absolute()
@@ -32,8 +31,7 @@ pub fn read_text(root: &Path, rel: &str) -> Option<String> {
{
return None;
}
// UTF-16 with a BOM and Windows-1252 too, as the code graph reads them.
compliance_graph::encoding::read_source(&root.join(rel_path)).ok()
std::fs::read_to_string(root.join(rel_path)).ok()
}
/// Lines `start..=end` (1-based, inclusive) of `root/rel`, capped at
+87 -688
View File
@@ -1,55 +1,37 @@
//! 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.
//! How many scans run at once, and what happens to a scan requested while the
//! same target is already 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. These rules now apply to every trigger (click, webhook, scheduler):
//! other. Two 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.
//! * **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.
//! * **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.
//!
//! 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::collections::VecDeque;
use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
use std::sync::Arc;
use std::time::Duration;
use dashmap::mapref::entry::Entry;
use dashmap::DashMap;
use rand::Rng;
use tokio::sync::oneshot;
use tokio::sync::{OwnedSemaphorePermit, Semaphore};
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.
@@ -63,108 +45,33 @@ 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 queued or running for this target: the caller now holds
/// it and runs its scans through [`ScanGate::start`].
/// Nothing was running for this target: the caller runs the scan now.
Run,
/// 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.
/// 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.
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<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>,
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>>,
}
impl ScanGate {
/// A gate allowing `concurrency` scans at once (at least one).
pub fn new(concurrency: usize) -> Self {
Self {
slots: Arc::new(Slots {
queue: Mutex::new(Queue {
free: concurrency.max(1),
person: VecDeque::new(),
background: VecDeque::new(),
person_grants: 0,
}),
}),
targets: DashMap::new(),
slots: Arc::new(Semaphore::new(concurrency.max(1))),
running: DashMap::new(),
}
}
@@ -176,253 +83,60 @@ 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, 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()) {
pub fn admit(&self, key: &str, trigger: ScanTrigger) -> Admission {
match self.running.entry(key.to_string()) {
Entry::Vacant(v) => {
v.insert(Held {
current: job,
running: false,
pending: None,
});
v.insert(None);
Admission::Run
}
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,
}
Entry::Occupied(mut o) if o.get().is_none() => {
o.insert(Some(trigger));
Admission::Coalesced
}
// 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,
}
}
/// 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
}
/// 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
}
}
Entry::Vacant(_) => false,
},
Entry::Vacant(_) => None,
}
}
/// 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.targets.remove(key);
self.running.remove(key);
}
/// 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.
/// Wait for one of the global scan slots. The slot is freed when the
/// returned permit is dropped.
///
/// # Errors
///
/// 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();
}
/// 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
}
}
@@ -461,20 +175,10 @@ impl Drop for HeldTarget<'_> {
#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
use super::{
start_delay, Admission, HeldTarget, Job, Priority, ScanGate, PERSON_GRANTS_IN_A_ROW,
SCHEDULED_SCAN_JITTER,
};
use super::{start_delay, Admission, HeldTarget, ScanGate, 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)
@@ -498,163 +202,52 @@ mod tests {
}
#[test]
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() {
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, 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
);
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);
}
// The holder runs the one follow-up, then releases the target.
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
);
assert!(gate.finish(&key).is_some());
assert!(gate.finish(&key).is_none());
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
}
#[test]
fn a_scan_still_waiting_covers_requests_that_are_not_a_persons() {
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, ScanTrigger::Scheduled), Admission::Run);
assert_eq!(
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 }
gate.admit(&key, ScanTrigger::Scheduled),
Admission::Coalesced
);
// 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
);
// 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);
assert!(gate.finish(&key));
assert_eq!(gate.finish(&key), Some(ScanTrigger::Manual));
}
#[test]
fn targets_and_tenants_are_independent() {
let gate = ScanGate::new(2);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t1"), job(ScanTrigger::Manual, "a")),
gate.admit(&ScanGate::key("acme", "t1"), ScanTrigger::Manual),
Admission::Run
);
assert_eq!(
gate.admit(&ScanGate::key("acme", "t2"), job(ScanTrigger::Manual, "b")),
gate.admit(&ScanGate::key("acme", "t2"), ScanTrigger::Manual),
Admission::Run
);
// Same target id in another tenant is another target.
assert_eq!(
gate.admit(
&ScanGate::key("globex", "t1"),
job(ScanTrigger::Manual, "c")
),
gate.admit(&ScanGate::key("globex", "t1"), ScanTrigger::Manual),
Admission::Run
);
}
@@ -663,228 +256,34 @@ 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, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
{
// The holding task ends without calling finish (panic / shutdown).
let _held = HeldTarget::new(&gate, key.clone());
}
assert_eq!(
gate.admit(&key, job(ScanTrigger::Manual, "r2")),
Admission::Run
);
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
}
#[tokio::test]
async fn a_disarmed_holder_leaves_the_state_to_finish() {
#[test]
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, job(ScanTrigger::Manual, "r1")),
Admission::Run
);
let _slot = gate.start(&key).await.unwrap();
assert_eq!(gate.admit(&key, ScanTrigger::Manual), Admission::Run);
HeldTarget::new(&gate, key.clone()).disarm();
// Still held: disarm does not release, finish does.
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"
);
assert_eq!(gate.admit(&key, ScanTrigger::Webhook), Admission::Coalesced);
}
#[tokio::test]
async fn slots_bound_how_many_scans_run_at_once() {
let gate = ScanGate::new(2);
let a = gate.slot(Priority::Background).await.unwrap();
let _b = gate.slot(Priority::Background).await.unwrap();
let a = gate.slot().await.unwrap();
let _b = gate.slot().await.unwrap();
// A third slot is not available until one is freed.
let third =
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
assert!(third.is_err(), "a third concurrent scan must wait");
drop(a);
let third =
tokio::time::timeout(Duration::from_millis(50), gate.slot(Priority::Person)).await;
let third = tokio::time::timeout(std::time::Duration::from_millis(50), gate.slot()).await;
assert!(third.is_ok(), "a freed slot is reused");
}
}
+1 -7
View File
@@ -7,7 +7,7 @@
use chrono::{TimeZone, Utc};
use compliance_agent::database::DatabasePool;
use compliance_agent::metering::{charge, month_summary, usage};
use compliance_agent::metering::{charge, usage};
use compliance_core::models::{
admit, Admission, PlanLimits, Refusal, RunCharge, PRUEFUNGEN_PER_PRUEFTAG,
};
@@ -79,11 +79,5 @@ 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
@@ -1,250 +0,0 @@
//! 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,71 +80,3 @@ 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();
}
-39
View File
@@ -121,20 +121,6 @@ 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>,
@@ -153,9 +139,6 @@ 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,
@@ -204,25 +187,3 @@ 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);
}
}
+2 -128
View File
@@ -186,79 +186,6 @@ 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> {
@@ -268,14 +195,10 @@ 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; a target the
/// customer swapped in comes before the oldest, one swapped out after the
/// newest.
/// active targets are included and the rest are extra.
///
/// # Arguments
///
@@ -292,12 +215,7 @@ 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| {
IncludedChoice::rank(a.choice)
.cmp(&IncludedChoice::rank(b.choice))
.then(a.created_at.cmp(&b.created_at))
.then(a.id.cmp(&b.id))
});
ordered.sort_unstable_by(|a, b| 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
@@ -327,53 +245,9 @@ 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.
+2 -3
View File
@@ -59,9 +59,8 @@ pub use license_policy::{
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
pub use mcp_token::{McpToken, McpTokenView};
pub use metering::{
admit, check_swap, split_included, Admission, BillableTarget, DayUsage, IncludedChoice,
MonthUsage, PlanLimits, Refusal, RunCharge, ScanAttribution, SwapRefusal, TargetBilling,
PRUEFUNGEN_PER_PRUEFTAG,
admit, split_included, Admission, BillableTarget, DayUsage, MonthUsage, PlanLimits, Refusal,
RunCharge, ScanAttribution, TargetBilling, PRUEFUNGEN_PER_PRUEFTAG,
};
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
pub use onboarding::{
-14
View File
@@ -665,18 +665,6 @@ 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",
@@ -718,8 +706,6 @@ 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,9 +70,6 @@ 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).
@@ -83,16 +80,6 @@ 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 {
@@ -167,18 +154,8 @@ 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
@@ -217,12 +194,6 @@ 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")]
@@ -455,7 +426,6 @@ 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(),
@@ -464,20 +434,9 @@ 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 {
+264 -189
View File
@@ -1,241 +1,231 @@
// 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.
// ═══════════════════════════════════════════════════════════════
// Graph Visualization — vis-network wrapper for Code Knowledge Graph
// Obsidian Control theme
// ═══════════════════════════════════════════════════════════════
(function () {
"use strict";
// 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",
// 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" },
};
var SHAPE = { file: "diamond", module: "square", folder: "hexagon" };
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)",
};
// 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;
const DEFAULT_NODE_COLOR = { bg: "#5e7291", border: "#3d506b", font: "#e4eaf4" };
const DEFAULT_EDGE_COLOR = "rgba(94, 114, 145, 0.3)";
var network = null;
var nodesDataset = null;
var edgesDataset = null;
var rawNodes = [];
var rawEdges = [];
var texts = { kinds: {}, edges: {}, program: "", plc: [], layout: "", entry: "", file: "" };
let network = null;
let nodesDataset = null;
let edgesDataset = null;
let rawNodes = [];
let rawEdges = [];
function token(name) {
return getComputedStyle(document.documentElement).getPropertyValue(name).trim();
function getNodeColor(kind) {
return NODE_COLORS[kind] || DEFAULT_NODE_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"),
};
function getEdgeColor(kind) {
return EDGE_COLORS[kind] || DEFAULT_EDGE_COLOR;
}
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;
}
// 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 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: isGroup ? node.name + "\n" + node.member_count : node.name,
title: title,
size: isGroup ? undefined : size,
value: isGroup ? node.member_count : undefined,
label: node.name,
title: `${node.kind}: ${node.qualified_name}\nFile: ${node.file_path}:${node.start_line}`,
size: size,
color: {
background: color,
border: node.is_entry_point ? colors.ring : color,
highlight: { background: color, border: colors.ring },
hover: { background: color, border: colors.ring },
background: color.bg,
border: color.border,
highlight: { background: color.bg, border: "#ffffff" },
hover: { background: color.bg, border: "#ffffff" },
},
font: {
color: colors.text,
size: isGroup ? 13 : 11,
face: colors.font,
strokeWidth: 3,
strokeColor: colors.halo,
color: color.font,
size: 10,
face: "'JetBrains Mono', monospace",
strokeWidth: 2,
strokeColor: "#060a13",
},
borderWidth: node.is_entry_point ? 3 : 1,
borderWidth: 1,
borderWidthSelected: 3,
shape: SHAPE[node.kind] || "dot",
shape: node.kind === "file" ? "diamond" : node.kind === "module" ? "square" : "dot",
// Store raw data for click handler
_raw: node,
};
}
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;
function toVisEdge(edge) {
const color = getEdgeColor(edge.kind);
const isDim = edge.kind === "contains" || edge.kind === "type_ref";
return {
id: edge.source + "|" + edge.target + "|" + edge.kind,
from: edge.source,
to: edge.target,
color: {
color: color,
highlight: colors.ring,
highlight: "#ffffff",
hover: color,
opacity: edge.kind === "bundle" ? 0.35 : 0.7,
},
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,
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,
};
}
// 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;
});
}
/**
* Draw `nodes` and `edges`, then select and show the nodes named in
* `focus` (may be empty). `labels` holds the UI texts. Called from Rust.
* Initialize or reload the graph visualization.
* Called from Rust via eval().
*/
window.__loadGraph = function (nodes, edges, labels, focus) {
window.__loadGraph = function (nodes, edges) {
var container = document.getElementById("graph-canvas");
if (!container) return;
texts = labels;
if (!container) {
console.error("[graph-viz] #graph-canvas not found");
return;
}
rawNodes = uniqueBy(nodes, function (n) { return n.qualified_name; });
rawEdges = uniqueBy(edges, function (e) { return e.source + "|" + e.target + "|" + e.kind; });
// 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;
});
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 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 large = rawNodes.length > LARGE;
var options = {
// 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 = {
nodes: {
scaling: {
min: 12,
max: 56,
label: { enabled: true, min: 22, max: 48, drawThreshold: 5, maxVisible: 30 },
},
font: { color: "#e4eaf4", size: 10 },
scaling: { min: 8, max: 35 },
},
edges: {
font: { color: "#5e7291", size: 9, strokeWidth: 0 },
selectionWidth: 3,
},
physics: {
enabled: true,
solver: "forceAtlas2Based",
forceAtlas2Based: {
gravitationalConstant: -60,
centralGravity: 0.008,
springLength: 110,
gravitationalConstant: -80,
centralGravity: 0.005,
springLength: 120,
springConstant: 0.04,
damping: 0.6,
avoidOverlap: 0.5,
damping: 0.5,
avoidOverlap: 0.6,
},
stabilization: { enabled: true, iterations: large ? 300 : 1000, updateInterval: 25 },
maxVelocity: 40,
stabilization: {
enabled: true,
iterations: 1500,
updateInterval: 25,
},
maxVelocity: 50,
minVelocity: 0.75,
},
interaction: {
hover: true,
tooltipDelay: 200,
hideEdgesOnDrag: large,
hideEdgesOnZoom: large,
keyboard: { enabled: true, bindToWindow: false },
hideEdgesOnDrag: false,
hideEdgesOnZoom: false,
multiselect: false,
navigationButtons: false,
keyboard: { enabled: true },
},
layout: {
improvedLayout: uniqueNodes.length < 300,
},
layout: { improvedLayout: rawNodes.length < 300 },
};
if (network) network.destroy();
network = new vis.Network(container, { nodes: nodesDataset, edges: edgesDataset }, options);
// Destroy previous instance
if (network) {
network.destroy();
}
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) return;
var raw = rawNodes.find(function (n) { return n.qualified_name === params.nodes[0]; });
if (raw && window.__onNodeClick) window.__onNodeClick(JSON.stringify(raw));
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));
}
}
});
// 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";
@@ -243,35 +233,120 @@
network.on("stabilizationProgress", function (params) {
var pct = Math.round((params.iterations / params.total) * 100);
if (progressFill) progressFill.style.width = pct + "%";
if (pctLabel) pctLabel.textContent = texts.layout + " · " + pct + " %";
if (progressFill) {
progressFill.style.width = pct + "%";
}
if (pctLabel) {
pctLabel.textContent = pct + "% — computing layout";
}
});
network.once("stabilizationIterationsDone", function () {
network.on("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"; }, 600);
setTimeout(function () {
overlay.style.display = "none";
}, 900);
}
// 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 || []);
// 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,
},
});
});
console.log(
"[graph-viz] Loaded " + nodes.length + " nodes, " + edges.length + " edges"
);
};
/** Select the named nodes that are drawn and show them. */
/**
* 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).
*/
window.__highlightNodes = function (qualifiedNames) {
if (!network || !nodesDataset) return;
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" } });
network.selectNodes(qualifiedNames);
if (qualifiedNames.length > 0) {
network.fit({
nodes: qualifiedNames,
animation: { duration: 500, easingFunction: "easeInOutQuad" },
});
}
};
/** Fit the whole drawing in view. */
/**
* 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.
*/
window.__fitGraph = function () {
if (!network) return;
network.fit({ animation: { duration: 400, easingFunction: "easeInOutQuad" } });
network.fit({
animation: { duration: 400, easingFunction: "easeInOutQuad" },
});
};
})();
+155 -160
View File
@@ -101,18 +101,6 @@
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. */
@@ -1774,6 +1762,85 @@ 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;
@@ -1787,9 +1854,23 @@ tbody tr:last-child td {
.graph-stab-progress-fill {
height: 100%;
width: 0%;
background: var(--accent);
background: linear-gradient(90deg, var(--accent), #e040fb);
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 {
@@ -1804,11 +1885,16 @@ tbody tr:last-child td {
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 240px;
height: 100%;
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;
@@ -1819,6 +1905,37 @@ 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;
@@ -1832,96 +1949,40 @@ tbody tr:last-child td {
letter-spacing: 0.04em;
}
/* 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-function, .node-kind-method {
background: var(--accent-muted);
color: var(--accent);
border: 1px solid var(--border-accent);
}
.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-struct, .node-kind-class {
background: rgba(224, 64, 251, 0.12);
color: #e040fb;
border: 1px solid rgba(224, 64, 251, 0.2);
}
.graph-legend li {
display: inline-flex;
align-items: center;
gap: 6px;
.node-kind-enum {
background: rgba(255, 176, 32, 0.12);
color: #ffb020;
border: 1px solid rgba(255, 176, 32, 0.2);
}
.graph-legend-dot {
width: 9px;
height: 9px;
border-radius: 50%;
background: var(--kind);
.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-entry {
background: transparent;
border: 2px solid var(--text-primary);
.node-kind-module {
background: rgba(255, 138, 61, 0.12);
color: #ff8a3d;
border: 1px solid rgba(255, 138, 61, 0.2);
}
.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);
.node-kind-file {
background: var(--success-bg);
color: var(--success);
border: 1px solid color-mix(in oklch, var(--success) 30%, transparent);
}
/* Code Inspector Panel */
@@ -2182,23 +2243,12 @@ 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;
}
@@ -4732,21 +4782,6 @@ 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;
@@ -4762,21 +4797,6 @@ 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;
}
@@ -4896,30 +4916,6 @@ 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));
@@ -5178,7 +5174,6 @@ 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 {},
// The code graph opens from its card on the target page.
#[redirect("/graph", || Route::TargetsPage {})]
#[route("/graph")]
GraphIndexPage {},
#[route("/graph/:repo_id")]
GraphExplorerPage { repo_id: String },
#[route("/graph/:repo_id/impact/:finding_id")]
@@ -1,121 +0,0 @@
//! 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,22 +1,17 @@
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 || {
@@ -35,20 +30,18 @@ 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 graph-kind-{node_kind}", {tx::node_kind(&node_kind, &node_language).get(lang)} }
span { class: "node-label-badge node-kind-{node_kind}", "{node_kind}" }
span { class: "code-inspector-node-name", "{node_name}" }
if start_line > 0 && end_line > 0 {
span { class: "code-inspector-lines", "{tx::LINES.get(lang)} {start_line}–{end_line}" }
span { class: "code-inspector-lines", "L{start_line}–L{end_line}" }
}
}
button {
class: "btn btn-ghost btn-sm code-inspector-close",
r#type: "button",
title: tx::CLOSE.get(lang),
"aria-label": tx::CLOSE.get(lang),
class: "btn-sm code-inspector-close",
onclick: move |_| on_close.call(()),
"\u{2715}"
}
@@ -86,10 +79,12 @@ pub fn CodeInspector(
}
},
Some(None) => rsx! {
div { class: "code-inspector-empty", {tx::FILE_FAILED.get(lang)} }
div { class: "code-inspector-empty",
"Could not load file content."
}
},
None => rsx! {
div { class: "loading", {tx::FILE_LOADING.get(lang)} }
div { class: "loading", "Loading file..." }
},
}
}
@@ -1,7 +1,6 @@
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;
@@ -29,6 +28,5 @@ 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,7 +108,9 @@ 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.is_open()));
.is_some_and(|list| {
list.is_empty() || list.iter().any(|r| r.status == ScanRunStatus::Running)
});
if waiting {
runs.restart();
}
@@ -159,8 +161,7 @@ fn run_transitions(
let mut finished = Vec::new();
for run in runs {
let id = run.id.map(|id| id.to_hex()).unwrap_or_default();
// A queued run counts: it may finish before it is ever seen running.
if run.status.is_open() {
if run.status == ScanRunStatus::Running {
running.push(id);
} else if seen_running.contains(&id) && !finished_here.contains(&id) {
finished.push(id);
@@ -175,20 +176,13 @@ 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;",
{started_label.get(lang)} ": {started}"
{scans::STARTED.get(lang)} ": {started}"
}
if let Some(finished) = finished {
span { style: "font-size: 0.9em;",
@@ -219,11 +213,6 @@ 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)}
@@ -461,7 +450,6 @@ 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),
@@ -554,24 +542,6 @@ 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);
@@ -1,87 +0,0 @@
//! 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,24 +93,6 @@ 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 {
@@ -213,16 +195,6 @@ 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,19 +367,6 @@ 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",
@@ -883,56 +870,6 @@ 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.",
@@ -1141,36 +1078,6 @@ 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",
@@ -1296,14 +1203,6 @@ 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");
}
}
}
@@ -3172,8 +3071,6 @@ pub mod compliance {
"rust" => "Rust",
"csharp" => "C#",
"swift" => "Swift",
"structured_text" => "Structured Text",
"plcopen" => "PLCopen XML",
other => other,
}
}
@@ -4536,413 +4433,3 @@ 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,16 +11,6 @@ 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)]
@@ -28,6 +18,12 @@ 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>,
@@ -52,42 +48,6 @@ 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}"))
@@ -120,19 +80,32 @@ 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> {
// 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 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()))?;
let body: FileContentResponse = resp
.json()
.await
@@ -142,12 +115,13 @@ 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"))
.await?
.query(&[("q", query.as_str()), ("limit", "50")])
.send()
.await
.map_err(|e| ServerFnError::new(e.to_string()))?;
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 body: SearchResponse = resp
.json()
.await
@@ -1,51 +0,0 @@
//! 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,7 +12,6 @@ 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,15 +113,11 @@ pub async fn set_archive_password(
}
/// Whether any of `targets` (as the list endpoint returns them) has a scan
/// running or waiting for a slot, so a page showing them should keep
/// refreshing.
/// running, so a page showing them should keep refreshing.
pub fn any_scan_running(targets: &[serde_json::Value]) -> bool {
targets.iter().any(|t| {
matches!(
t["last_scan"]["status"].as_str(),
Some("running" | "queued")
)
})
targets
.iter()
.any(|t| t["last_scan"]["status"].as_str() == Some("running"))
}
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
@@ -549,22 +545,6 @@ 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> {
@@ -717,10 +697,8 @@ 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.clone(), fresh, busy]));
assert!(any_scan_running(&[idle, queued]));
assert!(any_scan_running(&[idle, fresh, busy]));
}
#[test]
@@ -7,13 +7,11 @@ 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, graph as graph_tx};
use crate::i18n::{format_count, format_time, use_lang};
use crate::i18n::texts::{common, findings as tx};
use crate::i18n::{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.
@@ -59,24 +57,6 @@ 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 {
@@ -214,21 +194,6 @@ 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)} }
+344 -391
View File
@@ -1,350 +1,253 @@
//! 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::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)),
}
}
}
use crate::infrastructure::graph::{fetch_graph, search_nodes, trigger_graph_build};
#[component]
pub fn GraphExplorerPage(repo_id: String) -> Element {
let lang = use_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 }
"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 can_write = crate::components::no_access::use_can_write();
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() }
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()
}
});
// 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 selected = use_signal(|| Option::<Value>::None);
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 search_query = use_signal(String::new);
let mut search_results = use_signal(Vec::<Value>::new);
let mut search_results = use_signal(Vec::<serde_json::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);
// 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()?,
))
});
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);
use_effect(move || {
let drawn = drawn.read();
let Some(drawn) = drawn.as_ref().filter(|d| !d.nodes.is_empty()) else {
let ready = graph_ready();
if !ready {
return;
};
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 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);
});
});
// 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()
let sel = selected_node();
let sel_file = sel
.as_ref()
.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"
};
.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;
rsx! {
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(", ")} }
}
}
if repo_id.is_empty() {
div { class: "card",
p { "Select a repository to view its code graph." }
}
if can_write {
div { class: "target-head-actions",
} else {
// Toolbar
div { class: "graph-toolbar",
if can_write {
button {
class: "btn btn-secondary",
class: "btn btn-primary",
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, tx::BUILD_STARTED.get(lang)),
Ok(_) => toasts.push(ToastType::Success, "Graph build triggered"),
Err(e) => toasts.push(ToastType::Error, e.to_string()),
}
building.set(false);
view.set(None);
graph.restart();
graph_data.restart();
});
}
},
Icon { icon: BsArrowRepeat, width: 14, height: 14 }
if building() { {tx::BUILDING.get(lang)} } else { {tx::REBUILD.get(lang)} }
if building() { "Building..." } else { "Build Graph" }
}
}
}
}
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: "search",
placeholder: tx::SEARCH.get(lang),
"aria-label": tx::SEARCH.get(lang),
r#type: "text",
placeholder: "Search nodes...",
value: "{search_query}",
oninput: {
let rid = repo_id.clone();
move |e: FormEvent| {
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 {
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 {
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(); }");
});
}
});
}
}
},
}
@@ -352,22 +255,29 @@ pub fn GraphExplorerPage(repo_id: String) -> Element {
div { class: "search-suggestions",
for node in search_results() {
{
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();
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();
rsx! {
button {
div {
class: "search-suggestion-item",
r#type: "button",
onclick: move |_| {
reveal(vec![node_id(&node).to_string()]);
selected.set(Some(node.clone()));
let nc = node_clone.clone();
let qn = qname.clone();
selected_node.set(Some(nc));
inspector_open.set(true);
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", {tx::node_kind(&kind, &language).get(lang)} }
span { class: "search-suggestion-path", "{path}" }
span { class: "search-suggestion-kind", "{kind}" }
span { class: "search-suggestion-path", "{file_path}" }
}
}
}
@@ -375,134 +285,177 @@ pub fn GraphExplorerPage(repo_id: String) -> Element {
}
}
}
button {
class: "btn btn-secondary btn-sm",
class: "btn-sm",
onclick: move |_| {
let _ = document::eval("window.__fitGraph && window.__fitGraph();");
spawn(async move {
let _ = document::eval("if (window.__fitGraph) { window.__fitGraph(); }");
});
},
Icon { icon: BsArrowsFullscreen, width: 14, height: 14 }
{tx::FIT.get(lang)}
"Fit View"
}
}
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.
// Hidden input for JS → Rust node click communication
input {
id: "graph-node-click-data",
r#type: "hidden",
value: "",
oninput: move |e| {
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)));
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);
}
Err(_) => selected.set(Some(node)),
}
},
}
div { class: layout_class,
// 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: "file-tree-panel",
div { class: "file-tree-header", h4 { {tx::FILES.get(lang)} } }
div { class: "file-tree-header",
h4 { "Files" }
}
div { class: "file-tree-search",
input {
r#type: "search",
placeholder: tx::FILTER_FILES.get(lang),
"aria-label": tx::FILTER_FILES.get(lang),
r#type: "text",
placeholder: "Filter files...",
value: "{file_filter}",
oninput: move |e| file_filter.set(e.value()),
}
}
div { class: "file-tree-content",
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",
})));
},
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);
});
},
}
}
}
}
if let Some(node) = sel {
// Left-center: Code Inspector (between file tree and graph)
if inspector_open() && selected_node().is_some() {
CodeInspector {
repo_id: repo_id.clone(),
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),
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);
},
}
}
// Right: Graph Canvas
div { class: "graph-canvas-panel",
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" }
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 { class: "graph-stab-pct", id: "graph-stab-pct", {tx::LAYOUT.get(lang)} }
}
} 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." }
}
}
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)} }
// 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(\", \")}" }
}
}
}
}
}
}
}
}
}
/// 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)}
}
}
}
@@ -0,0 +1,94 @@
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..." }
},
}
}
}
@@ -1,479 +0,0 @@
//! 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"] })));
}
}
+85 -122
View File
@@ -1,144 +1,107 @@
//! 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 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::components::page_header::PageHeader;
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 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) }
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 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()
};
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 {
span { class: "target-figure", "{blast_radius}" }
span { class: "target-figure-label", {tx::BLAST_RADIUS.get(lang)} }
}
}
}
}
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}" }
}
code { "{step}" }
}
}
}
}
}
}
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(),
onclick: move |_| { navigator().go_back(); },
Icon { icon: BsArrowLeft, width: 16, height: 16 }
{tx::BACK.get(lang)}
"Back"
}
}
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}" } }
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)" }
}
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" }
}
}
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", " → " }
}
}
}
}
}
}
}
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(\"-\")}" } }
}
}
}
}
}
}
},
Some(None) => rsx! {
p { "No impact analysis data available for this finding." }
},
None => rsx! {
p { "Loading impact analysis..." }
},
}
}
}
+2 -1
View File
@@ -8,7 +8,7 @@ pub mod dast_targets;
pub mod finding_detail;
pub mod findings;
pub mod graph_explorer;
pub(crate) mod graph_view;
pub mod graph_index;
pub mod impact_analysis;
pub mod issues;
pub mod mcp_servers;
@@ -31,6 +31,7 @@ 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;
+1 -48
View File
@@ -8,7 +8,6 @@ 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;
@@ -21,11 +20,10 @@ 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, compliance::language_name, kinds, targets as tx};
use crate::i18n::texts::{common, 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,
@@ -113,8 +111,6 @@ 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);
@@ -158,9 +154,6 @@ 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 {}
@@ -229,16 +222,6 @@ 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",
@@ -271,36 +254,6 @@ 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,7 +15,6 @@ 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};
@@ -133,7 +132,6 @@ pub fn TargetsPage() -> Element {
title: tx::TITLE.get(lang),
description: tx::SUBTITLE.get(lang),
}
UsageSummary {}
div { class: "page-actions",
if can_write {
-6
View File
@@ -13,10 +13,6 @@ chrono = { workspace = true }
tracing = { workspace = true }
tokio = { workspace = true }
mongodb = { workspace = true }
thiserror = { workspace = true }
# Decoding source files: BOM sniffing, UTF-16, Windows-1252
encoding_rs = { workspace = true }
# Tree-sitter parsing
tree-sitter = "0.24"
@@ -24,8 +20,6 @@ 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"
-170
View File
@@ -1,170 +0,0 @@
//! 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_graph::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::*;
use crate::test_tree::utf16;
#[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-graph-no-such-file.cs");
assert!(matches!(read_source(&missing), Err(SourceTextError::Io(_))));
}
}
+1 -2
View File
@@ -29,8 +29,7 @@ pub fn extract_chunks(
for node in nodes {
let file = repo_path.join(&node.file_path);
// Decoded as the graph's parser read it, so every node has its lines.
let source = match crate::encoding::read_source(&file) {
let source = match std::fs::read_to_string(&file) {
Ok(s) => s,
Err(_) => continue,
};
+220 -107
View File
@@ -1,143 +1,257 @@
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> {
/// Run Louvain community detection on the code graph.
/// Returns the number of communities detected.
/// Mutates node community_id in place.
pub fn detect_communities(code_graph: &CodeGraph) -> 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;
if node_count == 0 {
return 0;
}
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();
// 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);
}
// 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();
// 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;
}
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 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;
}
let remove_cost = edges_to[current as usize]
- (totals[current as usize] - node_degree) * node_degree / m2;
let mut best = current;
// 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 in &touched {
if candidate == current {
for (&candidate_comm, &edges_to_candidate) in &comm_edges {
if candidate_comm == current_comm {
continue;
}
let gain = edges_to[candidate as usize]
- totals[candidate as usize] * node_degree / m2
- remove_cost;
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 = candidate;
best_comm = candidate_comm;
}
}
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;
if best_comm != current_comm {
community.insert(node, best_comm);
improved = true;
}
}
if !improved {
break;
}
// 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;
}
}
// 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;
// Apply to community map
for c in community.values_mut() {
if let Some(&new_id) = comm_remap.get(c) {
*c = new_id;
}
*c = *slot;
}
community
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
}
/// 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.
pub fn detect_communities(code_graph: &CodeGraph) -> u32 {
count(&louvain(code_graph))
}
/// Detect communities and write each node's community into `community_id`.
///
/// # Returns
///
/// The number of communities detected.
/// Apply community assignments back to code nodes
pub fn apply_communities(code_graph: &mut CodeGraph) -> u32 {
let communities = louvain(code_graph);
for node in &mut code_graph.nodes {
if let Some(&community) = node.graph_index.and_then(|gi| communities.get(gi as usize)) {
node.community_id = Some(community);
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;
}
}
}
let communities = count(&communities);
info!(communities, "Community detection complete");
communities
// 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
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);
}
}
}
next_id
}
#[cfg(test)]
@@ -145,7 +259,6 @@ 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 {
+122 -367
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, CodeNodeKind, GraphBuildRun, GraphBuildStatus,
CodeEdge, CodeEdgeKind, CodeNode, 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::apply_communities;
use super::community::detect_communities;
use super::impact::ImpactAnalyzer;
/// Walk up the qualified-name hierarchy to find the closest ancestor
@@ -39,141 +39,6 @@ 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,
@@ -203,56 +68,38 @@ 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");
let parsed = self.parser_registry.parse_directory(
// Phase 1: Parse all files
let parse_output = 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))
}
/// 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 2: Build petgraph
let code_graph = self.build_petgraph(parse_output)?;
let community_count = apply_communities(&mut code_graph);
// Phase 3: Run community detection
let community_count = detect_communities(&code_graph);
// 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);
}
// 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();
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.into_iter().map(str::to_string).collect();
build_run.file_count = Some(files);
build_run.entry_point_count = Some(entry_points);
build_run.languages_parsed = languages;
build_run.status = GraphBuildStatus::Completed;
build_run.completed_at = Some(Utc::now());
@@ -285,15 +132,19 @@ 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 = index.resolve(&edge.target, &edge.file_path);
let resolved = self.resolve_edge_target(&edge.target, &node_map);
if let (Some(&src), Some(tgt)) = (source_idx, resolved) {
// A node's weight is its qualified name.
edge.target = graph[tgt].clone();
let resolved_name = node_map
.iter()
.find(|(_, &idx)| idx == tgt)
.map(|(name, _)| name.clone());
if let Some(name) = resolved_name {
edge.target = name;
}
graph.add_edge(src, tgt, edge.kind.clone());
resolved_edges.push(edge);
}
@@ -349,6 +200,70 @@ 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)
@@ -392,62 +307,61 @@ 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 result = resolve(
&["src/main.rs::foo", "src/main.rs::bar"],
"src/main.rs::foo",
);
assert_eq!(result.as_deref(), Some("src/main.rs::foo"));
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"]);
}
#[test]
fn test_resolve_edge_target_short_name_match() {
let result = resolve(&["src/main.rs::foo", "src/main.rs::bar"], "foo");
assert_eq!(result.as_deref(), Some("src/main.rs::foo"));
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"]);
}
#[test]
fn test_resolve_edge_target_method_match() {
let result = resolve(&["src/main.rs::MyStruct::do_thing"], "do_thing");
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);
assert!(result.is_some());
}
#[test]
fn test_resolve_edge_target_self_method() {
let result = resolve(&["src/main.rs::MyStruct::process"], "self.process");
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);
assert!(result.is_some());
}
#[test]
fn test_resolve_edge_target_no_match() {
let result = resolve(&["src/main.rs::foo"], "nonexistent");
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);
assert!(result.is_none());
}
#[test]
fn test_resolve_edge_target_empty_map() {
let result = resolve(&[], "anything");
let engine = GraphEngine::new(1000);
let node_map = HashMap::new();
let result = engine.resolve_edge_target("anything", &node_map);
assert!(result.is_none());
}
#[test]
fn test_resolve_edge_target_dot_notation() {
let result = resolve(&["src/app.js.handler"], "handler");
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);
assert!(result.is_some());
}
@@ -590,127 +504,13 @@ mod tests {
#[test]
fn test_cross_file_resolution_with_module_path() {
let result = resolve(
&["src/config.rs::load_config", "src/main.rs::main"],
"crate::config::load_config",
);
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);
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(&[
@@ -729,49 +529,4 @@ 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));
}
}
-4
View File
@@ -1,13 +1,9 @@
#![allow(clippy::only_used_in_recursion)]
#![allow(clippy::too_many_arguments)]
pub mod encoding;
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
@@ -1,389 +0,0 @@
//! 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
@@ -1,208 +0,0 @@
//! 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
@@ -1,461 +0,0 @@
//! 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,10 +1,5 @@
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;
+12 -94
View File
@@ -3,25 +3,13 @@ use std::path::Path;
use compliance_core::error::CoreError;
use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput};
use tracing::{debug, info, warn};
use tracing::{debug, info};
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>>,
@@ -36,8 +24,6 @@ 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();
@@ -89,36 +75,15 @@ impl ParserRegistry {
Ok(Some(output))
}
/// Parse all supported files in a directory tree.
///
/// Each file is decoded by [`crate::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.
/// Parse all supported files in a directory tree
pub fn parse_directory(
&self,
dir: &Path,
repo_id: &str,
graph_build_id: &str,
max_nodes: u32,
) -> Result<DirectoryParse, CoreError> {
let mut combined = DirectoryParse::default();
) -> Result<ParseOutput, CoreError> {
let mut combined = ParseOutput::default();
let mut node_count: u32 = 0;
self.walk_directory(
@@ -131,17 +96,9 @@ 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.output.nodes.len(),
edges = combined.output.edges.len(),
unreadable_files = combined.unreadable_files,
nodes = combined.nodes.len(),
edges = combined.edges.len(),
"Directory parsing complete"
);
@@ -156,7 +113,7 @@ impl ParserRegistry {
graph_build_id: &str,
max_nodes: u32,
node_count: &mut u32,
combined: &mut DirectoryParse,
combined: &mut ParseOutput,
) -> Result<(), CoreError> {
let entries = std::fs::read_dir(dir).map_err(|e| {
CoreError::Graph(format!("Failed to read directory {}: {e}", dir.display()))
@@ -205,19 +162,15 @@ impl ParserRegistry {
// Use relative path from base
let rel_path = path.strip_prefix(base).unwrap_or(&path);
let source = match crate::encoding::read_source(&path) {
Ok(text) => text,
Err(error) => {
debug!(file = %rel_path.display(), %error, "Source file not readable");
combined.unreadable_files += 1;
continue;
}
let source = match std::fs::read_to_string(&path) {
Ok(s) => s,
Err(_) => continue, // Skip binary/unreadable files
};
if let Some(output) = self.parse_file(rel_path, &source, repo_id, graph_build_id)? {
*node_count += output.nodes.len() as u32;
combined.output.nodes.extend(output.nodes);
combined.output.edges.extend(output.edges);
combined.nodes.extend(output.nodes);
combined.edges.extend(output.edges);
}
}
}
@@ -337,41 +290,6 @@ 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,69 +363,6 @@ 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::*;
@@ -633,3 +570,66 @@ 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
@@ -1,73 +0,0 @@
//! 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()
}
+480
View File
@@ -0,0 +1,480 @@
# Active testing: a throwaway copy first, the live system later
**Status:** proposed design for the user to decide (t83) · 2026-11-06, revised
2026-11-07 after the registry review. Nothing is enabled by this note.
**Not published:** `docs/design/` is excluded from the documentation site.
## Summary
Production runs with `PW_FEATURES=source_only`. That switches off DAST, the
LLM-driven pentest, the ICS probe and OpenPLC provision-and-test for the whole
deployment. The Leistungsbeschreibung (LB 1.0.2, §4 Abs. 3) excludes active tests.
Production can import results from a test someone else ran (#337, #349).
**The proposal: active tests run against a throwaway copy by default.**
1. **The Prüfumgebung (default).** We build the customer's application from the repository
Prüfwerk already has. It is built and started in a short-lived, isolated sandbox. While
building, the only way out is a package mirror; while testing, the network is internal
only. DAST and the automated pentest run against that copy only. Then everything is
thrown away. We never send traffic to a customer's server.
2. **The code graph steers the test.** Routes taken from the code say what to test,
instead of a crawl guessing. A static finding that an entry point reaches is tried
against the copy. It is then reported as *confirmed exploitable* or *possible*.
3. **Live testing is not part of phase 1.** It would cover what only the live system
shows: TLS, headers, exposed ports, WAF, cloud configuration. It needs written
authorisation, our source IPs, rate limits and complaint handling, and that load is
out of proportion for now. The analysis below (L1–L7) stays so it can be decided later.
4. **Price per Testtag**, a unit like the Prüftag: up to 3 runs of one target on one day.
A run costs a build plus a sandbox, so it can't be unlimited. The customer books a
Testtag only by starting a run, and can cap them per month.
**Why the copy first:**
| | Prüfumgebung (copy) | Live system |
| --- | --- | --- |
| Authorisation | The code is the customer's and already ours to process under the Prüfwerk contract; the copy runs on our hardware. No third party is touched. | Written authorisation, proof of ownership, a time window |
| Traffic from our IPs to the internet | none | yes: complaints, abuse reports, WAF blocks |
| Aggressive tests (writes, fuzzing, LLM-chosen URLs) | allowed: the copy is thrown away | restricted to non-destructive at a low rate |
| Logged-in tests | easy: the Prüfprofil brings test users | needs the customer's credentials (unused today, see L4) |
| What it can't show | the real deployment (TLS, WAF, reverse proxy, cloud, real data) | that is exactly what it shows |
| Hard part | **building it** (see [What qualifies](#what-qualifies-and-what-doesnt)) | legal and operations |
## What exists today
All of this was checked against `origin/main` (168cbe9).
### Engines
| Engine | What it does | Where |
| --- | --- | --- |
| DAST | Our own Rust code; there is no ZAP or Nuclei inside (those are import formats only). Steps: recon, a depth-limited crawler, then five agents in parallel: SQL injection, XSS, auth bypass, SSRF, API fuzzer. Targets: web app, REST API, GraphQL. | `compliance-dast` |
| Automated pentest | An LLM tool loop: at most 50 iterations, 30 min by default, at most 5 sessions at once. Tools: the DAST agents, plus TLS, headers, cookies, CSP, CORS, DNS/DMARC, a rate-limit tester, an OpenAPI parser and a Chrome browser over CDP. | `compliance-agent/src/pentest`, `compliance-dast/src/tools` |
| ICS probe | Read-only: Modbus/TCP function codes 0x03, 0x01 and 0x2B/0x0E; the OPC UA HEL/ACK handshake; EtherNet/IP ListIdentity; a TCP connect scan of nine OT ports; 5 s per probe. | `werkbank-exec/src/ics` |
| OpenPLC provision-and-test | Starts a throwaway OpenPLC container per scan, loads the ST program extracted from the customer's PLC project, and runs DAST and the ICS probe against it. | `werkbank-exec/src/plc` |
### The sandbox base we already have
`werkbank-exec/src/plc/provision.rs` (306 lines) is the nearest thing to a Prüfumgebung:
- **Container hardening:**
- one container per scan, named uniquely;
- `--memory`, `--cpus` and `--pids-limit 512`;
- `--security-opt no-new-privileges` and `--stop-timeout 5`;
- no `-p`, so no port is ever published to the host.
- **Cleanup:**
- an owner label;
- a reaper that removes instances older than twice their maximum lifetime.
- **Tests:** the `docker` argument list comes from pure functions, so it is unit-tested
without Docker.
- **The DAST guard:** it runs DAST with `NetGuard::allow_private()`, but only against
that instance (`werkbank-exec/src/plc/mod.rs:253`).
**What it does not do, and a Prüfumgebung needs:**
| Gap | Today | Needed |
| --- | --- | --- |
| Network isolation | The container joins **the agent's own network** (`--network cfg.network`), so it can reach the agent, Mongo and the internet. | Building: outbound only through a package mirror (below). Testing: a fresh `docker network create --internal` per run, holding only the copy, its dependencies and the test tools. Nothing else is reachable, and nothing leaves. |
| Building | It runs a ready-made OpenPLC image. | Build the customer's image from their Dockerfile or Compose file (below). |
| Several containers | one | A Compose project: the app plus a database, cache and so on. |
| Readiness | A fixed Modbus/WebVisu port. | A health URL from the Prüfprofil, with a deadline. |
| Isolation strength | A plain Docker container, started through a Docker socket mount, which is root on the host. | Customer code is untrusted. A run needs a VM boundary (Kata/Firecracker or gVisor `runsc`), on a host that is **not** a platform node. |
| Gate | `PLC_RUNTIME_ENABLED` | The existing `PW_ALLOW_UNTRUSTED_CODE_EXEC` policy (`compliance-core/src/exec_policy.rs:83`) already says tenant code may run only "on a single-tenant or sandboxed deployment". The multi-tenant agent keeps it off. |
**Where the Prüfumgebung runs.** It runs on a Breakpilot-hosted **Werkbank runner**: a
dedicated host outside the platform nodes, not inside the agent. The Werkbank contract
already has the right shape. The control plane queues a job, and a runner leases it,
provisions, runs and posts results (`handlers/werkbank_jobs.rs`). `JobType` already has
`Dast` and `Pentest` (`compliance-core/src/models/werkbank.rs:25-33`), but nothing creates
them yet; `enqueue` only builds PLC provision jobs. On production the Werkbank path is
off.
The same runner design also serves a customer who wants the Prüfumgebung inside their own
network. That is the on-premises Werkbank direction already decided.
### What the graph does today
- **The pentest reads the graph.** `pentest/context.rs:93-140` loads up to 50 nodes
with `is_entry_point: true` and links SAST findings to them by file path. The prompt
gets a "Code Entry Points (Knowledge Graph)" section (`prompt_builder.rs:205-271`).
- **Reachability exists.** `compliance-graph/src/graph/impact.rs:30-70` searches
backwards from a finding to the entry points that reach it. It also builds call chains
of up to 10 hops, and forward blast radius. Triage puts this in its prompt
(`llm/triage.rs:317-344`).
- **Entry points are coarse.**
- Rust: `main`, `#[test]`, `#[tokio::main]` and every `pub` function.
- JavaScript: every exported function.
- Python: `main`, `__main__` and the decorators `app.route`, `app.get` and `app.post`.
- TypeScript: its own rule.
- There is no HTTP route model (method, path, parameters), and C and C# are not parsed
(that is t82).
- **No exploitability status.** Nothing marks a finding as confirmed exploitable. A
DAST finding and a SAST finding on the same weakness are not linked.
### Tests
| Area | Tests | In CI |
| --- | --- | --- |
| net_guard, guarded_net | 10 + 5 unit tests | yes |
| ICS probe, OpenPLC provisioning | 13 + 10 unit tests | yes |
| Pentest orchestrator, prompt builder | 7 + 20 unit tests | yes |
| DAST agents and tools | about 63 unit tests | **no**: `compliance-dast` is missing from CI's clippy and test steps (`ci.yml:128-164`) |
| DAST API | 2 integration tests | yes |
| A full run against a real target | none; there is no `pw-target` | no |
## Proposed design
### 1. The Prüfumgebung (default)
**The Prüfprofil.** The customer describes how to start their application. It can be a
file in the repository (`.breakpilot/pruefprofil.yml`) or a form on the target page:
- **compose:** the path of the Compose file, or a Dockerfile with a port.
- **service:** the container and port under test.
- **health:** a URL that answers 200 once the app is up.
- **seed:** an optional command that loads test data.
- **users:** test accounts with roles, which makes logged-in testing possible.
- **env:** configuration and **test secrets only**. The profile says so, and a check
refuses values that look like real keys, using the secret scanner we already run.
**A run, in outline:**
- The control plane queues a Werkbank job with the target's code and Prüfprofil.
- A Breakpilot-hosted runner builds the copy, waits for its health URL, runs DAST or the
automated pentest against it, posts the findings back, and throws everything away.
- The detailed runner and isolation design is a follow-up, written and reviewed with
infra before any code.
### The build needs the network
Building a Dockerfile already runs customer code: every `RUN` step is a command from the
repository. It also downloads packages (npm, NuGet, pip, Maven, apt). So the build is as
untrusted as the test and gets the same protection:
- **The same VM sandbox** as the test, on the same runner, never on a platform node.
- **Outbound traffic only through a package mirror.** The build network reaches a
pull-through proxy for the public registries (npm, NuGet, PyPI, Maven Central, Debian
and Alpine mirrors, Docker Hub through Harbor) and nothing else. No other egress: no
DNS to the outside, no Git clones from arbitrary hosts, no `curl` to the internet. A
build that needs anything else fails, and the build log says which host it tried.
- **The test phase stays internal-only.** The built images move to a fresh internal
network without the mirror; the test tools join it there.
- **Base images** come through the same Harbor proxy, so they are cached and logged.
**Private package feeds** need real credentials, and the Prüfprofil forbids those. Two
options:
1. **Not supported in phase 1** (recommended). A build that needs a private feed fails
as the customer's input, and the Probelauf shows it for free. The customer can vendor
the packages into the repository or publish a build image to us instead.
2. **Later: a feed token stored separately.** It is stored in the tenant's secret store,
not in the Prüfprofil; write-only from the portal, so nobody reads it back after
saving; scoped read-only to that one feed; and injected only into the build step as a
BuildKit secret, never into the image, the test phase or a log. The mirror allowlist
then gets that feed's host for this tenant only.
### Where the data lives and when it is deleted
The runner host is a new place where customer code is processed, so:
- **Location:** in Germany. If it is not our own hardware, the provider goes on the AVV's
subprocessor list before the first customer run.
- **TOM:** the runner (VM isolation, egress only through the mirror, deletion after each
run, access only for the platform team) is added to the technical and organisational
measures.
- **During a run:** the checkout, images, containers, volumes and networks exist only on
the runner, on the run's own disk, and are removed at the end of the run, with a reaper
for leftovers. Nothing is pushed to a registry.
- **After a run, on the platform** (in the tenant's database, like scan results):
- the findings;
- the build log and the start log, capped in size and passed through the secret
scanner before storing.
They are deleted with the target or the tenant, or after a retention period to be set
(proposed: logs 90 days, findings like other findings).
- **The runner keeps no customer data** after a run. Its own logs carry run ids and
counts, never code, paths or repository names.
### What qualifies and what doesn't
| Target | Prüfumgebung | Notes |
| --- | --- | --- |
| Web app or API with a working Dockerfile or Compose file and a Prüfprofil | **yes** | Phase 1. Linux containers only. |
| ASP.NET on .NET 6 or later | yes, with a Dockerfile | Routes from code need the C# parser (t82). |
| ASP.NET on .NET Framework (Windows only) | **no** | It would need Windows containers, which we don't offer. |
| PLC programs (ST, PLCopen) | yes, through the existing OpenPLC Werkbank path | Already built; off on production. |
| Firmware | only through emulation | Not in phase 1; a separate decision. |
| Desktop HMI, mobile apps | no | Static analysis only. |
| A repository with no Dockerfile or Compose file | no | We don't guess how to build it. The target page says what is missing. |
**Building is the hard part, and the note says so plainly.** Most customer repositories
don't start cleanly from a fresh checkout. They depend on a database, configuration or
private packages. Phase 1 therefore takes only what the customer has made startable: a
working Dockerfile or Compose file plus a Prüfprofil. A free **Probelauf** lets the
customer find this out before paying (see the next section).
### When the build fails
The Testtag is what is billed, not the run. A run **counts** unless it failed through our
fault: a finished run (also one stopped at its time limit, with what it found) and a run
that failed on the customer's input both count.
| Cause | Example | Counts toward the 3 runs |
| --- | --- | --- |
| Ours | The runner fails, our time limit is hit through our own load, a toolchain we claim to support is missing | **no**; the customer can start another run |
| The customer's input | The Dockerfile doesn't build, the health URL never answers, the Prüfprofil is missing or wrong | **yes**, as with t72's "failures on the customer's input count" |
| Probelauf | Only build and start, then a health check, with no test | **no**, and it books no Testtag, so the customer can fix their profile for free |
**A Testtag is charged unless all of its runs failed through our fault** (the user's
decision, 2026-11-07). A run that fails on the customer's input counts and makes the
Testtag chargeable; the free Probelauf is how a customer checks their build first.
The run's page shows which of these it was, with the build log, so the customer can fix
their side.
### Limits per run
- **Wall clock:** about 15 min to build and start, about 30 min to test, 60 min in total.
At the limit the run stops and keeps what it found.
- **Resources:** a fixed CPU, memory and disk budget per run (proposed: 4 CPUs, 8 GB,
20 GB), sized together with infra.
- **Concurrency:** one run per tenant at a time, and a fixed number per runner.
- **Cleanup:** nothing survives a run: images, containers, networks and data are removed
every time, and a reaper removes leftovers.
### 2. The graph steers the test
| Step | Exists | New |
| --- | --- | --- |
| Entry points in the pentest prompt | yes (`pentest/context.rs`) | – |
| From a finding back to the entry points that reach it, with call chains | yes (`graph/impact.rs`, used in triage) | – |
| **HTTP routes from code** (method, path, parameters) | no; entry points are coarse | Route extractors per framework: ASP.NET attributes and minimal APIs (after the C# parser of t82), Express, Flask/FastAPI, axum. An OpenAPI file in the repository counts too. The test goes through exactly these routes instead of crawling. |
| **Confirm a static finding** | no | For a SAST finding whose entry point is a route, the matching DAST check runs against that route on the copy (SQL injection for CWE-89, XSS for CWE-79, SSRF for CWE-918 and so on). |
| **Exploitability status** on a finding | no | `confirmed exploitable` (the copy showed it), `possible` (reachable, not shown) or `not tested`. The finding list and the CRA view can sort by it. |
The benefit: fewer false alarms in front of the customer, and a smaller LLM budget,
because the pentest starts from known routes and known suspects instead of exploring.
### 3. Live testing (not in phase 1)
Live testing covers what a copy can't show: TLS, security headers, exposed ports, WAF
behaviour and cloud configuration.
**Recommendation: leave it out of phase 1 entirely** and decide later. The legal work
(authorisation clause, ownership proof), the complaint handling and the operations
(published IPs, abuse contact, kill switches) are a fixed load that a small add-on
price doesn't carry: the earlier suggestion of 29 € a month with 5 runs is too low for it.
The analysis stays here so the decision can be made on it later. If it comes, it is off
by default and switched on per tenant.
**Conditions:**
- **Written authorisation:** the customer owns the target or is authorised in writing by
the owner. Draft clause below, for legal review.
- **Proof of ownership:** a DNS record or file token, checked before every run.
- **A time window** set by the customer, inside which runs may start.
- **Our source IPs**, published so customers can allowlist them, with reverse DNS and an
info page naming Breakpilot.
- **Rate limits:** low request rates, non-destructive checks only, a short time limit.
- **Complaint handling:** an abuse contact, a runbook, and kill switches globally, per
tenant, per target and per run.
**What has to change in the code before live testing** (from the survey; none of it is
reachable on production today):
| # | Gap | Size |
| --- | --- | --- |
| L1 | No ownership check exists. | M |
| L2 | Once enabled, every live-URL target would get DAST and the ICS probe every 6 hours (`change.rs:86`). Live tests must run only on request. | S |
| L3 | The target's rate limit is ignored (a fixed 100 ms in `dast.rs:172`); there is no page cap, no timeout and no overall deadline; DAST runs outside the scan concurrency limit. | M |
| L4 | `auth_config` is stored but unused, so live tests are unauthenticated. | M (later) |
| L5 | The pentest's browser and the URLs the LLM picks are not held to the target host. | M |
| L6 | `allow_destructive` is enforced only for DELETE. | S |
| L7 | The DAST and pentest routes check no role. | S |
These also apply to the Prüfumgebung, except L1 and L2:
- `compliance-dast` has to join CI;
- the routes need a role check (L7);
- the caps in L3 keep a run inside its budget.
**Draft clause** (live add-on only), for legal review:
> Der Kunde versichert, dass er Inhaber des angegebenen Prüfobjekts ist oder vom Inhaber
> schriftlich ermächtigt wurde, aktive Sicherheitsprüfungen daran zu beauftragen. Er
> beauftragt Breakpilot, das Prüfobjekt im angegebenen Zeitfenster von den in der
> Leistungsbeschreibung genannten Quell-IP-Adressen aus automatisiert zu prüfen. Der
> Kunde sorgt für eine aktuelle Sicherung und informiert betroffene Dritte, etwa seinen
> Hosting-Anbieter. Er stellt Breakpilot von Ansprüchen Dritter frei, die auf einer
> fehlenden oder unzutreffenden Ermächtigung beruhen.
### 4. Entitlement per tenant
`PW_FEATURES=source_only` stays as the global kill switch. Below it, the tenant registry
decides per tenant, as in t72:
- The entitlement check already takes an `addon` parameter that every caller passes as
`None` (`registry.rs:369`).
- The add-on name: `pruefumgebung` (and `live_testing`, only if that is decided later).
- The dashboard reads features only from the global `/version` handshake. It needs a
tenant-scoped answer: add the add-ons to the usage response of t72
(`GET /api/v1/metering/usage`).
- **Booking:** a Testtag is booked only when the customer starts a run by hand, on the
first run of that target on that day. Never automatically, never from a schedule or
a scan, and a Probelauf never books one.
- **A monthly cap set by the customer** in the portal, like `prueftag_cap`: at most N
Testtage per calendar month, none by default. At the cap, starting a run that would
book a new Testtag is refused with a message; runs on a Testtag already booked that day
still work.
- Usage events, counts only, never names:
- `testtag.booked`, key `testtag:{tenant}:{target}:{YYYY-MM-DD}`, with the number of
runs that count at the end of the day (0, when every run failed through our fault,
means not charged);
- `probelauf.run`, a count only, with no ERP item.
- Recommendation: an active run does **not** count against the t72 Prüfung quota. It is
metered on its own.
- **Testtage in the plans** (a decision for the user). Suggestion: none included in
Standard and Business in phase 1, until we have measured the cost per run on stage;
Enterprise by arrangement. A later option is N per month in Business (for example 2).
### 5. Cost and price
**Our cost per run** is an estimate, to be measured on stage:
- **Compute:**
- building and starting the copy takes about 10–15 min on 4 CPUs;
- a test takes about 30 min, with the copy and the test tools together on about 4 CPUs;
- in total about 2.5–3 CPU-hours and up to 8 GB of memory per run.
- **On a dedicated runner host** (assumption, to confirm with infra: 16 cores and 64 GB
at about 100–150 € per month), that is about 4 runs at once:
- full use: well under 0.10 € of compute per run;
- 10 % use: about 0.30–0.60 € per run.
- **The automated pentest** adds LLM time on our own model: up to 50 rounds, roughly
0.5–1 million tokens per session. That is GPU time, not money per token; measure it on
stage.
- **Fixed costs** are lower than for live testing (no complaints, no legal exposure to
third parties). They remain the runner host, support for failed builds, and the
Prüfprofil help.
**Price suggestion**, set against the 9,99 € Prüftag and the 5,99 € extra target:
ERP item codes follow the ERP scheme:
| Item | Contents | Suggestion |
| --- | --- | --- |
| `CRA-CSA-CLD-TST` (Testtag) | The Prüfumgebung for one target on one Berlin day, with up to 3 runs (DAST or automated pentest), so a customer can fix and test again the same day; not charged when all of its runs failed through our fault | 24,99 € per Testtag |
| Probelauf | Build and start only, no test | free; no ERP item, counted by `probelauf.run` |
Only if live testing is decided later (codes reserved, prices to be set then; the earlier
29 € a month with 5 runs is too low for the fixed load):
| Item | Contents |
| --- | --- |
| `CRA-CSA-CLD-LIV` | Live add-on, monthly, per tenant |
| `CRA-CSA-CLD-LRN` | An extra live run beyond those included |
A Testtag mirrors the Prüftag that customers already know. It caps our cost per booking,
and it fits how fixes really go: test, fix, test again.
## Test plan on stage
1. **pw-target:** our own deliberately vulnerable web app with a Dockerfile and a
Prüfprofil. Ideally one in ASP.NET, which also tests the C# routes from t82, and one
in Node.
2. **A repository with Compose:** an open-source app with a database in its Compose
file, to prove that several containers build and start.
3. **Probelauf:** for both, it passes; with a broken Dockerfile it fails visibly, as the
customer's fault, books no Testtag and is not charged.
4. **Runs:** DAST and the automated pentest on both. The known vulnerabilities of
pw-target are the baseline; add a nightly fixture that compares against it.
5. **Graph steering:** the routes found in code match pw-target's real routes. A planted
SQL injection found by SAST comes back as `confirmed exploitable`, and an
unreachable one as `possible`.
6. **Limits and cleanup:** the run stops at its time limit; nothing is left behind after
a run; a second run of the same tenant waits.
7. **Entitlement and metering:**
- a tenant without the add-on is refused;
- a Testtag is booked once, by the first run started by hand, and allows 3 runs;
- a run that fails on our side doesn't use one of the 3; a Testtag whose runs all
failed on our side is reported with 0 and not charged;
- a run that fails on a broken Dockerfile counts, and its Testtag is charged;
- at the monthly cap, a run that would book a new Testtag is refused;
- the usage events carry counts only.
8. **Measure** minutes, CPU, memory and LLM tokens per run, for the price.
9. **Build network:** a build that fetches from the package mirror passes; one that
tries any other host fails, and its log names the host.
10. **Live add-on:** not in phase 1; only after the user decides on it. It would run
against pw-target under a public stage name, reachable only from stage's own
address, and cover the ownership check, the time window, the rate limits and the
kill switches.
Production stays on `source_only` until the user gives the go.
## Decisions for the user
1. **The Prüfumgebung as the default** for active tests. Recommended.
2. **Live testing out of phase 1** entirely, to be decided later on the L1–L7 analysis.
Recommended.
3. **Phase 1 scope:** web apps and APIs with a Dockerfile or Compose file plus a
Prüfprofil; PLC through the existing OpenPLC path; firmware later.
4. **Private package feeds:** not supported in phase 1 (recommended), or a separately
stored, write-only feed token used only during the build.
5. **Charging** (decided 2026-11-07): billed per Testtag; failures on our side don't use
one of the 3 runs, failures on the customer's input do; a Testtag is charged unless
all of its runs failed through our fault; the Probelauf is free and books nothing.
6. **Price:** the Testtag (`CRA-CSA-CLD-TST`) at 24,99 €.
7. **Testtage in the plans:** none in Standard and Business in phase 1, Enterprise by
arrangement (suggestion); or N per month in Business.
8. **Retention:** build and start logs 90 days (proposed), findings like other findings.
9. **The runner host:** in Germany; own hardware or a provider that goes on the AVV's
subprocessor list. With infra.
10. **Order:**
1. `compliance-dast` into CI, the role check and the caps (L3, L7);
2. the runner, build-network and isolation design with infra, plus the AVV and TOM
entries;
3. the Prüfprofil;
4. routes from code (after t82);
5. the exploitability status;
6. the stage test plan.
## Needed from the registry, ERP and LB side
**For the registry and ERP:**
- The add-on `pruefumgebung` (`live_testing` only if decided later).
- The ERP item `CRA-CSA-CLD-TST` (Testtag). `CRA-CSA-CLD-LIV` and `CRA-CSA-CLD-LRN` are
reserved for a later live add-on. The Probelauf has no ERP item.
- A customer-set monthly Testtag cap in the portal, like `prueftag_cap`, none by default.
- The usage events `testtag.booked` (with the number of runs that count) and
`probelauf.run`, counts only.
**For the AVV and TOM:** the runner host as a place of processing (Germany), and its
provider as a subprocessor if it is not our own hardware.
**LB wording** for the version that ships phase 1. It replaces the exclusion in §4
Abs. 3 for tenants who booked the add-on:
> **Prüfumgebung (Zusatzleistung).** Für gebuchte Mandanten baut Prüfwerk die Anwendung
> des Kunden aus dem bereitgestellten Quellcode in einer abgeschotteten, nur für diese
> Prüfung erzeugten Umgebung in Deutschland auf und prüft sie dort aktiv auf
> Schwachstellen, unter anderem SQL-Injection, Cross-Site-Scripting, Umgehung der
> Zugriffskontrolle und Server-Side Request Forgery. Systeme des Kunden oder Dritter
> werden dabei nicht angesprochen; beim Aufbau werden Pakete ausschließlich über einen
> Paket-Spiegel aus öffentlichen Quellen bezogen. Voraussetzung ist ein lauffähiges
> Dockerfile oder eine Compose-Datei sowie ein Prüfprofil mit Testdaten; produktive
> Daten oder Zugangsdaten dürfen nicht enthalten sein. Die Umgebung wird nach jeder
> Prüfung vollständig gelöscht.
>
> Abgerechnet wird je **Testtag**. Ein Testtag umfasst bis zu drei Prüfläufe eines
> Prüfobjekts an einem Kalendertag (Europe/Berlin) und wird nur gebucht, wenn der Kunde
> einen Prüflauf startet, nie automatisch. Ein Prüflauf, der aus Gründen fehlschlägt,
> die Breakpilot zu vertreten hat, wird nicht auf die drei Prüfläufe angerechnet. Ein
> Testtag wird nicht berechnet, wenn alle seine Prüfläufe aus Gründen fehlschlagen, die
> Breakpilot zu vertreten hat. Der Kunde kann im Portal
> eine monatliche Höchstzahl an Testtagen festlegen. Ein Probelauf (nur Aufbau und
> Start) ist kostenfrei. Die Prüfung ist automatisiert und ersetzt keinen manuellen
> Penetrationstest.
**For a later live add-on** (only if decided), a starting point:
> **Live-Prüfung (Zusatzleistung).** Auf gesonderte Beauftragung prüft Prüfwerk ein vom
> Kunden benanntes, erreichbares System, dessen Inhaberschaft der Kunde nachgewiesen
> hat, im vereinbarten Zeitfenster von den unten genannten Quell-IP-Adressen aus mit
> nicht-destruktiven Prüfungen (u. a. TLS, Sicherheits-Header, offene Dienste).
> Steuerungen und industrielle Protokolle werden nicht aus dem Rechenzentrum geprüft.