mediation 0.1.0

Telecom usage mediation domain library — 3GPP CDR local-time-plus-offset arithmetic (quarter-hour offsets, DST-adjusted), integer octet volumes, validated identifiers (IMSI/MSISDN/IMEI/ICCID/SUPI/GPSI/PEI, PLMN, TADIG), natural-key deduplication, RFC 1982 wrap-aware sequence-gap detection, partial-record reassembly, cross-node correlation, signed restatement, a numbered validation catalogue, a conservation law that spans batches, TBCD/BCD wire codecs, a zero-copy BER reader, usage aggregation, roaming-batch reconciliation, longest-prefix number ranges with portability, User Location Information (CGI/SAI/ECGI/NCGI/TAI), conserving tariff-band apportionment, two-question jurisdiction determination and an EU/German regulatory layer. Zero I/O, no async, no clock, exact integer quantities.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
//! The identifiers that tie a record to the session it describes.
//!
//! A single subscriber action produces records at every node it traverses, and
//! the same record may arrive more than once. Both problems — joining the legs
//! of one usage, and recognising a retransmission — are solved by the same
//! fields, so they live together.
//!
//! # A Charging ID is not unique on its own
//!
//! 3GPP TS 32.251 is explicit: the Charging ID **together with the P-GW IP
//! address** constitutes the unique identifier for an IP-CAN bearer. Two
//! gateways will happily allocate the same 32-bit value, and a mediation layer
//! that keys on the Charging ID alone therefore discards one of two genuinely
//! different sessions — a silent under-count that only surfaces as an
//! unexplained revenue gap.
//!
//! [`CorrelationKeys::packet_session`] returns the pair or nothing; there is no
//! accessor that hands back a bare Charging ID for use as a key.
//!
//! ```rust
//! use mediation::{ChargingId, CorrelationKeys};
//! use std::net::Ipv4Addr;
//!
//! let complete = CorrelationKeys::default()
//!     .with_charging_id(ChargingId::new(1_234))
//!     .with_gateway(Ipv4Addr::new(10, 0, 0, 1).into());
//! assert!(complete.packet_session().is_some());
//!
//! // A Charging ID with no gateway does not identify a session.
//! let partial = CorrelationKeys::default().with_charging_id(ChargingId::new(1_234));
//! assert!(partial.packet_session().is_none());
//! ```
//!
//! # The recording entity is not the node the file came from
//!
//! A `localSequenceNumber` is unique **within the recording entity that
//! assigned it** — the MSC, SGSN or CSCF that created the record — and a
//! Charging Gateway Function may collect records from many of them into one
//! file. Keying on the file's node instead therefore gives the *same* record
//! two different keys when it is collected through two gateways, and every
//! retransmission passes.
//!
//! So the recording entity is a field of its own, carried on the record rather
//! than inferred from where the file arrived.
//!
//! # An ICID identifies a session, a Linked ICID identifies its predecessor
//!
//! In IMS the first network element to handle a session-initiating `INVITE`
//! generates the ICID and every subsequent message of that session carries it
//! (3GPP TS 32.260). When an element starts a new call leg it records a
//! *linked* ICID pointing at the previous one, which is what lets a multi-leg
//! call be reassembled into a call history. The two are separate fields here
//! because conflating them collapses a forwarded call into a single leg.

use std::fmt;
use std::net::IpAddr;
use std::str::FromStr;

use crate::error::ParseError;
use crate::record::NodeId;

// ── ChargingId ───────────────────────────────────────────────────────────────

/// The 3GPP charging identifier for an IP-CAN bearer or PDU session.
///
/// A 32-bit value assigned by the gateway. Unique **only** in combination with
/// that gateway's address — see the module documentation.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ChargingId(u32);

impl ChargingId {
    /// An identifier from its raw value.
    #[must_use]
    pub const fn new(value: u32) -> Self {
        Self(value)
    }

    /// The raw 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"))
    }
}

// ── Icid ─────────────────────────────────────────────────────────────────────

/// An IMS Charging Identifier, as carried in the `P-Charging-Vector` header.
///
/// Opaque: generated by the first IMS element to handle the session, with a
/// format the generating network chooses. Treated here as a token, validated
/// for shape only.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Icid(String);

/// The shape [`Icid`] accepts, as rendered in a [`ParseError`].
const ICID_FORMAT: &str = "1 to 255 printable ASCII characters without whitespace";

impl Icid {
    /// The identifier as written.
    #[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))
        }
    }
}

// ── PacketSessionId ──────────────────────────────────────────────────────────

/// The pair that actually identifies a packet session: Charging ID **and** the
/// gateway that allocated it.
///
/// Constructible only from both halves, so a caller cannot accidentally key on
/// the Charging ID alone.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PacketSessionId {
    charging_id: ChargingId,
    gateway: IpAddr,
}

impl PacketSessionId {
    /// The identifier from its two halves.
    #[must_use]
    pub const fn new(charging_id: ChargingId, gateway: IpAddr) -> Self {
        Self {
            charging_id,
            gateway,
        }
    }

    /// The gateway-assigned charging identifier.
    #[must_use]
    pub const fn charging_id(self) -> ChargingId {
        self.charging_id
    }

    /// The gateway that assigned it.
    #[must_use]
    pub const fn gateway(self) -> IpAddr {
        self.gateway
    }
}

