async-snmp 0.18.1

Modern async-first SNMP client library for Rust
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
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
//! Core infrastructure for UDP response correlation.
//!
//! Provides a sharded pending request map with per-request wakeup.

use bytes::Bytes;
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::net::SocketAddr;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::Notify;
use tokio::time::Instant;

use super::{Candidate, CorrelationWindow, RequestRegistration, ResponseIdentity};
use crate::error::{Error, Result};

const SHARDS: usize = 64;
const MAX_PARKED_CANDIDATES: usize = 16;

/// Sharded pending request tracking with per-request wakeup.
///
/// Uses 64 shards to reduce lock contention under high load.
/// Each pending request has its own [`Notify`], so delivering a
/// response wakes only the task waiting for that specific request.
pub struct UdpCore {
    shards: Box<[Shard; SHARDS]>,
    stats: CoreStats,
    /// Set when the owning transport shuts down; waiters fail immediately.
    closed: AtomicBool,
}

/// Counters for transport health monitoring.
struct CoreStats {
    /// Datagrams successfully correlated and queued for a pending request.
    correlated_datagrams: AtomicU64,
    /// Requests that timed out without receiving a response.
    expired_registrations: AtomicU64,
    /// Datagrams discarded because they were late, duplicate, unregistered,
    /// over queue capacity, or rejected by source/community correlation.
    discarded_datagrams: AtomicU64,
    /// Datagrams from which no request ID could be extracted.
    malformed_datagrams: AtomicU64,
}

/// UDP endpoint statistics.
///
/// These cumulative counters are shared by every transport, handle, client,
/// and control capability using the same UDP endpoint.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct UdpStats {
    /// Datagrams successfully correlated and queued for a pending request.
    pub correlated_datagrams: u64,
    /// Requests that timed out without receiving a response.
    pub expired_registrations: u64,
    /// Datagrams discarded because they were late, duplicate, unregistered,
    /// over queue capacity, or rejected by source/community correlation.
    pub discarded_datagrams: u64,
    /// Datagrams from which no request ID could be extracted.
    pub malformed_datagrams: u64,
}

struct Shard {
    pending: Mutex<HashMap<i32, PendingEntry>>,
}

struct RegistrationOwner {
    /// Timing remains available after periodic cleanup removes map entries.
    registered_at: Instant,
    deadline: Instant,
    retries: u32,
    expired: AtomicBool,
    notify: Arc<Notify>,
    correlation_window_id: Option<u64>,
}

impl RegistrationOwner {
    fn note_expired(&self, stats: &CoreStats) {
        if !self.expired.swap(true, Ordering::AcqRel) {
            stats.expired_registrations.fetch_add(1, Ordering::Relaxed);
        }
    }

    fn elapsed(&self, now: Instant) -> Duration {
        now.saturating_duration_since(self.registered_at)
    }
}

struct ResponseSlot {
    responses: VecDeque<(Bytes, SocketAddr)>,
    owner: Arc<RegistrationOwner>,
    /// Configured target, used by conditional community rewrite policy.
    target_source: SocketAddr,
    /// When true, only responses from exactly the target are delivered.
    strict_source: bool,
    registration: RequestRegistration,
}

enum PendingEntry {
    Slot(ResponseSlot),
    /// Retransmission window alias: datagrams keyed by a prior attempt's
    /// msgID are delivered to the current attempt's slot.
    Alias {
        primary: i32,
        owner: Arc<RegistrationOwner>,
    },
}

impl PendingEntry {
    fn owner(&self) -> &Arc<RegistrationOwner> {
        match self {
            Self::Slot(slot) => &slot.owner,
            Self::Alias { owner, .. } => owner,
        }
    }
}

/// Owns one UDP correlation registration.
///
/// Standalone registrations remove their entries on drop. Retry-window
/// registrations remain available for atomic handoff and are removed when the
/// exchange-lifetime [`CorrelationWindow`] is dropped.
pub(crate) struct UdpRegistration {
    core: Arc<UdpCore>,
    primary: i32,
    aliases: BTreeSet<i32>,
    owner: Arc<RegistrationOwner>,
    correlation_window: Option<Arc<CorrelationWindow>>,
}

impl UdpRegistration {
    pub(crate) fn request_id(&self) -> i32 {
        self.primary
    }

    pub(crate) fn deadline(&self) -> Instant {
        self.owner.deadline
    }

    pub(crate) fn timeout_error(&self, target: SocketAddr) -> Box<Error> {
        let now = Instant::now();
        self.owner.note_expired(&self.core.stats);
        Error::Timeout {
            target,
            elapsed: self.owner.elapsed(now),
            retries: self.owner.retries,
        }
        .boxed()
    }
}

