diff --git a/compliance-agent/src/agent.rs b/compliance-agent/src/agent.rs index 9ec6f86..aed8b3e 100644 --- a/compliance-agent/src/agent.rs +++ b/compliance-agent/src/agent.rs @@ -139,6 +139,19 @@ impl ComplianceAgent { metric: &str, key: String, properties: serde_json::Value, + ) { + self.emit_usage_quantity(tenant_id, metric, key, 1.0, properties); + } + + /// [`Self::emit_usage`] with a `quantity` other than one, such as the + /// month's peak of extra targets (t72). + pub fn emit_usage_quantity( + &self, + tenant_id: &str, + metric: &str, + key: String, + quantity: f64, + properties: serde_json::Value, ) { let Some(registry) = self.registry.clone() else { return; @@ -148,7 +161,7 @@ impl ComplianceAgent { tenant_id: tenant_id.to_string(), product: registry.product().to_string(), metric: metric.to_string(), - quantity: 1.0, + quantity, occurred_at: chrono::Utc::now().to_rfc3339(), properties: Some(properties), }; @@ -209,7 +222,7 @@ impl ComplianceAgent { db: &crate::database::Database, included: Option, ) -> Vec { - match crate::metering::assign_billing(db, included).await { + let changes = match crate::metering::assign_billing(db, included).await { Ok(changes) => { if !changes.is_empty() { tracing::info!(tenant_id, changed = changes.len(), "target billing updated"); @@ -218,8 +231,33 @@ impl ComplianceAgent { } Err(e) => { tracing::warn!(tenant_id, "target billing not updated: {e}"); - Vec::new() + return Vec::new(); } + }; + self.report_extra_peak(tenant_id, db).await; + changes + } + + /// Send the month's peak of extra targets as `target.extra` when it + /// rose, and once a day besides (t72). The key carries the peak, so the + /// registry keeps every rise and drops the daily re-send as a duplicate; + /// billing takes the highest quantity per tenant-month. Count only: no + /// target names leave Prüfwerk. Best-effort. + async fn report_extra_peak(&self, tenant_id: &str, db: &crate::database::Database) { + let now = chrono::Utc::now(); + match crate::metering::record_extra_peak(db, now).await { + Ok(Some(peak)) => { + let (month, _) = crate::metering::berlin_period(now); + self.emit_usage_quantity( + tenant_id, + "target.extra", + format!("target-extra:{tenant_id}:{month}:{peak}"), + f64::from(peak), + serde_json::json!({ "month": month }), + ); + } + Ok(None) => {} + Err(e) => tracing::warn!(tenant_id, "extra targets not recorded: {e}"), } } diff --git a/compliance-agent/src/metering.rs b/compliance-agent/src/metering.rs index ce58300..f740c93 100644 --- a/compliance-agent/src/metering.rs +++ b/compliance-agent/src/metering.rs @@ -201,7 +201,11 @@ pub async fn charge( .upsert(true) .await?; let quota_filter = match limits.monthly_pruefungen { - Some(quota) => doc! { "_id": &month, "pruefungen": { "$lt": i64::from(quota) } }, + // `$not $gte` also matches a month document without the counter. + Some(quota) => doc! { + "_id": &month, + "pruefungen": { "$not": { "$gte": i64::from(quota) } }, + }, None => doc! { "_id": &month }, }; let in_quota = months @@ -257,6 +261,61 @@ pub async fn charge( }) } +/// Record how many of the tenant's active targets are extra at `at`, as +/// the month's peak (t72): the 5,99 € line bills the highest number of +/// extra targets at once in the calendar month (Europe/Berlin). +/// +/// # Returns +/// +/// The month's peak when it goes to the registry as `target.extra`: when it +/// rose, and once a day besides (a re-send the registry drops as a +/// duplicate of its key). `None` otherwise, and while no target was extra. +/// +/// # Errors +/// +/// Returns an error if the targets or the month's counters cannot be read +/// or written. +pub async fn record_extra_peak( + db: &Database, + at: DateTime, +) -> Result, AgentError> { + let extra = mongodb::bson::to_bson(&TargetBilling::Extra) + .map_err(|e| AgentError::Other(e.to_string()))?; + let now = db + .onboarded_targets() + .count_documents(doc! { "archived_at": null, "billing": extra }) + .await?; + let now = u32::try_from(now).unwrap_or(u32::MAX); + let (month, day) = berlin_period(at); + let months = db.raw_collection(MONTHS); + // The document before the update: the peak and the day it was last sent. + let before = months + .find_one_and_update( + doc! { "_id": &month }, + doc! { + "$max": { "extra_peak": i64::from(now) }, + "$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 }, + }, + ) + .upsert(true) + .await?; + let previous = count(before.as_ref(), "extra_peak"); + let sent_on = before + .as_ref() + .and_then(|d| d.get_str("extra_sent_on").ok()); + let peak = previous.max(now); + if peak == 0 || (peak == previous && sent_on == Some(day.as_str())) { + return Ok(None); + } + months + .update_one( + doc! { "_id": &month }, + doc! { "$set": { "extra_sent_on": &day } }, + ) + .await?; + Ok(Some(peak)) +} + #[cfg(test)] mod tests { use super::*; diff --git a/compliance-agent/tests/extra_peak.rs b/compliance-agent/tests/extra_peak.rs new file mode 100644 index 0000000..0ac7561 --- /dev/null +++ b/compliance-agent/tests/extra_peak.rs @@ -0,0 +1,80 @@ +//! The month's peak of extra targets goes to the registry when it rises and +//! once a day besides; a new month starts again (t72). Runs against a live +//! Mongo (`TEST_MONGODB_URI`) and skips cleanly without one. + +#![allow(clippy::expect_used, clippy::unwrap_used)] + +use chrono::{Duration, TimeZone, Utc}; +use compliance_agent::database::DatabasePool; +use compliance_agent::metering::{assign_billing, charge, record_extra_peak}; +use compliance_core::models::{OnboardedTarget, PlanLimits, RunCharge, TargetType}; +use mongodb::bson::doc; + +const TENANT: &str = "extra-peak"; + +#[tokio::test] +async fn the_peak_is_sent_when_it_rises_and_once_a_day() { + let uri = std::env::var("TEST_MONGODB_URI") + .unwrap_or_else(|_| "mongodb://root:example@localhost:27017/?authSource=admin".into()); + let prefix = format!( + "extrapeak_{}", + &uuid::Uuid::new_v4().simple().to_string()[..10] + ); + let Ok(pool) = DatabasePool::connect(&uri, &prefix).await else { + eprintln!("SKIP extra_peak: no MongoDB reachable at {uri}"); + return; + }; + let db = pool.for_tenant_id(TENANT).await.unwrap(); + // Arrange: three targets on a plan that includes one, on 6 Nov. + 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()); + } + assign_billing(&db, Some(1)).await.unwrap(); + let nov6 = Utc.with_ymd_and_hms(2026, 11, 6, 9, 0, 0).single().unwrap(); + + // Act / Assert: two extra targets, sent once that day. + assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), Some(2)); + assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), None); + + // One extra target is archived: the month's peak stays two. + db.onboarded_targets() + .update_one( + doc! { "_id": ids[2] }, + doc! { "$set": { "archived_at": mongodb::bson::DateTime::now() } }, + ) + .await + .unwrap(); + assign_billing(&db, Some(1)).await.unwrap(); + assert_eq!(record_extra_peak(&db, nov6).await.unwrap(), None); + assert_eq!( + record_extra_peak(&db, nov6 + Duration::days(1)) + .await + .unwrap(), + Some(2), + "re-sent once the next day" + ); + + // A new month starts from the targets extra now. + let dec1 = Utc.with_ymd_and_hms(2026, 12, 1, 9, 0, 0).single().unwrap(); + assert_eq!(record_extra_peak(&db, dec1).await.unwrap(), Some(1)); + + // The month document the peak created still counts the quota. + let plan = PlanLimits { + monthly_pruefungen: Some(1), + prueftag_cap: None, + }; + assert_eq!( + charge(&db, "t", plan, dec1).await.unwrap().charge, + RunCharge::Quota + ); + assert_eq!( + charge(&db, "t", plan, dec1).await.unwrap().charge, + RunCharge::Prueftag + ); + + pool.drop_tenant(TENANT).await.ok(); +}