mediation 0.2.0

Telecom usage mediation domain library — one-pass batch processing with a conservation law that proves no record was lost, 3GPP CDR local-time-plus-offset arithmetic (quarter-hour offsets, DST-adjusted), integer octet volumes, validated identifiers (IMSI/MSISDN/IMEI/ICCID/SUPI/GPSI/PEI/SUCI, PLMN, TADIG), natural-key deduplication, RFC 1982 wrap-aware sequence-gap detection, partial-record reassembly, cross-node correlation, signed restatement, a numbered validation catalogue, wire codecs for TBCD/BCD, ISDN-AddressString, the PLMN identity and the full User Location Information element, a zero-copy BER reader, usage aggregation, roaming-batch reconciliation, longest-prefix number ranges with portability, conserving tariff-band apportionment, two-question jurisdiction determination and an EU/German regulatory layer. Zero I/O, no async, no clock, exact integer quantities, and no input can panic a parser.
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
//! Deduplication: the natural key is the whole design.
//!
//! Duplicates are not an edge case. They are the normal consequence of a
//! retransmission after a lost acknowledgement, a re-sent file after a
//! partner's failed load, and a node's own recovery replay. Getting this wrong
//! bills the same usage twice.
//!
//! # Why hashing the record fails
//!
//! A retransmitted record is frequently **not** byte-identical to the original:
//! node identifiers, padding, extension fields and file-level context differ.
//! A whole-record hash therefore lets retransmissions straight through — the
//! exact failure the mechanism exists to prevent.
//!
//! # Why keying on subscriber and start time also fails
//!
//! It over-deduplicates. **Concurrent sessions on one subscription are
//! normal**: a 5G handset holds several simultaneous PDU sessions across
//! different data networks and slices, and two of them can be established in
//! the same second. Keying on subscriber and timestamp silently discards one —
//! under-billing, and invisible.
//!
//! # The natural key comes from the standard
//!
//! | Domain | Key |
//! |---|---|
//! | Packet data, 5G and LTE | Charging ID **and gateway address**, plus the partial-record sequence |
//! | IMS | ICID, the recording entity, and the partial-record sequence |
//! | Anything with a recording-entity serial | the **recording entity** and its `localSequenceNumber` |
//!
//! 3GPP TS 32.251 is explicit that a Charging ID is unique only together with
//! the P-GW address, which is why [`crate::CorrelationKeys::packet_session`]
//! yields the pair or nothing.
//!
//! # The recording entity is not the collecting node
//!
//! A `localSequenceNumber` is unique within the element that **created** the
//! record, and a gateway routinely collects records from several elements into
//! one file. Keying on the file's node would give one record two different keys
//! when it is collected through two gateways — so every retransmission would
//! pass, which is the failure this whole module exists to prevent.
//!
//! [`crate::CorrelationKeys::recording_entity`] therefore carries the creating
//! element, and a serial number without it is [`NotKeyable`] rather than
//! silently scoped to the wrong thing.
//!
//! # A record that cannot be keyed cannot be deduplicated
//!
//! [`RecordKey::of`] returns a [`NotKeyable`] rather than falling back to
//! provenance. A provenance-derived key — node, file, offset — is unique per
//! *arrival*, which is the opposite of what deduplication needs: it is
//! different for every copy of the same record, so every retransmission would
//! pass. Saying so is the only safe answer.
//!
//! ```rust
//! use mediation::{NotKeyable, RecordKey};
//! # use mediation::{ChargedParty, ChargingId, CorrelationKeys, RecordType, SourceRef,
//! #                 SubscriberRef, UsageRecord};
//! # use std::net::Ipv4Addr;
//! # let party = ChargedParty::Subscriber(
//! #     SubscriberRef::new("imsi-262021234567890".parse().unwrap()));
//! # let source = SourceRef::new("pgw-01".parse().unwrap(), 0);
//! # let opened = "2026-07-28T10:00:00+02:00".parse().unwrap();
//! let bare = UsageRecord::new(RecordType::PduSession, party.clone(), opened, source.clone());
//! assert_eq!(RecordKey::of(&bare), Err(NotKeyable::NoCorrelatorPresent));
//!
//! let keyed = bare.with_correlation(
//!     CorrelationKeys::default()
//!         .with_charging_id(ChargingId::new(1_234))
//!         .with_gateway(Ipv4Addr::new(10, 0, 0, 1).into()),
//! );
//! assert!(RecordKey::of(&keyed).is_ok());
//! ```
//!
//! # The window is a promise about the outside world
//!
//! An unbounded store is not a design, it is a memory leak, so the window is
//! mandatory. It encodes "our partners never resend later than this" — and if
//! that is false, duplicates pass and revenue is billed twice.
//! [`DedupWindow::from_bound`] is named for the fact it records rather than for
//! the buffer it sizes.

