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
//! `asndata` schema: per-source AS reference-data tasks.
//!
//! Each task loads one source independently and produces CSV lines for the
//! generic snapshot-refresh runner. A failing source only fails its own task.

use super::refresh::{TableSpec, build_csv_line, push_csv_field};
use bgpkit_commons::asinfo::{
    AllocationStatus, AsInfo, AsInfoBuilder, IANA_SPECIAL_ASN_RANGES, allocation_status_of_record,
};
use bgpkit_commons::delegated::{self, DelegatedRecord};

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Task {
    Asnames,
    As2org,
    Population,
    Hegemony,
    Delegated,
    Allocations,
}

pub(crate) const ALL_TASKS: &[Task] = &[
    Task::Asnames,
    Task::As2org,
    Task::Population,
    Task::Hegemony,
    Task::Delegated,
    Task::Allocations,
];

impl Task {
    pub(crate) const fn spec(self) -> TableSpec {
        match self {
            Task::Asnames => TableSpec {
                task: "asndata.asnames",
                table: "asndata.asnames",
                staging_ddl: "CREATE TABLE asndata.asnames_staging (
                    asn bigint NOT NULL,
                    name text NOT NULL,
                    country text NOT NULL,
                    data_as_of timestamptz NOT NULL,
                    source_revision text NOT NULL
                )",
                copy_columns: "asn, name, country, data_as_of, source_revision",
                index_ddl: &[
                    "ALTER TABLE asndata.asnames_staging ADD CONSTRAINT asnames_staging_pkey PRIMARY KEY (asn)",
                ],
                index_swaps: &[("asndata.asnames_staging_pkey", "asnames_pkey")],
            },
            Task::As2org => TableSpec {
                task: "asndata.as2org",
                table: "asndata.as2org",
                staging_ddl: "CREATE TABLE asndata.as2org_staging (
                    asn bigint NOT NULL,
                    name text NOT NULL,
                    country text NOT NULL,
                    org_id text NOT NULL,
                    org_name text NOT NULL,
                    data_as_of timestamptz NOT NULL,
                    source_revision text NOT NULL
                )",
                copy_columns: "asn, name, country, org_id, org_name, data_as_of, source_revision",
                index_ddl: &[
                    "ALTER TABLE asndata.as2org_staging ADD CONSTRAINT as2org_staging_pkey PRIMARY KEY (asn)",
                    "CREATE INDEX as2org_staging_org_name_idx ON asndata.as2org_staging (org_name)",
                ],
                index_swaps: &[
                    ("asndata.as2org_staging_pkey", "as2org_pkey"),
                    ("asndata.as2org_staging_org_name_idx", "as2org_org_name_idx"),
                ],
            },
            Task::Population => TableSpec {
                task: "asndata.population",
                table: "asndata.population",
                staging_ddl: "CREATE TABLE asndata.population_staging (
                    asn bigint NOT NULL,
                    user_count bigint NOT NULL,
                    percent_country double precision NOT NULL,
                    percent_global double precision NOT NULL,
                    sample_count bigint NOT NULL,
                    data_as_of timestamptz NOT NULL,
                    source_revision text NOT NULL
                )",
                copy_columns: "asn, user_count, percent_country, percent_global, sample_count, data_as_of, source_revision",
                index_ddl: &[
                    "ALTER TABLE asndata.population_staging ADD CONSTRAINT population_staging_pkey PRIMARY KEY (asn)",
                ],
                index_swaps: &[("asndata.population_staging_pkey", "population_pkey")],
            },
            Task::Hegemony => TableSpec {
                task: "asndata.hegemony",
                table: "asndata.hegemony",
                staging_ddl: "CREATE TABLE asndata.hegemony_staging (
                    asn bigint NOT NULL,
                    ipv4 double precision NOT NULL,
                    ipv6 double precision NOT NULL,
                    data_as_of timestamptz NOT NULL,
                    source_revision text NOT NULL
                )",
                copy_columns: "asn, ipv4, ipv6, data_as_of, source_revision",
                index_ddl: &[
                    "ALTER TABLE asndata.hegemony_staging ADD CONSTRAINT hegemony_staging_pkey PRIMARY KEY (asn)",
                ],
                index_swaps: &[("asndata.hegemony_staging_pkey", "hegemony_pkey")],
            },
            Task::Allocations => TableSpec {
                task: "asndata.asn_allocation",
                table: "asndata.asn_allocation",
                // One row per allocation *range*, not per ASN: the RFC 6996 private
                // blocks span about 95 million ASNs, so a per-ASN table could not hold
                // them. A point lookup is a containment test on the range index.
                staging_ddl: "CREATE TABLE asndata.asn_allocation_staging (
                    start_asn bigint NOT NULL,
                    end_asn bigint NOT NULL,
                    allocation_status text NOT NULL,
                    registry text NOT NULL,
                    country text NOT NULL,
                    allocation_date text NOT NULL,
                    data_as_of timestamptz NOT NULL,
                    source_revision text NOT NULL
                )",
                copy_columns: "start_asn, end_asn, allocation_status, registry, country, allocation_date, data_as_of, source_revision",
                index_ddl: &[
                    "CREATE INDEX asn_allocation_staging_range_idx ON asndata.asn_allocation_staging USING gist (int8range(start_asn, end_asn, '[]'))",
                ],
                index_swaps: &[(
                    "asndata.asn_allocation_staging_range_idx",
                    "asn_allocation_range_idx",
                )],
            },
            Task::Delegated => TableSpec {
                task: "asndata.delegated",
                table: "asndata.delegated",
                staging_ddl: "CREATE TABLE asndata.delegated_staging (
                    registry text NOT NULL,
                    country text NOT NULL,
                    record_type text NOT NULL,
                    start text NOT NULL,
                    value text NOT NULL,
                    date text NOT NULL,
                    status text NOT NULL,
                    extensions jsonb,
                    data_as_of timestamptz NOT NULL,
                    source_revision text NOT NULL
                )",
                copy_columns: "registry, country, record_type, start, value, date, status, extensions, data_as_of, source_revision",
                index_ddl: &[
                    "CREATE INDEX delegated_staging_type_registry_idx ON asndata.delegated_staging (record_type, registry)",
                ],
                index_swaps: &[(
                    "asndata.delegated_staging_type_registry_idx",
                    "delegated_type_registry_idx",
                )],
            },
        }
    }

    pub(crate) const fn load_fn(self) -> super::refresh::LoadFn {
        match self {
            Task::Asnames => load_asnames,
            Task::As2org => load_as2org,
            Task::Population => load_population,
            Task::Hegemony => load_hegemony,
            Task::Delegated => load_delegated,
            Task::Allocations => load_allocations,
        }
    }
}