impl Drop for UdpRegistration {
    fn drop(&mut self) {
        if self.correlation_window.is_some() {
            return;
        }
        self.core.remove_owned(self.primary, &self.owner);
        for alias in &self.aliases {
            self.core.remove_owned(*alias, &self.owner);
        }
    }
}

impl UdpCore {
    /// Create a new `UdpCore` with empty shards.
    pub fn new() -> Self {
        let shards: Vec<Shard> = (0..SHARDS)
            .map(|_| Shard {
                pending: Mutex::new(HashMap::new()),
            })
            .collect();

        Self {
            shards: shards
                .try_into()
                .unwrap_or_else(|_| unreachable!("Vec has exactly SHARDS elements")),
            stats: CoreStats {
                correlated_datagrams: AtomicU64::new(0),
                expired_registrations: AtomicU64::new(0),
                discarded_datagrams: AtomicU64::new(0),
                malformed_datagrams: AtomicU64::new(0),
            },
            closed: AtomicBool::new(false),
        }
    }

    /// Mark the core closed and wake all pending waiters.
    ///
    /// Called when the transport's recv loop exits. Waiters observe the
    /// closed flag and fail immediately instead of at their deadlines;
    /// any already-delivered response is still returned.
    pub fn close(&self) {
        self.closed.store(true, Ordering::Release);
        for shard in self.shards.iter() {
            let notifies: Vec<_> = shard
                .pending
                .lock()
                .unwrap()
                .values()
                .filter_map(|entry| match entry {
                    PendingEntry::Slot(slot) => Some(slot.owner.notify.clone()),
                    PendingEntry::Alias { .. } => None,
                })
                .collect();
            for notify in notifies {
                notify.notify_one();
            }
        }
    }

    /// Get the shard for a given request ID.
    fn shard_index(request_id: i32) -> usize {
        request_id as usize % SHARDS
    }

    fn shard(&self, request_id: i32) -> &Shard {
        &self.shards[Self::shard_index(request_id)]
    }

    /// Atomically reserve a primary request ID and all of its unique aliases.
    pub fn register(
        self: &Arc<Self>,
        registration: RequestRegistration,
        target_source: SocketAddr,
        strict_source: bool,
    ) -> Result<UdpRegistration> {
        if self.closed.load(Ordering::Acquire) {
            return Err(Error::Closed {
                target: target_source,
            }
            .boxed());
        }

        let primary = registration.request_id();
        let now = Instant::now();
        let deadline = registration.deadline();
        let aliases = registration.aliases().clone();
        let correlation_window = registration.correlation_window().cloned();
        let correlation_window_id = correlation_window.as_deref().map(CorrelationWindow::id);

        let mut ids = Vec::with_capacity(1 + aliases.len());
        ids.push(primary);
        ids.extend(aliases.iter().copied());

        // Hold every involved shard in ascending order so no observer can see
        // a partially installed alias set.
        let mut shard_indices: Vec<_> = ids.iter().map(|id| Self::shard_index(*id)).collect();
        shard_indices.sort_unstable();
        shard_indices.dedup();
        let mut guards: Vec<_> = shard_indices
            .iter()
            .map(|index| (*index, self.shards[*index].pending.lock().unwrap()))
            .collect();

        // Synchronize with `close()`: once it has marked the core closed, no
        // registration may be installed, even if this call began just before
        // cancellation and was waiting for a shard lock.
        if self.closed.load(Ordering::Acquire) {
            return Err(Error::Closed {
                target: target_source,
            }
            .boxed());
        }

        let mut expired_owners = Vec::new();
        let mut collision = None;
        let mut replaced_owners = Vec::new();
        for id in &ids {
            let shard_index = Self::shard_index(*id);
            let guard_index = guards
                .binary_search_by_key(&shard_index, |(index, _)| *index)
                .unwrap();
            let pending = &mut guards[guard_index].1;
            if let Some(entry) = pending.get(id) {
                if entry.owner().deadline <= now {
                    let owner = entry.owner().clone();
                    pending.remove(id);
                    expired_owners.push(owner);
                } else if correlation_window_id.is_some()
                    && entry.owner().correlation_window_id == correlation_window_id
                {
                    if !replaced_owners
                        .iter()
                        .any(|owner| Arc::ptr_eq(owner, entry.owner()))
                    {
                        replaced_owners.push(entry.owner().clone());
                    }
                } else {
                    collision = Some(*id);
                    break;
                }
            }
        }

        if let Some(request_id) = collision {
            drop(guards);
            for owner in expired_owners {
                owner.note_expired(&self.stats);
                owner.notify.notify_one();
            }
            return Err(Error::RequestIdInUse { request_id }.boxed());
        }

        // A datagram may arrive after the prior attempt future is dropped but
        // before this handoff installs its successor. Move such candidates to
        // the new slot while all involved shards remain locked.
        let mut carried_responses = VecDeque::new();
        if correlation_window_id.is_some() {
            for id in &ids {
                let shard_index = Self::shard_index(*id);
                let guard_index = guards
                    .binary_search_by_key(&shard_index, |(index, _)| *index)
                    .unwrap();
                if let Some(PendingEntry::Slot(slot)) = guards[guard_index].1.get_mut(id)
                    && slot.owner.correlation_window_id == correlation_window_id
                {
                    while carried_responses.len() < MAX_PARKED_CANDIDATES {
                        let Some(response) = slot.responses.pop_front() else {
                            break;
                        };
                        carried_responses.push_back(response);
                    }
                }
            }
        }

        let owner = Arc::new(RegistrationOwner {
            registered_at: now,
            deadline,
            retries: 0,
            expired: AtomicBool::new(false),
            notify: Arc::new(Notify::new()),
            correlation_window_id,
        });
        let mut registration = registration;
        registration.clear_correlation_window();
        let slot = ResponseSlot {
            responses: carried_responses,
            owner: owner.clone(),
            target_source,
            strict_source,
            registration,
        };

        let primary_shard = Self::shard_index(primary);
        let primary_guard = guards
            .binary_search_by_key(&primary_shard, |(index, _)| *index)
            .unwrap();
        guards[primary_guard]
            .1
            .insert(primary, PendingEntry::Slot(slot));
        for alias in &aliases {
            let shard_index = Self::shard_index(*alias);
            let guard_index = guards
                .binary_search_by_key(&shard_index, |(index, _)| *index)
                .unwrap();
            guards[guard_index].1.insert(
                *alias,
                PendingEntry::Alias {
                    primary,
                    owner: owner.clone(),
                },
            );
        }
        drop(guards);

        for expired_owner in expired_owners {
            expired_owner.note_expired(&self.stats);
            expired_owner.notify.notify_one();
        }
        for replaced_owner in replaced_owners {
            replaced_owner.notify.notify_one();
        }
        if let Some(window) = &correlation_window {
            window.register_udp_core(self);
        }

        Ok(UdpRegistration {
            core: self.clone(),
            primary,
            aliases,
            owner,
            correlation_window,
        })
    }

