use std::collections::HashMap;
use std::fmt;
use crate::correlation::{Icid, PacketSessionId};
use crate::record::UsageRecord;
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum CorrelationKey {
PacketBearer(PacketSessionId),
ImsSession(Icid),
}
impl CorrelationKey {
#[must_use]
pub const fn kind(&self) -> &'static str {
match self {
Self::PacketBearer(_) => "PACKET_BEARER",
Self::ImsSession(_) => "IMS_SESSION",
}
}
}
impl fmt::Display for CorrelationKey {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::PacketBearer(session) => write!(f, "PACKET_BEARER:{session}"),
Self::ImsSession(icid) => write!(f, "IMS_SESSION:{icid}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CorrelationConfig {
join_packet_bearers: bool,
join_ims_sessions: bool,
follow_leg_chains: bool,
}
impl CorrelationConfig {
#[must_use]
pub const fn packet_bearer() -> Self {
Self {
join_packet_bearers: true,
join_ims_sessions: false,
follow_leg_chains: false,
}
}
#[must_use]
pub const fn ims() -> Self {
Self {
join_packet_bearers: false,
join_ims_sessions: true,
follow_leg_chains: true,
}
}
#[must_use]
pub const fn all() -> Self {
Self {
join_packet_bearers: true,
join_ims_sessions: true,
follow_leg_chains: true,
}
}
#[must_use]
pub const fn without_leg_chains(mut self) -> Self {
self.follow_leg_chains = false;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CorrelatedGroup {
pub key: CorrelationKey,
pub members: Vec<usize>,
pub quantity_bearing: usize,
}
impl CorrelatedGroup {
#[must_use]
pub const fn would_double_count(&self) -> bool {
self.quantity_bearing > 1
}
#[must_use]
pub fn is_solitary(&self) -> bool {
self.members.len() == 1
}
#[must_use]
pub fn len(&self) -> usize {
self.members.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
false
}
}
impl fmt::Display for CorrelatedGroup {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} — {} record(s), {} bearing a quantity",
self.key,
self.members.len(),
self.quantity_bearing
)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum UnmatchedReason {
NoCorrelator,
PredecessorAbsent,
}
impl UnmatchedReason {
pub const ALL: &'static [Self] = &[Self::NoCorrelator, Self::PredecessorAbsent];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::NoCorrelator => "NO_CORRELATOR",
Self::PredecessorAbsent => "PREDECESSOR_ABSENT",
}
}
}
impl fmt::Display for UnmatchedReason {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Unmatched {
pub record_index: usize,
pub reason: UnmatchedReason,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LegChain {
pub legs: Vec<Icid>,
}
impl LegChain {
#[must_use]
pub fn len(&self) -> usize {
self.legs.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
false
}
#[must_use]
pub fn is_forwarded(&self) -> bool {
self.legs.len() > 1
}
#[must_use]
pub fn origin(&self) -> &Icid {
&self.legs[0]
}
}
impl fmt::Display for LegChain {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (position, leg) in self.legs.iter().enumerate() {
if position > 0 {
f.write_str(" → ")?;
}
write!(f, "{leg}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct CorrelationResult {
groups: Vec<CorrelatedGroup>,
unmatched: Vec<Unmatched>,
chains: Vec<LegChain>,
}
impl CorrelationResult {
#[must_use]
pub fn groups(&self) -> &[CorrelatedGroup] {
&self.groups
}
#[must_use]
pub fn unmatched(&self) -> &[Unmatched] {
&self.unmatched
}
#[must_use]
pub fn chains(&self) -> &[LegChain] {
&self.chains
}
#[must_use]
pub fn double_counting_groups(&self) -> Vec<&CorrelatedGroup> {
self.groups
.iter()
.filter(|g| g.would_double_count())
.collect()
}
#[must_use]
pub fn accounts_for(&self, total: usize) -> bool {
let grouped: usize = self.groups.iter().map(CorrelatedGroup::len).sum();
grouped + self.unmatched.len() == total
}
}
impl fmt::Display for CorrelationResult {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{} group(s), {} unmatched, {} chain(s), {} at risk of double counting",
self.groups.len(),
self.unmatched.len(),
self.chains.len(),
self.double_counting_groups().len()
)
}
}
#[must_use]
pub fn correlate(records: &[UsageRecord], config: &CorrelationConfig) -> CorrelationResult {
let mut buckets: HashMap<CorrelationKey, Vec<usize>> = HashMap::new();
let mut unmatched = Vec::new();
for (index, record) in records.iter().enumerate() {
let key = if config.join_packet_bearers
&& let Some(session) = record.correlation.packet_session()
{
Some(CorrelationKey::PacketBearer(session))
} else if config.join_ims_sessions
&& let Some(icid) = &record.correlation.icid
{
Some(CorrelationKey::ImsSession(icid.clone()))
} else {
None
};
match key {
Some(key) => buckets.entry(key).or_default().push(index),
None => unmatched.push(Unmatched {
record_index: index,
reason: UnmatchedReason::NoCorrelator,
}),
}
}
let mut groups: Vec<CorrelatedGroup> = buckets
.into_iter()
.map(|(key, mut members)| {
members.sort_unstable();
let quantity_bearing = members
.iter()
.filter(|index| !records[**index].is_zero_usage())
.count();
CorrelatedGroup {
key,
members,
quantity_bearing,
}
})
.collect();
groups.sort_by_key(|group| group.members[0]);
let chains = if config.follow_leg_chains {
build_leg_chains(records, &mut unmatched)
} else {
Vec::new()
};
unmatched.sort_by_key(|u| u.record_index);
CorrelationResult {
groups,
unmatched,
chains,
}
}
fn build_leg_chains(records: &[UsageRecord], unmatched: &mut Vec<Unmatched>) -> Vec<LegChain> {
let mut present: HashMap<&Icid, usize> = HashMap::new();
let mut successor: HashMap<&Icid, &Icid> = HashMap::new();
let mut linked_from: Vec<(usize, &Icid, &Icid)> = Vec::new();
for (index, record) in records.iter().enumerate() {
if let Some(icid) = &record.correlation.icid {
present.entry(icid).or_insert(index);
if let Some(previous) = &record.correlation.linked_icid {
linked_from.push((index, icid, previous));
}
}
}
for (index, icid, previous) in &linked_from {
if present.contains_key(previous) {
successor.insert(previous, icid);
} else {
unmatched.push(Unmatched {
record_index: *index,
reason: UnmatchedReason::PredecessorAbsent,
});
}
}
let has_predecessor: std::collections::HashSet<&Icid> = linked_from
.iter()
.filter(|(_, _, previous)| present.contains_key(previous))
.map(|(_, icid, _)| *icid)
.collect();
let mut origins: Vec<(&Icid, usize)> = present
.iter()
.filter(|(icid, _)| !has_predecessor.contains(*icid))
.map(|(icid, index)| (*icid, *index))
.collect();
origins.sort_by_key(|(_, index)| *index);
origins
.into_iter()
.map(|(origin, _)| {
let mut legs = vec![origin.clone()];
let mut cursor = origin;
while legs.len() <= present.len()
&& let Some(next) = successor.get(cursor)
{
legs.push((*next).clone());
cursor = next;
}
LegChain { legs }
})
.collect()
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{CorrelationKey, LegChain, Unmatched, UnmatchedReason};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
impl Serialize for UnmatchedReason {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for UnmatchedReason {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct V;
impl Visitor<'_> for V {
type Value = UnmatchedReason;
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("an unmatched reason code")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<UnmatchedReason, E> {
UnmatchedReason::ALL
.iter()
.find(|r| r.as_str() == v)
.copied()
.ok_or_else(|| de::Error::custom(format!("unknown reason {v:?}")))
}
}
deserializer.deserialize_str(V)
}
}
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename = "CorrelationKey")]
enum KeyRepr {
#[serde(rename = "PACKET_BEARER")]
PacketBearer {
session: crate::correlation::PacketSessionId,
},
#[serde(rename = "IMS_SESSION")]
ImsSession { icid: crate::correlation::Icid },
}
impl Serialize for CorrelationKey {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Self::PacketBearer(session) => KeyRepr::PacketBearer { session: *session },
Self::ImsSession(icid) => KeyRepr::ImsSession { icid: icid.clone() },
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for CorrelationKey {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
Ok(match KeyRepr::deserialize(deserializer)? {
KeyRepr::PacketBearer { session } => Self::PacketBearer(session),
KeyRepr::ImsSession { icid } => Self::ImsSession(icid),
})
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "Unmatched")]
struct UnmatchedRepr {
record_index: usize,
reason: UnmatchedReason,
}
impl Serialize for Unmatched {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
UnmatchedRepr {
record_index: self.record_index,
reason: self.reason,
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for Unmatched {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = UnmatchedRepr::deserialize(deserializer)?;
Ok(Unmatched {
record_index: r.record_index,
reason: r.reason,
})
}
}
impl Serialize for LegChain {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
self.legs.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for LegChain {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let legs = Vec::<crate::correlation::Icid>::deserialize(deserializer)?;
if legs.is_empty() {
return Err(de::Error::custom("a leg chain has at least one leg"));
}
Ok(LegChain { legs })
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::correlation::{ChargingId, CorrelationKeys};
use crate::party::{ChargedParty, SubscriberRef};
use crate::record::{RecordType, SourceRef};
use crate::volume::{Octets, VolumePair};
use std::net::Ipv4Addr;
fn record(node: &str, keys: CorrelationKeys, volume: Option<VolumePair>) -> UsageRecord {
let mut record = UsageRecord::new(
RecordType::PduSession,
ChargedParty::Subscriber(SubscriberRef::new("imsi-262021234567890".parse().unwrap())),
"2026-07-28T10:00:00+02:00".parse().unwrap(),
SourceRef::new(node.parse().unwrap(), 0),
)
.with_correlation(keys);
record.volume = volume;
record
}
fn bearer(charging_id: u32) -> CorrelationKeys {
CorrelationKeys::default()
.with_charging_id(ChargingId::new(charging_id))
.with_gateway(Ipv4Addr::new(10, 0, 0, 1).into())
}
fn some_volume() -> Option<VolumePair> {
Some(VolumePair::new(Octets::new(100), Octets::new(900)))
}
#[test]
fn two_nodes_on_one_bearer_are_flagged_before_they_are_billed_twice() {
let records = vec![
record("sgw-01", bearer(42), some_volume()),
record("pgw-01", bearer(42), some_volume()),
];
let result = correlate(&records, &CorrelationConfig::packet_bearer());
assert_eq!(result.groups().len(), 1);
let group = &result.groups()[0];
assert_eq!(group.members, vec![0, 1]);
assert_eq!(group.quantity_bearing, 2);
assert!(group.would_double_count());
assert_eq!(result.double_counting_groups().len(), 1);
}
#[test]
fn a_quantityless_counterpart_is_not_double_counting() {
let records = vec![
record("sgw-01", bearer(42), None),
record("pgw-01", bearer(42), some_volume()),
];
let result = correlate(&records, &CorrelationConfig::packet_bearer());
let group = &result.groups()[0];
assert_eq!(group.len(), 2);
assert_eq!(group.quantity_bearing, 1);
assert!(!group.would_double_count());
}
#[test]
fn the_gateway_is_part_of_the_join() {
let other_gateway = CorrelationKeys::default()
.with_charging_id(ChargingId::new(42))
.with_gateway(Ipv4Addr::new(10, 0, 0, 2).into());
let records = vec![
record("pgw-01", bearer(42), some_volume()),
record("pgw-02", other_gateway, some_volume()),
];
let result = correlate(&records, &CorrelationConfig::packet_bearer());
assert_eq!(result.groups().len(), 2);
assert!(result.groups().iter().all(CorrelatedGroup::is_solitary));
}
#[test]
fn every_record_is_accounted_for() {
let records = vec![
record("pgw-01", bearer(1), some_volume()),
record("sgw-01", bearer(1), some_volume()),
record("smsc-01", CorrelationKeys::none(), some_volume()),
record("pgw-01", bearer(2), some_volume()),
];
let result = correlate(&records, &CorrelationConfig::packet_bearer());
assert!(result.accounts_for(records.len()));
assert_eq!(result.unmatched().len(), 1);
assert_eq!(result.unmatched()[0].record_index, 2);
assert_eq!(result.unmatched()[0].reason, UnmatchedReason::NoCorrelator);
}
#[test]
fn the_join_is_order_independent() {
let make = |order: [usize; 4]| {
let all = [
record("pgw-01", bearer(1), some_volume()),
record("sgw-01", bearer(1), some_volume()),
record("pgw-01", bearer(2), some_volume()),
record("sgw-01", bearer(2), some_volume()),
];
order.map(|i| all[i].clone()).to_vec()
};
let forward = correlate(&make([0, 1, 2, 3]), &CorrelationConfig::packet_bearer());
let shuffled = correlate(&make([3, 1, 0, 2]), &CorrelationConfig::packet_bearer());
assert_eq!(forward.groups().len(), shuffled.groups().len());
for result in [&forward, &shuffled] {
assert!(result.groups().iter().all(|g| g.len() == 2));
assert!(result.accounts_for(4));
}
}
fn leg(icid: &str, linked: Option<&str>) -> UsageRecord {
let mut keys = CorrelationKeys::default().with_icid(icid.parse().unwrap());
if let Some(previous) = linked {
keys = keys.with_linked_icid(previous.parse().unwrap());
}
record("scscf-01", keys, some_volume())
}
#[test]
fn a_forwarded_call_reassembles_into_one_history() {
let records = vec![
leg("leg-a", None),
leg("leg-b", Some("leg-a")),
leg("leg-c", Some("leg-b")),
];
let result = correlate(&records, &CorrelationConfig::ims());
assert_eq!(result.chains().len(), 1);
let chain = &result.chains()[0];
assert_eq!(chain.len(), 3);
assert!(chain.is_forwarded());
assert_eq!(chain.origin().as_str(), "leg-a");
assert_eq!(chain.to_string(), "leg-a → leg-b → leg-c");
}
#[test]
fn a_lost_predecessor_is_reported_rather_than_assumed_to_be_the_origin() {
let records = vec![leg("leg-b", Some("leg-a"))];
let result = correlate(&records, &CorrelationConfig::ims());
assert_eq!(result.unmatched().len(), 1);
assert_eq!(
result.unmatched()[0].reason,
UnmatchedReason::PredecessorAbsent
);
assert_eq!(result.chains().len(), 1);
assert!(!result.chains()[0].is_forwarded());
}
#[test]
fn a_direct_call_is_a_chain_of_one() {
let result = correlate(&[leg("leg-a", None)], &CorrelationConfig::ims());
assert_eq!(result.chains().len(), 1);
assert!(!result.chains()[0].is_forwarded());
assert!(result.unmatched().is_empty());
}
#[test]
fn a_cycle_in_linked_identifiers_terminates() {
let records = vec![leg("leg-a", Some("leg-b")), leg("leg-b", Some("leg-a"))];
let result = correlate(&records, &CorrelationConfig::ims());
assert!(result.chains().iter().all(|c| c.len() <= 2));
assert!(result.accounts_for(records.len()));
}
#[test]
fn leg_chains_can_be_switched_off() {
let records = vec![leg("leg-a", None), leg("leg-b", Some("leg-a"))];
let result = correlate(&records, &CorrelationConfig::ims().without_leg_chains());
assert!(result.chains().is_empty());
assert_eq!(result.groups().len(), 2);
}
#[test]
fn packet_and_ims_records_can_be_joined_together() {
let records = vec![
record("pgw-01", bearer(1), some_volume()),
leg("leg-a", None),
];
let result = correlate(&records, &CorrelationConfig::all());
assert_eq!(result.groups().len(), 2);
assert_eq!(result.groups()[0].key.kind(), "PACKET_BEARER");
assert_eq!(result.groups()[1].key.kind(), "IMS_SESSION");
assert!(result.accounts_for(2));
}
#[test]
fn an_empty_input_produces_an_empty_result() {
let result = correlate(&[], &CorrelationConfig::all());
assert!(result.groups().is_empty());
assert!(result.unmatched().is_empty());
assert!(result.accounts_for(0));
assert_eq!(result.double_counting_groups().len(), 0);
}
}