use std::collections::HashMap;
use std::fmt;

use time::{Duration, OffsetDateTime};

use crate::correlation::{Icid, PacketSessionId};
use crate::record::{NodeId, UsageRecord};

// ── RecordKey ────────────────────────────────────────────────────────────────

/// The identity a record keeps across retransmission.
///
/// Derived from the record's own domain fields, never from a random value and
/// never from where it arrived: the key must be **stable across
/// retransmission**, which is a different property from uniqueness and the
/// reason a generated identifier would be wrong here.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum RecordKey {
    /// A packet-data record, keyed on the session and its partial sequence.
    PacketSession {
        /// Charging ID together with the gateway that assigned it.
        session: PacketSessionId,
        /// The partial-record sequence, absent on a record that is whole.
        sequence: Option<u32>,
    },
    /// An IMS record, keyed on the session and its partial sequence.
    ///
    /// The ICID is generated once, by the first element to handle the session,
    /// and is globally unique — so unlike a `localSequenceNumber` it needs no
    /// entity to scope it, and adding one would split a session's records
    /// across the elements that reported them.
    Ims {
        /// The IMS session identifier.
        icid: Icid,
        /// The partial-record sequence, absent on a record that is whole.
        sequence: Option<u32>,
    },
    /// Any record carrying a serial number unique within its recording entity.
    RecordingEntity {
        /// The element that **created** the record and assigned the serial —
        /// not the node whose file it arrived in.
        entity: NodeId,
        /// The serial number, unique within that entity.
        local_sequence: u32,
    },
}

impl RecordKey {
    /// The natural key of a record, or why it has none.
    ///
    /// Prefers the most specific correlator the record carries. The order is
    /// stable and documented so that two copies of one record — which may
    /// carry different subsets of the correlators — cannot key differently:
    ///
    /// 1. packet session (Charging ID **and** gateway)
    /// 2. IMS session (the globally unique ICID)
    /// 3. recording entity **and** its `localSequenceNumber`
    ///
    /// # Errors
    ///
    /// [`NotKeyable`] when the record carries none of the above. Such a record
    /// must be dispositioned rather than deduplicated — see the module
    /// documentation.
    pub fn of(record: &UsageRecord) -> Result<Self, NotKeyable> {
        let keys = &record.correlation;

        // Every complete correlator is tried first, in preference order. A
        // *half* one is only a reason to refuse the record when nothing else
        // keyed it — an IMS record that happens to carry a bearer's Charging ID
        // without its gateway is still perfectly keyable on its ICID, and
        // rejecting it for the stray field would lose the usage.
        if let Some(session) = keys.packet_session() {
            return Ok(Self::PacketSession {
                session,
                sequence: keys.record_sequence_number,
            });
        }
        if let Some(icid) = &keys.icid {
            return Ok(Self::Ims {
                icid: icid.clone(),
                sequence: keys.record_sequence_number,
            });
        }
        if let Some((entity, local_sequence)) = keys.entity_serial() {
            return Ok(Self::RecordingEntity {
                entity: entity.clone(),
                local_sequence,
            });
        }

        // Nothing keyed it. Now say which half-identity is present, because
        // that points at a decoder dropping a field rather than at a record
        // type that never carries one — a different fix, in a different place.
        if keys.charging_id.is_some() != keys.gateway.is_some() {
            return Err(NotKeyable::IncompletePacketSessionId);
        }
        if keys.local_sequence_number.is_some() || keys.recording_entity.is_some() {
            return Err(NotKeyable::IncompleteEntitySerial);
        }
        Err(NotKeyable::NoCorrelatorPresent)
    }

