bgpkit-commons 0.14.2

A library for common BGP-related data and functions.
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
//! PeeringDB data module
//!
//! This module provides typed access to PeeringDB's API data, with structs that
//! faithfully mirror the [PeeringDB REST API](https://www.peeringdb.com/api/)
//! endpoints. Each struct captures all fields returned by its corresponding
//! endpoint — no projection or data loss.
//!
//! # Data sources
//!
//! - PeeringDB API: <https://www.peeringdb.com/api/>
//!
//! # PeeringDB API key
//!
//! It is strongly recommended to obtain a [PeeringDB API key](https://docs.peeringdb.com/blog/api_keys/)
//! and set the `PEERINGDB_API_KEY` environment variable.
//! Without it, the API call will likely fail due to rate limiting.
//!
//! # Endpoint coverage
//!
//! | Struct | API endpoint | Description |
//! |--------|------------|-------------|
//! | [`Network`] | `/net` | Network (AS) information |
//! | [`InternetExchange`] | `/ix` | Internet exchange point |
//! | [`IxLan`] | `/ixlan` | IXP peering LAN |
//! | [`IxPrefix`] | `/ixpfx` | IXP peering LAN prefix |
//! | [`NetworkIxLan`] | `/netixlan` | Network–IXP membership |
//! | [`Facility`] | `/fac` | Facility (data center) |
//! | [`NetworkFacility`] | `/netfac` | Network–facility co-location |
//! | [`IxFacility`] | `/ixfac` | IXP–facility association |
//! | [`Organization`] | `/org` | Organization |
//! | [`Campus`] | `/campus` | Facility campus |
//! | [`Carrier`] | `/carrier` | Transport carrier |
//! | [`CarrierFacility`] | `/carrierfac` | Carrier–facility association |
//! | *(map)* | `/as_set` | AS-set names by ASN |

mod client;
mod tables;

pub use tables::*;

use std::collections::HashMap;

use crate::errors::data_sources;
use crate::{BgpkitCommonsError, Result};
use tracing::info;

/// PeeringDB data container with all tables loaded from the API.
///
/// Use [`Peeringdb::new`] to fetch all data from the PeeringDB API, or
/// [`Peeringdb::new_networks_only`] for the lightweight network-only load
/// (backward-compatible with the original behavior).
pub struct Peeringdb {
    /// Network records keyed by ASN (`/net`).
    pub networks: HashMap<u32, Network>,
    /// Internet exchange records keyed by `ix_id` (`/ix`).
    pub internet_exchanges: HashMap<u32, InternetExchange>,
    /// IXP peering-LAN records keyed by `ixlan_id` (`/ixlan`).
    pub ixp_lans: HashMap<u32, IxLan>,
    /// IXP prefix records (`/ixpfx`).
    pub ixp_prefixes: Vec<IxPrefix>,
    /// Network–IXP membership records (`/netixlan`).
    pub network_ixp_membership: Vec<NetworkIxLan>,
    /// Facility records keyed by `fac_id` (`/fac`).
    pub facilities: HashMap<u32, Facility>,
    /// Network–facility co-location records (`/netfac`).
    pub network_facilities: Vec<NetworkFacility>,
    /// IXP–facility association records (`/ixfac`).
    pub ixp_facilities: Vec<IxFacility>,
    /// Organization records keyed by `org_id` (`/org`).
    pub organizations: HashMap<u32, Organization>,
    /// Campus records keyed by `campus_id` (`/campus`).
    pub campuses: HashMap<u32, Campus>,
    /// Carrier records keyed by `carrier_id` (`/carrier`).
    pub carriers: HashMap<u32, Carrier>,
    /// Carrier–facility association records (`/carrierfac`).
    pub carrier_facilities: Vec<CarrierFacility>,
    /// AS-set names by ASN (`/as_set`); the value is the raw published string
    /// and may hold several space-separated names.
    pub as_set: HashMap<u32, String>,
}