    /// Remove every registration retained by an exchange-lifetime V3 window.
    pub(crate) fn remove_window(&self, window_id: u64) {
        let mut guards: Vec<_> = self
            .shards
            .iter()
            .map(|shard| shard.pending.lock().unwrap())
            .collect();
        let mut owners = Vec::new();
        for pending in &mut guards {
            pending.retain(|_, entry| {
                if entry.owner().correlation_window_id == Some(window_id) {
                    if !owners.iter().any(|owner| Arc::ptr_eq(owner, entry.owner())) {
                        owners.push(entry.owner().clone());
                    }
                    false
                } else {
                    true
                }
            });
        }
        drop(guards);
        for owner in owners {
            owner.notify.notify_one();
        }
    }

    /// Deliver a response to its waiting request.
    ///
    /// Returns `true` if the slot existed and the response was stored,
    /// `false` if there was no matching pending request.
    pub fn deliver(&self, request_id: i32, data: Bytes, source: SocketAddr) -> bool {
        let (target_id, owner) = {
            let pending = self.shard(request_id).pending.lock().unwrap();
            match pending.get(&request_id) {
                Some(PendingEntry::Slot(slot)) => (request_id, Some(slot.owner.clone())),
                Some(PendingEntry::Alias { primary, owner, .. }) => (*primary, Some(owner.clone())),
                None => (request_id, None),
            }
        };
        self.deliver_to(target_id, owner.as_ref(), request_id, data, source)
    }

