async-snmp 0.16.0

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
//! Walk stream implementations.

// Allow complex types for boxed futures in manual Stream implementations.
// The `pending` fields require `Option<Pin<Box<dyn Future<Output = ...> + Send>>>`
// which triggers this lint but is the standard pattern for storing futures.
#![allow(clippy::type_complexity)]

/// Implement `next()` and `collect()` for a Stream type that implements `poll_next`.
macro_rules! impl_stream_helpers {
    ($type:ident < $($gen:tt),+ >) => {
        impl<$($gen),+> $type<$($gen),+>
        where
            $($gen: crate::transport::Transport + 'static,)+
        {
            /// Get the next varbind, or None when complete.
            pub async fn next(&mut self) -> Option<crate::error::Result<crate::varbind::VarBind>> {
                std::future::poll_fn(|cx| std::pin::Pin::new(&mut *self).poll_next(cx)).await
            }

            /// Collect all remaining varbinds.
            ///
            /// If the walk completes with no results, a fallback GET is attempted
            /// on the base OID to handle scalar objects (e.g. `sysDescr.0`) that a
            /// GETNEXT/GETBULK walk would step past. The result is only returned
            /// when it is a real value and the `max_results` cap permits it;
            /// genuine absence is swallowed and real errors are propagated.
            pub async fn collect(mut self) -> crate::error::Result<Vec<crate::varbind::VarBind>> {
                let mut results = Vec::new();
                while let Some(result) = self.next().await {
                    results.push(result?);
                }
                if results.is_empty() {
                    crate::client::walk::walk_scalar_fallback(
                        &self.client,
                        &self.base_oid,
                        self.max_results,
                        &mut results,
                    )
                    .await?;
                }
                Ok(results)
            }
        }
    };
}

use std::collections::{HashSet, VecDeque};
use std::pin::Pin;
use std::task::{Context, Poll};

use futures_core::Stream;

use crate::error::{Error, Result, WalkAbortReason};
use crate::oid::Oid;
use crate::transport::Transport;
use crate::varbind::VarBind;
use crate::version::Version;

use super::Client;

/// Walk operation mode.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum WalkMode {
    /// Auto-select based on version (default).
    /// V1 uses GETNEXT, V2c/V3 uses GETBULK.
    #[default]
    Auto,
    /// Always use GETNEXT (slower but more compatible).
    GetNext,
    /// Always use GETBULK (faster, errors on v1).
    GetBulk,
}

/// OID ordering behavior during walk operations.
///
/// SNMP walks rely on agents returning OIDs in strictly increasing
/// lexicographic order. However, some buggy agents violate this requirement,
/// returning OIDs out of order or even repeating OIDs (which would cause
/// infinite loops).
///
/// This enum controls how the library handles ordering violations:
///
/// - [`Strict`](Self::Strict) (default): Terminates immediately with
///   [`Error::WalkAborted`](crate::Error::WalkAborted) on any violation.
///   Use this unless you know the agent has ordering bugs.
///
/// - [`AllowNonIncreasing`](Self::AllowNonIncreasing): Tolerates out-of-order
///   OIDs but tracks all seen OIDs to detect cycles. Returns
///   [`Error::WalkAborted`](crate::Error::WalkAborted) if the same OID appears twice.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum OidOrdering {
    /// Require strictly increasing OIDs (default).
    ///
    /// Walk terminates with [`Error::WalkAborted`](crate::Error::WalkAborted)
    /// on first violation. Most efficient: O(1) memory, O(1) per-item check.
    #[default]
    Strict,

    /// Allow non-increasing OIDs, with cycle detection.
    ///
    /// Some buggy agents return OIDs out of order. This mode tracks all seen
    /// OIDs in a `HashSet` to detect cycles, terminating with an error if the
    /// same OID is returned twice.
    ///
    /// **Warning**: This uses O(n) memory where n = number of walk results.
    /// Always pair with [`ClientBuilder::max_walk_results`] to bound memory
    /// usage. Cycle detection only catches duplicate OIDs; a pathological
    /// agent could still return an infinite sequence of unique OIDs within
    /// the subtree.
    ///
    /// [`ClientBuilder::max_walk_results`]: crate::ClientBuilder::max_walk_results
    AllowNonIncreasing,
}

enum OidTracker {
    Strict { last: Option<Oid> },
    Relaxed { seen: HashSet<Oid> },
}

/// Outcome of validating a single varbind from a walk response.
enum VarbindOutcome {
    /// Varbind is valid and within the subtree; emit it.
    Yield,
    /// Walk is complete (end-of-MIB or out-of-subtree).
    Done,
    /// Walk should abort with the given error.
    Abort(Box<Error>),
}