impl Peeringdb {
    /// Fetch all PeeringDB tables from the API.
    ///
    /// This makes multiple API calls (one per endpoint). Requires
    /// `PEERINGDB_API_KEY` to avoid rate limiting.
    pub fn new() -> Result<Self> {
        info!("loading all PeeringDB tables from API...");
        let networks = Self::load_table::<Network>(client::NET_API_URL)?
            .into_iter()
            .filter_map(|n| n.asn.map(|asn| (asn, n)))
            .collect();
        let internet_exchanges = Self::load_table_id(client::IX_API_URL)?;
        let ixp_lans = Self::load_table_id(client::IXLAN_API_URL)?;
        let ixp_prefixes = Self::load_table(client::IXPFX_API_URL)?;
        let network_ixp_membership = Self::load_table(client::NETIXLAN_API_URL)?;
        let facilities = Self::load_table_id(client::FAC_API_URL)?;
        let network_facilities = Self::load_table(client::NETFAC_API_URL)?;
        let ixp_facilities = Self::load_table(client::IXFAC_API_URL)?;
        let organizations = Self::load_table_id(client::ORG_API_URL)?;
        let campuses = Self::load_table_id(client::CAMPUS_API_URL)?;
        let carriers = Self::load_table_id(client::CARRIER_API_URL)?;
        let carrier_facilities = Self::load_table(client::CARRIERFAC_API_URL)?;
        let as_set = Self::load_as_set(client::AS_SET_API_URL)?;
        info!("loaded all PeeringDB tables");
        Ok(Self {
            networks,
            internet_exchanges,
            ixp_lans,
            ixp_prefixes,
            network_ixp_membership,
            facilities,
            network_facilities,
            ixp_facilities,
            organizations,
            campuses,
            carriers,
            carrier_facilities,
            as_set,
        })
    }

    /// Fetch only the `/net` table (lightweight, backward-compatible).
    ///
    /// This is equivalent to the original `Peeringdb::new()` behavior before
    /// the data-layer expansion.
    pub fn new_networks_only() -> Result<Self> {
        info!("loading PeeringDB /net table...");
        let networks: HashMap<u32, Network> = Self::load_table::<Network>(client::NET_API_URL)?
            .into_iter()
            .filter_map(|n| n.asn.map(|asn| (asn, n)))
            .collect();
        info!("loaded {} PeeringDB networks", networks.len());
        Ok(Self {
            networks,
            internet_exchanges: HashMap::new(),
            ixp_lans: HashMap::new(),
            ixp_prefixes: Vec::new(),
            network_ixp_membership: Vec::new(),
            facilities: HashMap::new(),
            network_facilities: Vec::new(),
            ixp_facilities: Vec::new(),
            organizations: HashMap::new(),
            campuses: HashMap::new(),
            carriers: HashMap::new(),
            carrier_facilities: Vec::new(),
            as_set: HashMap::new(),
        })
    }

    /// Load a table as a `Vec<T>` of records.
    fn load_table<R: serde::de::DeserializeOwned>(url: &str) -> Result<Vec<R>> {
        let mut reader = client::get_peeringdb_reader(url)?;
        let mut buf = String::new();
        reader.read_to_string(&mut buf)?;
        let res: PeeringdbResponse<R> = serde_json::from_str(&buf)?;
        Ok(res.data)
    }

    /// Load a table as a `HashMap<u32, T>` keyed by the `id` field.
    fn load_table_id<T: serde::de::DeserializeOwned + HasId>(url: &str) -> Result<HashMap<u32, T>> {
        Ok(Self::load_table::<T>(url)?
            .into_iter()
            .map(|r| (r.id(), r))
            .collect())
    }

    /// Load the `/as_set` map.
    ///
    /// Unlike the other tables, this endpoint returns a single ASN -> as-set
    /// name object rather than a list of records, so it needs its own parser.
    fn load_as_set(url: &str) -> Result<HashMap<u32, String>> {
        let mut reader = client::get_peeringdb_reader(url)?;
        let mut buf = String::new();
        reader.read_to_string(&mut buf)?;
        Self::parse_as_set(&buf)
    }