    /// The identity of the **session** this record belongs to, if it has one.
    ///
    /// The same key with the partial-record sequence removed — which is what a
    /// run of partials must be gathered by. Two partials of one session have
    /// different keys (that is the point: neither deduplicates the other) and
    /// the same scope.
    ///
    /// `None` for a [`RecordingEntity`](Self::RecordingEntity) key, and that
    /// `None` is load-bearing. A serial number scoped to an element identifies
    /// **the record**, not the session above it, so there is nothing to gather
    /// a run by. Returning the key unchanged would make every such partial a
    /// run of one — and a run of one that does not begin at sequence 1 is an
    /// orphan, so an ordinary SGSN partial numbered 3 would be rejected as
    /// malformed. A run that cannot be gathered is not a broken run; it is a
    /// question this key cannot answer.
    #[must_use]
    pub fn session_scope(&self) -> Option<Self> {
        match self {
            Self::PacketSession { session, .. } => Some(Self::PacketSession {
                session: *session,
                sequence: None,
            }),
            Self::Ims { icid, .. } => Some(Self::Ims {
                icid: icid.clone(),
                sequence: None,
            }),
            Self::RecordingEntity { .. } => None,
        }
    }

    /// A short code naming the key's shape, for grouping and reporting.
    #[must_use]
    pub const fn kind(&self) -> &'static str {
        match self {
            Self::PacketSession { .. } => "PACKET_SESSION",
            Self::Ims { .. } => "IMS",
            Self::RecordingEntity { .. } => "RECORDING_ENTITY",
        }
    }
}

impl fmt::Display for RecordKey {
    /// Writes `KIND:parts`, compact enough for a duplicate-report line.
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::PacketSession { session, sequence } => {
                write!(f, "PACKET_SESSION:{session}")?;
                if let Some(sequence) = sequence {
                    write!(f, "/{sequence}")?;
                }
                Ok(())
            }
            Self::Ims { icid, sequence } => {
                write!(f, "IMS:{icid}")?;
                if let Some(sequence) = sequence {
                    write!(f, "/{sequence}")?;
                }
                Ok(())
            }
            Self::RecordingEntity {
                entity,
                local_sequence,
            } => write!(f, "RECORDING_ENTITY:{entity}/{local_sequence}"),
        }
    }
}

/// Why a record has no natural key.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum NotKeyable {
    /// The record carried no correlator this crate can key on.
    NoCorrelatorPresent,
    /// A Charging ID without its gateway, or a gateway without its Charging ID.
    ///
    /// Distinguished from [`NoCorrelatorPresent`](Self::NoCorrelatorPresent)
    /// because it points at a decoder dropping a field rather than at a record
    /// type that never carries one — a different fix, in a different place.
    IncompletePacketSessionId,
    /// A `localSequenceNumber` with no recording entity, or the reverse.
    ///
    /// The serial is unique only within the element that assigned it, so one
    /// half of the pair identifies nothing.
    IncompleteEntitySerial,
}

impl NotKeyable {
    /// Every variant, for exhaustive iteration in tests and mappings.
    pub const ALL: &'static [Self] = &[
        Self::NoCorrelatorPresent,
        Self::IncompletePacketSessionId,
        Self::IncompleteEntitySerial,
    ];

    /// The canonical string form.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NoCorrelatorPresent => "NO_CORRELATOR_PRESENT",
            Self::IncompletePacketSessionId => "INCOMPLETE_PACKET_SESSION_ID",
            Self::IncompleteEntitySerial => "INCOMPLETE_ENTITY_SERIAL",
        }
    }
}

impl fmt::Display for NotKeyable {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

impl std::error::Error for NotKeyable {}

// ── DedupWindow ──────────────────────────────────────────────────────────────

/// How far back the deduplication store remembers.
///
/// A promise about partner behaviour, not a buffer size: a duplicate arriving
/// after the window closes will **not** be caught. The crate documents that
/// consequence rather than offering an unbounded alternative, because an
/// unbounded store is a memory leak with a correctness story attached.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct DedupWindow(Duration);

impl DedupWindow {
    /// A window from the longest retransmission delay a partner may exhibit.
    ///
    /// `None` for a non-positive duration: a zero window catches nothing while
    /// appearing to be deduplication.
    #[must_use]
    pub const fn from_bound(bound: Duration) -> Option<Self> {
        if bound.is_positive() {
            Some(Self(bound))
        } else {
            None
        }
    }

    /// The window's length.
    #[must_use]
    pub const fn get(self) -> Duration {
        self.0
    }