    fn deliver_to(
        &self,
        target_id: i32,
        expected_owner: Option<&Arc<RegistrationOwner>>,
        request_id: i32,
        data: Bytes,
        source: SocketAddr,
    ) -> bool {
        let shard = self.shard(target_id);
        let mut pending = shard.pending.lock().unwrap();

        if let Some(PendingEntry::Slot(slot)) = pending.get_mut(&target_id)
            && expected_owner.is_none_or(|owner| Arc::ptr_eq(owner, &slot.owner))
        {
            if slot.owner.deadline <= Instant::now() {
                let owner = slot.owner.clone();
                drop(pending);
                owner.note_expired(&self.stats);
                owner.notify.notify_one();
                self.stats
                    .discarded_datagrams
                    .fetch_add(1, Ordering::Relaxed);
                return false;
            }

            let source_is_target = slot.target_source == source;
            if slot.strict_source && !source_is_target {
                // Leave the slot and original deadline intact.
                drop(pending);
                self.stats
                    .discarded_datagrams
                    .fetch_add(1, Ordering::Relaxed);
                tracing::debug!(target: "async_snmp::transport::udp", { request_id, %source }, "response rejected by strict source correlation");
                return false;
            }
            match slot
                .registration
                .evaluate_response_identity(&data, source_is_target)
            {
                ResponseIdentity::Reject => {
                    drop(pending);
                    self.stats
                        .discarded_datagrams
                        .fetch_add(1, Ordering::Relaxed);
                    tracing::debug!(target: "async_snmp::transport::udp", { request_id, %source }, "response rejected by community correlation");
                    return false;
                }
                ResponseIdentity::AcceptedCommunityMismatch => {
                    tracing::warn!(target: "async_snmp::transport::udp", { request_id, %source }, "accepted rewritten response community");
                }
                ResponseIdentity::Match => {}
            }
            if slot
                .responses
                .iter()
                .any(|(parked, parked_source)| *parked_source == source && *parked == data)
                || slot.responses.len() >= MAX_PARKED_CANDIDATES
            {
                // Ignore exact duplicates and bound per-exchange memory if
                // candidates arrive faster than
                // the waiting task can validate them.
                drop(pending);
                self.stats
                    .discarded_datagrams
                    .fetch_add(1, Ordering::Relaxed);
                return false;
            }
            slot.responses.push_back((data, source));
            let notify = slot.owner.notify.clone();
            drop(pending);
            notify.notify_one();
            self.stats
                .correlated_datagrams
                .fetch_add(1, Ordering::Relaxed);
            return true;
        }
        self.stats
            .discarded_datagrams
            .fetch_add(1, Ordering::Relaxed);
        false
    }

    /// Record a datagram from which no request ID could be extracted.
    pub(crate) fn note_malformed(&self) {
        self.stats
            .malformed_datagrams
            .fetch_add(1, Ordering::Relaxed);
    }

    /// Wait until a response candidate is accepted for the given request.
    pub async fn wait_for_response_with<T, F>(
        &self,
        registration: &UdpRegistration,
        target: SocketAddr,
        mut validate: F,
    ) -> Result<T>
    where
        F: FnMut(Bytes, SocketAddr) -> Result<Candidate<T>>,
    {
        let request_id = registration.primary;
        let shard = self.shard(request_id);

        loop {
            // Enforce the absolute deadline before offering even an already
            // parked candidate to the validator. In particular, a zero timeout
            // is an immediate timeout rather than a race with response delivery.
            let now = Instant::now();
            if now >= registration.owner.deadline {
                registration.owner.note_expired(&self.stats);
                let elapsed = registration.owner.elapsed(now);
                tracing::debug!(target: "async_snmp::transport::udp", { request_id, %target, ?elapsed }, "transport timeout");
                return Err(Error::Timeout {
                    target,
                    elapsed,
                    retries: registration.owner.retries,
                }
                .boxed());
            }

            // Take a parked candidate without removing the registration. This
            // allows validation to reject it while preserving the owner and
            // original deadline.
            let response = {
                let mut pending = shard.pending.lock().unwrap();
                if let Some(PendingEntry::Slot(slot)) = pending.get_mut(&request_id)
                    && Arc::ptr_eq(&slot.owner, &registration.owner)
                {
                    slot.responses.pop_front()
                } else if self.closed.load(Ordering::Acquire) {
                    tracing::debug!(target: "async_snmp::transport::udp", { request_id, %target }, "transport shut down (slot missing)");
                    return Err(Error::Closed { target }.boxed());
                } else {
                    let now = Instant::now();
                    registration.owner.note_expired(&self.stats);
                    let elapsed = registration.owner.elapsed(now);
                    tracing::debug!(target: "async_snmp::transport::udp", { request_id, %target, ?elapsed }, "transport timeout (slot missing)");
                    return Err(Error::Timeout {
                        target,
                        elapsed,
                        retries: registration.owner.retries,
                    }
                    .boxed());
                }
            };

            if let Some((data, source)) = response {
                match validate(data, source)? {
                    Candidate::Accept(value) => {
                        self.remove_owned(request_id, &registration.owner);
                        return Ok(value);
                    }
                    Candidate::Reject => {
                        tracing::debug!(target: "async_snmp::transport::udp", { request_id, %source }, "response rejected by client validation");
                        continue;
                    }
                }
            }

            // Checked after the response lookup so a response delivered
            // before shutdown is still offered to the validator.
            if self.closed.load(Ordering::Acquire) {
                tracing::debug!(target: "async_snmp::transport::udp", { request_id, %target }, "transport shut down");
                return Err(Error::Closed { target }.boxed());
            }

            tokio::select! {
                () = registration.owner.notify.notified() => {}
                () = tokio::time::sleep_until(registration.owner.deadline) => {}
            }
        }
    }

