use std::fmt;
use std::net::IpAddr;
use std::str::FromStr;
use crate::error::ParseError;
use crate::record::NodeId;
#[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, 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>,
}
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,
}
}
#[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()
}
#[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 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::{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!(
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>,
}
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(),
}
.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,
})
}
}
}
#[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());
}
}