    /// The oldest observation instant still inside the window at `as_of`.
    #[must_use]
    pub fn cutoff(self, as_of: OffsetDateTime) -> OffsetDateTime {
        as_of - self.0
    }
}

// ── DedupStore ───────────────────────────────────────────────────────────────

/// What happened when a key was observed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DedupDecision {
    /// Not seen before within the window. The record proceeds.
    First,
    /// Seen before, at the carried instant. The record is suppressed.
    Duplicate {
        /// When the surviving copy was first observed.
        first_seen: OffsetDateTime,
    },
}

impl DedupDecision {
    /// `true` when this observation is the one that proceeds.
    #[must_use]
    pub const fn is_first(self) -> bool {
        matches!(self, Self::First)
    }
}

/// Remembers which keys have been seen, within a bounded window.
///
/// **Caller-owned.** The crate holds no state of its own, so a run is a pure
/// mapping from `(input, store, as_of)` to `(outcome, store′)` — which is what
/// makes a replay reproducible.
///
/// Not automatically evicting: [`evict`](Self::evict) is called by the caller,
/// at a cadence they choose, and reports how many keys it dropped. Automatic
/// eviction inside `observe` would make the store's size depend on arrival
/// order, and therefore on how the caller batched their input.
#[derive(Debug, Clone)]
pub struct DedupStore {
    window: DedupWindow,
    seen: HashMap<RecordKey, OffsetDateTime>,
}

impl DedupStore {
    /// An empty store bound to a window.
    ///
    /// The window is held by the store rather than passed to each eviction, so
    /// two calls cannot disagree about how long the promise runs — a store
    /// evicted against a shorter window than it was filled under silently loses
    /// duplicate detection for the difference.
    #[must_use]
    pub fn new(window: DedupWindow) -> Self {
        Self {
            window,
            seen: HashMap::new(),
        }
    }

    /// An empty store with room for `capacity` keys.
    #[must_use]
    pub fn with_capacity(window: DedupWindow, capacity: usize) -> Self {
        Self {
            window,
            seen: HashMap::with_capacity(capacity),
        }
    }

    /// The window this store remembers within.
    #[must_use]
    pub const fn window(&self) -> DedupWindow {
        self.window
    }

    /// Record an observation of `key` at `at`.
    ///
    /// Idempotent: observing the same key repeatedly yields
    /// [`DedupDecision::First`] exactly once, then
    /// [`DedupDecision::Duplicate`] every time after — never twice, never zero
    /// times. The first-seen instant is retained rather than refreshed, so a
    /// stream of retransmissions cannot keep a key alive past its window.
    pub fn observe(&mut self, key: RecordKey, at: OffsetDateTime) -> DedupDecision {
        match self.seen.entry(key) {
            std::collections::hash_map::Entry::Occupied(entry) => DedupDecision::Duplicate {
                first_seen: *entry.get(),
            },
            std::collections::hash_map::Entry::Vacant(entry) => {
                entry.insert(at);
                DedupDecision::First
            }
        }
    }

    /// Drop keys first seen before the window's cutoff, returning how many.
    ///
    /// After this, a duplicate of a dropped key will be classified as
    /// [`DedupDecision::First`] and will be billed again. That is the window's
    /// stated consequence, not a defect — but it is why the bound must reflect
    /// real partner behaviour.
    pub fn evict(&mut self, as_of: OffsetDateTime) -> usize {
        let cutoff = self.window.cutoff(as_of);
        let before = self.seen.len();
        self.seen.retain(|_, first_seen| *first_seen >= cutoff);
        before - self.seen.len()
    }

    /// When a key was first seen, if it is still remembered.
    #[must_use]
    pub fn first_seen(&self, key: &RecordKey) -> Option<OffsetDateTime> {
        self.seen.get(key).copied()
    }

    /// How many keys are remembered.
    #[must_use]
    pub fn len(&self) -> usize {
        self.seen.len()
    }