/// Build an `AsInfo` map with the given source flags and return it
/// ASN-sorted. `asnames` is always loaded (it is the base dataset).
fn load_infos(builder: AsInfoBuilder) -> Result<Vec<AsInfo>, String> {
    let utils = builder
        .build()
        .map_err(|e| format!("failed to load asinfo data: {e}"))?;
    let mut infos: Vec<AsInfo> = utils.asinfo_map.into_values().collect();
    infos.sort_by_key(|i| i.asn);
    Ok(infos)
}

fn quoted(value: &str) -> String {
    let mut out = String::with_capacity(value.len() + 2);
    push_csv_field(&mut out, value);
    out
}

fn load_asnames(data_as_of: &str) -> Result<Vec<String>, String> {
    let infos = load_infos(AsInfoBuilder::new())?;
    Ok(infos
        .iter()
        .map(|i| {
            let fields = vec![
                Some(i.name.clone()),
                Some(i.country.clone()),
                Some(data_as_of.to_string()),
                Some(super::refresh::SOURCE_REVISION.to_string()),
            ];
            format!("{},{}", i.asn, build_csv_line(&fields))
        })
        .collect())
}

fn load_as2org(data_as_of: &str) -> Result<Vec<String>, String> {
    let infos = load_infos(AsInfoBuilder::new().with_as2org())?;
    Ok(infos
        .iter()
        .filter_map(|i| {
            let a2o = i.as2org.as_ref()?;
            let fields = vec![
                Some(a2o.name.clone()),
                Some(a2o.country.clone()),
                Some(a2o.org_id.clone()),
                Some(a2o.org_name.clone()),
                Some(data_as_of.to_string()),
                Some(super::refresh::SOURCE_REVISION.to_string()),
            ];
            Some(format!("{},{}", i.asn, build_csv_line(&fields)))
        })
        .collect())
}

