Skip to main content

bgpkit_parser/render/
text.rs

1//! Layered text rendering of MRT records.
2//!
3//! One record becomes one indented block: session context
4//! (`TIME`/`TYPE`/`PEER`/`LOCAL`), then the message body — `UPDATE:` sections
5//! for withdrawn/announced prefixes and every path attribute, `OPEN:`
6//! capabilities, session states, RIB entries, or the peer table. RFC 7606
7//! validation findings appear under `WARNINGS:` when present.
8//!
9//! The layout is our own (built from this crate's `Display` vocabulary);
10//! inspired by bgpdump's human-readable output, not byte-compatible with
11//! it.
12//!
13//! [`Style::ansi`] adds terminal colors for labels, section headers,
14//! prefixes, and next hops; the plain blocks are unchanged by it, since
15//! styling is a post-pass over the rendered text rather than part of it.
16
17use crate::models::*;
18
19const INDENT: &str = "  ";
20
21/// Render a record block with a trailing `HEX:` line carrying the raw
22/// bytes (e.g. from [`crate::render::hex::encode`]), so the block
23/// can be pasted straight into a byte-level dissector.
24pub fn format_record_with_hex(record: &MrtRecord, hex: &str) -> String {
25    let mut out = format_record(record);
26    out.push_str(&format!("{INDENT}HEX: {hex}\n"));
27    out
28}
29
30/// Render one MRT record as a layered text block.
31///
32/// Pure function of the record; see the [module docs](self) for scope and
33/// limitations (RIB peer indices, warning anchoring).
34pub fn format_record(record: &MrtRecord) -> String {
35    let mut out = String::with_capacity(512);
36    let ts = match record.common_header.microsecond_timestamp {
37        Some(us) => format!("{}.{:06}", record.common_header.timestamp, us),
38        None => record.common_header.timestamp.to_string(),
39    };
40    out.push_str(&format!("TIME: {ts}\n"));
41    out.push_str(&format!(
42        "TYPE: {:?}/{}\n",
43        record.common_header.entry_type,
44        entry_subtype_name(record)
45    ));
46
47    match &record.message {
48        MrtMessage::Bgp4Mp(msg) => render_bgp4mp(&mut out, msg),
49        MrtMessage::LegacyBgp(msg) => render_legacy_bgp(&mut out, msg),
50        MrtMessage::TableDumpMessage(msg) => render_table_dump(&mut out, msg),
51        MrtMessage::TableDumpMessageBatch(messages) => {
52            out.push_str(&format!("TABLE_DUMP: {} entries\n", messages.len()));
53            for msg in messages {
54                render_table_dump(&mut out, msg);
55            }
56        }
57        MrtMessage::TableDumpV2Message(msg) => render_table_dump_v2(&mut out, msg),
58    }
59    out
60}
61
62/// ANSI styling for the text format.
63///
64/// Accents are drawn from the basic ANSI set (bold where noted) instead of fixed RGB values, so
65/// they follow the reader's terminal theme and stay legible on light and dark backgrounds.
66#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
67pub struct Style {
68    ansi: bool,
69}
70
71impl Style {
72    /// Plain text, no escape sequences (the default).
73    pub const fn plain() -> Self {
74        Self { ansi: false }
75    }
76
77    /// ANSI SGR accents, for a terminal.
78    pub const fn ansi() -> Self {
79        Self { ansi: true }
80    }
81}
82
83const ANSI_LABEL: &str = "\x1b[1;34m";
84const ANSI_SECTION: &str = "\x1b[1;35m";
85const ANSI_PREFIX: &str = "\x1b[32m";
86const ANSI_NEXT_HOP: &str = "\x1b[33m";
87const ANSI_RESET: &str = "\x1b[0m";
88
89/// Headers whose indented lines are prefix lists.
90const PREFIX_SECTIONS: [&str; 3] = ["WITHDRAWN", "ANNOUNCED", "ANNOUNCED (labeled)"];
91/// Headers rendered in the section accent; every other `NAME: value` line is a property.
92const SECTION_LABELS: [&str; 17] = [
93    "UPDATE",
94    "OPEN",
95    "KEEPALIVE",
96    "NOTIFICATION",
97    "ROUTE_REFRESH",
98    "STATE_CHANGE",
99    "ATTRIBUTES",
100    "WARNINGS",
101    "CAPABILITIES",
102    "LINK_STATE_NLRI",
103    "FLOWSPEC_NLRI",
104    "TABLE_DUMP",
105    "PEER_INDEX_TABLE",
106    "GEO_PEER_TABLE",
107    "RIB_ENTRY",
108    "RIB_AFI",
109    "RIB_GENERIC",
110];
111/// Properties whose value is a next hop.
112const NEXT_HOP_LABELS: [&str; 2] = ["NEXT_HOP", "MP_REACH_NLRI"];
113/// Properties whose value is a prefix (table-dump RIB entries label it instead of listing it).
114const PREFIX_LABELS: [&str; 1] = ["PREFIX"];
115/// Properties rendered without a value.
116const BARE_LABELS: [&str; 1] = ["ATOMIC_AGGREGATE"];
117/// Property names that carry a space; matched by prefix because the type number varies.
118const SPACED_LABEL_PREFIXES: [&str; 3] =
119    ["RAW ATTRIBUTE (type", "DEPRECATED (type", "UNKNOWN (type"];
120
121/// Render one MRT record as a layered text block, styled for a terminal.
122///
123/// Styling is applied to the block [`format_record`] produces, so the text itself (and the
124/// unstyled output) is unaffected.
125pub fn format_record_with_style(record: &MrtRecord, style: Style) -> String {
126    let plain = format_record(record);
127    if style.ansi {
128        colorize(&plain)
129    } else {
130        plain
131    }
132}
133
134/// Render a record block with a trailing `HEX:` line (see [`format_record_with_hex`]),
135/// styled for a terminal.
136pub fn format_record_with_hex_and_style(record: &MrtRecord, hex: &str, style: Style) -> String {
137    let plain = format_record_with_hex(record, hex);
138    if style.ansi {
139        colorize(&plain)
140    } else {
141        plain
142    }
143}
144
145/// Accent the labels, section headers, prefixes and next hops of a plain block.
146///
147/// A line that matches nothing is copied through untouched, so a newly added line can only lose
148/// its accent, never gain broken output.
149fn colorize(plain: &str) -> String {
150    let mut out = String::with_capacity(plain.len() + plain.len() / 4);
151    let mut prefix_section = false;
152    for line in plain.split_inclusive('\n') {
153        let (content, newline) = match line.strip_suffix('\n') {
154            Some(content) => (content, "\n"),
155            None => (line, ""),
156        };
157        let trimmed = content.trim_start();
158        let indent = content.len() - trimmed.len();
159        let painted = if trimmed.is_empty() {
160            None
161        } else if indent >= 4 && prefix_section {
162            // a bare prefix, optionally followed by `labels=[...]` / `path-id` metadata;
163            // only the prefix itself is a route. (Colons inside IPv6 addresses rule out
164            // splitting on the label separator here.)
165            let (prefix, rest) = trimmed.split_once(' ').unwrap_or((trimmed, ""));
166            let rest = match rest.is_empty() {
167                true => String::new(),
168                false => format!(" {rest}"),
169            };
170            Some(format!("{ANSI_PREFIX}{prefix}{ANSI_RESET}{rest}"))
171        } else if let Some((label, value)) = trimmed.split_once(':') {
172            let label = label.trim_end();
173            let value = value.strip_prefix(' ').unwrap_or(value);
174            if value.is_empty() {
175                prefix_section = PREFIX_SECTIONS.contains(&label);
176                let accent = if prefix_section || SECTION_LABELS.contains(&label) {
177                    ANSI_SECTION
178                } else {
179                    ANSI_LABEL
180                };
181                Some(format!("{accent}{label}:{ANSI_RESET}"))
182            } else if SECTION_LABELS.contains(&label) {
183                // RIB_AFI/RIB_GENERIC summaries carry `PREFIX: <prefix>` inside the heading
184                Some(match value.split_once("PREFIX: ") {
185                    Some((head, tail)) => {
186                        let (prefix, rest) = tail.split_once(' ').unwrap_or((tail, ""));
187                        let rest = match rest.is_empty() {
188                            true => String::new(),
189                            false => format!(" {rest}"),
190                        };
191                        format!(
192                            "{ANSI_SECTION}{label}:{ANSI_RESET} {head}PREFIX: {ANSI_PREFIX}{prefix}{ANSI_RESET}{rest}"
193                        )
194                    }
195                    None => format!("{ANSI_SECTION}{label}:{ANSI_RESET} {value}"),
196                })
197            } else if PREFIX_LABELS.contains(&label) {
198                Some(format!(
199                    "{ANSI_LABEL}{label}:{ANSI_RESET} {ANSI_PREFIX}{value}{ANSI_RESET}"
200                ))
201            } else if NEXT_HOP_LABELS.contains(&label) {
202                // `MP_REACH_NLRI` renders `<afi>/<safi> next-hop <addr>`; only the address
203                // is a next hop, and a family without one stays plain. `NEXT_HOP` values are
204                // the address alone.
205                Some(match value.split_once(" next-hop ") {
206                    Some((family, address)) => format!(
207                        "{ANSI_LABEL}{label}:{ANSI_RESET} {family} next-hop {ANSI_NEXT_HOP}{address}{ANSI_RESET}"
208                    ),
209                    None if label == "NEXT_HOP" => {
210                        format!("{ANSI_LABEL}{label}:{ANSI_RESET} {ANSI_NEXT_HOP}{value}{ANSI_RESET}")
211                    }
212                    None => format!("{ANSI_LABEL}{label}:{ANSI_RESET} {value}"),
213                })
214            } else if !label.contains(' ')
215                || SPACED_LABEL_PREFIXES
216                    .iter()
217                    .any(|prefix| label.starts_with(prefix))
218            {
219                Some(format!("{ANSI_LABEL}{label}:{ANSI_RESET} {value}"))
220            } else {
221                // a sentence (e.g. a validation warning), not an identifier
222                None
223            }
224        } else if BARE_LABELS.contains(&trimmed) {
225            Some(format!("{ANSI_LABEL}{trimmed}{ANSI_RESET}"))
226        } else {
227            None
228        };
229        match painted {
230            Some(painted) => {
231                out.push_str(&" ".repeat(indent));
232                out.push_str(&painted);
233            }
234            None => out.push_str(content),
235        }
236        out.push_str(newline);
237    }
238    out
239}
240
241fn render_legacy_bgp(out: &mut String, msg: &LegacyBgp) {
242    // Deprecated MRT type-5 records (RFC 6396 Appendix B) carry the same
243    // endpoint metadata and BGP payloads as BGP4MP; render them fully.
244    match msg {
245        LegacyBgp::Message(m) => {
246            out.push_str(&format!(
247                "PEER: {} AS{}\nLOCAL: {} AS{}\n",
248                m.peer_ip, m.peer_asn, m.local_ip, m.local_asn
249            ));
250            render_bgp_message(out, &m.bgp_message);
251        }
252        LegacyBgp::StateChange(m) => {
253            out.push_str(&format!("PEER: {} AS{}\n", m.peer_ip, m.peer_asn));
254            out.push_str("STATE_CHANGE:\n");
255            out.push_str(&format!(
256                "{INDENT}OLD_STATE: {:?}\n{INDENT}NEW_STATE: {:?}\n",
257                m.old_state, m.new_state
258            ));
259        }
260    }
261}
262
263fn entry_subtype_name(record: &MrtRecord) -> String {
264    match &record.message {
265        MrtMessage::Bgp4Mp(msg) => format!("{:?}", msg.msg_type()),
266        _ => record.common_header.entry_subtype.to_string(),
267    }
268}
269
270fn render_bgp4mp(out: &mut String, msg: &Bgp4MpEnum) {
271    match msg {
272        Bgp4MpEnum::StateChange(m) => {
273            out.push_str(&format!(
274                "PEER: {} AS{}\nLOCAL: {} AS{}\n",
275                m.peer_ip, m.peer_asn, m.local_addr, m.local_asn
276            ));
277            out.push_str("STATE_CHANGE:\n");
278            out.push_str(&format!(
279                "{INDENT}OLD_STATE: {:?}\n{INDENT}NEW_STATE: {:?}\n",
280                m.old_state, m.new_state
281            ));
282        }
283        Bgp4MpEnum::Message(m) => {
284            out.push_str(&format!(
285                "PEER: {} AS{}\nLOCAL: {} AS{}\n",
286                m.peer_ip, m.peer_asn, m.local_ip, m.local_asn
287            ));
288            render_bgp_message(out, &m.bgp_message);
289        }
290    }
291}
292
293fn render_bgp_message(out: &mut String, msg: &BgpMessage) {
294    match msg {
295        BgpMessage::Open(open) => {
296            out.push_str("OPEN:\n");
297            out.push_str(&format!(
298                "{INDENT}VERSION: {}\n{INDENT}MY_AS: {}\n{INDENT}HOLD_TIME: {}s\n{INDENT}BGP_ID: {}\n",
299                open.version, open.asn, open.hold_time, open.bgp_identifier
300            ));
301            if open.opt_params.is_empty() {
302                return;
303            }
304            out.push_str(&format!("{INDENT}CAPABILITIES:\n"));
305            for param in &open.opt_params {
306                if let ParamValue::Capacities(caps) = &param.param_value {
307                    for cap in caps {
308                        out.push_str(&format!("{INDENT}{INDENT}{}\n", capability_summary(cap)));
309                    }
310                }
311            }
312        }
313        BgpMessage::Update(update) => {
314            out.push_str("UPDATE:\n");
315            render_update(out, update);
316        }
317        BgpMessage::Notification(n) => {
318            out.push_str("NOTIFICATION:\n");
319            out.push_str(&format!(
320                "{INDENT}ERROR: {:?} ({} bytes of data)\n",
321                n.error,
322                n.data.len()
323            ));
324        }
325        BgpMessage::KeepAlive => {
326            out.push_str("KEEPALIVE:\n");
327        }
328        BgpMessage::RouteRefresh(r) => {
329            out.push_str("ROUTE_REFRESH:\n");
330            out.push_str(&format!(
331                "{INDENT}AFI: {} SAFI: {} SUBTYPE: {}\n",
332                r.afi, r.safi, r.subtype
333            ));
334        }
335    }
336}
337
338fn capability_summary(cap: &Capability) -> String {
339    match &cap.value {
340        CapabilityValue::MultiprotocolExtensions(mp) => {
341            format!("{:?}: {:?}/{:?}", cap.ty, mp.afi, mp.safi)
342        }
343        CapabilityValue::FourOctetAs(foa) => format!("{:?}: AS{}", cap.ty, foa.asn),
344        CapabilityValue::AddPath(ap) => format!(
345            "{:?}: {} address families",
346            cap.ty,
347            ap.address_families.len()
348        ),
349        _ => format!("{:?}", cap.ty),
350    }
351}
352
353/// One EVPN route as a single line: route type, route distinguisher, and the
354/// fields an operator looks at first (MAC, prefix, originator, label).
355fn render_evpn_route(route: &EvpnNlri) -> String {
356    let route_distinguisher = route.route_distinguisher;
357    let path_id = route
358        .path_id
359        .map_or_else(String::new, |id| format!(" path-id {id}"));
360    match &route.payload {
361        EvpnRoutePayload::MacIpAdvertisement(body) => {
362            let mac = body
363                .mac
364                .iter()
365                .map(|octet| format!("{octet:02x}"))
366                .collect::<Vec<_>>()
367                .join(":");
368            let ip = body.ip.map_or_else(|| "-".to_string(), |ip| ip.to_string());
369            format!(
370                "[2] RD {route_distinguisher} MAC {mac} IP {ip} label {}{path_id}",
371                body.raw_label
372            )
373        }
374        EvpnRoutePayload::InclusiveMulticast(body) => format!(
375            "[3] RD {route_distinguisher} originator {}{path_id}",
376            body.originating_router_ip
377        ),
378        EvpnRoutePayload::IpPrefix(body) => format!(
379            "[5] RD {route_distinguisher} {} via {} label {}{path_id}",
380            body.ip_prefix, body.gateway_ip, body.raw_label
381        ),
382        EvpnRoutePayload::Raw(octets) => format!(
383            "[{}] RD {route_distinguisher} {} octets (not decoded){path_id}",
384            u8::from(route.route_type),
385            octets.len()
386        ),
387    }
388}
389
390fn render_update(out: &mut String, update: &BgpUpdateMessage) {
391    // Withdrawn prefixes: the standard field plus any carried in
392    // MP_UNREACH_NLRI, so the transcript never silently drops routes.
393    // Labeled (MPLS) announcements, link-state NLRI, and FlowSpec rules
394    // live in their own MP collections and get dedicated sections.
395    let mut withdrawn: Vec<&NetworkPrefix> = update.withdrawn_prefixes.iter().collect();
396    let mut announced: Vec<&NetworkPrefix> = update.announced_prefixes.iter().collect();
397    let mut labeled_announced: Vec<&LabeledNetworkPrefix> = Vec::new();
398    let mut evpn_withdrawn: Vec<&EvpnNlri> = Vec::new();
399    let mut evpn_announced: Vec<&EvpnNlri> = Vec::new();
400    let mut link_state_count = 0usize;
401    let mut flowspec_count = 0usize;
402    for attr in update.attributes.iter() {
403        match attr {
404            AttributeValue::MpUnreachNlri(nlri) => {
405                withdrawn.extend(nlri.prefixes.iter());
406                evpn_withdrawn.extend(nlri.evpn_nlris.iter().flatten());
407                link_state_count += nlri.link_state_nlris.as_ref().map_or(0, Vec::len);
408                flowspec_count += nlri.flowspec_nlris.as_ref().map_or(0, Vec::len);
409            }
410            AttributeValue::MpReachNlri(nlri) => {
411                announced.extend(nlri.prefixes.iter());
412                labeled_announced.extend(nlri.labeled_prefixes.iter().flatten());
413                evpn_announced.extend(nlri.evpn_nlris.iter().flatten());
414                link_state_count += nlri.link_state_nlris.as_ref().map_or(0, Vec::len);
415                flowspec_count += nlri.flowspec_nlris.as_ref().map_or(0, Vec::len);
416            }
417            _ => {}
418        }
419    }
420
421    if !withdrawn.is_empty() {
422        out.push_str(&format!("{INDENT}WITHDRAWN:\n"));
423        for prefix in withdrawn {
424            out.push_str(&format!("{INDENT}{INDENT}{prefix}\n"));
425        }
426    }
427    if !announced.is_empty() {
428        out.push_str(&format!("{INDENT}ANNOUNCED:\n"));
429        for prefix in announced {
430            out.push_str(&format!("{INDENT}{INDENT}{prefix}\n"));
431        }
432    }
433    if !labeled_announced.is_empty() {
434        // RFC 3107/8277 labeled routes; withdrawals carry no labels and
435        // arrive through the plain prefix lists above.
436        out.push_str(&format!("{INDENT}ANNOUNCED (labeled):\n"));
437        for labeled in labeled_announced {
438            let labels: Vec<String> = labeled
439                .labels
440                .iter()
441                .map(|label| label.value().to_string())
442                .collect();
443            let path_id = labeled
444                .path_id
445                .map_or_else(String::new, |id| format!(" path-id {id}"));
446            out.push_str(&format!(
447                "{INDENT}{INDENT}{} labels=[{}]{path_id}\n",
448                labeled.prefix,
449                labels.join(", ")
450            ));
451        }
452    }
453    if !evpn_withdrawn.is_empty() {
454        out.push_str(&format!("{INDENT}WITHDRAWN (EVPN):\n"));
455        for route in evpn_withdrawn {
456            out.push_str(&format!("{INDENT}{INDENT}{}\n", render_evpn_route(route)));
457        }
458    }
459    if !evpn_announced.is_empty() {
460        out.push_str(&format!("{INDENT}ANNOUNCED (EVPN):\n"));
461        for route in evpn_announced {
462            out.push_str(&format!("{INDENT}{INDENT}{}\n", render_evpn_route(route)));
463        }
464    }
465    if link_state_count > 0 {
466        out.push_str(&format!(
467            "{INDENT}LINK_STATE_NLRI: {link_state_count} entries (BGP-LS)\n"
468        ));
469    }
470    if flowspec_count > 0 {
471        out.push_str(&format!(
472            "{INDENT}FLOWSPEC_NLRI: {flowspec_count} rules (RFC 8955)\n"
473        ));
474    }
475
476    let mut attrs = update.attributes.iter().peekable();
477    if attrs.peek().is_some() {
478        out.push_str(&format!("{INDENT}ATTRIBUTES:\n"));
479        for attr in attrs {
480            if let Some(line) = render_attribute(attr) {
481                out.push_str(&format!("{INDENT}{INDENT}{line}\n"));
482            }
483        }
484    }
485
486    let warnings = update.attributes.validation_warnings();
487    if !warnings.is_empty() {
488        out.push_str(&format!("{INDENT}WARNINGS:\n"));
489        for warning in warnings {
490            out.push_str(&format!("{INDENT}{INDENT}{warning}\n"));
491        }
492    }
493}
494
495/// One line per attribute. The MP prefix lists are folded into the
496/// WITHDRAWN/ANNOUNCED sections above; the attribute summary line (family,
497/// next hop) is retained here.
498fn render_attribute(value: &AttributeValue) -> Option<String> {
499    let line = match value {
500        AttributeValue::Origin(v) => format!("ORIGIN: {v}"),
501        AttributeValue::AsPath(v) => format!("AS_PATH: {v}"),
502        AttributeValue::As4Path(v) => format!("AS4_PATH: {v}"),
503        AttributeValue::NextHop(v) => format!("NEXT_HOP: {v}"),
504        AttributeValue::MultiExitDiscriminator(v) => format!("MULTI_EXIT_DISC: {v}"),
505        AttributeValue::LocalPreference(v) => format!("LOCAL_PREF: {v}"),
506        AttributeValue::OnlyToCustomer(v) => format!("ONLY_TO_CUSTOMER: {v}"),
507        AttributeValue::AtomicAggregate => "ATOMIC_AGGREGATE".to_string(),
508        AttributeValue::Aggregator { asn, id } => format!("AGGREGATOR: AS{asn} by {id}"),
509        AttributeValue::As4Aggregator { asn, id } => {
510            format!("AS4_AGGREGATOR: AS{asn} by {id}")
511        }
512        AttributeValue::Communities(v) => {
513            let rendered: Vec<String> = v.iter().map(|c| c.to_string()).collect();
514            format!("COMMUNITIES: {}", rendered.join(" "))
515        }
516        AttributeValue::LargeCommunities(v) => {
517            let rendered: Vec<String> = v.iter().map(|c| c.to_string()).collect();
518            format!("LARGE_COMMUNITIES: {}", rendered.join(" "))
519        }
520        AttributeValue::ExtendedCommunities(v) => {
521            let rendered: Vec<String> = v.iter().map(|c| c.to_string()).collect();
522            format!("EXTENDED_COMMUNITIES: {}", rendered.join(" "))
523        }
524        AttributeValue::Ipv6AddressSpecificExtendedCommunities(v) => {
525            let rendered: Vec<String> = v.iter().map(|c| c.to_string()).collect();
526            format!("IPV6_EXTENDED_COMMUNITIES: {}", rendered.join(" "))
527        }
528        AttributeValue::OriginatorId(v) => format!("ORIGINATOR_ID: {v}"),
529        AttributeValue::Clusters(v) => {
530            let rendered: Vec<String> = v.iter().map(|c| c.to_string()).collect();
531            format!("CLUSTER_LIST: {}", rendered.join(" "))
532        }
533        AttributeValue::MpReachNlri(nlri) => {
534            let next_hop = match &nlri.next_hop {
535                Some(nh) => format!(" next-hop {nh}"),
536                None => String::new(),
537            };
538            format!("MP_REACH_NLRI: {:?}/{:?}{next_hop}", nlri.afi, nlri.safi)
539        }
540        AttributeValue::MpUnreachNlri(nlri) => {
541            format!("MP_UNREACH_NLRI: {:?}/{:?}", nlri.afi, nlri.safi)
542        }
543        AttributeValue::Aigp(v) => format!("AIGP: {v:?}"),
544        AttributeValue::BfdDiscriminator(v) => format!("BFD_DISCRIMINATOR: {v:?}"),
545        AttributeValue::DomainPath(v) => format!("BGP_DOMAIN_PATH: {v:?}"),
546        AttributeValue::TrafficEngineering(v) => format!("TRAFFIC_ENGINEERING: {v:?}"),
547        AttributeValue::TunnelEncapsulation(v) => format!("TUNNEL_ENCAPSULATION: {v:?}"),
548        AttributeValue::LinkState(v) => format!("BGP_LS: {v:?}"),
549        AttributeValue::BgpPrefixSid(v) => format!("BGP_PREFIX_SID: {v:?}"),
550        AttributeValue::Bier(v) => format!("BIER: {v:?}"),
551        AttributeValue::Sfp(v) => format!("SFP: {v:?}"),
552        AttributeValue::AttrSet(v) => {
553            format!("ATTR_SET: attributes of AS{}", v.origin_as)
554        }
555        AttributeValue::Development(v) => format!("DEVELOPMENT: {} bytes", v.len()),
556        AttributeValue::Raw(v) => {
557            format!("RAW ATTRIBUTE (type {}): {} bytes", v.code, v.bytes.len())
558        }
559        AttributeValue::Deprecated(v) => {
560            format!("DEPRECATED (type {}): {} bytes", v.code, v.bytes.len())
561        }
562        AttributeValue::Unknown(v) => {
563            format!("UNKNOWN (type {}): {} bytes", v.code, v.bytes.len())
564        }
565    };
566    Some(line)
567}
568
569fn render_table_dump(out: &mut String, msg: &TableDumpMessage) {
570    out.push_str(&format!(
571        "RIB_ENTRY:\n{INDENT}PREFIX: {}\n{INDENT}PEER: {} AS{}\n{INDENT}ORIGINATED: {}\n",
572        msg.prefix, msg.peer_ip, msg.peer_asn, msg.originated_time
573    ));
574    render_attributes_block(out, &msg.attributes, 1);
575}
576
577fn render_table_dump_v2(out: &mut String, msg: &TableDumpV2Message) {
578    match msg {
579        TableDumpV2Message::PeerIndexTable(pit) => {
580            out.push_str(&format!(
581                "PEER_INDEX_TABLE: {} peers\n",
582                pit.id_peer_map.len()
583            ));
584            // Peer order follows the collector's index assignment.
585            let mut peers: Vec<_> = pit.id_peer_map.iter().collect();
586            peers.sort_by_key(|(id, _)| **id);
587            for (id, peer) in peers {
588                out.push_str(&format!(
589                    "{INDENT}PEER[{id}]: {} AS{}\n",
590                    peer.peer_ip, peer.peer_asn
591                ));
592            }
593        }
594        TableDumpV2Message::RibAfi(rib) => {
595            out.push_str(&format!(
596                "RIB_AFI: {:?} PREFIX: {} ({} entries)\n",
597                rib.rib_type,
598                rib.prefix,
599                rib.rib_entries.len()
600            ));
601            for entry in &rib.rib_entries {
602                out.push_str(&format!(
603                    "{INDENT}RIB_ENTRY:\n{INDENT}{INDENT}PEER_INDEX: {}\n{INDENT}{INDENT}ORIGINATED: {}\n",
604                    entry.peer_index, entry.originated_time
605                ));
606                render_attributes_block(out, &entry.attributes, 2);
607            }
608        }
609        TableDumpV2Message::RibGeneric(rib) => {
610            out.push_str(&format!(
611                "RIB_GENERIC: {:?}/{:?} PREFIX: {} ({} entries)\n",
612                rib.afi,
613                rib.safi,
614                rib.nlri,
615                rib.rib_entries.len()
616            ));
617            for entry in &rib.rib_entries {
618                out.push_str(&format!(
619                    "{INDENT}RIB_ENTRY:\n{INDENT}{INDENT}PEER_INDEX: {}\n{INDENT}{INDENT}ORIGINATED: {}\n",
620                    entry.peer_index, entry.originated_time
621                ));
622                render_attributes_block(out, &entry.attributes, 2);
623            }
624        }
625        TableDumpV2Message::GeoPeerTable(gpt) => {
626            out.push_str(&format!("GEO_PEER_TABLE: {} peers\n", gpt.geo_peers.len()));
627        }
628    }
629}
630
631fn render_attributes_block(out: &mut String, attributes: &Attributes, depth: usize) {
632    let pad = INDENT.repeat(depth + 1);
633    let mut iter = attributes.iter().peekable();
634    // An empty attribute list can still carry validation findings (RIB
635    // entries run check_mandatory_attributes during parsing), so the
636    // warnings section renders regardless of the attribute count.
637    if iter.peek().is_some() {
638        out.push_str(&format!("{}ATTRIBUTES:\n", INDENT.repeat(depth)));
639    }
640    for attr in iter {
641        if let Some(line) = render_attribute(attr) {
642            out.push_str(&format!("{pad}{line}\n"));
643        }
644    }
645    let warnings = attributes.validation_warnings();
646    if !warnings.is_empty() {
647        out.push_str(&format!("{}WARNINGS:\n", INDENT.repeat(depth)));
648        for warning in warnings {
649            out.push_str(&format!("{pad}{warning}\n"));
650        }
651    }
652}
653
654#[cfg(test)]
655mod tests {
656    use super::*;
657    use crate::error::BgpValidationWarning;
658    use crate::models::capabilities::{
659        BgpCapabilityType, FourOctetAsCapability, MultiprotocolExtensionsCapability,
660    };
661    use std::net::IpAddr;
662    use std::net::Ipv4Addr;
663    use std::str::FromStr;
664
665    fn update_record(attributes: Attributes) -> MrtRecord {
666        MrtRecord {
667            common_header: CommonHeader {
668                timestamp: 1_666_542_810,
669                microsecond_timestamp: Some(970_000),
670                entry_type: EntryType::BGP4MP,
671                entry_subtype: Bgp4MpType::MessageAs4 as u16,
672                length: 0,
673            },
674            message: MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(Bgp4MpMessage {
675                msg_type: Bgp4MpType::MessageAs4,
676                peer_asn: Asn::new_32bit(64496),
677                local_asn: Asn::new_32bit(64497),
678                interface_index: 0,
679                peer_ip: IpAddr::from_str("192.0.2.1").unwrap(),
680                local_ip: IpAddr::from_str("192.0.2.2").unwrap(),
681                bgp_message: BgpMessage::Update(BgpUpdateMessage {
682                    withdrawn_prefixes: vec![NetworkPrefix::from_str("203.0.113.0/24").unwrap()],
683                    attributes,
684                    announced_prefixes: vec![NetworkPrefix::from_str("198.51.100.0/24").unwrap()],
685                }),
686            })),
687        }
688    }
689
690    #[test]
691    fn renders_evpn_routes() {
692        let announced = EvpnNlri {
693            path_id: None,
694            route_type: EvpnRouteType::MacIpAdvertisement,
695            route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 11, 0, 2]),
696            payload: EvpnRoutePayload::MacIpAdvertisement(MacIpAdvertisement {
697                esi: [0; 10],
698                ethernet_tag_id: 0,
699                mac: [0xaa, 0xc1, 0xab, 0x73, 0x01, 0x4d],
700                ip: Some(IpAddr::from_str("10.100.0.101").unwrap()),
701                raw_label: 100,
702                raw_label2: None,
703            }),
704        };
705        let withdrawn = EvpnNlri {
706            path_id: None,
707            route_type: EvpnRouteType::IpPrefix,
708            route_distinguisher: RouteDistinguisher([0, 1, 10, 10, 0, 12, 0, 2]),
709            payload: EvpnRoutePayload::IpPrefix(IpPrefixRoute {
710                esi: [0; 10],
711                ethernet_tag_id: 0,
712                ip_prefix: ipnet::IpNet::from_str("198.51.100.0/24").unwrap(),
713                gateway_ip: IpAddr::from_str("0.0.0.0").unwrap(),
714                raw_label: 100,
715            }),
716        };
717        let attributes = Attributes::from_iter(vec![
718            AttributeValue::MpReachNlri(Nlri::new_evpn_reachable(
719                Some(IpAddr::from_str("10.10.0.11").unwrap()),
720                vec![announced],
721            )),
722            AttributeValue::MpUnreachNlri(Nlri::new_evpn_unreachable(vec![withdrawn])),
723        ]);
724
725        let text = format_record(&update_record(attributes));
726
727        assert!(
728            text.contains("ANNOUNCED (EVPN):\n    [2] RD 00:01:0a:0a:00:0b:00:02 MAC aa:c1:ab:73:01:4d IP 10.100.0.101 label 100"),
729            "missing EVPN announcement line in:\n{text}"
730        );
731        assert!(
732            text.contains("WITHDRAWN (EVPN):\n    [5] RD 00:01:0a:0a:00:0c:00:02 198.51.100.0/24 via 0.0.0.0 label 100"),
733            "missing EVPN withdrawal line in:\n{text}"
734        );
735    }
736
737    fn full_attributes() -> Attributes {
738        let mut attributes = Attributes::default();
739        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
740        attributes.add_attr(
741            AttributeValue::AsPath(AsPath::from_segments(vec![
742                AsPathSegment::sequence([65001, 65002]),
743                AsPathSegment::set([65010, 65011]),
744            ]))
745            .into(),
746        );
747        attributes
748            .add_attr(AttributeValue::NextHop(IpAddr::from_str("192.0.2.254").unwrap()).into());
749        attributes.add_attr(AttributeValue::LocalPreference(100).into());
750        attributes.add_attr(AttributeValue::OnlyToCustomer(64512.into()).into());
751        attributes.add_attr(
752            AttributeValue::Communities(vec![
753                Community::Custom(Asn::new_32bit(64512), 100),
754                Community::NoExport,
755            ])
756            .into(),
757        );
758        attributes.add_attr(
759            AttributeValue::LargeCommunities(vec![LargeCommunity::new(64496, [1, 2])]).into(),
760        );
761        attributes
762    }
763
764    #[test]
765    fn renders_hex_line_variant() {
766        let text = format_record_with_hex(&update_record(full_attributes()), "deadbeef");
767        assert!(text.trim_end().ends_with("  HEX: deadbeef"));
768        // everything before the HEX line is the plain block
769        let plain = format_record(&update_record(full_attributes()));
770        assert!(text.starts_with(&plain));
771    }
772
773    #[test]
774    fn renders_layered_update_block() {
775        let text = format_record(&update_record(full_attributes()));
776        let expected = "\
777TIME: 1666542810.970000
778TYPE: BGP4MP/MessageAs4
779PEER: 192.0.2.1 AS64496
780LOCAL: 192.0.2.2 AS64497
781UPDATE:
782  WITHDRAWN:
783    203.0.113.0/24
784  ANNOUNCED:
785    198.51.100.0/24
786  ATTRIBUTES:
787    ORIGIN: IGP
788    AS_PATH: 65001 65002 {65010,65011}
789    NEXT_HOP: 192.0.2.254
790    LOCAL_PREF: 100
791    ONLY_TO_CUSTOMER: 64512
792    COMMUNITIES: 64512:100 no-export
793    LARGE_COMMUNITIES: 64496:1:2
794";
795        assert_eq!(text, expected);
796    }
797
798    #[test]
799    fn renders_warnings_section() {
800        let mut attributes = full_attributes();
801        attributes.add_validation_warning(BgpValidationWarning::DuplicateAttribute {
802            attr_type: AttrType::ORIGIN,
803        });
804        let text = format_record(&update_record(attributes));
805        assert!(text.contains("  WARNINGS:\n"));
806        assert!(text.contains("Duplicate attribute: ORIGIN"));
807        // the warning follows the attributes section
808        let attr_pos = text.find("LARGE_COMMUNITIES").unwrap();
809        let warn_pos = text.find("WARNINGS").unwrap();
810        assert!(warn_pos > attr_pos);
811    }
812
813    #[test]
814    fn renders_mp_reach_prefixes_in_sections() {
815        let mut attributes = Attributes::default();
816        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
817        attributes.add_attr(
818            AttributeValue::MpReachNlri(Nlri {
819                afi: Afi::Ipv6,
820                safi: Safi::Unicast,
821                next_hop: Some(NextHopAddress::Ipv6("2001:db8::1".parse().unwrap())),
822                prefixes: vec![NetworkPrefix::from_str("2001:db8::/32").unwrap()],
823                labeled_prefixes: None,
824                link_state_nlris: None,
825                flowspec_nlris: None,
826                evpn_nlris: None,
827            })
828            .into(),
829        );
830        let text = format_record(&update_record(attributes));
831        assert!(text.contains("    198.51.100.0/24\n    2001:db8::/32\n"));
832        assert!(text.contains("MP_REACH_NLRI: Ipv6/Unicast next-hop 2001:db8::1"));
833    }
834
835    /// Strip ANSI SGR sequences, to compare styled output with its plain form.
836    fn strip_sgr(text: &str) -> String {
837        let mut out = String::with_capacity(text.len());
838        let mut rest = text;
839        while let Some(start) = rest.find('\x1b') {
840            out.push_str(&rest[..start]);
841            match rest[start..].find('m') {
842                Some(end) => rest = &rest[start + end + 1..],
843                None => return out,
844            }
845        }
846        out.push_str(rest);
847        out
848    }
849
850    #[test]
851    fn style_plain_is_byte_identical() {
852        let record = update_record(full_attributes());
853        assert_eq!(
854            format_record_with_style(&record, Style::plain()),
855            format_record(&record)
856        );
857        assert_eq!(
858            format_record_with_hex_and_style(&record, "deadbeef", Style::plain()),
859            format_record_with_hex(&record, "deadbeef")
860        );
861    }
862
863    #[test]
864    fn style_accents_labels_sections_prefixes_and_next_hops() {
865        let mut attributes = full_attributes();
866        attributes.add_attr(
867            AttributeValue::MpReachNlri(Nlri {
868                afi: Afi::Ipv6,
869                safi: Safi::Unicast,
870                // a comma-joined RFC 2545 pair, as RIS Live projects it
871                next_hop: Some(NextHopAddress::Ipv6LinkLocal(
872                    "2001:db8::1".parse().unwrap(),
873                    "fe80::1".parse().unwrap(),
874                )),
875                prefixes: vec![NetworkPrefix::from_str("2001:db8:1::/48").unwrap()],
876                labeled_prefixes: None,
877                link_state_nlris: None,
878                flowspec_nlris: None,
879                evpn_nlris: None,
880            })
881            .into(),
882        );
883        let record = update_record(attributes);
884        let plain = format_record(&record);
885        let styled = format_record_with_style(&record, Style::ansi());
886
887        // styling wraps spans, it never rewrites the text
888        assert_ne!(styled, plain);
889        assert_eq!(strip_sgr(&styled), plain);
890
891        assert!(styled.contains(&format!("{ANSI_LABEL}TIME:{ANSI_RESET} 1666542810.970000")));
892        assert!(styled.contains(&format!("{ANSI_LABEL}PEER:{ANSI_RESET} 192.0.2.1 AS64496")));
893        assert!(styled.contains(&format!("{ANSI_SECTION}UPDATE:{ANSI_RESET}")));
894        assert!(styled.contains(&format!("{ANSI_SECTION}ANNOUNCED:{ANSI_RESET}")));
895        assert!(styled.contains(&format!("{ANSI_SECTION}ATTRIBUTES:{ANSI_RESET}")));
896        assert!(styled.contains(&format!("    {ANSI_PREFIX}198.51.100.0/24{ANSI_RESET}")));
897        assert!(styled.contains(&format!("{ANSI_LABEL}ORIGIN:{ANSI_RESET} IGP")));
898        assert!(styled.contains(&format!(
899            "{ANSI_LABEL}MP_REACH_NLRI:{ANSI_RESET} Ipv6/Unicast next-hop {ANSI_NEXT_HOP}2001:db8::1,fe80::1{ANSI_RESET}"
900        )));
901    }
902
903    #[test]
904    fn style_accents_table_dump_prefixes() {
905        let mut attributes = Attributes::default();
906        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
907        let rib = MrtRecord {
908            common_header: CommonHeader {
909                timestamp: 6,
910                microsecond_timestamp: None,
911                entry_type: EntryType::TABLE_DUMP_V2,
912                entry_subtype: 2,
913                length: 0,
914            },
915            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(RibAfiEntries {
916                rib_type: TableDumpV2Type::RibIpv4Unicast,
917                sequence_number: 1,
918                prefix: NetworkPrefix::from_str("198.51.100.0/24").unwrap(),
919                rib_entries: vec![RibEntry {
920                    peer_index: 0,
921                    originated_time: 1_666_542_000,
922                    path_id: None,
923                    attributes,
924                }],
925            })),
926        };
927        let styled = format_record_with_style(&rib, Style::ansi());
928        // the RIB_AFI summary embeds the prefix in its heading line
929        assert!(styled.contains(&format!(
930            "PREFIX: {ANSI_PREFIX}198.51.100.0/24{ANSI_RESET} (1 entries)"
931        )));
932
933        // a legacy type-5 RIB entry labels the prefix instead of listing it
934        let entry = MrtRecord {
935            common_header: CommonHeader {
936                timestamp: 6,
937                microsecond_timestamp: None,
938                entry_type: EntryType::TABLE_DUMP,
939                entry_subtype: 12,
940                length: 0,
941            },
942            message: MrtMessage::TableDumpMessage(TableDumpMessage {
943                view_number: 0,
944                sequence_number: 1,
945                prefix: NetworkPrefix::from_str("198.51.100.0/24").unwrap(),
946                status: 1,
947                originated_time: 1_666_542_000,
948                peer_ip: IpAddr::from_str("192.0.2.1").unwrap(),
949                peer_asn: Asn::new_16bit(64496),
950                attributes: Attributes::default(),
951            }),
952        };
953        let styled = format_record_with_style(&entry, Style::ansi());
954        assert!(styled.contains(&format!(
955            "{ANSI_LABEL}PREFIX:{ANSI_RESET} {ANSI_PREFIX}198.51.100.0/24{ANSI_RESET}\n"
956        )));
957    }
958
959    #[test]
960    fn style_accents_bare_and_spaced_property_labels() {
961        let plain = "UPDATE:\n  ATTRIBUTES:\n    ATOMIC_AGGREGATE\n    RAW ATTRIBUTE (type 99): 4 bytes\n    Duplicate attribute: ORIGIN\n";
962        let styled = colorize(plain);
963        assert!(styled.contains(&format!("{ANSI_LABEL}ATOMIC_AGGREGATE{ANSI_RESET}")));
964        assert!(styled.contains(&format!(
965            "{ANSI_LABEL}RAW ATTRIBUTE (type 99):{ANSI_RESET} 4 bytes"
966        )));
967        // validation warnings are prose, not identifiers: still untouched
968        assert!(styled.contains("    Duplicate attribute: ORIGIN\n"));
969        assert_eq!(strip_sgr(&styled), plain);
970    }
971
972    #[test]
973    fn style_accents_only_the_prefix_in_labeled_entries() {
974        let plain = "UPDATE:\n  ANNOUNCED (labeled):\n    2001:db8::/32 labels=[16] path-id 3\n";
975        let styled = colorize(plain);
976        assert!(styled.contains(&format!(
977            "    {ANSI_PREFIX}2001:db8::/32{ANSI_RESET} labels=[16] path-id 3"
978        )));
979        assert_eq!(strip_sgr(&styled), plain);
980    }
981
982    #[test]
983    fn style_leaves_sentence_lines_plain() {
984        let mut attributes = full_attributes();
985        attributes.add_validation_warning(BgpValidationWarning::DuplicateAttribute {
986            attr_type: AttrType::ORIGIN,
987        });
988        let styled = format_record_with_style(&update_record(attributes), Style::ansi());
989        // a warning is a sentence, not an identifier: no accent, no escape sequences
990        assert!(styled.contains("    Duplicate attribute: ORIGIN\n"));
991    }
992
993    #[test]
994    fn renders_state_change_open_and_keepalive() {
995        let state = MrtRecord {
996            common_header: CommonHeader {
997                timestamp: 2,
998                microsecond_timestamp: None,
999                entry_type: EntryType::BGP4MP,
1000                entry_subtype: Bgp4MpType::StateChange as u16,
1001                length: 0,
1002            },
1003            message: MrtMessage::Bgp4Mp(Bgp4MpEnum::StateChange(Bgp4MpStateChange {
1004                msg_type: Bgp4MpType::StateChange,
1005                peer_asn: Asn::new_16bit(64496),
1006                local_asn: Asn::new_16bit(64497),
1007                interface_index: 0,
1008                peer_ip: IpAddr::from_str("192.0.2.1").unwrap(),
1009                local_addr: IpAddr::from_str("192.0.2.2").unwrap(),
1010                old_state: BgpState::Idle,
1011                new_state: BgpState::Established,
1012            })),
1013        };
1014        let text = format_record(&state);
1015        assert!(text.contains("PEER: 192.0.2.1 AS64496"));
1016        assert!(text.contains("LOCAL: 192.0.2.2 AS64497"));
1017        assert!(text.contains("STATE_CHANGE:"));
1018        assert!(text.contains("OLD_STATE: Idle"));
1019        assert!(text.contains("NEW_STATE: Established"));
1020
1021        let keepalive = MrtRecord {
1022            common_header: CommonHeader {
1023                timestamp: 3,
1024                microsecond_timestamp: None,
1025                entry_type: EntryType::BGP4MP,
1026                entry_subtype: Bgp4MpType::MessageAs4 as u16,
1027                length: 0,
1028            },
1029            message: MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(Bgp4MpMessage {
1030                msg_type: Bgp4MpType::MessageAs4,
1031                peer_asn: Asn::new_32bit(64496),
1032                local_asn: Asn::new_32bit(64497),
1033                interface_index: 0,
1034                peer_ip: IpAddr::from_str("192.0.2.1").unwrap(),
1035                local_ip: IpAddr::from_str("192.0.2.2").unwrap(),
1036                bgp_message: BgpMessage::KeepAlive,
1037            })),
1038        };
1039        assert!(format_record(&keepalive).contains("KEEPALIVE:"));
1040
1041        let open = MrtRecord {
1042            common_header: CommonHeader {
1043                timestamp: 4,
1044                microsecond_timestamp: None,
1045                entry_type: EntryType::BGP4MP,
1046                entry_subtype: Bgp4MpType::MessageAs4 as u16,
1047                length: 0,
1048            },
1049            message: MrtMessage::Bgp4Mp(Bgp4MpEnum::Message(Bgp4MpMessage {
1050                msg_type: Bgp4MpType::MessageAs4,
1051                peer_asn: Asn::new_32bit(64496),
1052                local_asn: Asn::new_32bit(64497),
1053                interface_index: 0,
1054                peer_ip: IpAddr::from_str("192.0.2.1").unwrap(),
1055                local_ip: IpAddr::from_str("192.0.2.2").unwrap(),
1056                bgp_message: BgpMessage::Open(BgpOpenMessage {
1057                    version: 4,
1058                    asn: Asn::new_16bit(64496),
1059                    hold_time: 180,
1060                    bgp_identifier: Ipv4Addr::new(192, 0, 2, 1),
1061                    extended_length: false,
1062                    opt_params: vec![OptParam {
1063                        param_type: 2,
1064                        param_value: ParamValue::Capacities(vec![
1065                            Capability {
1066                                ty: BgpCapabilityType::MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4,
1067                                value: CapabilityValue::MultiprotocolExtensions(
1068                                    MultiprotocolExtensionsCapability::new(
1069                                        Afi::Ipv4,
1070                                        Safi::Unicast,
1071                                    ),
1072                                ),
1073                            },
1074                            Capability {
1075                                ty: BgpCapabilityType::SUPPORT_FOR_4_OCTET_AS_NUMBER_CAPABILITY,
1076                                value: CapabilityValue::FourOctetAs(FourOctetAsCapability::new(
1077                                    64496,
1078                                )),
1079                            },
1080                        ]),
1081                    }],
1082                }),
1083            })),
1084        };
1085        let text = format_record(&open);
1086        assert!(text.contains("OPEN:"));
1087        assert!(text.contains("MY_AS: 64496"));
1088        assert!(text.contains("MULTIPROTOCOL_EXTENSIONS_FOR_BGP_4: Ipv4/Unicast"));
1089        assert!(text.contains("SUPPORT_FOR_4_OCTET_AS_NUMBER_CAPABILITY: AS64496"));
1090    }
1091
1092    #[test]
1093    fn renders_labeled_linkstate_and_flowspec_sections() {
1094        use crate::models::{LabeledNetworkPrefix, MplsLabel};
1095
1096        let labeled = LabeledNetworkPrefix {
1097            prefix: "192.0.2.0/24".parse().unwrap(),
1098            labels: smallvec::SmallVec::from_vec(vec![
1099                MplsLabel::try_new(24001).unwrap(),
1100                MplsLabel::try_new(16).unwrap(),
1101            ]),
1102            path_id: Some(7),
1103        };
1104        let mut attributes = Attributes::default();
1105        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
1106        attributes.add_attr(
1107            AttributeValue::MpReachNlri(Nlri {
1108                afi: Afi::Ipv4,
1109                safi: Safi::MplsLabel,
1110                next_hop: Some(NextHopAddress::Ipv4("192.0.2.254".parse().unwrap())),
1111                prefixes: vec![],
1112                labeled_prefixes: Some(vec![labeled]),
1113                link_state_nlris: Some(vec![]),
1114                flowspec_nlris: Some(vec![]),
1115                evpn_nlris: None,
1116            })
1117            .into(),
1118        );
1119        let text = format_record(&update_record(attributes));
1120        assert!(text.contains("  ANNOUNCED (labeled):\n"));
1121        assert!(text.contains("    192.0.2.0/24 labels=[24001, 16] path-id 7\n"));
1122        // empty link-state/flowspec collections produce no sections
1123        assert!(!text.contains("LINK_STATE_NLRI"));
1124        assert!(!text.contains("FLOWSPEC_NLRI"));
1125    }
1126
1127    #[test]
1128    fn renders_rib_warnings_with_empty_attributes() {
1129        // RIB parsers run check_mandatory_attributes during parsing, so an
1130        // entry can reach the renderer with an empty attribute list but
1131        // non-empty findings — the warnings section must render without an
1132        // ATTRIBUTES section. (Warnings are attached here directly because
1133        // the record is built structurally, not parsed from the wire.)
1134        let mut empty_with_warnings = Attributes::default();
1135        empty_with_warnings.add_validation_warning(
1136            BgpValidationWarning::MissingWellKnownAttribute {
1137                attr_type: AttrType::ORIGIN,
1138            },
1139        );
1140        let rib = MrtRecord {
1141            common_header: CommonHeader {
1142                timestamp: 9,
1143                microsecond_timestamp: None,
1144                entry_type: EntryType::TABLE_DUMP_V2,
1145                entry_subtype: 2,
1146                length: 0,
1147            },
1148            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(RibAfiEntries {
1149                rib_type: TableDumpV2Type::RibIpv4Unicast,
1150                sequence_number: 1,
1151                prefix: NetworkPrefix::from_str("198.51.100.0/24").unwrap(),
1152                rib_entries: vec![RibEntry {
1153                    peer_index: 0,
1154                    originated_time: 1,
1155                    path_id: None,
1156                    attributes: empty_with_warnings,
1157                }],
1158            })),
1159        };
1160        let text = format_record(&rib);
1161        assert!(text.contains("WARNINGS:"));
1162        assert!(text.contains("Missing well-known mandatory attribute: ORIGIN"));
1163        assert!(!text.contains("ATTRIBUTES:"));
1164    }
1165
1166    #[test]
1167    fn renders_legacy_bgp_records() {
1168        let legacy = MrtRecord {
1169            common_header: CommonHeader {
1170                timestamp: 7,
1171                microsecond_timestamp: None,
1172                entry_type: EntryType::BGP,
1173                entry_subtype: 5,
1174                length: 0,
1175            },
1176            message: MrtMessage::LegacyBgp(LegacyBgp::Message(LegacyBgpMessage {
1177                peer_asn: Asn::new_16bit(5409),
1178                peer_ip: IpAddr::from_str("195.211.222.254").unwrap(),
1179                local_asn: Asn::new_16bit(12654),
1180                local_ip: IpAddr::from_str("193.0.0.1").unwrap(),
1181                bgp_message: BgpMessage::KeepAlive,
1182            })),
1183        };
1184        let text = format_record(&legacy);
1185        assert!(text.contains("PEER: 195.211.222.254 AS5409"));
1186        assert!(text.contains("LOCAL: 193.0.0.1 AS12654"));
1187        assert!(text.contains("KEEPALIVE:"));
1188
1189        let state = MrtRecord {
1190            common_header: CommonHeader {
1191                timestamp: 8,
1192                microsecond_timestamp: None,
1193                entry_type: EntryType::BGP,
1194                entry_subtype: 6,
1195                length: 0,
1196            },
1197            message: MrtMessage::LegacyBgp(LegacyBgp::StateChange(LegacyBgpStateChange {
1198                peer_asn: Asn::new_16bit(5409),
1199                peer_ip: IpAddr::from_str("195.211.222.254").unwrap(),
1200                old_state: BgpState::Established,
1201                new_state: BgpState::Idle,
1202            })),
1203        };
1204        let text = format_record(&state);
1205        assert!(text.contains("PEER: 195.211.222.254 AS5409"));
1206        // a legacy state change carries only the peer endpoint
1207        assert!(!text.contains("LOCAL:"));
1208        assert!(text.contains("STATE_CHANGE:"));
1209        assert!(text.contains("OLD_STATE: Established"));
1210        assert!(text.contains("NEW_STATE: Idle"));
1211    }
1212
1213    #[test]
1214    fn renders_peer_index_table_and_rib_entries() {
1215        let mut peers = std::collections::HashMap::new();
1216        peers.insert(
1217            0u16,
1218            Peer::new(
1219                Ipv4Addr::new(10, 0, 0, 1),
1220                IpAddr::from_str("192.0.2.1").unwrap(),
1221                Asn::new_32bit(64496),
1222            ),
1223        );
1224        let pit = MrtRecord {
1225            common_header: CommonHeader {
1226                timestamp: 5,
1227                microsecond_timestamp: None,
1228                entry_type: EntryType::TABLE_DUMP_V2,
1229                entry_subtype: 1,
1230                length: 0,
1231            },
1232            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::PeerIndexTable(
1233                PeerIndexTable {
1234                    collector_bgp_id: Ipv4Addr::new(10, 0, 0, 254),
1235                    view_name: "".to_string(),
1236                    id_peer_map: peers,
1237                    peer_ip_id_map: std::collections::HashMap::new(),
1238                },
1239            )),
1240        };
1241        let text = format_record(&pit);
1242        assert!(text.contains("PEER_INDEX_TABLE: 1 peers"));
1243        assert!(text.contains("PEER[0]: 192.0.2.1 AS64496"));
1244
1245        let mut attributes = Attributes::default();
1246        attributes.add_attr(AttributeValue::Origin(Origin::IGP).into());
1247        attributes.add_attr(AttributeValue::AsPath(AsPath::from_sequence([64500])).into());
1248        let rib = MrtRecord {
1249            common_header: CommonHeader {
1250                timestamp: 6,
1251                microsecond_timestamp: None,
1252                entry_type: EntryType::TABLE_DUMP_V2,
1253                entry_subtype: 2,
1254                length: 0,
1255            },
1256            message: MrtMessage::TableDumpV2Message(TableDumpV2Message::RibAfi(RibAfiEntries {
1257                rib_type: TableDumpV2Type::RibIpv4Unicast,
1258                sequence_number: 1,
1259                prefix: NetworkPrefix::from_str("198.51.100.0/24").unwrap(),
1260                rib_entries: vec![RibEntry {
1261                    peer_index: 0,
1262                    originated_time: 1_666_542_000,
1263                    path_id: None,
1264                    attributes,
1265                }],
1266            })),
1267        };
1268        let text = format_record(&rib);
1269        assert!(text.contains("PREFIX: 198.51.100.0/24 (1 entries)"));
1270        assert!(text.contains("PEER_INDEX: 0"));
1271        assert!(text.contains("AS_PATH: 64500"));
1272    }
1273}