    #[cfg(test)]
    async fn wait_for_response(
        &self,
        registration: &UdpRegistration,
        target: SocketAddr,
    ) -> Result<(Bytes, SocketAddr)> {
        self.wait_for_response_with(registration, target, |data, source| {
            Ok(Candidate::Accept((data, source)))
        })
        .await
    }

    /// Snapshot current stats.
    pub fn stats(&self) -> UdpStats {
        UdpStats {
            correlated_datagrams: self.stats.correlated_datagrams.load(Ordering::Relaxed),
            expired_registrations: self.stats.expired_registrations.load(Ordering::Relaxed),
            discarded_datagrams: self.stats.discarded_datagrams.load(Ordering::Relaxed),
            malformed_datagrams: self.stats.malformed_datagrams.load(Ordering::Relaxed),
        }
    }

    fn remove_owned(&self, request_id: i32, owner: &Arc<RegistrationOwner>) {
        let mut pending = self.shard(request_id).pending.lock().unwrap();
        let matches = match pending.get(&request_id) {
            Some(PendingEntry::Slot(slot)) => Arc::ptr_eq(&slot.owner, owner),
            Some(PendingEntry::Alias {
                owner: alias_owner, ..
            }) => Arc::ptr_eq(alias_owner, owner),
            None => false,
        };
        if matches {
            pending.remove(&request_id);
        }
    }

    #[cfg(test)]
    pub(crate) fn pending_counts(&self) -> (usize, usize) {
        self.shards.iter().fold((0, 0), |(slots, aliases), shard| {
            shard.pending.lock().unwrap().values().fold(
                (slots, aliases),
                |(slots, aliases), entry| match entry {
                    PendingEntry::Slot(_) => (slots + 1, aliases),
                    PendingEntry::Alias { .. } => (slots, aliases + 1),
                },
            )
        })
    }

    /// Remove all expired request slots.
    ///
    /// Should be called periodically to clean up slots that timed out
    /// but were never waited on.
    pub fn cleanup_expired(&self) {
        let now = Instant::now();
        let mut expired_owners = Vec::new();
        for shard in self.shards.iter() {
            let mut pending = shard.pending.lock().unwrap();
            pending.retain(|_, entry| {
                let keep = entry.owner().deadline > now;
                if !keep {
                    expired_owners.push(entry.owner().clone());
                }
                keep
            });
        }
        for owner in expired_owners {
            owner.note_expired(&self.stats);
            owner.notify.notify_one();
        }
    }
}

impl Default for UdpCore {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::super::CommunityResponsePolicy;
    use super::*;

    fn test_addr() -> SocketAddr {
        "127.0.0.1:161".parse().unwrap()
    }

    fn deadline_after(timeout: Duration) -> tokio::time::Instant {
        tokio::time::Instant::now() + timeout
    }

    fn register_v3(
        core: &Arc<UdpCore>,
        request_id: i32,
        timeout: Duration,
        strict: bool,
    ) -> UdpRegistration {
        core.register(
            RequestRegistration::test_unchecked(request_id, timeout),
            test_addr(),
            strict,
        )
        .unwrap()
    }

    #[test]
    fn closed_core_rejects_registration_without_pending_state() {
        let core = Arc::new(UdpCore::new());
        core.close();

        let result = core.register(
            RequestRegistration::test_unchecked(42, Duration::from_secs(30)),
            test_addr(),
            false,
        );
        let Err(error) = result else {
            panic!("closed core accepted a registration");
        };

        assert!(matches!(*error, Error::Closed { .. }));
        assert_eq!(core.pending_counts(), (0, 0));
    }

    fn community_packet(request_id: i32, community: &'static [u8]) -> Bytes {
        use crate::message::CommunityMessage;
        use crate::pdu::Pdu;

        CommunityMessage::v2c(
            Bytes::from_static(community),
            Pdu::response(request_id, 0, 0, Vec::new()),
        )
        .unwrap()
        .encode()
        .unwrap()
    }

    #[tokio::test]
    async fn timeout_reports_elapsed_from_registration() {
        let core = Arc::new(UdpCore::new());
        let timeout = Duration::from_millis(50);
        let registration = register_v3(&core, 1, timeout, false);

        let err = core
            .wait_for_response(&registration, test_addr())
            .await
            .unwrap_err();
        match *err {
            Error::Timeout {
                elapsed, retries, ..
            } => {
                assert!(elapsed >= timeout);
                assert!(elapsed < Duration::from_secs(1));
                assert_eq!(retries, 0);
            }
            other => panic!("expected Timeout, got {other:?}"),
        }
        drop(registration);
        assert_eq!(core.pending_counts(), (0, 0));
    }

    #[tokio::test]
    async fn correlation_window_carries_gap_candidate_across_retry_handoff() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let window = CorrelationWindow::new();
        let first = core
            .register(
                RequestRegistration::test_unchecked(10, Duration::from_secs(30))
                    .with_correlation_window(Arc::clone(&window)),
                target,
                false,
            )
            .unwrap();