fn load_population(data_as_of: &str) -> Result<Vec<String>, String> {
    let infos = load_infos(AsInfoBuilder::new().with_population())?;
    Ok(infos
        .iter()
        .filter_map(|i| {
            let p = i.population.as_ref()?;
            Some(format!(
                "{},{},{},{},{},{},{}",
                i.asn,
                p.user_count,
                p.percent_country,
                p.percent_global,
                p.sample_count,
                quoted(data_as_of),
                quoted(super::refresh::SOURCE_REVISION)
            ))
        })
        .collect())
}

fn load_hegemony(data_as_of: &str) -> Result<Vec<String>, String> {
    let infos = load_infos(AsInfoBuilder::new().with_hegemony())?;
    Ok(infos
        .iter()
        .filter_map(|i| {
            let h = i.hegemony.as_ref()?;
            Some(format!(
                "{},{},{},{},{}",
                i.asn,
                h.ipv4,
                h.ipv6,
                quoted(data_as_of),
                quoted(super::refresh::SOURCE_REVISION)
            ))
        })
        .collect())
}

fn load_delegated(data_as_of: &str) -> Result<Vec<String>, String> {
    let mut lines = Vec::new();
    for url in delegated::RIR_DELEGATED_STATS_URLS {
        let reader = delegated::fetch(url).map_err(|e| format!("failed to fetch {url}: {e}"))?;
        for record in delegated::parse_reader(reader) {
            let record = record.map_err(|e| format!("failed to parse {url}: {e}"))?;
            lines.push(delegated_line(&record, data_as_of));
        }
    }
    // Deterministic row order via the natural column order of the line.
    lines.sort();
    Ok(lines)
}

/// One row per allocation range: the ASN records of the five delegated files, plus the
/// IANA special-purpose table, which no RIR file restates.
///
/// The statuses are the ones [`bgpkit_commons::asinfo::AllocationStatus`] names, so the
/// API can read the verdict without re-deriving it; `available` records are dropped
/// because an absent row already means unallocated.
fn load_allocations(data_as_of: &str) -> Result<Vec<String>, String> {
    let mut lines = Vec::new();
    for url in delegated::RIR_DELEGATED_STATS_URLS {
        let reader = delegated::fetch(url).map_err(|e| format!("failed to fetch {url}: {e}"))?;
        for record in delegated::parse_reader(reader) {
            let record = record.map_err(|e| format!("failed to parse {url}: {e}"))?;
            let Some(status) = allocation_status_of_record(&record) else {
                continue;
            };
            if let Some(line) = allocation_line(&record, status, data_as_of) {
                lines.push(line);
            }
        }
    }
    for (start, end, status) in IANA_SPECIAL_ASN_RANGES {
        lines.push(special_allocation_line(*start, *end, *status, data_as_of));
    }
    // Deterministic row order, and no duplicate rows when two files state one range.
    lines.sort();
    lines.dedup();
    Ok(lines)
}

fn allocation_line(
    record: &DelegatedRecord,
    status: AllocationStatus,
    data_as_of: &str,
) -> Option<String> {
    let start = record.start.trim().parse::<u64>().ok()?;
    let count = record.value.trim().parse::<u64>().ok()?;
    let end = start.checked_add(count.saturating_sub(1))?;
    // `reserved` and `available` records state `*` for the country; it is not a code.
    let country = match record.country.trim() {
        "*" => "",
        other => other,
    };
    let fields = vec![
        Some(start.to_string()),
        Some(end.to_string()),
        Some(status.as_str().to_string()),
        Some(record.registry.trim().to_lowercase()),
        Some(country.to_string()),
        Some(record.date.trim().to_string()),
        Some(data_as_of.to_string()),
        Some(super::refresh::SOURCE_REVISION.to_string()),
    ];
    Some(build_csv_line(&fields))
}

