use std::fmt;
use std::str::FromStr;
use crate::cdrtime::{CdrTimestamp, Seconds};
use crate::container::ContainerSet;
use crate::correlation::CorrelationKeys;
use crate::error::ParseError;
use crate::identity::{Iccid, Pei};
use crate::partial::PartialInfo;
use crate::party::ChargedParty;
use crate::plmn::PlmnId;
use crate::session::SessionContext;
use crate::volume::VolumePair;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum ServiceDomain {
Voice,
Sms,
Mms,
Data,
Ims,
Fixed,
Iot,
NetworkApi,
Slice,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum PrimaryMeasure {
Duration,
Volume,
Events,
}
impl ServiceDomain {
pub const ALL: &'static [Self] = &[
Self::Voice,
Self::Sms,
Self::Mms,
Self::Data,
Self::Ims,
Self::Fixed,
Self::Iot,
Self::NetworkApi,
Self::Slice,
];
pub const CODES: &'static [&'static str] = &[
"VOICE",
"SMS",
"MMS",
"DATA",
"IMS",
"FIXED",
"IOT",
"NETWORK_API",
"SLICE",
];
#[must_use]
pub const fn primary_measure(self) -> PrimaryMeasure {
match self {
Self::Voice | Self::Ims | Self::Slice => PrimaryMeasure::Duration,
Self::Data | Self::Fixed | Self::Iot => PrimaryMeasure::Volume,
Self::Sms | Self::Mms | Self::NetworkApi => PrimaryMeasure::Events,
}
}
#[must_use]
pub const fn is_subscriber_bound(self) -> bool {
!matches!(self, Self::NetworkApi | Self::Slice)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Voice => "VOICE",
Self::Sms => "SMS",
Self::Mms => "MMS",
Self::Data => "DATA",
Self::Ims => "IMS",
Self::Fixed => "FIXED",
Self::Iot => "IOT",
Self::NetworkApi => "NETWORK_API",
Self::Slice => "SLICE",
}
}
}
impl fmt::Display for ServiceDomain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for ServiceDomain {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let t = s.trim().to_ascii_uppercase();
Self::ALL
.iter()
.find(|d| d.as_str() == t)
.copied()
.ok_or_else(|| ParseError::one_of("ServiceDomain", s, Self::CODES))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RecordType {
MobileOriginatedCall,
MobileTerminatedCall,
ForwardedCall,
SmsOriginated,
SmsTerminated,
MmsOriginated,
MmsTerminated,
PduSession,
PdpContext,
ImsSession,
FixedSession,
NetworkApiInvocation,
SliceLifecycle,
Registration,
}
impl RecordType {
pub const ALL: &'static [Self] = &[
Self::MobileOriginatedCall,
Self::MobileTerminatedCall,
Self::ForwardedCall,
Self::SmsOriginated,
Self::SmsTerminated,
Self::MmsOriginated,
Self::MmsTerminated,
Self::PduSession,
Self::PdpContext,
Self::ImsSession,
Self::FixedSession,
Self::NetworkApiInvocation,
Self::SliceLifecycle,
Self::Registration,
];
pub const CODES: &'static [&'static str] = &[
"MO_CALL",
"MT_CALL",
"FORWARDED_CALL",
"SMS_MO",
"SMS_MT",
"MMS_MO",
"MMS_MT",
"PDU_SESSION",
"PDP_CONTEXT",
"IMS_SESSION",
"FIXED_SESSION",
"NETWORK_API_INVOCATION",
"SLICE_LIFECYCLE",
"REGISTRATION",
];
#[must_use]
pub const fn service_domain(self) -> ServiceDomain {
match self {
Self::MobileOriginatedCall | Self::MobileTerminatedCall | Self::ForwardedCall => {
ServiceDomain::Voice
}
Self::SmsOriginated | Self::SmsTerminated => ServiceDomain::Sms,
Self::MmsOriginated | Self::MmsTerminated => ServiceDomain::Mms,
Self::PduSession | Self::PdpContext | Self::Registration => ServiceDomain::Data,
Self::ImsSession => ServiceDomain::Ims,
Self::FixedSession => ServiceDomain::Fixed,
Self::NetworkApiInvocation => ServiceDomain::NetworkApi,
Self::SliceLifecycle => ServiceDomain::Slice,
}
}
#[must_use]
pub const fn is_session(self) -> bool {
matches!(
self,
Self::MobileOriginatedCall
| Self::MobileTerminatedCall
| Self::ForwardedCall
| Self::PduSession
| Self::PdpContext
| Self::ImsSession
| Self::FixedSession
| Self::SliceLifecycle
)
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::MobileOriginatedCall => "MO_CALL",
Self::MobileTerminatedCall => "MT_CALL",
Self::ForwardedCall => "FORWARDED_CALL",
Self::SmsOriginated => "SMS_MO",
Self::SmsTerminated => "SMS_MT",
Self::MmsOriginated => "MMS_MO",
Self::MmsTerminated => "MMS_MT",
Self::PduSession => "PDU_SESSION",
Self::PdpContext => "PDP_CONTEXT",
Self::ImsSession => "IMS_SESSION",
Self::FixedSession => "FIXED_SESSION",
Self::NetworkApiInvocation => "NETWORK_API_INVOCATION",
Self::SliceLifecycle => "SLICE_LIFECYCLE",
Self::Registration => "REGISTRATION",
}
}
}
impl fmt::Display for RecordType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for RecordType {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let t = s.trim().to_ascii_uppercase();
Self::ALL
.iter()
.find(|r| r.as_str() == t)
.copied()
.ok_or_else(|| ParseError::one_of("RecordType", s, Self::CODES))
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct NodeId(String);
const NODE_ID_FORMAT: &str =
"1 to 64 printable ASCII characters without whitespace, such as pgw-fra-01";
impl NodeId {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for NodeId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for NodeId {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let t = s.trim();
let ok = !t.is_empty()
&& t.len() <= 64
&& t.bytes()
.all(|b| b.is_ascii_graphic() && !b.is_ascii_whitespace());
if ok {
Ok(Self(t.to_owned()))
} else {
Err(ParseError::format("NodeId", s, NODE_ID_FORMAT))
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SourceRef {
pub node_id: NodeId,
pub file_name: Option<String>,
pub file_sequence: Option<u32>,
pub record_index: u32,
}
impl SourceRef {
#[must_use]
pub const fn new(node_id: NodeId, record_index: u32) -> Self {
Self {
node_id,
file_name: None,
file_sequence: None,
record_index,
}
}
#[must_use]
pub fn with_file_name(mut self, name: impl Into<String>) -> Self {
self.file_name = Some(name.into());
self
}
#[must_use]
pub const fn with_file_sequence(mut self, sequence: u32) -> Self {
self.file_sequence = Some(sequence);
self
}
#[must_use]
pub const fn supports_completeness_check(&self) -> bool {
self.file_sequence.is_some()
}
}
impl fmt::Display for SourceRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.node_id)?;
if let Some(name) = &self.file_name {
write!(f, "/{name}")?;
}
if let Some(sequence) = self.file_sequence {
write!(f, "#{sequence}")?;
}
write!(f, ":{}", self.record_index)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UsageRecord {
pub record_type: RecordType,
pub party: ChargedParty,
pub equipment: Option<Pei>,
pub iccid: Option<Iccid>,
pub serving_plmn: Option<PlmnId>,
pub home_plmn: Option<PlmnId>,
pub opened: CdrTimestamp,
pub closed: Option<CdrTimestamp>,
pub duration: Option<Seconds>,
pub volume: Option<VolumePair>,
pub events: Option<u32>,
pub containers: ContainerSet,
pub partial: Option<PartialInfo>,
pub session: SessionContext,
pub correlation: CorrelationKeys,
pub provenance: SourceRef,
}
impl UsageRecord {
#[must_use]
pub const fn new(
record_type: RecordType,
party: ChargedParty,
opened: CdrTimestamp,
provenance: SourceRef,
) -> Self {
Self {
record_type,
party,
equipment: None,
iccid: None,
serving_plmn: None,
home_plmn: None,
opened,
closed: None,
duration: None,
volume: None,
events: None,
containers: ContainerSet::empty(),
partial: None,
session: SessionContext::none(),
correlation: CorrelationKeys::none(),
provenance,
}
}
#[must_use]
pub const fn service(&self) -> ServiceDomain {
self.record_type.service_domain()
}
#[must_use]
pub fn with_correlation(mut self, correlation: CorrelationKeys) -> Self {
self.correlation = correlation;
self
}
#[must_use]
pub fn with_containers(mut self, containers: ContainerSet) -> Self {
self.containers = containers;
self
}
#[must_use]
pub fn with_session(mut self, session: SessionContext) -> Self {
self.session = session;
self
}
#[must_use]
pub const fn with_partial(mut self, partial: PartialInfo) -> Self {
self.partial = Some(partial);
self
}
#[must_use]
pub const fn is_partial(&self) -> bool {
self.partial.is_some()
}
#[must_use]
pub fn billable_volume(&self) -> Option<VolumePair> {
self.volume.or_else(|| {
if self.containers.is_empty() {
None
} else {
self.containers.checked_total()
}
})
}
#[must_use]
pub fn containers_agree(&self) -> Option<bool> {
if self.containers.is_empty() {
return None;
}
self.containers.agrees_with(self.volume)
}
#[must_use]
pub const fn with_closed(mut self, closed: CdrTimestamp) -> Self {
self.closed = Some(closed);
self
}
#[must_use]
pub const fn with_duration(mut self, duration: Seconds) -> Self {
self.duration = Some(duration);
self
}
#[must_use]
pub const fn with_volume(mut self, volume: VolumePair) -> Self {
self.volume = Some(volume);
self
}
#[must_use]
pub const fn with_events(mut self, events: u32) -> Self {
self.events = Some(events);
self
}
#[must_use]
pub const fn with_equipment(mut self, equipment: Pei) -> Self {
self.equipment = Some(equipment);
self
}
#[must_use]
pub const fn with_iccid(mut self, iccid: Iccid) -> Self {
self.iccid = Some(iccid);
self
}
#[must_use]
pub const fn with_networks(mut self, serving: PlmnId, home: PlmnId) -> Self {
self.serving_plmn = Some(serving);
self.home_plmn = Some(home);
self
}
#[must_use]
pub fn wall_clock_span(&self) -> Option<Seconds> {
let closed = self.closed?;
let elapsed = (closed.to_utc() - self.opened.to_utc()).whole_seconds();
u32::try_from(elapsed).ok().map(Seconds::new)
}
#[must_use]
pub fn is_roaming(&self) -> Option<bool> {
let (serving, home) = (self.serving_plmn?, self.home_plmn?);
Some(!serving.is_same_network(home))
}
#[must_use]
pub fn local_date(&self) -> time::Date {
self.opened.local_date()
}
#[must_use]
pub fn is_zero_usage(&self) -> bool {
self.duration.is_none_or(Seconds::is_zero)
&& self.billable_volume().is_none_or(VolumePair::is_zero)
&& self.events.is_none_or(|e| e == 0)
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{NodeId, RecordType, ServiceDomain, SourceRef, UsageRecord};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
macro_rules! string_serde {
($ty:ty, $expecting:literal) => {
impl Serialize for $ty {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for $ty {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = $ty;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str($expecting)
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<$ty, E> {
v.parse().map_err(de::Error::custom)
}
}
deserializer.deserialize_str(V)
}
}
};
}
string_serde!(ServiceDomain, "a service domain code such as \"DATA\"");
string_serde!(RecordType, "a record type code such as \"PDU_SESSION\"");
string_serde!(NodeId, "a node identifier such as \"pgw-fra-01\"");
#[derive(Serialize, Deserialize)]
#[serde(rename = "SourceRef")]
struct SourceRefRepr {
node_id: NodeId,
#[serde(default, skip_serializing_if = "Option::is_none")]
file_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
file_sequence: Option<u32>,
record_index: u32,
}
impl Serialize for SourceRef {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
SourceRefRepr {
node_id: self.node_id.clone(),
file_name: self.file_name.clone(),
file_sequence: self.file_sequence,
record_index: self.record_index,
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for SourceRef {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = SourceRefRepr::deserialize(deserializer)?;
Ok(SourceRef {
node_id: r.node_id,
file_name: r.file_name,
file_sequence: r.file_sequence,
record_index: r.record_index,
})
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "UsageRecord")]
struct UsageRecordRepr {
record_type: RecordType,
party: crate::party::ChargedParty,
#[serde(default, skip_serializing_if = "Option::is_none")]
equipment: Option<crate::identity::Pei>,
#[serde(default, skip_serializing_if = "Option::is_none")]
iccid: Option<crate::identity::Iccid>,
#[serde(default, skip_serializing_if = "Option::is_none")]
serving_plmn: Option<crate::plmn::PlmnId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
home_plmn: Option<crate::plmn::PlmnId>,
opened: crate::cdrtime::CdrTimestamp,
#[serde(default, skip_serializing_if = "Option::is_none")]
closed: Option<crate::cdrtime::CdrTimestamp>,
#[serde(default, skip_serializing_if = "Option::is_none")]
duration_s: Option<crate::cdrtime::Seconds>,
#[serde(default, skip_serializing_if = "Option::is_none")]
volume: Option<crate::volume::VolumePair>,
#[serde(default, skip_serializing_if = "Option::is_none")]
events: Option<u32>,
#[serde(
default,
skip_serializing_if = "crate::container::ContainerSet::is_empty"
)]
containers: crate::container::ContainerSet,
#[serde(default, skip_serializing_if = "Option::is_none")]
partial: Option<crate::partial::PartialInfo>,
#[serde(
default,
skip_serializing_if = "crate::session::SessionContext::is_empty"
)]
session: crate::session::SessionContext,
#[serde(
default,
skip_serializing_if = "crate::correlation::CorrelationKeys::is_empty"
)]
correlation: crate::correlation::CorrelationKeys,
provenance: SourceRef,
}
impl Serialize for UsageRecord {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
UsageRecordRepr {
record_type: self.record_type,
party: self.party.clone(),
equipment: self.equipment,
iccid: self.iccid,
serving_plmn: self.serving_plmn,
home_plmn: self.home_plmn,
opened: self.opened,
closed: self.closed,
duration_s: self.duration,
volume: self.volume,
events: self.events,
containers: self.containers.clone(),
partial: self.partial,
session: self.session.clone(),
correlation: self.correlation.clone(),
provenance: self.provenance.clone(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for UsageRecord {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = UsageRecordRepr::deserialize(deserializer)?;
Ok(UsageRecord {
record_type: r.record_type,
party: r.party,
equipment: r.equipment,
iccid: r.iccid,
serving_plmn: r.serving_plmn,
home_plmn: r.home_plmn,
opened: r.opened,
closed: r.closed,
duration: r.duration_s,
volume: r.volume,
events: r.events,
containers: r.containers,
partial: r.partial,
session: r.session,
correlation: r.correlation,
provenance: r.provenance,
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::party::SubscriberRef;
use crate::volume::Octets;
fn party() -> ChargedParty {
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap()))
}
fn source() -> SourceRef {
SourceRef::new("pgw-fra-01".parse().unwrap(), 0)
}
fn call() -> UsageRecord {
UsageRecord::new(
RecordType::MobileOriginatedCall,
party(),
"2026-07-28T10:00:00+02:00".parse().unwrap(),
source(),
)
}
#[test]
fn chargeable_duration_and_wall_clock_span_are_different_numbers() {
let record = call()
.with_closed("2026-07-28T10:00:55+02:00".parse().unwrap())
.with_duration(Seconds::new(10));
assert_eq!(record.duration, Some(Seconds::new(10)));
assert_eq!(record.wall_clock_span(), Some(Seconds::new(55)));
let unanswered = call().with_closed("2026-07-28T10:00:45+02:00".parse().unwrap());
assert_eq!(unanswered.duration, None);
assert_eq!(unanswered.wall_clock_span(), Some(Seconds::new(45)));
}
#[test]
fn a_record_that_closed_before_it_opened_has_no_span() {
let broken = call().with_closed("2026-07-28T09:59:00+02:00".parse().unwrap());
assert_eq!(broken.wall_clock_span(), None);
assert_eq!(call().wall_clock_span(), None);
}
#[test]
fn a_span_across_a_dst_transition_measures_the_real_elapsed_time() {
let record = UsageRecord::new(
RecordType::PduSession,
party(),
"2026-03-29T01:50:00+01:00".parse().unwrap(),
source(),
)
.with_closed("2026-03-29T03:20:00+02:00".parse().unwrap());
assert_eq!(record.wall_clock_span(), Some(Seconds::new(30 * 60)));
}
#[test]
fn roaming_is_unknown_rather_than_false_when_a_network_is_missing() {
let home: PlmnId = "262-02".parse().unwrap();
let visited: PlmnId = "310-260".parse().unwrap();
assert_eq!(call().is_roaming(), None);
assert_eq!(call().with_networks(home, home).is_roaming(), Some(false));
assert_eq!(call().with_networks(visited, home).is_roaming(), Some(true));
}
#[test]
fn zero_usage_is_detected_across_all_three_quantities() {
assert!(call().is_zero_usage());
assert!(call().with_duration(Seconds::ZERO).is_zero_usage());
assert!(!call().with_duration(Seconds::new(1)).is_zero_usage());
assert!(
!call()
.with_volume(VolumePair::new(Octets::ZERO, Octets::new(1)))
.is_zero_usage()
);
assert!(!call().with_events(1).is_zero_usage());
}
#[test]
fn the_service_domain_follows_from_the_record_type() {
assert_eq!(call().service(), ServiceDomain::Voice);
let session = UsageRecord::new(
RecordType::PduSession,
party(),
"2026-07-28T10:00:00+02:00".parse().unwrap(),
source(),
);
assert_eq!(session.service(), ServiceDomain::Data);
assert_eq!(session.service(), session.record_type.service_domain());
}
#[test]
fn correlators_are_optional_and_additive() {
use crate::correlation::{ChargingId, CorrelationKeys};
use std::net::Ipv4Addr;
assert!(call().correlation.packet_session().is_none());
let keyed = call().with_correlation(
CorrelationKeys::default()
.with_charging_id(ChargingId::new(7))
.with_gateway(Ipv4Addr::new(10, 0, 0, 1).into()),
);
assert!(keyed.correlation.packet_session().is_some());
assert_eq!(keyed.duration, call().duration);
}
#[test]
fn every_record_type_maps_to_a_domain_and_every_code_round_trips() {
assert_eq!(RecordType::ALL.len(), RecordType::CODES.len());
for (r, code) in RecordType::ALL.iter().zip(RecordType::CODES) {
assert_eq!(r.as_str(), *code);
assert_eq!(code.parse::<RecordType>().unwrap(), *r);
assert!(ServiceDomain::ALL.contains(&r.service_domain()));
}
assert_eq!(ServiceDomain::ALL.len(), ServiceDomain::CODES.len());
for (d, code) in ServiceDomain::ALL.iter().zip(ServiceDomain::CODES) {
assert_eq!(d.as_str(), *code);
assert_eq!(code.parse::<ServiceDomain>().unwrap(), *d);
}
}
#[test]
fn only_network_api_and_slice_are_subscriber_free() {
for d in ServiceDomain::ALL {
let expected = !matches!(d, ServiceDomain::NetworkApi | ServiceDomain::Slice);
assert_eq!(d.is_subscriber_bound(), expected, "{d}");
}
}
#[test]
fn provenance_reports_whether_gaps_are_detectable() {
let bare = source();
assert!(!bare.supports_completeness_check());
assert_eq!(bare.to_string(), "pgw-fra-01:0");
let full = source()
.with_file_name("CDR-20260728-0001")
.with_file_sequence(1);
assert!(full.supports_completeness_check());
assert_eq!(full.to_string(), "pgw-fra-01/CDR-20260728-0001#1:0");
}
#[test]
fn node_identifiers_reject_whitespace_and_overlong_input() {
assert!("pgw-fra-01".parse::<NodeId>().is_ok());
for s in ["", "has space", &"x".repeat(65)] {
assert!(s.parse::<NodeId>().is_err(), "{s:?} must not parse");
}
}
#[test]
fn sessions_and_events_are_distinguished() {
assert!(RecordType::PduSession.is_session());
assert!(RecordType::MobileOriginatedCall.is_session());
assert!(!RecordType::SmsOriginated.is_session());
assert!(!RecordType::NetworkApiInvocation.is_session());
}
#[test]
fn the_primary_measure_matches_the_domain() {
assert_eq!(
ServiceDomain::Voice.primary_measure(),
PrimaryMeasure::Duration
);
assert_eq!(
ServiceDomain::Data.primary_measure(),
PrimaryMeasure::Volume
);
assert_eq!(ServiceDomain::Sms.primary_measure(), PrimaryMeasure::Events);
assert_eq!(
ServiceDomain::NetworkApi.primary_measure(),
PrimaryMeasure::Events
);
}
}