feat(metering): included and extra targets, and why each scan ran (t72) (#927)
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 6s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 5m4s
CI / Deploy Dashboard (push) Successful in 6m57s
CI / Deploy Agent (push) Successful in 9m4s

First part of t72, Prüfwerk metering (LB §2 Abs. 4–5, §7). This PR records what a scan is metered by. Nothing is counted or enforced yet; counters, the 6-per-day limit and the Prüftag cap come in the next PR.

## What changes

- **Included vs extra targets.** Each target stores `billing: included | extra`.
  - The oldest active targets by `created_at` are included, up to the plan's `limits.included_targets` from the registry entitlement. The rest are extra.
  - The split is refreshed before each scan and when a target is created. Archiving an included target moves the oldest extra one up.
  - A plan without that key includes every target, which is every plan until the registry sends the limits. So this PR changes nothing for existing tenants.
- **Run attribution.** Each run records an `attribution`:
  - `request`: the customer started it (dashboard or API).
  - `support`: staff started it.
  - `change`: something the customer changed, i.e. new commits, other uploads, or a live URL.
  - `rescan`: only the Prüfwerk build changed.

  For scheduled and webhook scans it's set where change detection decides, so our rescan after an update is no longer counted as a customer change. `uploads_changed` / `content_changed` don't depend on `UPLOAD_CHANGE_SKIP`.
- **`chargeable`.** Says whether the run counts once it completes:
  - a request always counts;
  - a change counts only on an extra target;
  - rescans and support scans never count.

  `scan.completed` now carries `attribution` and `counted` as properties.
- **Dashboard.** The targets list shows a "Zusätzliches Prüfobjekt" badge on an extra target.

## Tests

- **Core:** the included/extra split, attribution, and the contract table of what counts.
- **Agent:** `content_changed`/`uploads_changed`, the `included_targets` limit, reading a stored target's billing, and a Mongo integration test (`tests/target_billing.rs`): the oldest are included, and an extra target moves up on archive.

Not built locally, per the CI-only rule; CI is the compiler here.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Sharang Parnerkar <30073382+mighty840@users.noreply.github.com>
Reviewed-on: #927
This commit was merged in pull request #927.
This commit is contained in:
sharangandSharang Parnerkar committed 2026-11-06 14:30:07 +00:00
1 parent c28f9e186b
commit ce786b716b
16 files changed
+752 -30

No files matched your search

+51 -3
View File
@@ -153,6 +153,46 @@ impl ComplianceAgent {
});
}
/// Store which of the tenant's targets are the plan's included ones and
/// which are extra (t72), from the plan's `included_targets`. Without a
/// registry every target is included. Best-effort: when the plan cannot
/// be read or the targets not updated, the stored split stays.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
pub async fn refresh_billing(
&self,
tenant_id: &str,
db: &crate::database::Database,
) -> Vec<(
mongodb::bson::oid::ObjectId,
compliance_core::models::TargetBilling,
)> {
let included = match &self.registry {
None => None,
Some(registry) => match registry.check_entitlement(tenant_id, None, None).await {
Ok(check) => check.included_targets(),
Err(e) => {
tracing::warn!(tenant_id, "plan not read, target billing kept: {e}");
return Vec::new();
}
},
};
match crate::metering::assign_billing(db, included).await {
Ok(changes) => {
if !changes.is_empty() {
tracing::info!(tenant_id, changed = changes.len(), "target billing updated");
}
changes
}
Err(e) => {
tracing::warn!(tenant_id, "target billing not updated: {e}");
Vec::new()
}
}
}
/// Scan a target, through the [`ScanGate`]: at most `SCAN_CONCURRENCY` scans
/// run at once, and a request for a target that is already being scanned is
/// coalesced — it becomes the one pending follow-up that this task runs next,
@@ -238,16 +278,24 @@ 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());
// Whether this target is included or extra decides whether its scan
// counts (t72).
self.refresh_billing(tenant_id, &db).await;
let started = chrono::Utc::now();
let scanned = orchestrator.run_target(target_id, trigger.clone()).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 scanned && trigger != compliance_core::models::ScanTrigger::Support {
if outcome.scanned && trigger != compliance_core::models::ScanTrigger::Support {
self.emit_usage(
tenant_id,
"scan.completed",
format!("scan:{tenant_id}:{target_id}:{}", started.timestamp()),
serde_json::json!({ "target_id": target_id, "trigger": format!("{trigger:?}") }),
serde_json::json!({
"target_id": target_id,
"trigger": format!("{trigger:?}"),
"attribution": outcome.attribution,
"counted": outcome.chargeable,
}),
);
}
self.notify_new_findings(tenant_id, target_id, &db, started);
+1
View File
@@ -17,6 +17,7 @@ pub mod ingest;
pub mod license_conclusions;
pub mod lifecycle;
pub mod llm;
pub mod metering;
pub mod pentest;
pub mod pipeline;
pub mod rag;
+122
View File
@@ -0,0 +1,122 @@
//! Which of a tenant's targets are the plan's included ones (t72).
//!
//! The oldest active targets are included, up to the plan's
//! `included_targets`; every other active target is extra. The split is
//! stored on each target ([`OnboardedTarget::billing`]) and brought up to
//! date before each scan and when a target is created, so archiving an
//! included target moves the oldest extra one up.
//!
//! [`OnboardedTarget::billing`]: compliance_core::models::OnboardedTarget::billing
use chrono::{DateTime, Utc};
use futures_util::TryStreamExt;
use mongodb::bson::{doc, oid::ObjectId, Document};
use compliance_core::models::{split_included, BillableTarget, TargetBilling};
use crate::database::Database;
use crate::error::AgentError;
/// Store the billing of the tenant's active targets for a plan that
/// includes `included` targets.
///
/// # Arguments
///
/// * `db` - The tenant's database.
/// * `included` - How many targets the plan includes; `None` is unlimited.
///
/// # Returns
///
/// The targets whose billing changed, with their new billing.
///
/// # Errors
///
/// Returns an error if the targets cannot be read or updated.
pub async fn assign_billing(
db: &Database,
included: Option<u32>,
) -> Result<Vec<(ObjectId, TargetBilling)>, AgentError> {
// Only the three fields the split needs: a whole target holds its
// artifacts, and older documents may lack fields the model requires.
let docs: Vec<Document> = db
.raw_collection("onboarded_targets")
.find(doc! { "archived_at": null })
.projection(doc! { "_id": 1, "created_at": 1, "billing": 1 })
.await?
.try_collect()
.await?;
let targets: Vec<BillableTarget<ObjectId>> = docs.iter().filter_map(billable).collect();
let changes = split_included(&targets, included);
for wanted in [TargetBilling::Included, TargetBilling::Extra] {
let ids: Vec<ObjectId> = changes
.iter()
.filter(|(_, billing)| *billing == wanted)
.map(|(id, _)| *id)
.collect();
if ids.is_empty() {
continue;
}
let value =
mongodb::bson::to_bson(&wanted).map_err(|e| AgentError::Other(e.to_string()))?;
db.onboarded_targets()
.update_many(
doc! { "_id": { "$in": ids } },
doc! { "$set": { "billing": value } },
)
.await?;
}
Ok(changes)
}
/// A stored target as the split sees it; `None` without an id. A target
/// without a creation time counts as the oldest, one without a billing as
/// included (stored before metering).
fn billable(target: &Document) -> Option<BillableTarget<ObjectId>> {
Some(BillableTarget {
id: target.get_object_id("_id").ok()?,
created_at: target
.get_datetime("created_at")
.map_or(DateTime::<Utc>::MIN_UTC, |at| at.to_chrono()),
billing: target
.get("billing")
.and_then(|b| mongodb::bson::from_bson(b.clone()).ok())
.unwrap_or_default(),
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_stored_target_reads_with_defaults_for_what_it_lacks() {
// Arrange
let id = ObjectId::new();
let at = mongodb::bson::DateTime::from_millis(1_700_000_000_000);
let extra = doc! { "_id": id, "created_at": at, "billing": "extra" };
let old = doc! { "_id": id };
// Act
let extra = billable(&extra);
let old = billable(&old);
// Assert
assert_eq!(
extra,
Some(BillableTarget {
id,
created_at: at.to_chrono(),
billing: TargetBilling::Extra,
})
);
assert_eq!(
old,
Some(BillableTarget {
id,
created_at: DateTime::<Utc>::MIN_UTC,
billing: TargetBilling::Included,
})
);
assert_eq!(billable(&doc! { "name": "no id" }), None);
}
}
+43
View File
@@ -70,6 +70,22 @@ pub fn uploads_allow_git_skip(target: &OnboardedTarget) -> bool {
upload_skip_enabled() && uploads_match(target)
}
/// Whether a file uploaded to `target` changed since its last completed
/// scan: it has uploads, and they are not the ones that scan read. For
/// metering (t72), independent of [`upload_skip_enabled`].
pub fn uploads_changed(target: &OnboardedTarget) -> bool {
target.artifacts.iter().any(is_upload) && !uploads_match(target)
}
/// Whether the customer changed what `target`, which has no git repository,
/// gives a scan to read since its last completed one: it was never scanned,
/// its uploads changed, or it has a live URL (the service changes on its
/// own). A scheduled scan that runs without such a change is our own rescan
/// (t72).
pub fn content_changed(target: &OnboardedTarget) -> bool {
target.live_url().is_some() || target.last_scan.is_none() || uploads_changed(target)
}
/// Whether the uploads of `target` are the ones its last completed scan read.
fn uploads_match(target: &OnboardedTarget) -> bool {
target
@@ -219,4 +235,31 @@ mod tests {
let unhashed = target(vec![upload("a", None)]);
assert_eq!(upload_inputs(&unhashed), None);
}
#[test]
fn only_a_change_the_customer_made_is_a_content_change() {
// Arrange: a target scanned once, by an older build.
let mut t = target(vec![upload("a", Some("h1"))]);
assert!(content_changed(&t), "never scanned");
t.last_scan = Some(LastScan {
build: "0.0.1+old".into(),
inputs: upload_inputs(&t),
});
// Act / Assert: a new build alone is no change of the customer's.
assert!(!content_changed(&t));
assert!(!uploads_changed(&t));
t.artifacts[0].content_hash = Some("h2".into());
assert!(content_changed(&t), "another upload");
assert!(uploads_changed(&t));
let mut live = target(vec![Artifact::live_url("https://pump.example.com")]);
live.last_scan = Some(LastScan {
build: build_id(),
inputs: None,
});
assert!(content_changed(&live), "a live service changes on its own");
assert!(!uploads_changed(&live), "nothing uploaded");
}
}
+104 -27
View File
@@ -37,6 +37,17 @@ pub struct GraphContext {
pub impacts: Vec<compliance_core::models::graph::ImpactAnalysis>,
}
/// How a scan of an onboarded target went, for its usage event (t72).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TargetScanOutcome {
/// `false` when it was skipped because nothing changed (#465).
pub scanned: bool,
/// Why it ran; `None` when it was skipped.
pub attribution: Option<ScanAttribution>,
/// Whether it counts toward the customer's usage.
pub chargeable: bool,
}
/// What a scan left out of its working copy before the first stage, as
/// paths relative to the tree.
#[derive(Debug, Default)]
@@ -174,25 +185,34 @@ impl PipelineOrchestrator {
// new to find; one a person started always runs (after a changed
// setting it can find something else), a new Prüfwerk build scans
// once (#465), and so does a file uploaded to the target since.
if !trigger.started_by_person()
&& repo.uploads_allow_skip
&& repo.last_scanned_build.as_deref()
== Some(crate::pipeline::change::build_id().as_str())
&& !GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?
{
tracing::info!("[{repo_id}] No new commits, skipping scan");
self.skip_stage(
if !trigger.started_by_person() {
let new_commits =
GitOps::has_new_commits(&repo_path, repo.last_scanned_commit.as_deref())?;
if !new_commits
&& repo.uploads_allow_skip
&& repo.last_scanned_build.as_deref()
== Some(crate::pipeline::change::build_id().as_str())
{
tracing::info!("[{repo_id}] No new commits, skipping scan");
self.skip_stage(
scan_run_id,
SkippedStage::new(
"change_detection",
SkipCode::NoNewCommits,
"no new commits since the last scan",
),
)
.await;
// Findings deferred by the catch-up's cap still get their issues.
self.catch_up_unchanged(repo, &repo_id).await;
return Ok(0);
}
self.attribute_run(
scan_run_id,
SkippedStage::new(
"change_detection",
SkipCode::NoNewCommits,
"no new commits since the last scan",
),
ScanAttribution::detected(trigger, new_commits || repo.changed_besides_commits),
repo.billing,
)
.await;
// Findings deferred by the catch-up's cap still get their issues.
self.catch_up_unchanged(repo, &repo_id).await;
return Ok(0);
}
// Submodules are part of what the product ships (a HAL, an RTOS).
@@ -1125,8 +1145,9 @@ impl PipelineOrchestrator {
///
/// # Returns
///
/// Whether it scanned: `false` when it was skipped because nothing changed
/// since the last completed scan (a scheduled or webhook scan, #465).
/// Whether it scanned (`false` when it was skipped because nothing changed
/// since the last completed scan, a scheduled or webhook scan, #465), and
/// how it is metered (t72).
///
/// # Errors
///
@@ -1135,7 +1156,7 @@ impl PipelineOrchestrator {
&self,
target_id: &str,
trigger: ScanTrigger,
) -> Result<bool, AgentError> {
) -> Result<TargetScanOutcome, AgentError> {
let oid = mongodb::bson::oid::ObjectId::parse_str(target_id)
.map_err(|e| AgentError::Other(e.to_string()))?;
let target = self
@@ -1145,7 +1166,13 @@ impl PipelineOrchestrator {
.await?
.ok_or_else(|| AgentError::Other(format!("Onboarded target {target_id} not found")))?;
let scan_run = ScanRun::new(target_id.to_string(), trigger.clone());
let mut scan_run = ScanRun::new(target_id.to_string(), trigger.clone());
// A scan a person started is attributed from the start; change
// detection attributes the others (t72).
if let Some(attribution) = ScanAttribution::of_person(&trigger) {
scan_run.attribution = Some(attribution);
scan_run.chargeable = attribution.chargeable(target.billing);
}
let insert = self.db.scan_runs().insert_one(&scan_run).await?;
let scan_run_id = insert
.inserted_id
@@ -1224,15 +1251,53 @@ impl PipelineOrchestrator {
}
}
result?;
let skipped = self
let run = self
.db
.scan_runs()
.count_documents(doc! {
"_id": &insert.inserted_id,
"skipped_stages.stage": "change_detection",
})
.await?;
Ok(skipped == 0)
.find_one(doc! { "_id": &insert.inserted_id })
.await?
.ok_or_else(|| AgentError::Other(format!("scan run of {target_id} not found")))?;
Ok(TargetScanOutcome {
scanned: !run
.skipped_stages
.iter()
.any(|s| s.stage == "change_detection"),
attribution: run.attribution,
chargeable: run.chargeable,
})
}
/// Record why the run `scan_run_id` runs and whether it counts, on a
/// target billed as `billing` (t72). A run with several code artifacts
/// is attributed once per artifact; a change found in any of them wins
/// over our rescan. Best-effort, like [`Self::skip_stage`].
async fn attribute_run(
&self,
scan_run_id: &str,
attribution: ScanAttribution,
billing: TargetBilling,
) {
let Ok(oid) = mongodb::bson::oid::ObjectId::parse_str(scan_run_id) else {
return;
};
let Ok(value) = mongodb::bson::to_bson(&attribution) else {
return;
};
let change = mongodb::bson::to_bson(&ScanAttribution::Change).unwrap_or_default();
if let Err(e) = self
.db
.scan_runs()
.update_one(
doc! { "_id": oid, "attribution": { "$ne": change } },
doc! { "$set": {
"attribution": value,
"chargeable": attribution.chargeable(billing),
} },
)
.await
{
tracing::warn!(scan_run_id, "scan run not attributed: {e}");
}
}
/// Run the applicable scans for a target. For a code target this reuses the
@@ -1277,6 +1342,18 @@ impl PipelineOrchestrator {
.await;
return Ok(0);
}
// A git target is attributed where its commits are compared.
if !trigger.started_by_person() && !has_git {
self.attribute_run(
scan_run_id,
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:
// a completed run must not read as "we looked and found nothing".
@@ -45,6 +45,11 @@ pub struct RepoView {
/// Whether the target's uploaded files let a scheduled scan without new
/// commits be skipped ([`crate::pipeline::change::uploads_allow_git_skip`]).
pub uploads_allow_skip: bool,
/// Whether the customer changed something besides the commits since the
/// last completed scan: an uploaded file, or a live URL to probe (t72).
pub changed_besides_commits: bool,
/// How the target is billed, for whether its scan counts (t72).
pub billing: compliance_core::models::TargetBilling,
/// Whether the tree is read as Yocto layers (its recipe inventory): it
/// was classified as one, or the target is a Yocto target. Set by the
/// caller after classification; `false` from [`Self::from_target`].
@@ -84,6 +89,9 @@ impl RepoView {
findings_count: target.findings_count,
managed: target.source_repo.is_some(),
uploads_allow_skip: crate::pipeline::change::uploads_allow_git_skip(target),
changed_besides_commits: target.live_url().is_some()
|| crate::pipeline::change::uploads_changed(target),
billing: target.billing,
yocto_layers: false,
exclude_paths: target.scan_config.exclude_paths.clone(),
build_outputs: Vec::new(),
+28
View File
@@ -63,6 +63,15 @@ impl EntitlementCheck {
pub fn member_blocked(&self) -> bool {
!self.allowed && self.reason.as_deref() == Some(MEMBER_BLOCKED)
}
/// How many targets the tenant's plan includes (t72):
/// `limits.included_targets`. `None` when the plan sets no limit (no
/// limits, the key missing or null), so every target is included.
pub fn included_targets(&self) -> Option<u32> {
let n = self.limits.as_ref()?.get("included_targets")?.as_u64()?;
// A count beyond u32 is no limit in practice.
Some(u32::try_from(n).unwrap_or(u32::MAX))
}
}
#[derive(Debug, Clone, Deserialize)]
@@ -634,6 +643,25 @@ pub fn scheduler_runs_for(status: &str) -> bool {
mod tests {
use super::*;
#[test]
fn the_plan_sets_how_many_targets_are_included() {
let check = |limits: serde_json::Value| -> EntitlementCheck {
serde_json::from_value(serde_json::json!({ "allowed": true, "limits": limits }))
.expect("an entitlement answer")
};
assert_eq!(
check(serde_json::json!({ "included_targets": 5 })).included_targets(),
Some(5)
);
assert_eq!(
check(serde_json::json!({ "included_targets": null })).included_targets(),
None
);
assert_eq!(check(serde_json::json!({})).included_targets(), None);
assert_eq!(check(serde_json::Value::Null).included_targets(), None);
}
#[test]
fn ladder_filter() {
for s in ["active", "trial", "demo", "warning", ""] {
+9
View File
@@ -26,6 +26,15 @@ pub async fn create_target(
) -> Result<OnboardedTarget, AgentError> {
let res = db.onboarded_targets().insert_one(&target).await?;
target.id = res.inserted_id.as_object_id();
// A target beyond the plan's included ones is extra from the start (t72).
if let Some((_, billing)) = agent
.refresh_billing(tenant_id, db)
.await
.into_iter()
.find(|(id, _)| Some(*id) == target.id)
{
target.billing = billing;
}
let target_id = target.id.map(|id| id.to_hex()).unwrap_or_default();
agent.emit_usage(
tenant_id,
+82
View File
@@ -0,0 +1,82 @@
//! The oldest active targets are the plan's included ones; the rest are
//! extra, and an extra one moves up when an included one is archived (t72).
//! Runs against a live Mongo (`TEST_MONGODB_URI`) and skips cleanly without
//! one.
#![allow(clippy::expect_used, clippy::unwrap_used)]
use chrono::{Duration, Utc};
use compliance_agent::database::{Database, DatabasePool};
use compliance_agent::metering::assign_billing;
use compliance_core::models::{OnboardedTarget, TargetBilling, TargetType};
use mongodb::bson::{doc, oid::ObjectId};
const TENANT: &str = "target-billing";
async fn billing(db: &Database, id: ObjectId) -> TargetBilling {
db.onboarded_targets()
.find_one(doc! { "_id": id })
.await
.unwrap()
.unwrap()
.billing
}
#[tokio::test]
async fn the_oldest_targets_are_included_and_an_extra_one_moves_up() {
let uri = std::env::var("TEST_MONGODB_URI")
.unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into());
let prefix = format!(
"billing_{}",
&uuid::Uuid::new_v4().simple().to_string()[..10]
);
let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else {
eprintln!("SKIP target_billing: no MongoDB reachable at {uri}");
return;
};
let db = pool.for_tenant_id(TENANT).await.unwrap();
// Arrange: three targets, created a day apart.
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]);
// Act: a plan with two included targets.
let changes = assign_billing(&db, Some(2)).await.unwrap();
// Assert: only the newest is extra, and it is the one change.
assert_eq!(changes, vec![(newest, TargetBilling::Extra)]);
assert_eq!(billing(&db, oldest).await, TargetBilling::Included);
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
assert_eq!(billing(&db, newest).await, TargetBilling::Extra);
assert!(
assign_billing(&db, Some(2)).await.unwrap().is_empty(),
"nothing changes a second time"
);
// Act: the oldest is archived.
db.onboarded_targets()
.update_one(
doc! { "_id": oldest },
doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } },
)
.await
.unwrap();
assign_billing(&db, Some(2)).await.unwrap();
// Assert: the extra one moved up.
assert_eq!(billing(&db, newest).await, TargetBilling::Included);
// Act / Assert: a plan without a limit includes every target.
assign_billing(&db, Some(0)).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Extra);
assign_billing(&db, None).await.unwrap();
assert_eq!(billing(&db, middle).await, TargetBilling::Included);
pool.drop_tenant(TENANT).await.ok();
}
+262
View File
@@ -0,0 +1,262 @@
//! Metering (t72): whether a target is one of the plan's included targets,
//! why a scan ran, and whether that scan counts toward the customer's usage.
//!
//! The contract (Leistungsbeschreibung Prüfwerk §2 Abs. 4–5, §7): change-driven
//! scans of an included target are not counted; Prüfungen the customer
//! requests are, and so is every scan of an extra target. Our own rescans and
//! support's scans never are.
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use super::repository::ScanTrigger;
/// Whether a target is one of the plan's included targets or an extra one
/// (billed per month on top).
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum TargetBilling {
/// One of the plan's included targets. Targets stored before metering
/// existed read as included.
#[default]
Included,
/// A target beyond the plan's included ones.
Extra,
}
/// Why a scan ran, as far as metering is concerned.
#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum ScanAttribution {
/// Started because something changed: new commits, other uploaded
/// files, or a live URL (scanned on every schedule).
Change,
/// The customer asked for it (dashboard or API).
Request,
/// Our own: a scheduled scan where nothing the customer changed, only
/// the Prüfwerk build. Never counted.
Rescan,
/// Started by Breakpilot support in the customer's tenant. Never counted.
Support,
}
impl ScanAttribution {
/// The attribution a scan started by a person has from the start, before
/// any change detection; `None` for a scheduled or webhook scan, which
/// change detection attributes.
pub fn of_person(trigger: &ScanTrigger) -> Option<Self> {
match trigger {
ScanTrigger::Manual => Some(Self::Request),
ScanTrigger::Support => Some(Self::Support),
ScanTrigger::Scheduled | ScanTrigger::Webhook => None,
}
}
/// The attribution of a scan that runs, from its trigger and whether
/// change detection found a change the customer made.
///
/// # Arguments
///
/// * `trigger` - What started the scan.
/// * `content_changed` - New commits, other uploaded files, or a live
/// URL. Ignored for a scan a person started.
pub fn detected(trigger: &ScanTrigger, content_changed: bool) -> Self {
match Self::of_person(trigger) {
Some(person) => person,
None if content_changed => Self::Change,
None => Self::Rescan,
}
}
/// Whether a scan with this attribution, on a target billed as
/// `billing`, counts toward the customer's usage once it completes.
///
/// # Examples
///
/// ```
/// use compliance_core::models::{ScanAttribution, TargetBilling};
///
/// assert!(!ScanAttribution::Change.chargeable(TargetBilling::Included));
/// assert!(ScanAttribution::Change.chargeable(TargetBilling::Extra));
/// assert!(ScanAttribution::Request.chargeable(TargetBilling::Included));
/// assert!(!ScanAttribution::Rescan.chargeable(TargetBilling::Extra));
/// ```
pub fn chargeable(self, billing: TargetBilling) -> bool {
match self {
Self::Request => true,
Self::Change => billing == TargetBilling::Extra,
Self::Rescan | Self::Support => false,
}
}
}
/// One active target as [`split_included`] sees it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BillableTarget<Id> {
/// The target's id.
pub id: Id,
/// When it was created: the oldest targets are the included ones.
pub created_at: DateTime<Utc>,
/// How it is billed now.
pub billing: TargetBilling,
}
/// The targets whose billing has to change so that the `included` oldest
/// active targets are included and the rest are extra.
///
/// # Arguments
///
/// * `targets` - The tenant's active (not archived) targets, in any order.
/// Ties on `created_at` are broken by id, so the split is stable.
/// * `included` - How many targets the plan includes; `None` is unlimited.
///
/// # Returns
///
/// Each target whose billing differs from what it should be, with the
/// billing it should have. Empty when nothing changes.
pub fn split_included<Id: Ord + Clone>(
targets: &[BillableTarget<Id>],
included: Option<u32>,
) -> Vec<(Id, TargetBilling)> {
let mut ordered: Vec<&BillableTarget<Id>> = targets.iter().collect();
ordered.sort_unstable_by(|a, b| a.created_at.cmp(&b.created_at).then(a.id.cmp(&b.id)));
// `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
.into_iter()
.enumerate()
.filter_map(|(rank, target)| {
let wanted = if rank < limit {
TargetBilling::Included
} else {
TargetBilling::Extra
};
(target.billing != wanted).then(|| (target.id.clone(), wanted))
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use chrono::TimeZone;
fn target(id: u32, day: u32, billing: TargetBilling) -> BillableTarget<u32> {
BillableTarget {
id,
created_at: Utc
.with_ymd_and_hms(2026, 11, day, 0, 0, 0)
.single()
.expect("valid date"),
billing,
}
}
#[test]
fn the_oldest_targets_are_included_and_the_rest_extra() {
// Arrange: three included targets, created on days 3, 1 and 2.
let targets = [
target(1, 3, TargetBilling::Included),
target(2, 1, TargetBilling::Included),
target(3, 2, TargetBilling::Included),
];
// Act
let changes = split_included(&targets, Some(2));
// Assert: only the newest one moves to extra.
assert_eq!(changes, vec![(1, TargetBilling::Extra)]);
}
#[test]
fn an_extra_target_moves_up_when_an_included_one_leaves() {
let targets = [
target(2, 2, TargetBilling::Included),
target(3, 3, TargetBilling::Extra),
];
assert_eq!(
split_included(&targets, Some(2)),
vec![(3, TargetBilling::Included)]
);
}
#[test]
fn without_a_limit_every_target_is_included() {
let targets = [
target(1, 1, TargetBilling::Extra),
target(2, 2, TargetBilling::Included),
];
assert_eq!(
split_included(&targets, None),
vec![(1, TargetBilling::Included)]
);
}
#[test]
fn equal_creation_times_split_by_id() {
let targets = [
target(9, 1, TargetBilling::Included),
target(4, 1, TargetBilling::Included),
];
assert_eq!(
split_included(&targets, Some(1)),
vec![(9, TargetBilling::Extra)]
);
}
#[test]
fn a_scan_a_person_started_keeps_its_attribution() {
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Manual, false),
ScanAttribution::Request
);
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Support, true),
ScanAttribution::Support
);
}
#[test]
fn a_scheduled_scan_is_a_change_or_our_rescan() {
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Scheduled, true),
ScanAttribution::Change
);
assert_eq!(
ScanAttribution::detected(&ScanTrigger::Webhook, false),
ScanAttribution::Rescan
);
}
#[test]
fn what_counts_follows_the_contract() {
use ScanAttribution::{Change, Request, Rescan, Support};
use TargetBilling::{Extra, Included};
let counted: Vec<(ScanAttribution, TargetBilling)> = [Change, Request, Rescan, Support]
.into_iter()
.flat_map(|a| [(a, Included), (a, Extra)])
.filter(|(a, b)| a.chargeable(*b))
.collect();
assert_eq!(
counted,
vec![(Change, Extra), (Request, Included), (Request, Extra)]
);
}
#[test]
fn stored_names_are_snake_case() {
assert_eq!(
serde_json::to_value(TargetBilling::Extra).expect("serializes"),
"extra"
);
assert_eq!(
serde_json::to_value(ScanAttribution::Rescan).expect("serializes"),
"rescan"
);
}
}
+2
View File
@@ -13,6 +13,7 @@ pub mod license;
pub mod license_policy;
pub mod mcp;
pub mod mcp_token;
pub mod metering;
pub mod notification;
pub mod onboarding;
pub mod oscal;
@@ -57,6 +58,7 @@ pub use license_policy::{
};
pub use mcp::{McpServerConfig, McpServerStatus, McpTransport};
pub use mcp_token::{McpToken, McpTokenView};
pub use metering::{split_included, BillableTarget, ScanAttribution, TargetBilling};
pub use notification::{CveNotification, NotificationSeverity, NotificationStatus};
pub use onboarding::{
default_compliance_profile, Artifact, ArtifactAuth, ArtifactKind, Classification,
+6
View File
@@ -660,6 +660,11 @@ pub struct OnboardedTarget {
/// its last scan; `None` for every other target.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layer_pins: Option<super::yocto::LayerPins>,
/// Whether the target is one of the plan's included targets or an extra
/// one (t72). The agent sets it from the plan; stored, so it never flips
/// unseen.
#[serde(default)]
pub billing: super::metering::TargetBilling,
/// Creation timestamp.
#[serde(
default = "chrono::Utc::now",
@@ -700,6 +705,7 @@ impl OnboardedTarget {
archived_at: None,
last_scan: None,
layer_pins: None,
billing: super::metering::TargetBilling::default(),
created_at: now,
updated_at: now,
}
+12
View File
@@ -184,6 +184,16 @@ pub struct ScanRun {
/// at the end of this run (sbomqs, #496); `None` when it was not scored.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sbom_quality: Option<super::sbom::SbomQuality>,
/// Why the run ran, for metering (t72): set when it starts for a scan a
/// person started, and by change detection otherwise. `None` for a run
/// skipped because nothing changed, and in runs from before metering.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attribution: Option<super::metering::ScanAttribution>,
/// Whether the run counts toward the customer's usage once it completes
/// ([`super::metering::ScanAttribution::chargeable`] for the target's
/// billing when it was attributed).
#[serde(default)]
pub chargeable: bool,
}
/// Why a stage was skipped, or what a run note is about
@@ -410,6 +420,8 @@ impl ScanRun {
languages: Vec::new(),
planned_phases: Vec::new(),
sbom_quality: None,
attribution: None,
chargeable: false,
}
}
}
+4
View File
@@ -4793,6 +4793,10 @@ tbody tr:last-child td {
margin-bottom: 2px;
}
.targets-extra {
margin-top: 4px;
}
.targets-cra {
min-width: 220px;
}
+11
View File
@@ -843,6 +843,17 @@ pub mod targets {
de: "+ Prüfobjekt anlegen",
en: "+ Add a target",
};
/// Badge of a target beyond the plan's included ones (t72).
pub const EXTRA: Text = Text {
de: "Zusätzliches Prüfobjekt",
en: "Extra target",
};
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.",
en: "Beyond the targets your plan includes: billed monthly on top, and each of \
its scans counts toward your quota.",
};
pub const COL_NAME: Text = Text {
de: "Name",
en: "Name",
@@ -233,6 +233,13 @@ pub fn TargetsPage() -> Element {
"{name}"
}
span { class: "targets-type", "{ttype}" }
if str_at(t, "billing") == "extra" {
span {
class: "badge badge-neutral targets-extra",
title: tx::EXTRA_HINT.get(lang),
{tx::EXTRA.get(lang)}
}
}
if let Some(Ok(all)) = projects.read().clone() {
ProjectChips { ids: project_ids_of(t), projects: all }
}