    /// Parse a raw `/as_set` response body into an ASN -> as-set names map.
    ///
    /// `data` must hold exactly one object whose keys are ASNs and whose
    /// values are the raw published strings (kept verbatim, including any
    /// space-separated names); other top-level fields such as `meta` are
    /// ignored. Anything else is refused as a PeeringDB data-source error
    /// rather than guessed at.
    fn parse_as_set(buf: &str) -> Result<HashMap<u32, String>> {
        let value: serde_json::Value = serde_json::from_str(buf)
            .map_err(|e| as_set_parse_error(format!("malformed JSON: {e}")))?;

        let data = value
            .get("data")
            .and_then(serde_json::Value::as_array)
            .ok_or_else(|| as_set_parse_error("expected a top-level object with a 'data' array"))?;

        if data.len() != 1 {
            return Err(as_set_parse_error(format!(
                "expected exactly one object in 'data', got {} element(s)",
                data.len()
            )));
        }

        let obj = data[0]
            .as_object()
            .ok_or_else(|| as_set_parse_error("expected 'data[0]' to be an object"))?;

        let mut as_set = HashMap::with_capacity(obj.len());
        for (key, value) in obj {
            let asn: u32 = key
                .parse()
                .map_err(|_| as_set_parse_error(format!("'{key}' is not a u32 ASN")))?;
            let name = value.as_str().ok_or_else(|| {
                as_set_parse_error(format!("value for ASN {asn} is not a string"))
            })?;
            as_set.insert(asn, name.to_string());
        }

        Ok(as_set)
    }

    // ---- Network accessors ----

    /// Get network data for a specific ASN.
    pub fn get_network(&self, asn: u32) -> Option<&Network> {
        self.networks.get(&asn)
    }

    /// Check if an ASN exists in the PeeringDB data.
    pub fn contains_network(&self, asn: u32) -> bool {
        self.networks.contains_key(&asn)
    }

    /// Number of networks loaded.
    pub fn network_count(&self) -> usize {
        self.networks.len()
    }

    /// Get all ASNs present in PeeringDB.
    pub fn all_asns(&self) -> Vec<u32> {
        self.networks.keys().copied().collect()
    }

    // ---- IXP accessors ----

    /// Get an internet exchange by its `ix_id`.
    pub fn get_ixp(&self, ix_id: u32) -> Option<&InternetExchange> {
        self.internet_exchanges.get(&ix_id)
    }

    /// Get all IXP memberships for a given ASN.
    pub fn get_ixp_memberships(&self, asn: u32) -> Vec<&NetworkIxLan> {
        self.network_ixp_membership
            .iter()
            .filter(|m| m.asn == asn)
            .collect()
    }

    /// Get all ASNs present at a given IXP.
    pub fn get_asns_at_ixp(&self, ix_id: u32) -> Vec<&NetworkIxLan> {
        self.network_ixp_membership
            .iter()
            .filter(|m| m.ix_id == ix_id)
            .collect()
    }

    /// Look up IXP prefix records by exact prefix string (e.g., `"206.223.115.0/24"`).
    pub fn lookup_ixp_prefix(&self, prefix: &str) -> Vec<&IxPrefix> {
        self.ixp_prefixes
            .iter()
            .filter(|p| p.prefix == prefix)
            .collect()
    }

    /// Check whether a prefix string is an IXP peering-LAN prefix.
    pub fn is_ixp_prefix(&self, prefix: &str) -> bool {
        self.ixp_prefixes.iter().any(|p| p.prefix == prefix)
    }

    /// Get all IXP prefixes.
    pub fn all_ixp_prefixes(&self) -> &[IxPrefix] {
        &self.ixp_prefixes
    }

    // ---- Facility accessors ----

    /// Get a facility by its `fac_id`.
    pub fn get_facility(&self, fac_id: u32) -> Option<&Facility> {
        self.facilities.get(&fac_id)
    }

    /// Get all facilities a network is present at.
    pub fn get_network_facilities(&self, asn: u32) -> Vec<&NetworkFacility> {
        self.network_facilities
            .iter()
            .filter(|nf| nf.local_asn == asn)
            .collect()
    }

    // ---- Organization accessors ----

    /// Get an organization by its `org_id`.
    pub fn get_organization(&self, org_id: u32) -> Option<&Organization> {
        self.organizations.get(&org_id)
    }

    // ---- AS-set accessors ----

    /// Get the raw published as-set name(s) registered for an ASN (`/as_set`).
    ///
    /// Returns `None` when the ASN has no registered as-set.
    pub fn get_as_set(&self, asn: u32) -> Option<&str> {
        self.as_set.get(&asn).map(String::as_str)
    }
}

/// Build the PeeringDB data-source error for an invalid `/as_set` response.
///
/// All `/as_set` shape-validation and JSON failures are wrapped this way so
/// callers see one error kind naming both the data source and the endpoint.
fn as_set_parse_error(reason: impl std::fmt::Display) -> BgpkitCommonsError {
    BgpkitCommonsError::data_source_error(
        data_sources::PEERINGDB,
        format!("/as_set response is invalid: {reason}"),
    )
}

