Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ BGPKIT-Commons is a Rust library for common BGP-related data and functions with
│ ├── bogons/ # Bogon detection (reserved IPs/ASNs)
│ ├── countries/ # Country code mappings
│ ├── mrt_collectors/ # BGP collector metadata
│ ├── peeringdb/ # PeeringDB API data (all 12 endpoints)
│ ├── peeringdb/ # PeeringDB API data (all 13 endpoints)
│ └── rpki/ # RPKI validation (ROA/ASPA)
├── examples/ # Feature-gated usage examples
└── tests/ # Integration tests
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ All notable changes to this project will be documented in this file.
* `pg-inserter-cli` feature and `pg_inserter` binary: loads BGP reference data into PostgreSQL with one schema per source (`asndata`, `peeringdb`, `irr`), independent snapshot refreshes via a staging COPY + atomic swap, and run provenance in `meta.ingest_run` ([#46](https://github.com/bgpkit/bgpkit-commons/pull/46)).
* Container image `bgpkit/pg-inserter`, built from `docker/pg-inserter.Dockerfile` with credentials supplied only through run-time environment variables (`docker/README.md`) ([#48](https://github.com/bgpkit/bgpkit-commons/pull/48)).
* `pg_inserter`: TLS is negotiated from the connection string like libpq's `sslmode` (`disable`, `prefer` default, `require`, `verify-ca`, `verify-full`) with `sslrootcert` for the verifying modes, so a deployment can move between plaintext and encrypted database links without a rebuild. `prefer` and `require` encrypt without verifying the certificate; `verify-ca`/`verify-full` verify the chain (and, for the latter, the hostname).
* `peeringdb`: new `as_set` table mirroring PeeringDB's `/api/as_set` endpoint (ASN -> registered as-set names), expanding the supported mirror to 13 tables; `pg_inserter` publishes it as `peeringdb.as_set` ([#49](https://github.com/bgpkit/bgpkit-commons/pull/49)).

### Fixed

Expand Down
14 changes: 7 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ assert!(commons.bogons_match("23456").unwrap()); // AS23456 is reserved
| `bogons` | `bogons` | IANA special registries | Reserved/bogon ASN and IP prefix detection |
| `countries` | `countries` | GeoNames | ISO country codes, capitals, continents, neighbors |
| `mrt_collectors` | `mrt_collectors` | RouteViews, RIPE RIS | BGP collector metadata (name, project, country, dates) |
| `peeringdb` | `peeringdb` | PeeringDB API | All 12 endpoints: networks, IXPs, facilities, orgs, carriers |
| `peeringdb` | `peeringdb` | PeeringDB API | 13 supported endpoints: networks, IXPs, facilities, orgs, carriers, AS-set names |
| `rpki` | `rpki` | Cloudflare, RIPE NCC, RPKIviews, RPKISPOOL | ROA and ASPA validation (real-time and historical) |
| `delegated` | `delegated` | NRO/RIR delegated stats | RIR allocation records (ASN, IPv4, IPv6) |
| `irr` | `irr` | RIPE, APNIC, ARIN, LACNIC, AFRINIC, NTTCOM, RADB, ... | RPSL aut-num, route, route6, as-set records |
Expand Down Expand Up @@ -110,7 +110,7 @@ assert!(commons.bogons_match_asn(65535).unwrap()); // reserved ASN
```rust
use bgpkit_commons::peeringdb::Peeringdb;

let pdb = Peeringdb::new().unwrap(); // all 12 endpoints
let pdb = Peeringdb::new().unwrap(); // the 13 supported endpoints
let cf = pdb.get_network(13335).unwrap();
println!("{}: {} IXP memberships", cf.name.unwrap(), cf.ix_count.unwrap());
```
Expand Down Expand Up @@ -160,7 +160,7 @@ bgpkit-export --output-dir ./output --with-peeringdb --with-irr --with-rpki
bgpkit-export --output-dir ./output --with-asninfo-jsonl
```

Output layout (one file per source):
Output layout (one file per source; `peeringdb/`, `irr/`, and `rpki/` exports are not yet implemented):

```
commons-export/
Expand All @@ -171,7 +171,7 @@ commons-export/
mrt_collectors.parquet
as_relationships.parquet
rir_delegated.parquet
peeringdb/ # 12 endpoint tables (--with-peeringdb)
peeringdb/ # 13 endpoint tables (--with-peeringdb)
Comment thread
Copilot marked this conversation as resolved.
Resolved
irr/records.parquet # RPSL records (--with-irr)
rpki/ # ROAs + ASPAs (--with-rpki)
asninfo.jsonl # legacy merged output (--with-asninfo-jsonl)
Expand All @@ -189,10 +189,10 @@ an atomic swap, with run provenance in `meta.ingest_run`.
cargo install bgpkit-commons --features pg-inserter-cli

export DATABASE_URL="postgresql://pg_inserter@db.example:5432/bgpkit_broker"
export PEERINGDB_API_KEY="..." # required for the full peeringdb mirror
export PEERINGDB_API_KEY="..." # required for the peeringdb mirror

pg_inserter asndata # asnames, as2org, population, hegemony, delegated
pg_inserter peeringdb # full PeeringDB table mirror
pg_inserter peeringdb # PeeringDB table mirror
pg_inserter irr # RPSL object store
```

Expand Down Expand Up @@ -220,7 +220,7 @@ See `docker/README.md` for the image catalog and the credential contract, and
| `delegated` | RIR delegated-statistics parser |
| `irr` | IRR RPSL record parsing (aut-num, route, as-set) |
| `mrt_collectors` | MRT collector metadata |
| `peeringdb` | PeeringDB API data (all 12 endpoints) |
| `peeringdb` | PeeringDB API data (13 supported endpoints) |
| `rpki` | RPKI validation (ROA and ASPA) |
| `all` *(default)* | Enables all data modules above |
| `export` | Parquet export of all loaded sources (adds `arrow` + `parquet`) |
Expand Down
2 changes: 1 addition & 1 deletion src/bin/pg_inserter/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ enum Commands {
Delegated,
/// Run every asndata task sequentially
Asndata,
/// peeringdb schema: full PeeringDB mirror (12 tables)
/// peeringdb schema: mirror of the 13 supported PeeringDB tables
Peeringdb,
/// irr schema: full IRR RPSL object store (snapshot-only)
Irr,
Expand Down
77 changes: 73 additions & 4 deletions src/bin/pg_inserter/peeringdb.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,10 @@
//! `peeringdb` schema: full PeeringDB API mirror (12 tables).
//! `peeringdb` schema: mirror of the 13 supported PeeringDB API tables.
//!
//! One `Peeringdb::new()` load (all 12 endpoints) is dumped into 12 snapshot
//! One `Peeringdb::new()` load (the 13 supported endpoints) is dumped into 13 snapshot
//! tables. Per-table shape: native PeeringDB id as PK, typed foreign-key and
//! search columns, the complete API object in a `record` JSONB column, and
//! `data_as_of`/`source_revision` provenance. Per-table independence inside
//! `data_as_of`/`source_revision` provenance; `as_set` is the exception (no
//! `id`/`record`, its value is the payload). Per-table independence inside
//! the PeeringDB family is deferred: the whole family refreshes atomically.

use super::refresh::{SOURCE_REVISION, TableSpec, build_csv_line};
Expand All @@ -14,7 +15,7 @@ use bgpkit_commons::peeringdb::{
use serde::Serialize;
use std::collections::HashMap;

/// Load the full PeeringDB dataset and map it to `(TableSpec, lines)` pairs,
/// Load the PeeringDB dataset and map it to `(TableSpec, lines)` pairs,
/// one per table. Runs on the blocking pool.
pub(crate) fn load_all(data_as_of: &str) -> Result<Vec<(TableSpec, Vec<String>)>, String> {
let pdb = Peeringdb::new().map_err(|e| format!("failed to load PeeringDB data: {e}"))?;
Expand Down Expand Up @@ -64,6 +65,7 @@ pub(crate) fn load_all(data_as_of: &str) -> Result<Vec<(TableSpec, Vec<String>)>
CARRIERFAC_SPEC,
dump_vec(&pdb.carrier_facilities, data_as_of, carrierfac_line)?,
),
(AS_SET_SPEC, dump_as_set(&pdb.as_set, data_as_of)?),
];
Ok(tables)
}
Expand Down Expand Up @@ -285,6 +287,25 @@ const CARRIERFAC_SPEC: TableSpec = TableSpec {
index_swaps: &[("peeringdb.carrierfac_staging_pkey", "carrierfac_pkey")],
};

/// Shape exception to the other twelve tables: the upstream `/as_set`
/// payload is a bare `{asn: name}` map, so there are no `id`/`record`
/// columns; the string value itself is the payload.
const AS_SET_SPEC: TableSpec = TableSpec {
task: "peeringdb.as_set",
table: "peeringdb.as_set",
staging_ddl: "CREATE TABLE peeringdb.as_set_staging (
asn bigint NOT NULL,
as_set text NOT NULL,
data_as_of timestamptz NOT NULL,
source_revision text NOT NULL
)",
copy_columns: "asn, as_set, data_as_of, source_revision",
index_ddl: &[
"ALTER TABLE peeringdb.as_set_staging ADD CONSTRAINT as_set_staging_pkey PRIMARY KEY (asn)",
],
index_swaps: &[("peeringdb.as_set_staging_pkey", "as_set_pkey")],
};

// ---- row mapping -----------------------------------------------------------

/// Serialize one record to a double-quoted JSON field. Serialization cannot
Expand Down Expand Up @@ -329,6 +350,25 @@ fn dump_networks(
.collect()
}

/// Dump the `/as_set` map: one line per ASN, sorted by ASN ascending.
fn dump_as_set(map: &HashMap<u32, String>, data_as_of: &str) -> Result<Vec<String>, String> {
let mut asns: Vec<u32> = map.keys().copied().collect();
asns.sort_unstable();
asns.iter()
.map(|asn| {
let value = map
.get(asn)
.ok_or_else(|| format!("missing as_set entry {asn}"))?;
Ok(build_csv_line(&[
Some(asn.to_string()),
Some(value.clone()),
Some(data_as_of.to_string()),
Some(SOURCE_REVISION.to_string()),
]))
})
.collect()
}

fn dump_records<T: Serialize>(
map: &HashMap<u32, T>,
data_as_of: &str,
Expand Down Expand Up @@ -495,4 +535,33 @@ mod tests {
);
assert!(line.starts_with("1,,\"3\",\"{"));
}

#[test]
fn as_set_lines_sorted_by_asn_numerically() {
let map = HashMap::from([
(10u32, "TEN".to_string()),
(2u32, "TWO".to_string()),
(1u32, "ONE".to_string()),
]);
let lines = dump_as_set(&map, "2026-09-09T00:00:00+00:00").unwrap();
assert_eq!(lines.len(), 3);
// Numeric order: a lexicographic sort would yield 1, 10, 2.
assert!(lines[0].starts_with("\"1\","));
assert!(lines[1].starts_with("\"2\","));
assert!(lines[2].starts_with("\"10\","));
}

#[test]
fn as_set_line_escapes_csv_and_stays_one_four_field_line() {
let map = HashMap::from([(13335u32, "a,b\"c\nd".to_string())]);
let lines = dump_as_set(&map, "2026-09-09T00:00:00+00:00").unwrap();
assert_eq!(lines.len(), 1);
// Exact 4-field shape: asn, escaped value, data_as_of, source_revision.
assert_eq!(
lines[0],
format!(
"\"13335\",\"a,b\"\"c\nd\",\"2026-09-09T00:00:00+00:00\",\"{SOURCE_REVISION}\""
)
);
}
}
5 changes: 3 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,9 @@
//!
//! - Load: `Peeringdb::new()` (all tables), `Peeringdb::new_networks_only()` (lightweight)
//! - Access: `get_network(asn)`, `get_ixp(ix_id)`, `get_ixp_memberships(asn)`, `lookup_ixp_prefix(prefix)`, `get_facility(fac_id)`
//! - Typed structs mirroring all 12 PeeringDB API endpoints: networks, internet exchanges,
//! IXP prefixes, IXP membership, facilities, organizations, carriers, and more
//! - Typed structs and an ASN-to-AS-set map mirroring the 13 supported PeeringDB API endpoints:
//! networks, internet exchanges, IXP prefixes, IXP membership, facilities, organizations,
//! carriers, AS-set names, and more
//! - `PeeringdbData` is a type alias for the full `Network` struct (backward compatible)
//!
//! ### [`rpki`] — RPKI Validation
Expand Down
1 change: 1 addition & 0 deletions src/peeringdb/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ pub(crate) const ORG_API_URL: &str = "https://www.peeringdb.com/api/org";
pub(crate) const CAMPUS_API_URL: &str = "https://www.peeringdb.com/api/campus";
pub(crate) const CARRIER_API_URL: &str = "https://www.peeringdb.com/api/carrier";
pub(crate) const CARRIERFAC_API_URL: &str = "https://www.peeringdb.com/api/carrierfac";
pub(crate) const AS_SET_API_URL: &str = "https://www.peeringdb.com/api/as_set";

/// Get a reader for a PeeringDB API endpoint with proper authentication headers.
///
Expand Down
Loading
Loading