fn special_allocation_line(
    start: u32,
    end: u32,
    status: AllocationStatus,
    data_as_of: &str,
) -> String {
    let fields = vec![
        Some(start.to_string()),
        Some(end.to_string()),
        Some(status.as_str().to_string()),
        Some(String::new()),
        Some(String::new()),
        Some(String::new()),
        Some(data_as_of.to_string()),
        Some(super::refresh::SOURCE_REVISION.to_string()),
    ];
    build_csv_line(&fields)
}

fn delegated_line(record: &DelegatedRecord, data_as_of: &str) -> String {
    let fields = vec![
        Some(record.registry.clone()),
        Some(record.country.clone()),
        Some(record.record_type.clone()),
        Some(record.start.clone()),
        Some(record.value.clone()),
        Some(record.date.clone()),
        Some(record.status.clone()),
        Some(serde_json::to_string(&record.extensions).unwrap_or_default()),
        Some(data_as_of.to_string()),
        Some(super::refresh::SOURCE_REVISION.to_string()),
    ];
    build_csv_line(&fields)
}

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

    #[test]
    fn allocation_lines_cover_ranges_and_drop_the_absent_status() {
        let allocated = DelegatedRecord {
            registry: "APNIC".to_string(),
            country: "JP".to_string(),
            record_type: "asn".to_string(),
            start: "1200".to_string(),
            value: "3".to_string(),
            date: "20240101".to_string(),
            status: "allocated".to_string(),
            extensions: Vec::new(),
        };
        let available = DelegatedRecord {
            status: "available".to_string(),
            country: "*".to_string(),
            ..allocated.clone()
        };
        let reserved = DelegatedRecord {
            status: "reserved".to_string(),
            country: "*".to_string(),
            ..allocated.clone()
        };

        // `available` states no allocation: no row is written for it.
        assert!(allocation_status_of_record(&available).is_none());
        assert_eq!(
            allocation_status_of_record(&reserved),
            Some(AllocationStatus::Reserved)
        );

        let line = allocation_line(
            &allocated,
            AllocationStatus::Allocated,
            "2026-10-23T00:00:00+00:00",
        )
        .unwrap();
        // start,end,status,registry,country,date,data_as_of,revision — the range's last
        // ASN is start + count - 1, and the registry is lowercased like the source.
        assert!(
            line.starts_with("\"1200\",\"1202\",\"allocated\",\"apnic\",\"JP\""),
            "{line}"
        );
        // A reserved record carries `*` for the country, which is not a country code.
        let reserved_line = allocation_line(
            &reserved,
            AllocationStatus::Reserved,
            "2026-10-23T00:00:00+00:00",
        )
        .unwrap();
        assert!(
            reserved_line.contains("\"reserved\",\"apnic\",\"\""),
            "{reserved_line}"
        );
    }

    #[test]
    fn iana_special_rows_are_written_without_a_registry() {
        let line = special_allocation_line(
            64_512,
            65_534,
            AllocationStatus::Private,
            "2026-10-23T00:00:00+00:00",
        );
        assert!(
            line.starts_with("\"64512\",\"65534\",\"private\",\"\",\"\",\"\""),
            "{line}"
        );
        // The table the loader copies is the one the library classifies against.
        assert_eq!(IANA_SPECIAL_ASN_RANGES.len(), 9);
    }

    #[test]
    fn delegated_line_shape() {
        let record = DelegatedRecord {
            registry: "ripencc".to_string(),
            country: "NL".to_string(),
            record_type: "asn".to_string(),
            start: "1".to_string(),
            value: "1".to_string(),
            date: "20240101".to_string(),
            status: "allocated".to_string(),
            extensions: vec!["ext1".to_string()],
        };
        let expected = format!(
            "\"ripencc\",\"NL\",\"asn\",\"1\",\"1\",\"20240101\",\"allocated\",\"[\"\"ext1\"\"]\",\"2026-09-08T00:00:00+00:00\",\"{}\"",
            env!("CARGO_PKG_VERSION")
        );
        assert_eq!(
            delegated_line(&record, "2026-09-08T00:00:00+00:00"),
            expected
        );
    }
}