Skip to main content

bgpkit_parser/parser/iters/
fallible.rs

1/*!
2Fallible iterator implementations that return Results, exposing parsing errors to users.
3
4These iterators complement the default iterators by returning `Result<T, ParserErrorWithBytes>`
5instead of silently skipping errors. This allows users to handle errors explicitly while
6maintaining backward compatibility with existing code.
7*/
8use super::next_fallible_record;
9use crate::error::ParserErrorWithBytes;
10use crate::models::*;
11use crate::parser::BgpkitParser;
12use crate::{Elementor, Filterable};
13use std::io::Read;
14
15/// Fallible iterator over MRT records that returns parsing errors.
16///
17/// Unlike the default `RecordIterator`, this iterator returns `Result<MrtRecord, ParserErrorWithBytes>`
18/// allowing users to handle parsing errors explicitly instead of having them logged and skipped.
19pub struct FallibleRecordIterator<R> {
20    parser: BgpkitParser<R>,
21    elementor: Elementor,
22    finished: bool,
23    /// Whether the parser's filters are applied once per record.
24    ///
25    /// Elem iterators test every elem they build, so a record-level pass costs
26    /// a full elem conversion per record (plus a record clone) that is thrown
27    /// away. They construct this iterator with the pass disabled.
28    prefilter: bool,
29}
30
31impl<R> FallibleRecordIterator<R> {
32    pub(crate) fn new(parser: BgpkitParser<R>) -> Self {
33        FallibleRecordIterator {
34            parser,
35            elementor: Elementor::new(),
36            finished: false,
37            prefilter: true,
38        }
39    }
40
41    /// Skip the record-level filter pass for an iterator whose consumer filters
42    /// the elems it builds anyway.
43    pub(crate) fn without_prefilter(mut self) -> Self {
44        self.prefilter = false;
45        self
46    }
47}
48
49impl<R: Read> Iterator for FallibleRecordIterator<R> {
50    type Item = Result<MrtRecord, ParserErrorWithBytes>;
51
52    fn next(&mut self) -> Option<Self::Item> {
53        // Text-dump parsers have no MRT-record representation; short-circuit
54        // instead of repeatedly returning Unsupported errors from next_record().
55        if self.parser.text_dump_iter.is_some() {
56            return None;
57        }
58        loop {
59            match next_fallible_record(&mut self.parser, &mut self.finished) {
60                Some(Ok(record)) => {
61                    if !self.prefilter {
62                        return Some(Ok(record));
63                    }
64
65                    // Apply filters if any are set
66                    let filters = &self.parser.filters;
67                    if filters.is_empty() {
68                        return Some(Ok(record));
69                    }
70
71                    // Special handling for PeerIndexTable - always pass through
72                    if let MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(_)) =
73                        &record.message
74                    {
75                        let _ = self.elementor.record_to_elems(record.clone());
76                        return Some(Ok(record));
77                    }
78
79                    // Check if any elements from this record match the filters
80                    let elems = self.elementor.record_to_elems(record.clone());
81                    if elems.iter().any(|e| e.match_filters(filters)) {
82                        return Some(Ok(record));
83                    }
84                    // Record doesn't match filters, continue to next
85                    continue;
86                }
87                None => return None,
88                Some(Err(e)) => {
89                    // Return the error to the user
90                    return Some(Err(e));
91                }
92            }
93        }
94    }
95}
96
97/// Fallible iterator over BGP elements that returns parsing errors.
98///
99/// Unlike the default `ElemIterator`, this iterator returns `Result<BgpElem, ParserErrorWithBytes>`
100/// for each successfully parsed element, and surfaces any parsing errors encountered.
101pub struct FallibleElemIterator<R> {
102    cache_elems: Vec<BgpElem>,
103    record_iter: FallibleRecordIterator<R>,
104    elementor: Elementor,
105}
106
107impl<R> FallibleElemIterator<R> {
108    pub(crate) fn new(parser: BgpkitParser<R>) -> Self {
109        FallibleElemIterator {
110            record_iter: FallibleRecordIterator::new(parser).without_prefilter(),
111            cache_elems: vec![],
112            elementor: Elementor::new(),
113        }
114    }
115}
116
117impl<R: Read> Iterator for FallibleElemIterator<R> {
118    type Item = Result<BgpElem, ParserErrorWithBytes>;
119
120    fn next(&mut self) -> Option<Self::Item> {
121        loop {
122            // Fast path: drain streaming text-dump elems directly, with filter support.
123            if let Some(iter) = &mut self.record_iter.parser.text_dump_iter {
124                for elem in iter.by_ref() {
125                    if elem.match_filters(&self.record_iter.parser.filters) {
126                        return Some(Ok(elem));
127                    }
128                }
129                return None;
130            }
131
132            // First check if we have cached elements
133            if !self.cache_elems.is_empty() {
134                if let Some(elem) = self.cache_elems.pop() {
135                    if elem.match_filters(&self.record_iter.parser.filters) {
136                        return Some(Ok(elem));
137                    }
138                    // Element doesn't match filters, continue to next
139                    continue;
140                }
141            }
142
143            // Need to refill cache from next record
144            match self.record_iter.next() {
145                None => return None,
146                Some(Err(e)) => return Some(Err(e)),
147                Some(Ok(record)) => {
148                    let mut elems = self.elementor.record_to_elems(record);
149                    if elems.is_empty() {
150                        // No elements from this record, try next
151                        continue;
152                    }
153                    // Reverse to maintain order when popping
154                    elems.reverse();
155                    self.cache_elems = elems;
156                    continue;
157                }
158            }
159        }
160    }
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166    use std::io::Cursor;
167
168    /// Create a test parser with mock data that will cause parsing errors
169    fn create_test_parser_with_errors() -> BgpkitParser<Cursor<Vec<u8>>> {
170        // Create some invalid MRT data that will trigger parsing errors
171        let invalid_data = vec![
172            // MRT header with invalid type
173            0x00, 0x00, 0x00, 0x00, // timestamp
174            0xFF, 0xFF, // invalid type
175            0x00, 0x00, // subtype
176            0x00, 0x00, 0x00, 0x04, // length
177            0x00, 0x00, 0x00, 0x00, // dummy data
178        ];
179
180        let cursor = Cursor::new(invalid_data);
181        BgpkitParser::from_reader(cursor)
182    }
183
184    /// Create a test parser with valid data
185    fn create_test_parser_with_valid_data() -> BgpkitParser<Cursor<Vec<u8>>> {
186        // This would need actual valid MRT data - for now using empty data
187        // which will result in EOF
188        let cursor = Cursor::new(vec![]);
189        BgpkitParser::from_reader(cursor)
190    }
191
192    #[test]
193    fn test_fallible_record_iterator_with_errors() {
194        let parser = create_test_parser_with_errors();
195        let mut iter = parser.into_fallible_record_iter();
196
197        // First item should be an error
198        let result = iter.next();
199        assert!(result.is_some());
200        assert!(result.unwrap().is_err());
201    }
202
203    #[test]
204    fn test_fallible_record_iterator_eof() {
205        let parser = create_test_parser_with_valid_data();
206        let mut iter = parser.into_fallible_record_iter();
207
208        // Should return None on EOF
209        let result = iter.next();
210        assert!(result.is_none());
211    }
212
213    #[test]
214    fn test_fallible_elem_iterator_with_errors() {
215        let parser = create_test_parser_with_errors();
216        let mut iter = parser.into_fallible_elem_iter();
217
218        // First item should be an error
219        let result = iter.next();
220        assert!(result.is_some());
221        assert!(result.unwrap().is_err());
222    }
223
224    #[test]
225    fn test_fallible_elem_iterator_eof() {
226        let parser = create_test_parser_with_valid_data();
227        let mut iter = parser.into_fallible_elem_iter();
228
229        // Should return None on EOF
230        let result = iter.next();
231        assert!(result.is_none());
232    }
233}