use std::collections::BTreeMap;
use std::fmt;
use crate::cdrtime::Seconds;
use crate::container::RatingGroup;
use crate::disposition::{BatchReconciliation, Disposition};
use crate::record::UsageRecord;
use crate::volume::VolumePair;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct UsageTotal {
volume: VolumePair,
duration: Seconds,
events: u64,
records: u64,
unquantified: u64,
}
impl UsageTotal {
pub const ZERO: Self = Self {
volume: VolumePair::ZERO,
duration: Seconds::ZERO,
events: 0,
records: 0,
unquantified: 0,
};
#[must_use]
pub const fn volume(&self) -> VolumePair {
self.volume
}
#[must_use]
pub const fn duration(&self) -> Seconds {
self.duration
}
#[must_use]
pub const fn events(&self) -> u64 {
self.events
}
#[must_use]
pub const fn records(&self) -> u64 {
self.records
}
#[must_use]
pub const fn unquantified(&self) -> u64 {
self.unquantified
}
#[must_use]
pub const fn is_fully_quantified(&self) -> bool {
self.unquantified == 0
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.records == 0
}
#[must_use]
pub fn checked_add_record(self, record: &UsageRecord) -> Option<Self> {
Some(Self {
volume: self
.volume
.checked_add(record.billable_volume().unwrap_or(VolumePair::ZERO))?,
duration: self
.duration
.checked_add(record.duration.unwrap_or(Seconds::ZERO))?,
events: self
.events
.checked_add(u64::from(record.events.unwrap_or(0)))?,
records: self.records.checked_add(1)?,
unquantified: self
.unquantified
.checked_add(u64::from(record.is_zero_usage()))?,
})
}
#[must_use]
pub fn checked_add(self, other: Self) -> Option<Self> {
Some(Self {
volume: self.volume.checked_add(other.volume)?,
duration: self.duration.checked_add(other.duration)?,
events: self.events.checked_add(other.events)?,
records: self.records.checked_add(other.records)?,
unquantified: self.unquantified.checked_add(other.unquantified)?,
})
}
}
impl fmt::Display for UsageTotal {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} record(s): {} octets, {} s, {} event(s)",
self.records, self.volume, self.duration, self.events
)?;
if self.unquantified > 0 {
write!(f, " — {} carried no quantity", self.unquantified)?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AggregationError {
ContainerMismatch {
record_index: usize,
},
Overflow {
record_index: usize,
},
LengthMismatch {
records: usize,
dispositions: usize,
},
}
impl fmt::Display for AggregationError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::ContainerMismatch { record_index } => write!(
f,
"record {record_index} disagrees with its own container breakdown"
),
Self::Overflow { record_index } => {
write!(f, "the total overflowed at record {record_index}")
}
Self::LengthMismatch {
records,
dispositions,
} => write!(
f,
"{records} record(s) against {dispositions} disposition(s)"
),
}
}
}
impl std::error::Error for AggregationError {}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ReleasedTotals {
total: UsageTotal,
reconciliation: BatchReconciliation,
}
impl ReleasedTotals {
#[must_use]
pub const fn total(&self) -> UsageTotal {
self.total
}
#[must_use]
pub const fn reconciliation(&self) -> BatchReconciliation {
self.reconciliation
}
#[must_use]
pub const fn is_consistent(&self) -> bool {
self.reconciliation.balances() && self.total.records == self.reconciliation.released()
}
}
impl fmt::Display for ReleasedTotals {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} [{}]",
self.total,
if self.is_consistent() {
"consistent"
} else {
"INCONSISTENT"
}
)
}
}
pub fn aggregate(records: &[UsageRecord]) -> Result<UsageTotal, AggregationError> {
let mut total = UsageTotal::ZERO;
for (record_index, record) in records.iter().enumerate() {
check_containers(record, record_index)?;
total = total
.checked_add_record(record)
.ok_or(AggregationError::Overflow { record_index })?;
}
Ok(total)
}
pub fn aggregate_released(
records: &[UsageRecord],
dispositions: &[Disposition],
) -> Result<ReleasedTotals, AggregationError> {
if records.len() != dispositions.len() {
return Err(AggregationError::LengthMismatch {
records: records.len(),
dispositions: dispositions.len(),
});
}
let mut total = UsageTotal::ZERO;
let mut reconciliation = BatchReconciliation::EMPTY;
for (record_index, (record, disposition)) in records.iter().zip(dispositions).enumerate() {
reconciliation.observe(disposition);
if !disposition.is_released() {
continue;
}
check_containers(record, record_index)?;
total = total
.checked_add_record(record)
.ok_or(AggregationError::Overflow { record_index })?;
}
Ok(ReleasedTotals {
total,
reconciliation,
})
}
pub fn aggregate_by<K, F>(
records: &[UsageRecord],
key: F,
) -> Result<BTreeMap<K, UsageTotal>, AggregationError>
where
K: Ord,
F: Fn(&UsageRecord) -> K,
{
let mut buckets: BTreeMap<K, UsageTotal> = BTreeMap::new();
for (record_index, record) in records.iter().enumerate() {
check_containers(record, record_index)?;
let entry = buckets.entry(key(record)).or_insert(UsageTotal::ZERO);
*entry = entry
.checked_add_record(record)
.ok_or(AggregationError::Overflow { record_index })?;
}
Ok(buckets)
}
pub fn aggregate_rating_groups(
records: &[UsageRecord],
) -> Result<BTreeMap<Option<RatingGroup>, VolumePair>, AggregationError> {
let mut buckets: BTreeMap<Option<RatingGroup>, VolumePair> = BTreeMap::new();
for (record_index, record) in records.iter().enumerate() {
if record.containers.is_empty() {
let entry = buckets.entry(None).or_insert(VolumePair::ZERO);
*entry = entry
.checked_add(record.volume.unwrap_or(VolumePair::ZERO))
.ok_or(AggregationError::Overflow { record_index })?;
continue;
}
for container in &record.containers {
let entry = buckets
.entry(Some(container.rating_group))
.or_insert(VolumePair::ZERO);
*entry = entry
.checked_add(container.volume)
.ok_or(AggregationError::Overflow { record_index })?;
}
}
Ok(buckets)
}
fn check_containers(record: &UsageRecord, record_index: usize) -> Result<(), AggregationError> {
if record.containers_agree() == Some(false) {
return Err(AggregationError::ContainerMismatch { record_index });
}
Ok(())
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{ReleasedTotals, UsageTotal};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
#[derive(Serialize, Deserialize)]
#[serde(rename = "UsageTotal")]
struct TotalRepr {
volume: crate::volume::VolumePair,
duration_s: crate::cdrtime::Seconds,
events: u64,
records: u64,
#[serde(default)]
unquantified: u64,
}
impl Serialize for UsageTotal {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
TotalRepr {
volume: self.volume(),
duration_s: self.duration(),
events: self.events(),
records: self.records(),
unquantified: self.unquantified(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for UsageTotal {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = TotalRepr::deserialize(deserializer)?;
Ok(UsageTotal {
volume: r.volume,
duration: r.duration_s,
events: r.events,
records: r.records,
unquantified: r.unquantified,
})
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "ReleasedTotals")]
struct ReleasedRepr {
total: UsageTotal,
reconciliation: crate::disposition::BatchReconciliation,
}
impl Serialize for ReleasedTotals {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
ReleasedRepr {
total: self.total(),
reconciliation: self.reconciliation(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ReleasedTotals {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = ReleasedRepr::deserialize(deserializer)?;
Ok(ReleasedTotals {
total: r.total,
reconciliation: r.reconciliation,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::container::{ChangeCondition, ContainerSet, ServiceDataContainer};
use crate::disposition::{RejectReason, SuppressReason};
use crate::party::{ChargedParty, SubscriberRef};
use crate::record::{RecordType, SourceRef};
use crate::volume::Octets;
fn party() -> ChargedParty {
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap()))
}
fn record(opened: &str, up: u64, down: u64) -> UsageRecord {
UsageRecord::new(
RecordType::PduSession,
party(),
opened.parse().unwrap(),
SourceRef::new("pgw-01".parse().unwrap(), 0),
)
.with_volume(VolumePair::new(Octets::new(up), Octets::new(down)))
}
fn container(group: u32, up: u64) -> ServiceDataContainer {
ServiceDataContainer::new(RatingGroup::new(group), ChangeCondition::RecordClosure)
.with_volume(VolumePair::new(Octets::new(up), Octets::ZERO))
}
#[test]
fn quantities_sum_with_the_directions_kept_apart() {
let records = vec![
record("2026-07-28T10:00:00+02:00", 100, 900),
record("2026-07-28T11:00:00+02:00", 50, 450),
];
let total = aggregate(&records).unwrap();
assert_eq!(total.volume().uplink(), Octets::new(150));
assert_eq!(total.volume().downlink(), Octets::new(1_350));
assert_eq!(total.records(), 2);
assert!(!total.is_empty());
}
#[test]
fn a_total_carries_the_reconciliation_that_justifies_it() {
let records = vec![
record("2026-07-28T10:00:00+02:00", 100, 0),
record("2026-07-28T11:00:00+02:00", 200, 0),
record("2026-07-28T12:00:00+02:00", 400, 0),
];
let dispositions = vec![
Disposition::Billable,
Disposition::Billable,
Disposition::Rejected(RejectReason::Malformed),
];
let released = aggregate_released(&records, &dispositions).unwrap();
assert_eq!(released.total().volume().uplink(), Octets::new(300));
assert_eq!(released.total().records(), 2);
assert_eq!(released.reconciliation().ingested(), 3);
assert_eq!(released.reconciliation().released(), 2);
assert!(released.is_consistent());
}
#[test]
fn suppressed_and_duplicate_records_are_counted_but_not_summed() {
let records = vec![
record("2026-07-28T10:00:00+02:00", 100, 0),
record("2026-07-28T11:00:00+02:00", 999, 0),
record("2026-07-28T12:00:00+02:00", 999, 0),
];
let dispositions = vec![
Disposition::Billable,
Disposition::Suppressed(SuppressReason::TestIdentity),
Disposition::Duplicate(crate::dedup::RecordKey::RecordingEntity {
entity: "msc-01".parse().unwrap(),
local_sequence: 1,
}),
];
let released = aggregate_released(&records, &dispositions).unwrap();
assert_eq!(released.total().volume().uplink(), Octets::new(100));
assert_eq!(released.reconciliation().ingested(), 3);
assert!(released.is_consistent());
}
#[test]
fn records_and_dispositions_must_correspond() {
let records = vec![record("2026-07-28T10:00:00+02:00", 1, 0)];
assert_eq!(
aggregate_released(&records, &[]),
Err(AggregationError::LengthMismatch {
records: 1,
dispositions: 0,
})
);
}
#[test]
fn a_container_mismatch_stops_the_sum_and_names_the_record() {
let mut broken = record("2026-07-28T10:00:00+02:00", 999, 0);
broken.containers = ContainerSet::from(vec![container(10, 100)]);
let records = vec![record("2026-07-28T09:00:00+02:00", 1, 0), broken];
assert_eq!(
aggregate(&records),
Err(AggregationError::ContainerMismatch { record_index: 1 })
);
}
#[test]
fn an_overflowing_total_is_reported_and_located() {
let records = vec![
record("2026-07-28T10:00:00+02:00", u64::MAX, 0),
record("2026-07-28T11:00:00+02:00", 1, 0),
];
assert_eq!(
aggregate(&records),
Err(AggregationError::Overflow { record_index: 1 })
);
}
#[test]
fn grouping_by_local_day_follows_the_subscribers_calendar() {
let records = vec![
record("2026-07-28T00:30:00+05:45", 100, 0),
record("2026-07-28T23:00:00+05:45", 200, 0),
record("2026-07-29T01:00:00+05:45", 400, 0),
];
let by_day = aggregate_by(&records, UsageRecord::local_date).unwrap();
assert_eq!(by_day.len(), 2);
let first = by_day.values().next().unwrap();
assert_eq!(first.volume().uplink(), Octets::new(300));
assert_eq!(first.records(), 2);
}
#[test]
fn grouping_by_service_domain_partitions_the_batch() {
let mut sms = record("2026-07-28T10:00:00+02:00", 0, 0);
sms.record_type = RecordType::SmsOriginated;
sms.volume = None;
sms.events = Some(3);
let records = vec![record("2026-07-28T10:00:00+02:00", 100, 0), sms];
let by_service = aggregate_by(&records, UsageRecord::service).unwrap();
assert_eq!(by_service.len(), 2);
assert_eq!(by_service[&crate::record::ServiceDomain::Sms].events(), 3);
assert_eq!(
by_service[&crate::record::ServiceDomain::Data]
.volume()
.uplink(),
Octets::new(100)
);
}
#[test]
fn unclassified_usage_gets_its_own_bucket() {
let mut classified = record("2026-07-28T10:00:00+02:00", 300, 0);
classified.containers = ContainerSet::from(vec![container(10, 100), container(20, 200)]);
let unclassified = record("2026-07-28T11:00:00+02:00", 50, 0);
let groups = aggregate_rating_groups(&[classified, unclassified]).unwrap();
assert_eq!(groups.len(), 3);
assert_eq!(
groups[&Some(RatingGroup::new(10))].uplink(),
Octets::new(100)
);
assert_eq!(
groups[&Some(RatingGroup::new(20))].uplink(),
Octets::new(200)
);
assert_eq!(groups[&None].uplink(), Octets::new(50));
}
#[test]
fn rating_group_sums_never_consult_the_record_total() {
let mut disagreeing = record("2026-07-28T10:00:00+02:00", 9_999, 0);
disagreeing.containers = ContainerSet::from(vec![container(10, 100)]);
assert!(aggregate(std::slice::from_ref(&disagreeing)).is_err());
let groups = aggregate_rating_groups(std::slice::from_ref(&disagreeing)).unwrap();
assert_eq!(
groups[&Some(RatingGroup::new(10))].uplink(),
Octets::new(100)
);
}
#[test]
fn records_that_contributed_nothing_are_counted() {
let mut empty = record("2026-07-28T11:00:00+02:00", 0, 0);
empty.volume = None;
let total = aggregate(&[record("2026-07-28T10:00:00+02:00", 100, 0), empty]).unwrap();
assert_eq!(total.records(), 2);
assert_eq!(total.unquantified(), 1);
assert!(!total.is_fully_quantified());
assert!(total.to_string().contains("carried no quantity"), "{total}");
let clean = aggregate(&[record("2026-07-28T10:00:00+02:00", 100, 0)]).unwrap();
assert!(clean.is_fully_quantified());
assert!(!clean.to_string().contains("carried no quantity"));
}
#[test]
fn totals_merge_for_recombining_parallel_work() {
let left = aggregate(&[record("2026-07-28T10:00:00+02:00", 100, 0)]).unwrap();
let right = aggregate(&[
record("2026-07-28T11:00:00+02:00", 200, 0),
record("2026-07-28T12:00:00+02:00", 400, 0),
])
.unwrap();
let merged = left.checked_add(right).unwrap();
assert_eq!(merged.volume().uplink(), Octets::new(700));
assert_eq!(merged.records(), 3);
let huge = UsageTotal::ZERO
.checked_add_record(&record("2026-07-28T10:00:00+02:00", u64::MAX, 0))
.unwrap();
assert_eq!(huge.checked_add(huge), None);
}
#[test]
fn an_empty_batch_totals_to_nothing() {
let total = aggregate(&[]).unwrap();
assert_eq!(total, UsageTotal::ZERO);
assert!(total.is_empty());
assert!(
aggregate_by(&[], UsageRecord::local_date)
.unwrap()
.is_empty()
);
let released = aggregate_released(&[], &[]).unwrap();
assert!(released.is_consistent());
}
#[test]
fn a_record_with_only_containers_still_contributes() {
let mut container_only = record("2026-07-28T10:00:00+02:00", 0, 0);
container_only.volume = None;
container_only.containers = ContainerSet::from(vec![container(10, 250)]);
let total = aggregate(&[container_only]).unwrap();
assert_eq!(total.volume().uplink(), Octets::new(250));
}
}