Files
pruefwerk/compliance-agent/src/metering.rs
T
sharang 1df32d5e1a
CI / Check (push) Skipped
CI / Agent integration (push) Skipped
CI / Detect Changes (push) Successful in 3s
CI / Deploy Docs (push) Skipped
CI / Deploy MCP (push) Successful in 2m52s
CI / Deploy Dashboard (push) Successful in 5m31s
CI / Deploy Agent (push) Successful in 7m28s
feat(metering): a plan can allow no extra targets (entry plan) (#1079)
2026-11-28 22:09:18 +00:00

585 lines
20 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! Metering of a tenant's Prüfungen (t72).
//!
//! **Included and extra targets.** The oldest active targets are included,
//! up to the plan's `included_targets`; every other active target is extra.
//! A plan that allows no extra target (the entry plan) includes them all.
//! 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.
//!
//! **Counters.** A counted Prüfung is checked against the plan when it
//! starts ([`usage`] and [`compliance_core::models::admit`]) and charged
//! when it completes ([`charge`]): to the month's quota, else to the
//! target's Prüftag for the day, booking one if none is. Months and days
//! are calendar ones in Europe/Berlin. A run that fails because of us is
//! never charged, so nothing is refunded.
//!
//! [`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::{
check_swap, split_included, BillableTarget, DayUsage, IncludedChoice, MonthUsage, PlanLimits,
RunCharge, SwapRefusal, 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 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 })
.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(),
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 {
/// How many targets the plan includes; `None` is unlimited.
pub included_targets: Option<u32>,
/// How many extra targets may be active besides; `None` is unlimited.
pub extra_targets: Option<u32>,
/// The quota and the customer's Prüftag cap.
pub limits: PlanLimits,
}
impl Plan {
/// How many targets may be active at once: the included ones and the
/// extra ones the plan allows. `None` when either is unlimited, as on
/// every plan that bills extra targets.
pub fn target_cap(&self) -> Option<u32> {
Some(self.included_targets?.saturating_add(self.extra_targets?))
}
/// How many targets the billing split includes; `None` includes every
/// active target. A plan that allows no extra target bills none as
/// extra, not even those already active beyond its included ones.
pub fn billed_included(&self) -> Option<u32> {
match self.extra_targets {
Some(0) => None,
_ => self.included_targets,
}
}
}
/// The tenant's counted Prüfungen and booked Prüftage per month.
const MONTHS: &str = "metering_months";
/// Each target's Prüftag per day, once the quota was used up.
const DAYS: &str = "metering_days";
/// The calendar month and day of `at` in Europe/Berlin, as `YYYY-MM` and
/// `YYYY-MM-DD`: the periods the contract counts in.
pub fn berlin_period(at: DateTime<Utc>) -> (String, String) {
let local = at.with_timezone(&chrono_tz::Europe::Berlin);
(
local.format("%Y-%m").to_string(),
local.format("%Y-%m-%d").to_string(),
)
}
/// The id of a target's counter for one day.
fn day_id(target_id: &str, day: &str) -> String {
format!("{target_id}:{day}")
}
/// A stored counter as a `u32`; missing or negative reads as 0.
fn count(document: Option<&Document>, field: &str) -> u32 {
document
.and_then(|d| d.get(field))
.and_then(mongodb::bson::Bson::as_i64)
.or_else(|| document.and_then(|d| d.get_i32(field).ok()).map(i64::from))
.and_then(|n| u32::try_from(n).ok())
.unwrap_or(0)
}
/// What the tenant used this month and `target_id` today, at `at`.
///
/// # Errors
///
/// Returns an error if the counters cannot be read.
pub async fn usage(
db: &Database,
target_id: &str,
at: DateTime<Utc>,
) -> Result<(MonthUsage, DayUsage), AgentError> {
let (month, day) = berlin_period(at);
let month_doc = db
.raw_collection(MONTHS)
.find_one(doc! { "_id": &month })
.await?;
let day_doc = db
.raw_collection(DAYS)
.find_one(doc! { "_id": day_id(target_id, &day) })
.await?;
Ok((
MonthUsage {
pruefungen: count(month_doc.as_ref(), "pruefungen"),
prueftage: count(month_doc.as_ref(), "prueftage"),
},
DayUsage {
prueftag_booked: day_doc
.as_ref()
.and_then(|d| d.get_bool("prueftag_booked").ok())
.unwrap_or(false),
prueftag_pruefungen: count(day_doc.as_ref(), "prueftag_pruefungen"),
},
))
}
/// What [`charge`] charged a completed Prüfung to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Charged {
/// The quota or the target's Prüftag.
pub charge: RunCharge,
/// The Berlin day (`YYYY-MM-DD`) of a Prüftag this Prüfung booked; it
/// goes to the registry as `prueftag.booked`.
pub booked_prueftag: Option<String>,
}
/// Charge one completed, counted Prüfung on `target_id` at `at`: to the
/// month's quota while it lasts, else to the target's Prüftag that day,
/// booking it if none is. The start of the run checked the limits, so this
/// never refuses; scans of several targets finishing at once can take the
/// quota or a Prüftag over by the ones that raced.
///
/// # Errors
///
/// Returns an error if the counters cannot be written.
pub async fn charge(
db: &Database,
target_id: &str,
limits: PlanLimits,
at: DateTime<Utc>,
) -> Result<Charged, AgentError> {
let (month, day) = berlin_period(at);
let months = db.raw_collection(MONTHS);
months
.update_one(
doc! { "_id": &month },
doc! { "$setOnInsert": { "pruefungen": 0_i64, "prueftage": 0_i64 } },
)
.upsert(true)
.await?;
let quota_filter = match limits.monthly_pruefungen {
// `$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
.update_one(quota_filter, doc! { "$inc": { "pruefungen": 1_i64 } })
.await?;
if in_quota.matched_count == 1 {
return Ok(Charged {
charge: RunCharge::Quota,
booked_prueftag: None,
});
}
let days = db.raw_collection(DAYS);
let id = day_id(target_id, &day);
days.update_one(
doc! { "_id": &id },
doc! { "$setOnInsert": {
"target_id": target_id,
"day": &day,
"month": &month,
"prueftag_booked": false,
"prueftag_pruefungen": 0_i64,
} },
)
.upsert(true)
.await?;
let booked = days
.update_one(
doc! { "_id": &id, "prueftag_booked": false },
doc! { "$set": { "prueftag_booked": true, "prueftag_pruefungen": 1_i64 } },
)
.await?;
if booked.matched_count == 1 {
months
.update_one(
doc! { "_id": &month },
doc! { "$inc": { "prueftage": 1_i64 } },
)
.await?;
return Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: Some(day),
});
}
days.update_one(
doc! { "_id": &id },
doc! { "$inc": { "prueftag_pruefungen": 1_i64 } },
)
.await?;
Ok(Charged {
charge: RunCharge::Prueftag,
booked_prueftag: None,
})
}
/// 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<Utc>,
) -> Result<Option<u32>, 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))
}
/// 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 only_a_plan_capping_both_counts_caps_the_active_targets() {
let plan = |included_targets, extra_targets| Plan {
included_targets,
extra_targets,
..Plan::default()
};
assert_eq!(plan(Some(3), Some(0)).target_cap(), Some(3), "entry");
assert_eq!(plan(Some(3), Some(2)).target_cap(), Some(5));
assert_eq!(plan(Some(5), None).target_cap(), None, "extras billed");
assert_eq!(plan(None, Some(0)).target_cap(), None, "all included");
assert_eq!(plan(Some(u32::MAX), Some(1)).target_cap(), Some(u32::MAX));
}
#[test]
fn a_plan_allowing_no_extra_target_bills_none_as_extra() {
let plan = |included_targets, extra_targets| Plan {
included_targets,
extra_targets,
limits: PlanLimits::default(),
};
assert_eq!(plan(Some(2), Some(0)).billed_included(), None, "entry");
assert_eq!(plan(Some(5), None).billed_included(), Some(5));
assert_eq!(plan(Some(5), Some(2)).billed_included(), Some(5));
assert_eq!(plan(None, None).billed_included(), None);
}
#[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| {
Utc.with_ymd_and_hms(y, m, d, h, min, 0)
.single()
.expect("valid")
};
// 23:30 UTC on 31 Oct is already 1 Nov in Berlin (CET, UTC+1).
assert_eq!(
berlin_period(at(2026, 10, 31, 23, 30)),
("2026-11".to_string(), "2026-11-01".to_string())
);
// In summer (CEST, UTC+2) the day turns at 22:00 UTC.
assert_eq!(berlin_period(at(2026, 7, 14, 21, 59)).1, "2026-07-14");
assert_eq!(berlin_period(at(2026, 7, 14, 22, 0)).1, "2026-07-15");
}
#[test]
fn a_counter_reads_as_zero_when_missing() {
let stored = doc! { "pruefungen": 7_i64, "small": 3_i32, "negative": -1_i64 };
assert_eq!(count(Some(&stored), "pruefungen"), 7);
assert_eq!(count(Some(&stored), "small"), 3);
assert_eq!(count(Some(&stored), "negative"), 0);
assert_eq!(count(Some(&stored), "absent"), 0);
assert_eq!(count(None, "pruefungen"), 0);
}
#[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,
choice: None,
})
);
assert_eq!(
old,
Some(BillableTarget {
id,
created_at: DateTime::<Utc>::MIN_UTC,
billing: TargetBilling::Included,
choice: None,
})
);
assert_eq!(billable(&doc! { "name": "no id" }), None);
}
}