impl fmt::Display for PacketSessionId {
    /// Writes `charging_id@gateway`, which is the whole identity and never half
    /// of it.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}@{}", self.charging_id, self.gateway)
    }
}

/// The shape [`PacketSessionId`] accepts, as rendered in a [`ParseError`].
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);
        // Split from the right: an IPv6 literal contains colons but no `@`.
        let (id, gateway) = s.trim().rsplit_once('@').ok_or_else(err)?;
        Ok(Self::new(
            id.parse().map_err(|_| err())?,
            gateway.parse().map_err(|_| err())?,
        ))
    }
}

// ── CorrelationKeys ──────────────────────────────────────────────────────────

/// Every correlator a record might carry.
///
/// All fields are optional because real records are: a circuit-switched CDR has
/// no Charging ID, an IMS record has no gateway address, and a partial record
/// may arrive before the identifiers that would join it to its siblings. What
/// matters is that the *combinations* which actually identify something are
/// exposed as accessors, and the halves that do not are not.
#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CorrelationKeys {
    /// The gateway-assigned charging identifier, where the record carried one.
    pub charging_id: Option<ChargingId>,
    /// The address of the gateway that assigned the charging identifier.
    pub gateway: Option<IpAddr>,
    /// The IMS session identifier.
    pub icid: Option<Icid>,
    /// The IMS identifier of the preceding call leg, for multi-leg histories.
    pub linked_icid: Option<Icid>,
    /// The record's position within a run of partial records for one session.
    ///
    /// Present only on partial and last-partial records (3GPP TS 32.298).
    pub record_sequence_number: Option<u32>,
    /// A serial number unique within the recording entity that produced it.
    ///
    /// The circuit-switched domain's identifier for a record, and the only one
    /// available for many voice CDRs. Meaningless without
    /// [`recording_entity`](Self::recording_entity), which scopes it.
    pub local_sequence_number: Option<u32>,
    /// The network element that created the record.
    ///
    /// **Not** the node whose file it arrived in: a gateway may collect records
    /// from many elements, so the two differ routinely and only this one scopes
    /// [`local_sequence_number`](Self::local_sequence_number).
    pub recording_entity: Option<NodeId>,
}

impl CorrelationKeys {
    /// No correlators at all.
    #[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,
        }
    }

    /// The packet session this record belongs to, when **both** halves are
    /// present.
    ///
    /// `None` when either is missing. A Charging ID without its gateway does
    /// not identify a session and must never be used as though it did.
    #[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,
        }
    }

    /// `true` when this record names a predecessor leg.
    #[must_use]
    pub const fn is_linked_leg(&self) -> bool {
        self.linked_icid.is_some()
    }

    /// `true` when the record carried no correlator at all.
    ///
    /// Such a record can be neither joined to its siblings nor recognised as a
    /// retransmission, which is a finding rather than a neutral absence.
    #[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()
    }

    /// The record's own serial number, scoped by the entity that assigned it.
    ///
    /// `None` unless **both** are present. A serial number without its entity
    /// is not an identity: two elements will happily emit the same number.
    #[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,
        }
    }

    /// The same keys with a charging identifier.
    #[must_use]
    pub fn with_charging_id(mut self, id: ChargingId) -> Self {
        self.charging_id = Some(id);
        self
    }

    /// The same keys with the assigning gateway's address.
    #[must_use]
    pub fn with_gateway(mut self, gateway: IpAddr) -> Self {
        self.gateway = Some(gateway);
        self
    }

    /// The same keys with an IMS session identifier.
    #[must_use]
    pub fn with_icid(mut self, icid: Icid) -> Self {
        self.icid = Some(icid);
        self
    }

    /// The same keys with the preceding leg's IMS session identifier.
    #[must_use]
    pub fn with_linked_icid(mut self, icid: Icid) -> Self {
        self.linked_icid = Some(icid);
        self
    }

    /// The same keys with a partial-record sequence number.
    #[must_use]
    pub const fn with_record_sequence(mut self, sequence: u32) -> Self {
        self.record_sequence_number = Some(sequence);
        self
    }

    /// The same keys with a recording-entity-local serial number.
    #[must_use]
    pub const fn with_local_sequence(mut self, sequence: u32) -> Self {
        self.local_sequence_number = Some(sequence);
        self
    }

    /// The same keys with the element that created the record.
    #[must_use]
    pub fn with_recording_entity(mut self, entity: NodeId) -> Self {
        self.recording_entity = Some(entity);
        self
    }
}

// ── Serde ────────────────────────────────────────────────────────────────────

#[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 {
        /// A number: the charging identifier is a 32-bit counter.
        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)
        }
    }

    /// Field names are part of the public representation and covered by semver.
    #[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};

    /// The bug this API shape exists to prevent: keying a packet session on the
    /// Charging ID alone merges sessions from different gateways.
    #[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());

        // Two gateways, the same counter value, two different sessions.
        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);
        }
    }

    /// An IPv6 literal is full of colons, so the split must come from the right
    /// and must be on `@`.
    #[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"
            );
        }
    }

    /// A linked ICID is the predecessor leg, not the session — conflating them
    /// collapses a forwarded call into one leg.
    #[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");
    }

    /// The bug this field exists to prevent: a serial number scoped to the
    /// wrong thing gives one record two keys.
    #[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());
    }
}