/// Validate a varbind received during a walk.
///
/// Checks end-of-MIB, subtree containment, and OID ordering.
/// Returns the outcome, updating `oid_tracker` on success.
fn validate_walk_varbind(
    vb: &VarBind,
    base_oid: &Oid,
    oid_tracker: &mut OidTracker,
    target: std::net::SocketAddr,
) -> VarbindOutcome {
    if vb.value.is_exception() {
        return VarbindOutcome::Done;
    }
    if !vb.oid.starts_with(base_oid) {
        return VarbindOutcome::Done;
    }
    match oid_tracker.check(&vb.oid, target) {
        Ok(()) => VarbindOutcome::Yield,
        Err(e) => VarbindOutcome::Abort(e),
    }
}

/// Attempt a scalar-fallback GET on `base_oid` when a walk yielded no results.
///
/// Scalar objects (e.g. `sysDescr.0`) are not returned by a GETNEXT/GETBULK
/// walk rooted at the scalar object OID, so a direct GET is used as a fallback
/// when the walk produced nothing.
///
/// The fallback result is appended to `results` only when both:
/// - the GET returns a real value (not an exception), and
/// - the walk's `max_results` cap still permits another result (in particular
///   `Some(0)` yields zero results, matching the streaming cap behaviour).
///
/// Genuine absence is swallowed: v2c+ `noSuchObject`/`noSuchInstance`/
/// `endOfMibView` exception values, and the v1 `noSuchName` error-status. Any
/// other error (timeout, authentication failure, malformed response, ...) is
/// propagated to the caller.
async fn walk_scalar_fallback<T: Transport + 'static>(
    client: &Client<T>,
    base_oid: &Oid,
    max_results: Option<usize>,
    results: &mut Vec<VarBind>,
) -> Result<()> {
    // Respect the walk result cap; Some(0) must yield zero results.
    if matches!(max_results, Some(max) if results.len() >= max) {
        return Ok(());
    }
    match client.get(base_oid).await {
        // Real scalar value: return it.
        Ok(vb) if !vb.value.is_exception() => {
            results.push(vb);
            Ok(())
        }
        // Genuine absence (v2c+): exception value in an otherwise-Ok response.
        Ok(_) => Ok(()),
        // Genuine absence (v1): noSuchName error-status.
        Err(e)
            if matches!(
                &*e,
                Error::Snmp {
                    status: crate::error::ErrorStatus::NoSuchName,
                    ..
                }
            ) =>
        {
            Ok(())
        }
        // Real failure (timeout, auth, malformed, ...): propagate.
        Err(e) => Err(e),
    }
}

impl OidTracker {
    fn new(ordering: OidOrdering) -> Self {
        match ordering {
            OidOrdering::Strict => OidTracker::Strict { last: None },
            OidOrdering::AllowNonIncreasing => OidTracker::Relaxed {
                seen: HashSet::new(),
            },
        }
    }

    fn check(&mut self, oid: &Oid, target: std::net::SocketAddr) -> Result<()> {
        match self {
            OidTracker::Strict { last } => {
                if let Some(prev) = last
                    && oid <= prev
                {
                    tracing::debug!(target: "async_snmp::walk", { previous_oid = %prev, current_oid = %oid, %target }, "non-increasing OID detected");
                    return Err(Error::WalkAborted {
                        target,
                        reason: WalkAbortReason::NonIncreasing,
                    }
                    .boxed());
                }
                *last = Some(oid.clone());
                Ok(())
            }
            OidTracker::Relaxed { seen } => {
                if !seen.insert(oid.clone()) {
                    tracing::debug!(target: "async_snmp::walk", { %oid, %target }, "duplicate OID detected (cycle)");
                    return Err(Error::WalkAborted {
                        target,
                        reason: WalkAbortReason::Cycle,
                    }
                    .boxed());
                }
                Ok(())
            }
        }
    }
}

/// Async stream for walking an OID subtree using GETNEXT.
///
/// Created by [`Client::walk_getnext()`].
pub struct Walk<T: Transport> {
    client: Client<T>,
    base_oid: Oid,
    current_oid: Oid,
    /// OID tracker for ordering validation.
    oid_tracker: OidTracker,
    /// Maximum number of results to return (None = unlimited).
    max_results: Option<usize>,
    /// Count of results returned so far.
    count: usize,
    done: bool,
    pending: Option<Pin<Box<dyn std::future::Future<Output = Result<VarBind>> + Send>>>,
}

impl<T: Transport> Walk<T> {
    pub(crate) fn new(
        client: Client<T>,
        oid: Oid,
        ordering: OidOrdering,
        max_results: Option<usize>,
    ) -> Self {
        Self {
            client,
            base_oid: oid.clone(),
            current_oid: oid,
            oid_tracker: OidTracker::new(ordering),
            max_results,
            count: 0,
            done: false,
            pending: None,
        }
    }
}

