use std::collections::HashMap;
use std::fmt;
use std::net::IpAddr;
use std::str::FromStr;
use crate::error::ParseError;
use crate::record::{NodeId, UsageRecord};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChargingId(u32);
impl ChargingId {
#[must_use]
pub const fn new(value: u32) -> Self {
Self(value)
}
#[must_use]
pub const fn get(self) -> u32 {
self.0
}
}
impl fmt::Display for ChargingId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for ChargingId {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
s.trim()
.parse::<u32>()
.map(Self)
.map_err(|_| ParseError::format("ChargingId", s, "a 32-bit unsigned decimal integer"))
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Icid(String);
const ICID_FORMAT: &str = "1 to 255 printable ASCII characters without whitespace";
impl Icid {
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Display for Icid {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for Icid {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let t = s.trim();
let ok = !t.is_empty() && t.len() <= 255 && t.bytes().all(|b| b.is_ascii_graphic());
if ok {
Ok(Self(t.to_owned()))
} else {
Err(ParseError::format("Icid", s, ICID_FORMAT))
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CallId(String);
const CALL_ID_FORMAT: &str = "1 to 256 RFC 3261 word characters with at most one '@', such as a84b4c76e66710@pc33.example.com";
impl CallId {
pub const MAX_LEN: usize = 256;
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
const fn is_word_char(b: u8) -> bool {
b.is_ascii_alphanumeric()
|| matches!(
b,
b'-' | b'.'
| b'!'
| b'%'
| b'*'
| b'_'
| b'+'
| b'`'
| b'\''
| b'~'
| b'('
| b')'
| b'<'
| b'>'
| b':'
| b'\\'
| b'"'
| b'/'
| b'['
| b']'
| b'?'
| b'{'
| b'}'
)
}
impl fmt::Display for CallId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl FromStr for CallId {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let t = s.trim();
let mut parts = t.split('@');
let ok = !t.is_empty()
&& t.len() <= Self::MAX_LEN
&& parts.clone().count() <= 2
&& parts.all(|w| !w.is_empty() && w.bytes().all(is_word_char));
if ok {
Ok(Self(t.to_owned()))
} else {
Err(ParseError::withheld("CallId", CALL_ID_FORMAT))
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PacketSessionId {
charging_id: ChargingId,
gateway: IpAddr,
}
impl PacketSessionId {
#[must_use]
pub const fn new(charging_id: ChargingId, gateway: IpAddr) -> Self {
Self {
charging_id,
gateway,
}
}
#[must_use]
pub const fn charging_id(self) -> ChargingId {
self.charging_id
}
#[must_use]
pub const fn gateway(self) -> IpAddr {
self.gateway
}
}
impl fmt::Display for PacketSessionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}@{}", self.charging_id, self.gateway)
}
}
const PACKET_SESSION_FORMAT: &str =
"a charging identifier and gateway address, such as 1234@10.0.0.1";
impl FromStr for PacketSessionId {
type Err = ParseError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
let err = || ParseError::format("PacketSessionId", s, PACKET_SESSION_FORMAT);
let (id, gateway) = s.trim().rsplit_once('@').ok_or_else(err)?;
Ok(Self::new(
id.parse().map_err(|_| err())?,
gateway.parse().map_err(|_| err())?,
))
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CorrelationKeys {
pub charging_id: Option<ChargingId>,
pub gateway: Option<IpAddr>,
pub icid: Option<Icid>,
pub linked_icid: Option<Icid>,
pub record_sequence_number: Option<u32>,
pub local_sequence_number: Option<u32>,
pub recording_entity: Option<NodeId>,
pub call_id: Option<CallId>,
}
impl CorrelationKeys {
#[must_use]
pub const fn none() -> Self {
Self {
charging_id: None,
gateway: None,
icid: None,
linked_icid: None,
record_sequence_number: None,
local_sequence_number: None,
recording_entity: None,
call_id: None,
}
}
#[must_use]
pub const fn packet_session(&self) -> Option<PacketSessionId> {
match (self.charging_id, self.gateway) {
(Some(id), Some(gateway)) => Some(PacketSessionId::new(id, gateway)),
_ => None,
}
}
#[must_use]
pub const fn is_linked_leg(&self) -> bool {
self.linked_icid.is_some()
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.charging_id.is_none()
&& self.gateway.is_none()
&& self.icid.is_none()
&& self.linked_icid.is_none()
&& self.record_sequence_number.is_none()
&& self.local_sequence_number.is_none()
&& self.recording_entity.is_none()
&& self.call_id.is_none()
}
#[must_use]
pub const fn entity_serial(&self) -> Option<(&NodeId, u32)> {
match (&self.recording_entity, self.local_sequence_number) {
(Some(entity), Some(serial)) => Some((entity, serial)),
_ => None,
}
}
#[must_use]
pub const fn entity_call(&self) -> Option<(&NodeId, &CallId)> {
match (&self.recording_entity, &self.call_id) {
(Some(entity), Some(call_id)) => Some((entity, call_id)),
_ => None,
}
}
#[must_use]
pub fn with_call_id(mut self, call_id: CallId) -> Self {
self.call_id = Some(call_id);
self
}
#[must_use]
pub fn with_charging_id(mut self, id: ChargingId) -> Self {
self.charging_id = Some(id);
self
}
#[must_use]
pub fn with_gateway(mut self, gateway: IpAddr) -> Self {
self.gateway = Some(gateway);
self
}
#[must_use]
pub fn with_icid(mut self, icid: Icid) -> Self {
self.icid = Some(icid);
self
}
#[must_use]
pub fn with_linked_icid(mut self, icid: Icid) -> Self {
self.linked_icid = Some(icid);
self
}
#[must_use]
pub const fn with_record_sequence(mut self, sequence: u32) -> Self {
self.record_sequence_number = Some(sequence);
self
}
#[must_use]
pub const fn with_local_sequence(mut self, sequence: u32) -> Self {
self.local_sequence_number = Some(sequence);
self
}
#[must_use]
pub fn with_recording_entity(mut self, entity: NodeId) -> Self {
self.recording_entity = Some(entity);
self
}
}
#[cfg(feature = "serde")]
mod serde_impl {
use super::{CallId, ChargingId, CorrelationKeys, Icid, PacketSessionId};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
use std::net::IpAddr;
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!(Icid, "an IMS charging identifier");
string_serde!(
CallId,
"a SIP Call-ID such as \"a84b4c76e66710@pc33.example.com\""
);
string_serde!(
PacketSessionId,
"a charging identifier and gateway, such as \"1234@10.0.0.1\""
);
impl Serialize for ChargingId {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.serialize_u32(self.get())
}
}
impl<'de> Deserialize<'de> for ChargingId {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
u32::deserialize(deserializer).map(ChargingId::new)
}
}
#[derive(Serialize, Deserialize)]
#[serde(rename = "CorrelationKeys")]
struct CorrelationKeysRepr {
#[serde(default, skip_serializing_if = "Option::is_none")]
charging_id: Option<ChargingId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
gateway: Option<IpAddr>,
#[serde(default, skip_serializing_if = "Option::is_none")]
icid: Option<Icid>,
#[serde(default, skip_serializing_if = "Option::is_none")]
linked_icid: Option<Icid>,
#[serde(default, skip_serializing_if = "Option::is_none")]
record_sequence_number: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
local_sequence_number: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
recording_entity: Option<crate::record::NodeId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
call_id: Option<CallId>,
}
impl Serialize for CorrelationKeys {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
CorrelationKeysRepr {
charging_id: self.charging_id,
gateway: self.gateway,
icid: self.icid.clone(),
linked_icid: self.linked_icid.clone(),
record_sequence_number: self.record_sequence_number,
local_sequence_number: self.local_sequence_number,
recording_entity: self.recording_entity.clone(),
call_id: self.call_id.clone(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for CorrelationKeys {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = CorrelationKeysRepr::deserialize(deserializer)?;
Ok(CorrelationKeys {
charging_id: r.charging_id,
gateway: r.gateway,
icid: r.icid,
linked_icid: r.linked_icid,
record_sequence_number: r.record_sequence_number,
local_sequence_number: r.local_sequence_number,
recording_entity: r.recording_entity,
call_id: r.call_id,
})
}
}
}
#[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,
CorrelatorNotJoined,
}
impl UnmatchedReason {
pub const ALL: &'static [Self] = &[Self::NoCorrelator, Self::CorrelatorNotJoined];
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::NoCorrelator => "NO_CORRELATOR",
Self::CorrelatorNotJoined => "CORRELATOR_NOT_JOINED",
}
}
}
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 BrokenLeg {
pub record_index: usize,
pub missing: Icid,
}
#[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>,
broken_legs: Vec<BrokenLeg>,
}
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 broken_legs(&self) -> &[BrokenLeg] {
&self.broken_legs
}
#[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), {} broken leg(s), {} at risk of double counting",
self.groups.len(),
self.unmatched.len(),
self.chains.len(),
self.broken_legs.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 => {
let carries_one = record.correlation.packet_session().is_some()
|| record.correlation.icid.is_some();
unmatched.push(Unmatched {
record_index: index,
reason: if carries_one {
UnmatchedReason::CorrelatorNotJoined
} else {
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 mut broken_legs = Vec::new();
let chains = if config.follow_leg_chains {
build_leg_chains(records, &mut broken_legs)
} else {
Vec::new()
};
unmatched.sort_by_key(|u| u.record_index);
broken_legs.sort_by_key(|b| b.record_index);
CorrelationResult {
groups,
unmatched,
chains,
broken_legs,
}
}
fn build_leg_chains(records: &[UsageRecord], broken: &mut Vec<BrokenLeg>) -> 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 {
broken.push(BrokenLeg {
record_index: *index,
missing: (*previous).clone(),
});
}
}
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 correlate_serde {
use super::{BrokenLeg, CorrelationKey, LegChain, Unmatched, UnmatchedReason};
use serde::de::{self, Visitor};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::fmt;
#[derive(Serialize, Deserialize)]
#[serde(rename = "BrokenLeg")]
struct BrokenLegRepr {
record_index: usize,
missing: crate::correlation::Icid,
}
impl Serialize for BrokenLeg {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
BrokenLegRepr {
record_index: self.record_index,
missing: self.missing.clone(),
}
.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for BrokenLeg {
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let r = BrokenLegRepr::deserialize(deserializer)?;
Ok(BrokenLeg {
record_index: r.record_index,
missing: r.missing,
})
}
}
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 std::net::{Ipv4Addr, Ipv6Addr};
#[test]
fn a_charging_id_alone_does_not_identify_a_session() {
let bare = CorrelationKeys::default().with_charging_id(ChargingId::new(1_234));
assert!(bare.packet_session().is_none());
let complete = bare.clone().with_gateway(Ipv4Addr::new(10, 0, 0, 1).into());
assert!(complete.packet_session().is_some());
let other = bare.with_gateway(Ipv4Addr::new(10, 0, 0, 2).into());
assert_ne!(complete.packet_session(), other.packet_session());
}
#[test]
fn a_gateway_without_a_charging_id_is_equally_useless() {
let keys = CorrelationKeys::default().with_gateway(Ipv4Addr::LOCALHOST.into());
assert!(keys.packet_session().is_none());
}
#[test]
fn packet_session_identifiers_round_trip_over_both_address_families() {
for raw in [
"1234@10.0.0.1",
"0@127.0.0.1",
"4294967295@2001:db8::1",
"7@::1",
] {
let id: PacketSessionId = raw.parse().unwrap();
assert_eq!(id.to_string(), raw);
}
}
#[test]
fn an_ipv6_gateway_does_not_confuse_the_parser() {
let id: PacketSessionId = "99@2001:db8::dead:beef".parse().unwrap();
assert_eq!(id.charging_id(), ChargingId::new(99));
assert_eq!(
id.gateway(),
IpAddr::V6("2001:db8::dead:beef".parse::<Ipv6Addr>().unwrap())
);
}
#[test]
fn malformed_session_identifiers_are_rejected() {
for s in [
"1234",
"@10.0.0.1",
"1234@",
"abc@10.0.0.1",
"1234@not-an-ip",
"",
] {
assert!(
s.parse::<PacketSessionId>().is_err(),
"{s:?} must not parse"
);
}
}
#[test]
fn a_linked_icid_is_a_separate_field() {
let keys = CorrelationKeys::default()
.with_icid("leg-2".parse().unwrap())
.with_linked_icid("leg-1".parse().unwrap());
assert!(keys.is_linked_leg());
assert_ne!(keys.icid, keys.linked_icid);
assert_eq!(keys.icid.unwrap().as_str(), "leg-2");
}
#[test]
fn a_serial_number_is_nothing_without_its_recording_entity() {
let serial_only = CorrelationKeys::default().with_local_sequence(42);
assert_eq!(serial_only.entity_serial(), None);
let entity_only =
CorrelationKeys::default().with_recording_entity("msc-01".parse().unwrap());
assert_eq!(entity_only.entity_serial(), None);
let complete = serial_only.with_recording_entity("msc-01".parse().unwrap());
let (entity, serial) = complete.entity_serial().unwrap();
assert_eq!(entity.as_str(), "msc-01");
assert_eq!(serial, 42);
}
#[test]
fn icids_reject_whitespace_and_overlong_input() {
assert!("abc123".parse::<Icid>().is_ok());
for s in ["", "has space", &"x".repeat(256)] {
assert!(s.parse::<Icid>().is_err(), "{s:?} must not parse");
}
}
#[test]
fn charging_identifiers_round_trip() {
for raw in ["0", "1234", "4294967295"] {
assert_eq!(raw.parse::<ChargingId>().unwrap().to_string(), raw);
}
assert!("4294967296".parse::<ChargingId>().is_err());
assert!("-1".parse::<ChargingId>().is_err());
}
use crate::party::{ChargedParty, SubscriberRef};
use crate::record::{RecordType, SourceRef};
use crate::volume::{Octets, VolumePair};
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.broken_legs().len(), 1);
assert_eq!(result.broken_legs()[0].record_index, 0);
assert_eq!(result.broken_legs()[0].missing.as_str(), "leg-a");
assert!(result.unmatched().is_empty());
assert!(
result.accounts_for(records.len()),
"every record exactly once: {result}"
);
assert_eq!(result.chains().len(), 1);
assert!(!result.chains()[0].is_forwarded());
}
#[test]
fn every_record_is_accounted_for_exactly_once() {
let batches: Vec<Vec<UsageRecord>> = vec![
vec![],
vec![leg("leg-a", None)],
vec![leg("leg-b", Some("leg-a"))],
vec![leg("leg-a", None), leg("leg-b", Some("leg-a"))],
vec![leg("leg-a", Some("leg-b")), leg("leg-b", Some("leg-a"))],
vec![
record("sgw-01", bearer(42), some_volume()),
record("pgw-01", bearer(42), some_volume()),
leg("leg-a", None),
],
vec![record("msc-01", CorrelationKeys::default(), None)],
];
for records in batches {
for config in [
CorrelationConfig::all(),
CorrelationConfig::ims(),
CorrelationConfig::packet_bearer(),
] {
let result = correlate(&records, &config);
assert!(
result.accounts_for(records.len()),
"{} record(s): {result}",
records.len()
);
}
}
}
#[test]
fn a_correlator_the_configuration_ignores_says_so() {
let records = vec![leg("leg-a", None)];
let result = correlate(&records, &CorrelationConfig::packet_bearer());
assert_eq!(result.unmatched().len(), 1);
assert_eq!(
result.unmatched()[0].reason,
UnmatchedReason::CorrelatorNotJoined
);
}
#[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);
}
}