/// Trait for structs that have an `id` field, used by `load_table_id`.
pub trait HasId {
    fn id(&self) -> u32;
}

#[derive(serde::Deserialize)]
struct PeeringdbResponse<T> {
    data: Vec<T>,
}

impl std::fmt::Debug for Peeringdb {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Peeringdb")
            .field("networks", &self.networks.len())
            .field("internet_exchanges", &self.internet_exchanges.len())
            .field("ixp_lans", &self.ixp_lans.len())
            .field("ixp_prefixes", &self.ixp_prefixes.len())
            .field("network_ixp_membership", &self.network_ixp_membership.len())
            .field("facilities", &self.facilities.len())
            .field("network_facilities", &self.network_facilities.len())
            .field("ixp_facilities", &self.ixp_facilities.len())
            .field("organizations", &self.organizations.len())
            .field("campuses", &self.campuses.len())
            .field("carriers", &self.carriers.len())
            .field("carrier_facilities", &self.carrier_facilities.len())
            .field("as_set", &self.as_set.len())
            .finish()
    }
}

// ===========================================================================
// Backward compatibility: PeeringdbData and get_data
// ===========================================================================

/// Backward-compatible alias for [`Network`].
///
/// Code written before the data-layer expansion used `PeeringdbData` as the
/// primary PeeringDB type. It is now an alias for the full [`Network`] struct.
pub type PeeringdbData = Network;

impl Peeringdb {
    /// Get PeeringDB data for a specific ASN (backward-compatible accessor).
    ///
    /// This is the original accessor from before the data-layer expansion.
    /// New code should prefer [`Peeringdb::get_network`].
    pub fn get_data(&self, asn: u32) -> Option<&PeeringdbData> {
        self.networks.get(&asn)
    }

    /// Get all ASNs in the PeeringDB data.
    #[allow(dead_code)]
    pub fn get_all_asns(&self) -> Vec<u32> {
        self.all_asns()
    }

    /// Check if an ASN exists in the PeeringDB data.
    #[allow(dead_code)]
    pub fn contains(&self, asn: u32) -> bool {
        self.contains_network(asn)
    }

    /// Get the number of networks in the database.
    #[allow(dead_code)]
    pub fn len(&self) -> usize {
        self.network_count()
    }