impl_stream_helpers!(Walk<T>);

impl<T: Transport + 'static> Stream for Walk<T> {
    type Item = Result<VarBind>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        if self.done {
            return Poll::Ready(None);
        }

        // Check max_results limit
        if let Some(max) = self.max_results
            && self.count >= max
        {
            self.done = true;
            return Poll::Ready(None);
        }

        // Check if we have a pending request
        if self.pending.is_none() {
            // Start a new GETNEXT request
            let client = self.client.clone();
            let oid = self.current_oid.clone();

            let fut = Box::pin(async move { client.get_next(&oid).await });
            self.pending = Some(fut);
        }

        // Poll the pending future
        let pending = self.pending.as_mut().unwrap();
        match pending.as_mut().poll(cx) {
            Poll::Pending => Poll::Pending,
            Poll::Ready(result) => {
                self.pending = None;

                match result {
                    Ok(vb) => {
                        let target = self.client.peer_addr();
                        let base_oid = self.base_oid.clone();
                        match validate_walk_varbind(&vb, &base_oid, &mut self.oid_tracker, target) {
                            VarbindOutcome::Done => {
                                self.done = true;
                                return Poll::Ready(None);
                            }
                            VarbindOutcome::Abort(e) => {
                                self.done = true;
                                return Poll::Ready(Some(Err(e)));
                            }
                            VarbindOutcome::Yield => {}
                        }

                        // Update current OID for next iteration
                        self.current_oid = vb.oid.clone();
                        self.count += 1;

                        Poll::Ready(Some(Ok(vb)))
                    }
                    Err(e) => {
                        if self.client.inner.config.version == Version::V1
                            && matches!(
                                &*e,
                                Error::Snmp {
                                    status: crate::error::ErrorStatus::NoSuchName,
                                    ..
                                }
                            )
                        {
                            self.done = true;
                            return Poll::Ready(None);
                        }

                        self.done = true;
                        Poll::Ready(Some(Err(e)))
                    }
                }
            }
        }
    }
}

/// Async stream for walking an OID subtree using GETBULK.
///
/// Created by [`Client::bulk_walk()`].
pub struct BulkWalk<T: Transport> {
    client: Client<T>,
    base_oid: Oid,
    current_oid: Oid,
    max_repetitions: i32,
    /// OID tracker for ordering validation.
    oid_tracker: OidTracker,
    /// Maximum number of results to return (None = unlimited).
    max_results: Option<usize>,
    /// Count of results returned so far.
    count: usize,
    done: bool,
    /// Buffered results from the last GETBULK response
    buffer: VecDeque<VarBind>,
    pending: Option<Pin<Box<dyn std::future::Future<Output = Result<Vec<VarBind>>> + Send>>>,
}

impl<T: Transport> BulkWalk<T> {
    pub(crate) fn new(
        client: Client<T>,
        oid: Oid,
        max_repetitions: i32,
        ordering: OidOrdering,
        max_results: Option<usize>,
    ) -> Self {
        Self {
            client,
            base_oid: oid.clone(),
            current_oid: oid,
            max_repetitions,
            oid_tracker: OidTracker::new(ordering),
            max_results,
            count: 0,
            done: false,
            buffer: VecDeque::new(),
            pending: None,
        }
    }
}

impl_stream_helpers!(BulkWalk<T>);

impl<T: Transport + 'static> Stream for BulkWalk<T> {
    type Item = Result<VarBind>;

    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        loop {
            if self.done {
                return Poll::Ready(None);
            }

            // Check max_results limit
            if let Some(max) = self.max_results
                && self.count >= max
            {
                self.done = true;
                return Poll::Ready(None);
            }

            // Check if we have buffered results to return
            if let Some(vb) = self.buffer.pop_front() {
                let target = self.client.peer_addr();
                let base_oid = self.base_oid.clone();
                match validate_walk_varbind(&vb, &base_oid, &mut self.oid_tracker, target) {
                    VarbindOutcome::Done => {
                        self.done = true;
                        return Poll::Ready(None);
                    }
                    VarbindOutcome::Abort(e) => {
                        self.done = true;
                        return Poll::Ready(Some(Err(e)));
                    }
                    VarbindOutcome::Yield => {}
                }

                // Update current OID for next request
                self.current_oid = vb.oid.clone();
                self.count += 1;

                return Poll::Ready(Some(Ok(vb)));
            }

            // Buffer exhausted, need to fetch more
            if self.pending.is_none() {
                let client = self.client.clone();
                let oid = self.current_oid.clone();
                let max_rep = self.max_repetitions;

                let fut = Box::pin(async move { client.get_bulk(&[oid], 0, max_rep).await });
                self.pending = Some(fut);
            }

            // Poll the pending future
            let pending = self.pending.as_mut().unwrap();
            match pending.as_mut().poll(cx) {
                Poll::Pending => return Poll::Pending,
                Poll::Ready(result) => {
                    self.pending = None;

                    match result {
                        Ok(varbinds) => {
                            if varbinds.is_empty() {
                                self.done = true;
                                return Poll::Ready(None);
                            }

                            self.buffer = varbinds.into();
                            // Continue loop to process buffer
                        }
                        Err(e) => {
                            // On tooBig, degrade instead of aborting (RFC 3416
                            // 4.2.3): halve max-repetitions down to a floor of 1
                            // and retry the same position. Only surface the error
                            // if it still fails at max-repetitions = 1.
                            if self.max_repetitions > 1
                                && matches!(
                                    &*e,
                                    Error::Snmp {
                                        status: crate::error::ErrorStatus::TooBig,
                                        ..
                                    }
                                )
                            {
                                let reduced = (self.max_repetitions / 2).max(1);
                                tracing::debug!(target: "async_snmp::client", { peer = %self.client.peer_addr(), snmp.max_repetitions = self.max_repetitions, snmp.reduced_max_repetitions = reduced }, "tooBig response, reducing max-repetitions and retrying");
                                self.max_repetitions = reduced;
                                // Retry the same position with fewer repetitions.
                                continue;
                            }

                            self.done = true;
                            return Poll::Ready(Some(Err(e)));
                        }
                    }
                }
            }
        }
    }
}