    /// `true` when nothing is remembered.
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.seen.is_empty()
    }

    /// Forget everything.
    pub fn clear(&mut self) {
        self.seen.clear();
    }

    /// Every key remembered, with when it was first seen.
    ///
    /// The order is unspecified and varies between runs — the store is a hash
    /// map, and nothing about deduplication depends on iteration order. Sort
    /// the result if you need a stable rendering.
    pub fn iter(&self) -> impl Iterator<Item = (&RecordKey, OffsetDateTime)> {
        self.seen.iter().map(|(key, at)| (key, *at))
    }

    /// Rebuild a store from keys and their first-seen instants.
    ///
    /// The other half of [`iter`](Self::iter), and the reason both exist: the
    /// crate performs no I/O, so a store that survives a restart is something
    /// **you** serialise — and a store you cannot read out is one you cannot
    /// persist, which would leave every restart silently re-billing a window's
    /// worth of retransmissions.
    ///
    /// A repeated key keeps its **earliest** instant, so restoring from a
    /// concatenation of snapshots cannot extend a key's life past its window.
    ///
    /// ```rust
    /// use mediation::{DedupStore, DedupWindow, RecordKey};
    /// use time::{Duration, macros::datetime};
    /// # use mediation::{ChargingId, PacketSessionId};
    /// # use std::net::Ipv4Addr;
    /// # let key = RecordKey::PacketSession {
    /// #     session: PacketSessionId::new(ChargingId::new(1), Ipv4Addr::new(10, 0, 0, 1).into()),
    /// #     sequence: None,
    /// # };
    /// let window = DedupWindow::from_bound(Duration::days(7)).unwrap();
    /// let mut store = DedupStore::new(window);
    /// store.observe(key.clone(), datetime!(2026-07-28 10:00 UTC));
    ///
    /// // Round-trips through whatever you store it in.
    /// let saved: Vec<_> = store.iter().map(|(k, at)| (k.clone(), at)).collect();
    /// let restored = DedupStore::restore(window, saved);
    ///
    /// assert_eq!(restored.first_seen(&key), store.first_seen(&key));
    /// ```
    #[must_use]
    pub fn restore(
        window: DedupWindow,
        observations: impl IntoIterator<Item = (RecordKey, OffsetDateTime)>,
    ) -> Self {
        let mut store = Self::new(window);
        for (key, at) in observations {
            store
                .seen
                .entry(key)
                .and_modify(|first| {
                    if at < *first {
                        *first = at;
                    }
                })
                .or_insert(at);
        }
        store
    }
}