    /// Check if the database is empty.
    #[allow(dead_code)]
    pub fn is_empty(&self) -> bool {
        self.networks.is_empty()
    }
}

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

    #[test]
    fn test_peeringdb_data_is_network() {
        // Compile-time check that PeeringdbData is Network
        let _: PeeringdbData = Network {
            id: 1,
            asn: Some(13335),
            name: Some("Cloudflare".to_string()),
            name_long: None,
            aka: None,
            org_id: None,
            irr_as_set: None,
            website: None,
            info_traffic: None,
            info_scope: None,
            info_type: None,
            info_types: None,
            info_ratio: None,
            info_prefixes4: None,
            info_prefixes6: None,
            info_ipv6: None,
            info_unicast: None,
            info_multicast: None,
            info_never_via_route_servers: None,
            policy_general: None,
            policy_url: None,
            policy_contracts: None,
            policy_locations: None,
            policy_ratio: None,
            route_server: None,
            looking_glass: None,
            ix_count: None,
            fac_count: None,
            status: None,
            allow_ixp_update: None,
            social_media: None,
            notes: None,
            rir_status: None,
            rir_status_updated: None,
            status_dashboard: None,
            poc_updated: None,
            netixlan_updated: None,
            netfac_updated: None,
            created: None,
            updated: None,
        };
    }

    #[test]
    fn test_peeringdb_data_struct() {
        let data = PeeringdbData {
            id: 4224,
            asn: Some(13335),
            name: Some("Cloudflare".to_string()),
            name_long: Some("Cloudflare, Inc.".to_string()),
            aka: Some("CF".to_string()),
            org_id: Some(8061),
            irr_as_set: Some("AS-CLOUDFLARE".to_string()),
            website: Some("https://cloudflare.com".to_string()),
            info_traffic: Some("1-5Tbps+".to_string()),
            info_scope: Some("Global".to_string()),
            info_type: Some("Content".to_string()),
            info_types: Some(vec!["Content".to_string()]),
            info_ratio: Some("Heavy Outbound".to_string()),
            info_prefixes4: Some(300),
            info_prefixes6: Some(150),
            info_ipv6: Some(true),
            info_unicast: Some(true),
            info_multicast: Some(false),
            info_never_via_route_servers: Some(false),
            policy_general: Some("Open".to_string()),
            policy_url: Some("https://www.cloudflare.com/peering-policy".to_string()),
            policy_contracts: None,
            policy_locations: None,
            policy_ratio: Some(false),
            route_server: None,
            looking_glass: None,
            ix_count: Some(300),
            fac_count: Some(200),
            status: Some("ok".to_string()),
            allow_ixp_update: Some(false),
            social_media: Some(vec![]),
            notes: None,
            rir_status: Some("ok".to_string()),
            rir_status_updated: None,
            status_dashboard: None,
            poc_updated: None,
            netixlan_updated: None,
            netfac_updated: None,
            created: None,
            updated: None,
        };
        assert_eq!(data.asn, Some(13335));
        assert_eq!(data.name.as_deref(), Some("Cloudflare"));
        assert_eq!(data.info_traffic.as_deref(), Some("1-5Tbps+"));
        assert_eq!(data.ix_count, Some(300));
    }

    #[test]
    fn test_network_deserialization_minimal() {
        let json = r#"{"id":1,"name":"Test","asn":12345}"#;
        let net: Network = serde_json::from_str(json).unwrap();
        assert_eq!(net.id, 1);
        assert_eq!(net.asn, Some(12345));
        assert_eq!(net.name.as_deref(), Some("Test"));
        assert!(net.website.is_none());
    }

    #[test]
    fn test_ixprefix_deserialization() {
        let json = r#"{"prefix":"206.223.115.0/24","protocol":"IPv4","ixlan_id":1,"in_dfz":true,"id":1,"status":"ok","created":"2020-01-01T00:00:00Z","updated":"2020-01-01T00:00:00Z"}"#;
        let pfx: IxPrefix = serde_json::from_str(json).unwrap();
        assert_eq!(pfx.prefix, "206.223.115.0/24");
        assert_eq!(pfx.protocol, "IPv4");
        assert!(pfx.in_dfz);
    }

    #[test]
    fn test_networkixlan_deserialization() {
        let json = r#"{"id":13,"net_id":694,"ix_id":12,"ixlan_id":12,"asn":8075,"speed":100000,"is_rs_peer":false,"operational":true,"name":"Equinix New York","ipaddr4":"196.201.2.20","ipaddr6":null,"bfd_support":false,"status":"ok","notes":"","created":"2011-09-28T00:00:00Z","updated":"2018-10-11T06:11:28Z"}"#;
        let nxl: NetworkIxLan = serde_json::from_str(json).unwrap();
        assert_eq!(nxl.asn, 8075);
        assert_eq!(nxl.ix_id, 12);
        assert_eq!(nxl.speed, 100000);
        assert!(!nxl.is_rs_peer);
    }

    // ---- /as_set parser tests (pure, no network) ----

    /// Assert that `json` is refused as a PeeringDB data-source error naming
    /// the `/as_set` endpoint. Every validation failure must be wrapped this
    /// way instead of surfacing as a bare JSON error.
    fn assert_invalid_as_set(json: &str) {
        match Peeringdb::parse_as_set(json) {
            Err(BgpkitCommonsError::DataSourceError {
                data_source,
                details,
            }) => {
                assert_eq!(data_source, data_sources::PEERINGDB);
                assert!(
                    details.contains("/as_set"),
                    "error does not name the endpoint: {details}"
                );
            }
            other => panic!("expected PeeringDB data-source error, got {other:?}"),
        }
    }

    #[test]
    fn test_parse_as_set_single_object() {
        let json = r#"{"data":[{"13335":"AS13335:AS-CLOUDFLARE","15169":"RADB::AS-GOOGLE"}]}"#;
        let map = Peeringdb::parse_as_set(json).unwrap();
        assert_eq!(map.len(), 2);
        assert_eq!(
            map.get(&13335).map(String::as_str),
            Some("AS13335:AS-CLOUDFLARE")
        );
        assert_eq!(map.get(&15169).map(String::as_str), Some("RADB::AS-GOOGLE"));
    }

    #[test]
    fn test_parse_as_set_preserves_raw_values() {
        // Values are kept verbatim, including several space-separated names.
        let json = r#"{"data":[{"13335":"AS13335:AS-CLOUDFLARE AS13335:AS-CLOUDFLARE-V6"}]}"#;
        let map = Peeringdb::parse_as_set(json).unwrap();
        assert_eq!(
            map.get(&13335).map(String::as_str),
            Some("AS13335:AS-CLOUDFLARE AS13335:AS-CLOUDFLARE-V6")
        );
    }

    #[test]
    fn test_parse_as_set_empty_object_allowed() {
        let map = Peeringdb::parse_as_set(r#"{"data":[{}]}"#).unwrap();
        assert!(map.is_empty());
    }

    #[test]
    fn test_parse_as_set_refuses_bare_array() {
        assert_invalid_as_set("[]");
    }

    #[test]
    fn test_parse_as_set_refuses_empty_data_array() {
        assert_invalid_as_set(r#"{"data":[]}"#);
    }

    #[test]
    fn test_parse_as_set_refuses_multiple_elements() {
        assert_invalid_as_set(r#"{"data":[{"1":"AS-A"},{"2":"AS-B"}]}"#);
    }

    #[test]
    fn test_parse_as_set_refuses_non_object_element() {
        assert_invalid_as_set(r#"{"data":[["13335","AS-X"]]}"#);
    }

    #[test]
    fn test_parse_as_set_refuses_non_array_data() {
        assert_invalid_as_set(r#"{"data":{"13335":"AS-X"}}"#);
    }

    #[test]
    fn test_parse_as_set_refuses_non_numeric_key() {
        assert_invalid_as_set(r#"{"data":[{"AS13335":"AS-CLOUDFLARE"}]}"#);
    }

    #[test]
    fn test_parse_as_set_refuses_out_of_range_key() {
        // u32::MAX + 1 and negative keys are not valid ASNs.
        assert_invalid_as_set(r#"{"data":[{"4294967296":"AS-X"}]}"#);
        assert_invalid_as_set(r#"{"data":[{"-1":"AS-X"}]}"#);
    }

    #[test]
    fn test_parse_as_set_refuses_non_string_value() {
        assert_invalid_as_set(r#"{"data":[{"13335":42}]}"#);
    }

    #[test]
    fn test_parse_as_set_refuses_malformed_json() {
        assert_invalid_as_set(r#"{"data":[}"#);
    }

    // Integration tests that require network access - marked as ignored by default

    #[test]
    #[ignore]
    fn test_peeringdb_new_networks_only() {
        let pdb = Peeringdb::new_networks_only().expect("Failed to load PeeringDB");
        assert!(!pdb.is_empty());
        let cf = pdb.get_data(13335);
        assert!(cf.is_some());
        let cf = cf.unwrap();
        assert_eq!(cf.asn, Some(13335));
        assert!(cf.info_traffic.is_some() || cf.info_traffic.is_none()); // just check field exists
    }

    #[test]
    #[ignore]
    fn test_peeringdb_ixp_prefixes() {
        let pdb = Peeringdb::new().expect("Failed to load all PeeringDB");
        // DE-CIX Frankfurt peering LAN prefix
        let decix = pdb.lookup_ixp_prefix("80.81.192.0/21");
        assert!(
            !decix.is_empty(),
            "DE-CIX Frankfurt prefix should be present"
        );
        // Cloudflare should have IXP memberships
        let cf_ixps = pdb.get_ixp_memberships(13335);
        assert!(
            !cf_ixps.is_empty(),
            "Cloudflare should have IXP memberships"
        );
    }

    #[test]
    #[ignore]
    fn test_peeringdb_as_set() {
        // Live check of the `/as_set` endpoint only: the map must be non-empty
        // and resolve through the accessor. Values are not pinned because the
        // upstream data changes over time.
        let as_set = Peeringdb::load_as_set(client::AS_SET_API_URL)
            .expect("Failed to load PeeringDB /as_set");
        let pdb = Peeringdb {
            networks: HashMap::new(),
            internet_exchanges: HashMap::new(),
            ixp_lans: HashMap::new(),
            ixp_prefixes: Vec::new(),
            network_ixp_membership: Vec::new(),
            facilities: HashMap::new(),
            network_facilities: Vec::new(),
            ixp_facilities: Vec::new(),
            organizations: HashMap::new(),
            campuses: HashMap::new(),
            carriers: HashMap::new(),
            carrier_facilities: Vec::new(),
            as_set,
        };
        assert!(!pdb.as_set.is_empty());
        assert!(pdb.get_as_set(13335).is_some());
    }
}