// ============================================================================
// Unified WalkStream - auto-selects GETNEXT or GETBULK based on WalkMode
// ============================================================================

/// Unified walk stream that auto-selects between GETNEXT and GETBULK.
///
/// Created by [`Client::walk()`] when using `WalkMode::Auto` or explicit mode selection.
/// This type wraps either a [`Walk`] or [`BulkWalk`] internally based on:
/// - `WalkMode::Auto`: Uses GETNEXT for V1, GETBULK for V2c/V3
/// - `WalkMode::GetNext`: Always uses GETNEXT
/// - `WalkMode::GetBulk`: Always uses GETBULK (fails on V1)
pub enum WalkStream<T: Transport> {
    /// GETNEXT-based walk (used for V1 or when explicitly requested)
    GetNext(Walk<T>),
    /// GETBULK-based walk (used for V2c/V3 or when explicitly requested)
    GetBulk(BulkWalk<T>),
}

impl<T: Transport> WalkStream<T> {
    /// Create a new walk stream with auto-selection based on version and walk mode.
    pub(crate) fn new(
        client: Client<T>,
        oid: Oid,
        version: Version,
        walk_mode: WalkMode,
        ordering: OidOrdering,
        max_results: Option<usize>,
        max_repetitions: i32,
    ) -> Result<Self> {
        let use_bulk = match walk_mode {
            WalkMode::Auto => version != Version::V1,
            WalkMode::GetNext => false,
            WalkMode::GetBulk => {
                if version == Version::V1 {
                    return Err(Error::Config("GETBULK is not supported in SNMPv1".into()).boxed());
                }
                true
            }
        };

        Ok(if use_bulk {
            WalkStream::GetBulk(BulkWalk::new(
                client,
                oid,
                max_repetitions,
                ordering,
                max_results,
            ))
        } else {
            WalkStream::GetNext(Walk::new(client, oid, ordering, max_results))
        })
    }
}

impl<T: Transport + 'static> WalkStream<T> {
    /// Get the next varbind, or None when complete.
    pub async fn next(&mut self) -> Option<Result<VarBind>> {
        std::future::poll_fn(|cx| Pin::new(&mut *self).poll_next(cx)).await
    }

    /// Collect all remaining varbinds.
    ///
    /// If the walk completes with no results, a fallback GET is attempted on the
    /// base OID. This handles scalar OIDs (e.g. `sysDescr.0`) where GETNEXT would
    /// walk past the value. The GET result is only returned if it contains a real
    /// value (not `NoSuchObject`, `NoSuchInstance`, or `EndOfMibView`) and the
    /// `max_results` cap permits it. Genuine absence (including the v1
    /// `noSuchName` error-status) is swallowed; other errors (timeout,
    /// authentication failure, malformed response) are propagated. This matches
    /// the fallback behaviour of [`Walk::collect`] and [`BulkWalk::collect`].
    pub async fn collect(mut self) -> Result<Vec<VarBind>> {
        let mut results = Vec::new();
        while let Some(result) = self.next().await {
            results.push(result?);
        }
        if results.is_empty() {
            let (client, base_oid, max_results) = match &self {
                WalkStream::GetNext(w) => (&w.client, &w.base_oid, w.max_results),
                WalkStream::GetBulk(bw) => (&bw.client, &bw.base_oid, bw.max_results),
            };
            walk_scalar_fallback(client, base_oid, max_results, &mut results).await?;
        }
        Ok(results)
    }
}