impl<'a> IntoIterator for &'a DedupStore {
    type Item = (&'a RecordKey, OffsetDateTime);
    type IntoIter = std::iter::Map<
        std::collections::hash_map::Iter<'a, RecordKey, OffsetDateTime>,
        fn((&'a RecordKey, &'a OffsetDateTime)) -> (&'a RecordKey, OffsetDateTime),
    >;

    fn into_iter(self) -> Self::IntoIter {
        self.seen.iter().map(|(key, at)| (key, *at))
    }
}

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

#[cfg(feature = "serde")]
mod serde_impl {
    use super::{DedupStore, DedupWindow, NotKeyable, RecordKey};
    use time::OffsetDateTime;

    /// An instant in RFC 3339, which is what `time` offers and what a persisted
    /// store should be legible as.
    #[derive(Serialize, Deserialize)]
    #[serde(transparent)]
    struct Instant(#[serde(with = "time::serde::rfc3339")] OffsetDateTime);
    use serde::de::{self, Visitor};
    use serde::{Deserialize, Deserializer, Serialize, Serializer};
    use std::fmt;
    use std::str::FromStr;

    impl Serialize for NotKeyable {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            serializer.serialize_str(self.as_str())
        }
    }

    impl<'de> Deserialize<'de> for NotKeyable {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            struct V;
            impl Visitor<'_> for V {
                type Value = NotKeyable;
                fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
                    f.write_str("a not-keyable reason code")
                }
                fn visit_str<E: de::Error>(self, v: &str) -> Result<NotKeyable, E> {
                    NotKeyable::ALL
                        .iter()
                        .find(|r| r.as_str() == v)
                        .copied()
                        .ok_or_else(|| de::Error::custom(format!("unknown reason {v:?}")))
                }
            }
            deserializer.deserialize_str(V)
        }
    }

    /// An internally tagged representation: the `kind` discriminator is stable
    /// and readable, and adding a key shape does not renumber the others.
    #[derive(Serialize, Deserialize)]
    #[serde(tag = "kind", rename = "RecordKey")]
    enum RecordKeyRepr {
        #[serde(rename = "PACKET_SESSION")]
        PacketSession {
            session: crate::correlation::PacketSessionId,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            sequence: Option<u32>,
        },
        #[serde(rename = "IMS")]
        Ims {
            icid: crate::correlation::Icid,
            #[serde(default, skip_serializing_if = "Option::is_none")]
            sequence: Option<u32>,
        },
        #[serde(rename = "RECORDING_ENTITY")]
        RecordingEntity {
            entity: crate::record::NodeId,
            local_sequence: u32,
        },
    }

    impl Serialize for RecordKey {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let repr = match self {
                Self::PacketSession { session, sequence } => RecordKeyRepr::PacketSession {
                    session: *session,
                    sequence: *sequence,
                },
                Self::Ims { icid, sequence } => RecordKeyRepr::Ims {
                    icid: icid.clone(),
                    sequence: *sequence,
                },
                Self::RecordingEntity {
                    entity,
                    local_sequence,
                } => RecordKeyRepr::RecordingEntity {
                    entity: entity.clone(),
                    local_sequence: *local_sequence,
                },
            };
            repr.serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for RecordKey {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            Ok(match RecordKeyRepr::deserialize(deserializer)? {
                RecordKeyRepr::PacketSession { session, sequence } => {
                    Self::PacketSession { session, sequence }
                }
                RecordKeyRepr::Ims { icid, sequence } => Self::Ims { icid, sequence },
                RecordKeyRepr::RecordingEntity {
                    entity,
                    local_sequence,
                } => Self::RecordingEntity {
                    entity,
                    local_sequence,
                },
            })
        }
    }

    // Silence an unused-import warning when the feature is on but FromStr is
    // reached only through the visitors above.
    const _: fn(&str) -> Result<crate::correlation::Icid, crate::ParseError> =
        crate::correlation::Icid::from_str;

    /// A window and its keys, which is the whole of the store.
    ///
    /// Both halves are needed: a set of keys restored under a different window
    /// than it was filled under silently loses duplicate detection for the
    /// difference, and the window alone remembers nothing.
    #[derive(Serialize, Deserialize)]
    #[serde(rename = "DedupStore")]
    struct StoreRepr {
        /// The window, in whole seconds.
        window_seconds: i64,
        /// Every key with the instant it was first seen, sorted by key so the
        /// representation is stable across runs despite the hash map inside.
        ///
        /// RFC 3339, so a persisted store is legible in the file it lives in
        /// and survives a change of storage format.
        seen: Vec<(RecordKey, Instant)>,
    }

    impl Serialize for DedupStore {
        fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
            let mut seen: Vec<(RecordKey, Instant)> = self
                .iter()
                .map(|(key, at)| (key.clone(), Instant(at)))
                .collect();
            seen.sort_by(|a, b| a.0.cmp(&b.0));
            StoreRepr {
                window_seconds: self.window().get().whole_seconds(),
                seen,
            }
            .serialize(serializer)
        }
    }

    impl<'de> Deserialize<'de> for DedupStore {
        fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
            let r = StoreRepr::deserialize(deserializer)?;
            let window = DedupWindow::from_bound(time::Duration::seconds(r.window_seconds))
                .ok_or_else(|| de::Error::custom("a positive deduplication window"))?;
            Ok(DedupStore::restore(
                window,
                r.seen.into_iter().map(|(key, at)| (key, at.0)),
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::correlation::{ChargingId, CorrelationKeys};
    use crate::party::{ChargedParty, SubscriberRef};
    use crate::record::{RecordType, SourceRef};
    use std::net::Ipv4Addr;
    use time::macros::datetime;

    const NOW: OffsetDateTime = datetime!(2026-07-28 00:00:00 UTC);

    fn record(node: &str, correlation: CorrelationKeys) -> UsageRecord {
        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(correlation)
    }

    fn packet_keys(charging_id: u32, gateway: [u8; 4]) -> CorrelationKeys {
        CorrelationKeys::default()
            .with_charging_id(ChargingId::new(charging_id))
            .with_gateway(Ipv4Addr::from(gateway).into())
    }

    // ── Key derivation ───────────────────────────────────────────────────────

    /// The confirmed 3GPP rule: a Charging ID is unique only with its gateway,
    /// so two gateways using the same counter are two different sessions.
    #[test]
    fn the_gateway_is_part_of_the_packet_session_key() {
        let a = RecordKey::of(&record("pgw-01", packet_keys(1_234, [10, 0, 0, 1]))).unwrap();
        let b = RecordKey::of(&record("pgw-02", packet_keys(1_234, [10, 0, 0, 2]))).unwrap();
        assert_ne!(a, b, "same Charging ID, different gateways, different keys");

        // …and the node the record arrived through is *not* part of it, so the
        // same session collected twice keys identically.
        let same = RecordKey::of(&record("cgf-99", packet_keys(1_234, [10, 0, 0, 1]))).unwrap();
        assert_eq!(a, same);
    }

    /// The bug this returns an error for: half an identity looks usable and
    /// identifies the wrong thing.
    #[test]
    fn half_a_packet_session_identity_is_an_error_not_a_key() {
        let only_id = record(
            "pgw-01",
            CorrelationKeys::default().with_charging_id(ChargingId::new(1)),
        );
        assert_eq!(
            RecordKey::of(&only_id),
            Err(NotKeyable::IncompletePacketSessionId)
        );

        let only_gateway = record(
            "pgw-01",
            CorrelationKeys::default().with_gateway(Ipv4Addr::LOCALHOST.into()),
        );
        assert_eq!(
            RecordKey::of(&only_gateway),
            Err(NotKeyable::IncompletePacketSessionId)
        );
    }

    /// A record with nothing to key on must say so, not fall back to
    /// provenance — a provenance key differs for every copy, so every
    /// retransmission would pass.
    #[test]
    fn a_record_without_correlators_has_no_key() {
        let bare = record("pgw-01", CorrelationKeys::none());
        assert_eq!(RecordKey::of(&bare), Err(NotKeyable::NoCorrelatorPresent));
    }

    #[test]
    fn partials_of_one_session_are_distinct_keys() {
        let first = record(
            "pgw-01",
            packet_keys(7, [10, 0, 0, 1]).with_record_sequence(1),
        );
        let second = record(
            "pgw-01",
            packet_keys(7, [10, 0, 0, 1]).with_record_sequence(2),
        );
        let whole = record("pgw-01", packet_keys(7, [10, 0, 0, 1]));

        let (a, b, c) = (
            RecordKey::of(&first).unwrap(),
            RecordKey::of(&second).unwrap(),
            RecordKey::of(&whole).unwrap(),
        );
        assert_ne!(a, b);
        assert_ne!(a, c);
        assert_ne!(b, c);
    }

    /// A serial number scoped to its recording entity.
    fn entity_keys(entity: &str, serial: u32) -> CorrelationKeys {
        CorrelationKeys::default()
            .with_recording_entity(entity.parse().unwrap())
            .with_local_sequence(serial)
    }

    #[test]
    fn ims_and_recording_entity_keys_are_derived_in_order() {
        let ims = record(
            "cgf-01",
            entity_keys("scscf-01", 5).with_icid("icid-abc".parse().unwrap()),
        );
        // The ICID is globally unique, so it wins over the entity serial.
        assert!(matches!(
            RecordKey::of(&ims).unwrap(),
            RecordKey::Ims { .. }
        ));

        let serial = record("cgf-01", entity_keys("msc-01", 5));
        assert_eq!(
            RecordKey::of(&serial).unwrap(),
            RecordKey::RecordingEntity {
                entity: "msc-01".parse().unwrap(),
                local_sequence: 5,
            }
        );
    }

    /// A `localSequenceNumber` is unique only within the element that assigned
    /// it, so that element is part of the key.
    #[test]
    fn a_local_serial_is_scoped_to_its_recording_entity() {
        let a = record("cgf-01", entity_keys("msc-01", 5));
        let b = record("cgf-01", entity_keys("msc-02", 5));
        assert_ne!(RecordKey::of(&a).unwrap(), RecordKey::of(&b).unwrap());
    }

    /// The bug this key shape fixes: one record collected through two gateways
    /// must key identically, or every retransmission passes.
    #[test]
    fn the_collecting_node_is_not_part_of_any_key() {
        assert_eq!(
            RecordKey::of(&record("cgf-01", entity_keys("msc-01", 5))).unwrap(),
            RecordKey::of(&record("cgf-02", entity_keys("msc-01", 5))).unwrap(),
        );

        let ims = CorrelationKeys::default().with_icid("icid-abc".parse().unwrap());
        assert_eq!(
            RecordKey::of(&record("cgf-01", ims.clone())).unwrap(),
            RecordKey::of(&record("cgf-02", ims)).unwrap(),
        );
    }

    /// Half an entity-scoped identity identifies nothing, and says so.
    #[test]
    fn half_an_entity_serial_is_an_error_not_a_key() {
        for keys in [
            CorrelationKeys::default().with_local_sequence(5),
            CorrelationKeys::default().with_recording_entity("msc-01".parse().unwrap()),
        ] {
            assert_eq!(
                RecordKey::of(&record("cgf-01", keys)),
                Err(NotKeyable::IncompleteEntitySerial)
            );
        }
    }

    // ── Store ────────────────────────────────────────────────────────────────

    fn hour_window() -> DedupWindow {
        DedupWindow::from_bound(Duration::hours(1)).expect("positive")
    }

    #[test]
    fn observing_a_key_repeatedly_yields_one_first_and_then_duplicates() {
        let mut store = DedupStore::new(hour_window());
        let key = RecordKey::of(&record("pgw-01", packet_keys(1, [10, 0, 0, 1]))).unwrap();

        assert_eq!(store.observe(key.clone(), NOW), DedupDecision::First);
        for i in 1..5 {
            assert_eq!(
                store.observe(key.clone(), NOW + Duration::minutes(i)),
                DedupDecision::Duplicate { first_seen: NOW },
                "observation {i} must be a duplicate"
            );
        }
        assert_eq!(store.len(), 1);
    }

    /// The first-seen instant is retained rather than refreshed, so a stream of
    /// retransmissions cannot keep a key alive past its window.
    #[test]
    fn retransmissions_do_not_extend_a_keys_life() {
        let mut store = DedupStore::new(hour_window());
        let key = RecordKey::of(&record("pgw-01", packet_keys(1, [10, 0, 0, 1]))).unwrap();

        store.observe(key.clone(), NOW);
        store.observe(key.clone(), NOW + Duration::minutes(59));
        assert_eq!(store.first_seen(&key), Some(NOW));

        // Ninety minutes on, the key is older than the window despite the
        // recent retransmission.
        assert_eq!(store.evict(NOW + Duration::minutes(90)), 1);
        assert!(store.is_empty());
    }

    /// The window's stated consequence, asserted rather than left implicit.
    #[test]
    fn a_duplicate_arriving_after_the_window_is_not_caught() {
        let mut store = DedupStore::new(hour_window());
        let key = RecordKey::of(&record("pgw-01", packet_keys(1, [10, 0, 0, 1]))).unwrap();

        assert_eq!(store.observe(key.clone(), NOW), DedupDecision::First);
        store.evict(NOW + Duration::hours(2));
        assert_eq!(
            store.observe(key, NOW + Duration::hours(2)),
            DedupDecision::First,
            "past the window the store has forgotten, and says so by design"
        );
    }

    #[test]
    fn eviction_keeps_keys_inside_the_window() {
        let mut store = DedupStore::new(hour_window());

        for (i, at) in [NOW - Duration::hours(3), NOW - Duration::minutes(30), NOW]
            .into_iter()
            .enumerate()
        {
            let key = RecordKey::of(&record(
                "pgw-01",
                packet_keys(u32::try_from(i).unwrap(), [10, 0, 0, 1]),
            ))
            .unwrap();
            store.observe(key, at);
        }
        assert_eq!(store.len(), 3);
        assert_eq!(store.evict(NOW), 1);
        assert_eq!(store.len(), 2);
    }

    #[test]
    fn a_zero_or_negative_window_is_rejected() {
        assert!(DedupWindow::from_bound(Duration::ZERO).is_none());
        assert!(DedupWindow::from_bound(Duration::seconds(-1)).is_none());
        assert!(DedupWindow::from_bound(Duration::seconds(1)).is_some());
    }

    #[test]
    fn keys_render_legibly() {
        let packet = RecordKey::of(&record(
            "pgw-01",
            packet_keys(1_234, [10, 0, 0, 1]).with_record_sequence(2),
        ))
        .unwrap();
        assert_eq!(packet.to_string(), "PACKET_SESSION:1234@10.0.0.1/2");
        assert_eq!(packet.kind(), "PACKET_SESSION");

        let serial = RecordKey::of(&record(
            "cgf-01",
            CorrelationKeys::default()
                .with_recording_entity("msc-01".parse().unwrap())
                .with_local_sequence(9),
        ))
        .unwrap();
        assert_eq!(serial.to_string(), "RECORDING_ENTITY:msc-01/9");
    }
}