        drop(first);
        assert_eq!(core.pending_counts(), (1, 0));
        let delayed = Bytes::from_static(b"delayed prior response");
        assert!(core.deliver(10, delayed.clone(), target));

        let second = core
            .register(
                RequestRegistration::test_unchecked(11, Duration::from_secs(30))
                    .with_correlation_window(Arc::clone(&window))
                    .with_aliases([10])
                    .unwrap(),
                target,
                false,
            )
            .unwrap();
        assert_eq!(core.pending_counts(), (1, 1));
        let (accepted, source) = core.wait_for_response(&second, target).await.unwrap();
        assert_eq!(accepted, delayed);
        assert_eq!(source, target);

        drop(second);
        assert_eq!(core.pending_counts(), (0, 1));
        drop(window);
        assert_eq!(core.pending_counts(), (0, 0));
    }

    #[tokio::test]
    async fn distinct_candidates_are_queued_until_validation() {
        let core = Arc::new(UdpCore::new());
        let addr = test_addr();
        let registration = register_v3(&core, 7, Duration::from_secs(30), false);
        let first = Bytes::from_static(b"first");

        assert!(core.deliver(7, first.clone(), addr));
        assert!(core.deliver(7, Bytes::from_static(b"second"), addr));
        assert_eq!(core.stats().correlated_datagrams, 2);
        assert_eq!(core.stats().discarded_datagrams, 0);
        let (data, _) = core.wait_for_response(&registration, addr).await.unwrap();
        assert_eq!(data, first);
    }

    #[tokio::test]
    async fn validator_rejection_keeps_registration_for_queued_candidate() {
        let core = Arc::new(UdpCore::new());
        let addr = test_addr();
        let registration = register_v3(&core, 8, Duration::from_secs(30), false);
        assert!(core.deliver(8, Bytes::from_static(b"reject"), addr));
        assert!(core.deliver(8, Bytes::from_static(b"accept"), addr));

        let accepted = core
            .wait_for_response_with(&registration, addr, |data, _| {
                if data.as_ref() == b"accept" {
                    Ok(Candidate::Accept(data))
                } else {
                    Ok(Candidate::Reject)
                }
            })
            .await
            .unwrap();
        assert_eq!(accepted.as_ref(), b"accept");
        assert_eq!(core.pending_counts(), (0, 0));
    }

    #[tokio::test]
    async fn alias_routes_delivery_to_owned_primary() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let registration = core
            .register(
                RequestRegistration::test_unchecked(2, Duration::from_secs(5))
                    .with_aliases([1])
                    .unwrap(),
                target,
                false,
            )
            .unwrap();
        assert_eq!(core.pending_counts(), (1, 1));
        assert!(core.deliver(1, Bytes::from_static(b"late"), target));
        let (data, source) = core.wait_for_response(&registration, target).await.unwrap();
        assert_eq!(data.as_ref(), b"late");
        assert_eq!(source, target);
        drop(registration);
        assert_eq!(core.pending_counts(), (0, 0));
    }

    #[test]
    fn guard_drop_removes_primary_and_all_aliases() {
        let core = Arc::new(UdpCore::new());
        let registration = core
            .register(
                RequestRegistration::v3(30, deadline_after(Duration::from_secs(300)))
                    .with_aliases([10, 20, 25])
                    .unwrap(),
                test_addr(),
                false,
            )
            .unwrap();
        assert_eq!(core.pending_counts(), (1, 3));
        drop(registration);
        assert_eq!(core.pending_counts(), (0, 0));
    }

    #[tokio::test]
    async fn collisions_do_not_modify_the_first_owner() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let first = core
            .register(
                RequestRegistration::test_unchecked(20, Duration::from_secs(30))
                    .with_aliases([10, 11])
                    .unwrap(),
                target,
                false,
            )
            .unwrap();

        for registration in [
            RequestRegistration::v3(20, deadline_after(Duration::from_secs(30))),
            RequestRegistration::v3(10, deadline_after(Duration::from_secs(30))),
            RequestRegistration::v3(30, deadline_after(Duration::from_secs(30)))
                .with_aliases([11])
                .unwrap(),
        ] {
            let error = core
                .register(registration, target, false)
                .err()
                .expect("live primary or alias collision must fail");
            assert!(matches!(*error, Error::RequestIdInUse { .. }));
            assert_eq!(core.pending_counts(), (1, 2));
        }

        assert!(core.deliver(10, Bytes::from_static(b"first"), target));
        let (data, _) = core.wait_for_response(&first, target).await.unwrap();
        assert_eq!(data.as_ref(), b"first");
    }

    #[test]
    fn concurrent_collisions_allow_exactly_one_owner() {
        let target = test_addr();
        for (left, right) in [
            (
                RequestRegistration::v3(100, deadline_after(Duration::from_secs(30))),
                RequestRegistration::v3(100, deadline_after(Duration::from_secs(30))),
            ),
            (
                RequestRegistration::v3(100, deadline_after(Duration::from_secs(30)))
                    .with_aliases([90])
                    .unwrap(),
                RequestRegistration::v3(90, deadline_after(Duration::from_secs(30))),
            ),
            (
                RequestRegistration::v3(100, deadline_after(Duration::from_secs(30)))
                    .with_aliases([90])
                    .unwrap(),
                RequestRegistration::v3(200, deadline_after(Duration::from_secs(30)))
                    .with_aliases([90])
                    .unwrap(),
            ),
        ] {
            let core = Arc::new(UdpCore::new());
            let barrier = Arc::new(std::sync::Barrier::new(2));
            let spawn = |registration| {
                let core = core.clone();
                let barrier = barrier.clone();
                std::thread::spawn(move || {
                    barrier.wait();
                    core.register(registration, target, false)
                })
            };
            let left_task = spawn(left);
            let right_task = spawn(right);
            let left = left_task.join().unwrap();
            let right = right_task.join().unwrap();
            assert_ne!(left.is_ok(), right.is_ok());
            let error = left.err().or_else(|| right.err()).unwrap();
            assert!(matches!(*error, Error::RequestIdInUse { .. }));
        }
    }

    #[test]
    fn duplicate_aliases_are_reserved_once() {
        let core = Arc::new(UdpCore::new());
        let registration = core
            .register(
                RequestRegistration::v3(30, deadline_after(Duration::from_secs(30)))
                    .with_aliases([10, 10, 30, 11, 10, 11])
                    .unwrap(),
                test_addr(),
                false,
            )
            .unwrap();
        assert_eq!(registration.aliases, BTreeSet::from([10, 11]));
        assert_eq!(core.pending_counts(), (1, 2));
    }

    #[tokio::test]
    async fn cleanup_preserves_timeout_metadata_and_counts_once() {
        let core = Arc::new(UdpCore::new());
        let registration = register_v3(&core, 40, Duration::ZERO, false);
        std::thread::sleep(Duration::from_millis(2));

        core.cleanup_expired();
        core.cleanup_expired();
        let error = core
            .wait_for_response(&registration, test_addr())
            .await
            .unwrap_err();
        match *error {
            Error::Timeout {
                elapsed, retries, ..
            } => {
                assert!(elapsed >= Duration::from_millis(1));
                assert_eq!(retries, 0);
            }
            other => panic!("expected Timeout, got {other:?}"),
        }
        assert_eq!(core.stats().expired_registrations, 1);
    }

    #[test]
    fn over_maximum_aliases_are_rejected_before_registration() {
        let core = Arc::new(UdpCore::new());
        let aliases = 0..=crate::client::MAX_RETRIES as i32;
        let error = RequestRegistration::v3(50, deadline_after(Duration::from_secs(1)))
            .with_aliases(aliases)
            .unwrap_err();
        assert!(matches!(*error, Error::Config(_)));
        assert_eq!(core.pending_counts(), (0, 0));
    }

    #[tokio::test]
    async fn zero_deadline_does_not_accept_a_parked_candidate() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let registration = register_v3(&core, 51, Duration::ZERO, false);

        assert!(!core.deliver(51, Bytes::from_static(b"candidate"), target));
        let error = core
            .wait_for_response(&registration, target)
            .await
            .unwrap_err();
        assert!(matches!(*error, Error::Timeout { .. }));
        let stats = core.stats();
        assert_eq!(stats.correlated_datagrams, 0);
        assert_eq!(stats.expired_registrations, 1);
        assert_eq!(stats.discarded_datagrams, 1);

        core.cleanup_expired();
        assert_eq!(core.stats().expired_registrations, 1);
    }

    #[tokio::test]
    async fn parked_candidate_is_not_validated_after_deadline() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let registration = register_v3(&core, 52, Duration::from_millis(5), false);
        assert!(core.deliver(52, Bytes::from_static(b"candidate"), target));
        tokio::time::sleep(Duration::from_millis(10)).await;

        let mut validations = 0;
        let error = core
            .wait_for_response_with(&registration, target, |data, source| {
                validations += 1;
                Ok(Candidate::Accept((data, source)))
            })
            .await
            .unwrap_err();
        assert!(matches!(*error, Error::Timeout { .. }));
        assert_eq!(validations, 0);
        assert_eq!(core.stats().expired_registrations, 1);
    }

    #[test]
    fn expired_alias_cleanup_does_not_remove_live_primary() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let registration = core
            .register(
                RequestRegistration::v3(2, tokio::time::Instant::now())
                    .with_aliases([1])
                    .unwrap(),
                target,
                false,
            )
            .unwrap();
        core.cleanup_expired();
        assert_eq!(core.pending_counts(), (0, 0));
        assert_eq!(core.stats().expired_registrations, 1);
        drop(registration);
    }

    #[tokio::test]
    async fn community_rejection_is_non_consuming_and_preserves_deadline() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let other = "127.0.0.2:161".parse().unwrap();
        let request_id = 500;
        let registration = core
            .register(
                RequestRegistration::community(
                    request_id,
                    deadline_after(Duration::from_secs(5)),
                    crate::CommunityVersion::V2c,
                    Bytes::from_static(b"public"),
                    CommunityResponsePolicy::Exact,
                ),
                target,
                false,
            )
            .unwrap();
        let (notify, original_deadline) = {
            let pending = core.shard(request_id).pending.lock().unwrap();
            let PendingEntry::Slot(slot) = pending.get(&request_id).unwrap() else {
                panic!("expected pending slot");
            };
            (slot.owner.notify.clone(), slot.owner.deadline)
        };

        assert!(!core.deliver(request_id, community_packet(request_id, b"wrong"), other,));
        assert!(
            tokio::time::timeout(Duration::from_millis(10), notify.notified())
                .await
                .is_err()
        );
        {
            let pending = core.shard(request_id).pending.lock().unwrap();
            let PendingEntry::Slot(slot) = pending.get(&request_id).unwrap() else {
                panic!("expected retained pending slot");
            };
            assert_eq!(slot.owner.deadline, original_deadline);
            assert!(slot.responses.is_empty());
        }

        assert!(core.deliver(request_id, community_packet(request_id, b"public"), target,));
        let (accepted, _) = core.wait_for_response(&registration, target).await.unwrap();
        assert_eq!(
            super::super::extract_community_identity(&accepted)
                .unwrap()
                .1,
            b"public"
        );
    }

    #[tokio::test]
    async fn strict_suffix_rejection_preserves_registration_and_deadline() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let request_id = 501;
        let prior_request_id = 500;
        let registration = core
            .register(
                RequestRegistration::community(
                    request_id,
                    deadline_after(Duration::from_secs(5)),
                    crate::CommunityVersion::V2c,
                    Bytes::from_static(b"public"),
                    CommunityResponsePolicy::Exact,
                )
                .with_decode_config(crate::DecodeConfig::STRICT)
                .with_aliases([prior_request_id])
                .unwrap(),
                target,
                false,
            )
            .unwrap();
        let original_deadline = registration.owner.deadline;
        let clean = community_packet(request_id, b"public");
        let mut suffixed = community_packet(prior_request_id, b"public").to_vec();
        suffixed.extend_from_slice(b"suffix");

        assert!(!core.deliver(prior_request_id, Bytes::from(suffixed), target));
        {
            let pending = core.shard(request_id).pending.lock().unwrap();
            let PendingEntry::Slot(slot) = pending.get(&request_id).unwrap() else {
                panic!("expected retained pending slot");
            };
            assert!(Arc::ptr_eq(&slot.owner, &registration.owner));
            assert_eq!(slot.owner.deadline, original_deadline);
            assert!(slot.responses.is_empty());
        }
        {
            let pending = core.shard(prior_request_id).pending.lock().unwrap();
            let PendingEntry::Alias { primary, owner } = pending.get(&prior_request_id).unwrap()
            else {
                panic!("expected retained retry alias");
            };
            assert_eq!(*primary, request_id);
            assert!(Arc::ptr_eq(owner, &registration.owner));
            assert_eq!(owner.deadline, original_deadline);
        }
        assert_eq!(core.pending_counts(), (1, 1));
        assert_eq!(core.stats().discarded_datagrams, 1);
        assert_eq!(core.stats().expired_registrations, 0);

        assert!(core.deliver(request_id, clean.clone(), target));
        let (accepted, source) = core.wait_for_response(&registration, target).await.unwrap();
        assert_eq!(accepted, clean);
        assert_eq!(source, target);
        assert_eq!(core.pending_counts(), (0, 1));
        assert_eq!(core.stats().correlated_datagrams, 1);
        assert_eq!(core.stats().expired_registrations, 0);
        drop(registration);
        assert_eq!(core.pending_counts(), (0, 0));
    }

    #[test]
    fn strict_source_rejection_keeps_owned_slot() {
        let core = Arc::new(UdpCore::new());
        let target = test_addr();
        let other = "127.0.0.2:161".parse().unwrap();
        let _registration = register_v3(&core, 2, Duration::from_secs(5), true);
        assert!(!core.deliver(2, Bytes::from_static(b"spoof"), other));
        assert!(core.deliver(2, Bytes::from_static(b"real"), target));
    }
}