impl<T: Transport + 'static> Stream for WalkStream<T> {
    type Item = Result<VarBind>;

    fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
        // SAFETY: We're just projecting the pin to the inner enum variant
        match self.get_mut() {
            WalkStream::GetNext(walk) => Pin::new(walk).poll_next(cx),
            WalkStream::GetBulk(bulk_walk) => Pin::new(bulk_walk).poll_next(cx),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::oid;
    use crate::value::Value;

    fn target_addr() -> std::net::SocketAddr {
        "127.0.0.1:161".parse().unwrap()
    }

    #[test]
    fn test_walk_terminates_on_no_such_object() {
        let base = oid!(1, 3, 6, 1, 2, 1, 1);
        let mut tracker = OidTracker::new(OidOrdering::Strict);
        let vb = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::NoSuchObject);
        assert!(matches!(
            validate_walk_varbind(&vb, &base, &mut tracker, target_addr()),
            VarbindOutcome::Done
        ));
    }

    #[test]
    fn test_walk_terminates_on_no_such_instance() {
        let base = oid!(1, 3, 6, 1, 2, 1, 1);
        let mut tracker = OidTracker::new(OidOrdering::Strict);
        let vb = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::NoSuchInstance);
        assert!(matches!(
            validate_walk_varbind(&vb, &base, &mut tracker, target_addr()),
            VarbindOutcome::Done
        ));
    }

    #[test]
    fn test_walk_terminates_on_end_of_mib_view() {
        let base = oid!(1, 3, 6, 1, 2, 1, 1);
        let mut tracker = OidTracker::new(OidOrdering::Strict);
        let vb = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::EndOfMibView);
        assert!(matches!(
            validate_walk_varbind(&vb, &base, &mut tracker, target_addr()),
            VarbindOutcome::Done
        ));
    }

    #[test]
    fn test_walk_yields_normal_value() {
        let base = oid!(1, 3, 6, 1, 2, 1, 1);
        let mut tracker = OidTracker::new(OidOrdering::Strict);
        let vb = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::Integer(42));
        assert!(matches!(
            validate_walk_varbind(&vb, &base, &mut tracker, target_addr()),
            VarbindOutcome::Yield
        ));
    }

    #[test]
    fn test_walk_strict_aborts_on_non_increasing_oid() {
        let base = oid!(1, 3, 6, 1, 2, 1, 1);
        let mut tracker = OidTracker::new(OidOrdering::Strict);

        let vb1 = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 2, 0), Value::Integer(1));
        assert!(matches!(
            validate_walk_varbind(&vb1, &base, &mut tracker, target_addr()),
            VarbindOutcome::Yield
        ));

        // A lower in-subtree OID must abort with NonIncreasing.
        let vb2 = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::Integer(2));
        match validate_walk_varbind(&vb2, &base, &mut tracker, target_addr()) {
            VarbindOutcome::Abort(e) => match *e {
                Error::WalkAborted { reason, .. } => {
                    assert_eq!(reason, WalkAbortReason::NonIncreasing);
                }
                other => panic!("expected WalkAborted, got {other:?}"),
            },
            _ => panic!("expected Abort outcome"),
        }
    }

    #[test]
    fn test_walk_strict_aborts_on_equal_oid() {
        let base = oid!(1, 3, 6, 1, 2, 1, 1);
        let mut tracker = OidTracker::new(OidOrdering::Strict);

        let vb1 = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 2, 0), Value::Integer(1));
        assert!(matches!(
            validate_walk_varbind(&vb1, &base, &mut tracker, target_addr()),
            VarbindOutcome::Yield
        ));

        // Same OID again (the `<=` boundary) must also abort with NonIncreasing.
        let vb2 = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 2, 0), Value::Integer(1));
        match validate_walk_varbind(&vb2, &base, &mut tracker, target_addr()) {
            VarbindOutcome::Abort(e) => match *e {
                Error::WalkAborted { reason, .. } => {
                    assert_eq!(reason, WalkAbortReason::NonIncreasing);
                }
                other => panic!("expected WalkAborted, got {other:?}"),
            },
            _ => panic!("expected Abort outcome"),
        }
    }

    #[test]
    fn test_walk_relaxed_aborts_on_duplicate_oid_cycle() {
        let base = oid!(1, 3, 6, 1, 2, 1, 1);
        let mut tracker = OidTracker::new(OidOrdering::AllowNonIncreasing);

        let vb1 = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 2, 0), Value::Integer(1));
        assert!(matches!(
            validate_walk_varbind(&vb1, &base, &mut tracker, target_addr()),
            VarbindOutcome::Yield
        ));

        // Same OID again must abort with Cycle (not NonIncreasing).
        let vb2 = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 2, 0), Value::Integer(1));
        match validate_walk_varbind(&vb2, &base, &mut tracker, target_addr()) {
            VarbindOutcome::Abort(e) => match *e {
                Error::WalkAborted { reason, .. } => {
                    assert_eq!(reason, WalkAbortReason::Cycle);
                }
                other => panic!("expected WalkAborted, got {other:?}"),
            },
            _ => panic!("expected Abort outcome"),
        }
    }

    #[test]
    fn test_walk_relaxed_allows_non_increasing_distinct_oid() {
        let base = oid!(1, 3, 6, 1, 2, 1, 1);
        let mut tracker = OidTracker::new(OidOrdering::AllowNonIncreasing);

        // Higher OID first.
        let vb1 = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 3, 0), Value::Integer(1));
        assert!(matches!(
            validate_walk_varbind(&vb1, &base, &mut tracker, target_addr()),
            VarbindOutcome::Yield
        ));

        // Lower, but distinct, in-subtree OID: relaxed mode tolerates this (no abort).
        let vb2 = VarBind::new(oid!(1, 3, 6, 1, 2, 1, 1, 1, 0), Value::Integer(2));
        assert!(matches!(
            validate_walk_varbind(&vb2, &base, &mut tracker, target_addr()),
            VarbindOutcome::Yield
        ));
    }

    // -------------------------------------------------------------------------
    // Mock transport that returns tooBig for GETBULK when max-repetitions
    // exceeds a threshold, otherwise returns a terminating response. Used to
    // exercise BulkWalk degradation (RFC 3416 4.2.3): on tooBig the walk halves
    // max-repetitions and retries the same position instead of aborting.
    // -------------------------------------------------------------------------

    use crate::client::ClientConfig;
    use crate::error::ErrorStatus;
    use crate::message::CommunityMessage;
    use crate::pdu::{Pdu, PduType};
    use bytes::Bytes;
    use std::collections::VecDeque;
    use std::net::SocketAddr;
    use std::sync::{Arc, Mutex};

    #[derive(Clone)]
    struct BulkTooBigTransport {
        /// Highest max-repetitions the agent will accept; larger requests return tooBig.
        max_repetitions: i32,
        /// Records (request_id, max_repetitions) seen by `send`, drained by `recv`.
        pending: Arc<Mutex<VecDeque<(i32, i32)>>>,
        /// Total number of tooBig responses emitted.
        too_big_count: Arc<Mutex<usize>>,
    }

    impl BulkTooBigTransport {
        fn new(max_repetitions: i32) -> Self {
            Self {
                max_repetitions,
                pending: Arc::new(Mutex::new(VecDeque::new())),
                too_big_count: Arc::new(Mutex::new(0)),
            }
        }
    }

    impl Transport for BulkTooBigTransport {
        fn send(&self, data: &[u8]) -> impl std::future::Future<Output = Result<()>> + Send {
            let request_id = crate::transport::extract_request_id(data).unwrap_or(1);
            let msg = CommunityMessage::decode(Bytes::copy_from_slice(data)).unwrap();
            let pdu = msg.pdu.standard().unwrap();
            // For GETBULK, error_index carries max-repetitions.
            let max_rep = pdu.error_index;
            self.pending
                .lock()
                .unwrap()
                .push_back((request_id, max_rep));
            async { Ok(()) }
        }

        fn recv(
            &self,
            _request_id: i32,
        ) -> impl std::future::Future<Output = Result<(Bytes, SocketAddr)>> + Send {
            let (request_id, max_rep) = self.pending.lock().unwrap().pop_front().unwrap_or((1, 0));
            let threshold = self.max_repetitions;
            let too_big_count = self.too_big_count.clone();
            let peer: SocketAddr = "127.0.0.1:161".parse().unwrap();

            async move {
                let pdu = if max_rep > threshold {
                    *too_big_count.lock().unwrap() += 1;
                    Pdu {
                        pdu_type: PduType::Response,
                        request_id,
                        error_status: ErrorStatus::TooBig.as_i32(),
                        error_index: 0,
                        varbinds: vec![],
                    }
                } else {
                    // One in-subtree value, then EndOfMibView to terminate the walk.
                    let varbinds = vec![
                        VarBind::new(oid!(1, 3, 6, 1, 2, 1, 2, 1, 0), Value::Integer(1)),
                        VarBind::new(oid!(1, 3, 6, 1, 2, 1, 2, 2, 0), Value::EndOfMibView),
                    ];
                    Pdu {
                        pdu_type: PduType::Response,
                        request_id,
                        error_status: 0,
                        error_index: 0,
                        varbinds,
                    }
                };

                let msg = CommunityMessage::v2c(Bytes::from_static(b"public"), pdu);
                Ok((msg.encode(), peer))
            }
        }

        fn peer_addr(&self) -> SocketAddr {
            "127.0.0.1:161".parse().unwrap()
        }

        fn local_addr(&self) -> SocketAddr {
            "127.0.0.1:0".parse().unwrap()
        }

        fn is_reliable(&self) -> bool {
            true
        }
    }

    #[tokio::test]
    async fn bulk_walk_degrades_max_repetitions_on_too_big() {
        // Agent accepts at most max-repetitions=4. Starting at 25, the walk must
        // halve (25 -> 12 -> 6 -> 3) and retry the same position until it fits,
        // rather than surfacing the tooBig error.
        let transport = BulkTooBigTransport::new(4);
        let too_big_count = transport.too_big_count.clone();
        let config = ClientConfig {
            version: Version::V2c,
            retry: crate::client::retry::Retry::none(),
            ..Default::default()
        };
        let client = Client::new(transport, config);

        let results = client
            .bulk_walk(oid!(1, 3, 6, 1, 2, 1, 2), 25)
            .collect()
            .await
            .unwrap();

        // The reduced request succeeded and yielded the in-subtree varbind.
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].oid, oid!(1, 3, 6, 1, 2, 1, 2, 1, 0));
        // At least one tooBig was observed and recovered from.
        assert!(*too_big_count.lock().unwrap() >= 1);
    }

    #[tokio::test]
    async fn bulk_walk_too_big_at_min_repetitions_is_unrecoverable() {
        // Agent returns tooBig even at max-repetitions=1: degradation bottoms out
        // and the error is surfaced.
        let transport = BulkTooBigTransport::new(0);
        let config = ClientConfig {
            version: Version::V2c,
            retry: crate::client::retry::Retry::none(),
            ..Default::default()
        };
        let client = Client::new(transport, config);

        let err = client
            .bulk_walk(oid!(1, 3, 6, 1, 2, 1, 2), 8)
            .collect()
            .await
            .unwrap_err();

        assert!(
            matches!(
                &*err,
                Error::Snmp {
                    status: ErrorStatus::TooBig,
                    ..
                }
            ),
            "expected TooBig, got: {err}"
        );
    }

    // -------------------------------------------------------------------------
    // Mock transport exercising the scalar-fallback GET. Any GETNEXT/GETBULK
    // terminates the walk immediately (EndOfMibView) so the walk yields nothing
    // and `collect()` performs its fallback GET on the base OID. The GET
    // response is governed by `ScalarGetMode`.
    // -------------------------------------------------------------------------

    #[derive(Clone, Copy)]
    enum ScalarGetMode {
        /// GET returns a real scalar value.
        Value,
        /// GET returns a noSuchInstance exception (genuine absence).
        Absent,
        /// GET returns a non-absence SNMP error (genErr).
        Error,
    }

    #[derive(Clone)]
    struct ScalarFallbackTransport {
        mode: ScalarGetMode,
        /// Records (request_id, pdu_type) seen by `send`, drained by `recv`.
        pending: Arc<Mutex<VecDeque<(i32, PduType)>>>,
    }

    impl ScalarFallbackTransport {
        fn new(mode: ScalarGetMode) -> Self {
            Self {
                mode,
                pending: Arc::new(Mutex::new(VecDeque::new())),
            }
        }
    }

    impl Transport for ScalarFallbackTransport {
        fn send(&self, data: &[u8]) -> impl std::future::Future<Output = Result<()>> + Send {
            let request_id = crate::transport::extract_request_id(data).unwrap_or(1);
            let msg = CommunityMessage::decode(Bytes::copy_from_slice(data)).unwrap();
            let pdu = msg.pdu.standard().unwrap();
            self.pending
                .lock()
                .unwrap()
                .push_back((request_id, pdu.pdu_type));
            async { Ok(()) }
        }

        fn recv(
            &self,
            _request_id: i32,
        ) -> impl std::future::Future<Output = Result<(Bytes, SocketAddr)>> + Send {
            let (request_id, pdu_type) = self
                .pending
                .lock()
                .unwrap()
                .pop_front()
                .unwrap_or((1, PduType::GetRequest));
            let mode = self.mode;
            let peer: SocketAddr = "127.0.0.1:161".parse().unwrap();
            let base = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0);

            async move {
                let pdu = match pdu_type {
                    // Any walk step terminates immediately with no in-subtree value.
                    PduType::GetNextRequest | PduType::GetBulkRequest => Pdu {
                        pdu_type: PduType::Response,
                        request_id,
                        error_status: 0,
                        error_index: 0,
                        varbinds: vec![VarBind::new(
                            oid!(1, 3, 6, 1, 2, 1, 99),
                            Value::EndOfMibView,
                        )],
                    },
                    // Fallback GET on the base OID.
                    _ => match mode {
                        ScalarGetMode::Value => Pdu {
                            pdu_type: PduType::Response,
                            request_id,
                            error_status: 0,
                            error_index: 0,
                            varbinds: vec![VarBind::new(base.clone(), Value::Integer(7))],
                        },
                        ScalarGetMode::Absent => Pdu {
                            pdu_type: PduType::Response,
                            request_id,
                            error_status: 0,
                            error_index: 0,
                            varbinds: vec![VarBind::new(base.clone(), Value::NoSuchInstance)],
                        },
                        ScalarGetMode::Error => Pdu {
                            pdu_type: PduType::Response,
                            request_id,
                            error_status: ErrorStatus::GenErr.as_i32(),
                            error_index: 1,
                            varbinds: vec![VarBind::new(base.clone(), Value::Null)],
                        },
                    },
                };
                let msg = CommunityMessage::v2c(Bytes::from_static(b"public"), pdu);
                Ok((msg.encode(), peer))
            }
        }

        fn peer_addr(&self) -> SocketAddr {
            "127.0.0.1:161".parse().unwrap()
        }

        fn local_addr(&self) -> SocketAddr {
            "127.0.0.1:0".parse().unwrap()
        }

        fn is_reliable(&self) -> bool {
            true
        }
    }

    fn scalar_client(
        mode: ScalarGetMode,
        max_walk_results: Option<usize>,
    ) -> Client<ScalarFallbackTransport> {
        let config = ClientConfig {
            version: Version::V2c,
            retry: crate::client::retry::Retry::none(),
            max_walk_results,
            ..Default::default()
        };
        Client::new(ScalarFallbackTransport::new(mode), config)
    }

    #[tokio::test]
    async fn scalar_fallback_agrees_across_collect_paths() {
        // The scalar GET returns a real value; every collect path must surface
        // it identically (previously only WalkStream::collect did the fallback).
        let base = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0);
        let expected = VarBind::new(base.clone(), Value::Integer(7));

        let walk_getnext = scalar_client(ScalarGetMode::Value, None)
            .walk_getnext(base.clone())
            .collect()
            .await
            .unwrap();
        let bulk_walk = scalar_client(ScalarGetMode::Value, None)
            .bulk_walk(base.clone(), 10)
            .collect()
            .await
            .unwrap();
        let walk_stream = scalar_client(ScalarGetMode::Value, None)
            .walk(base.clone())
            .unwrap()
            .collect()
            .await
            .unwrap();

        assert_eq!(walk_getnext, vec![expected.clone()]);
        assert_eq!(bulk_walk, vec![expected.clone()]);
        assert_eq!(walk_stream, vec![expected]);
    }

    #[tokio::test]
    async fn scalar_fallback_swallows_genuine_absence() {
        // noSuchInstance from the fallback GET is genuine absence: yields nothing.
        let base = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0);
        for results in [
            scalar_client(ScalarGetMode::Absent, None)
                .walk_getnext(base.clone())
                .collect()
                .await
                .unwrap(),
            scalar_client(ScalarGetMode::Absent, None)
                .walk(base.clone())
                .unwrap()
                .collect()
                .await
                .unwrap(),
        ] {
            assert!(results.is_empty());
        }
    }

    #[tokio::test]
    async fn scalar_fallback_propagates_non_absence_error() {
        // A genErr from the fallback GET is not absence and must propagate
        // instead of being swallowed by a catch-all.
        let base = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0);

        let err = scalar_client(ScalarGetMode::Error, None)
            .walk_getnext(base.clone())
            .collect()
            .await
            .unwrap_err();
        assert!(
            matches!(
                &*err,
                Error::Snmp {
                    status: ErrorStatus::GenErr,
                    ..
                }
            ),
            "expected GenErr, got: {err}"
        );

        let err = scalar_client(ScalarGetMode::Error, None)
            .walk(base.clone())
            .unwrap()
            .collect()
            .await
            .unwrap_err();
        assert!(
            matches!(
                &*err,
                Error::Snmp {
                    status: ErrorStatus::GenErr,
                    ..
                }
            ),
            "expected GenErr, got: {err}"
        );
    }

    #[tokio::test]
    async fn scalar_fallback_respects_max_results_zero() {
        // max_walk_results = Some(0) caps the walk at zero results, so the
        // fallback GET must not add a result even when the scalar exists.
        let base = oid!(1, 3, 6, 1, 2, 1, 1, 1, 0);

        let walk_getnext = scalar_client(ScalarGetMode::Value, Some(0))
            .walk_getnext(base.clone())
            .collect()
            .await
            .unwrap();
        let walk_stream = scalar_client(ScalarGetMode::Value, Some(0))
            .walk(base.clone())
            .unwrap()
            .collect()
            .await
            .unwrap();

        assert!(walk_getnext.is_empty());
        assert!(walk_stream.is_empty());
    }
}