coip-reader 0.2.0

High-performance read-only reader for COI (.coi) columnar IP databases with projection, LRU caching, and serde support
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
use std::collections::BTreeMap;
use std::net::{IpAddr, Ipv4Addr};

use coip_builder::{
    BuildOptions, CoipBuilder, ImportFormat, ImportOptions, PruneConfig, build_from_mmdb_bytes,
    import_reader,
};
use coip_format::Value;
use coip_reader::Reader;

#[test]
fn test_overlapping_lpm_cidrs_and_explicit_v4_v6_holes() {
    let mut b = CoipBuilder::new(BuildOptions::default());

    let mut r_world = BTreeMap::new();
    r_world.insert("tier".into(), Value::Utf8("world".into()));
    let mut r_ten = BTreeMap::new();
    r_ten.insert("tier".into(), Value::Utf8("ten".into()));
    let mut r_host = BTreeMap::new();
    r_host.insert("tier".into(), Value::Utf8("host_v2".into()));
    let mut r_host_old = BTreeMap::new();
    r_host_old.insert("tier".into(), Value::Utf8("host_v1".into()));

    // Insert in scrambled order to verify LPM is order-independent except for identical-CIDR ties
    b.insert_ipv4_cidr(Ipv4Addr::new(10, 1, 1, 1), 32, r_host_old)
        .unwrap();
    b.insert_ipv4_cidr(Ipv4Addr::new(0, 0, 0, 0), 0, r_world.clone())
        .unwrap();
    b.insert_ipv4_cidr(Ipv4Addr::new(10, 0, 0, 0), 8, r_ten.clone())
        .unwrap();
    b.delete_ipv4_cidr(Ipv4Addr::new(10, 1, 0, 0), 16).unwrap();
    b.insert_ipv4_cidr(Ipv4Addr::new(10, 1, 1, 1), 32, r_host.clone())
        .unwrap();

    // IPv6: broad /32, finer /48, > /64 HostExt override, AND > /64 explicit hole inside /32!
    b.insert_ipv6_cidr("2001:db8::".parse().unwrap(), 32, r_world.clone())
        .unwrap();
    b.insert_ipv6_cidr("2001:db8:1::".parse().unwrap(), 48, r_ten.clone())
        .unwrap();
    b.insert_ipv6_cidr("2001:db8::99".parse().unwrap(), 128, r_host.clone())
        .unwrap();
    b.delete_ipv6_cidr("2001:db8::dead".parse().unwrap(), 128)
        .unwrap();

    let (bytes, _stats) = b.build().unwrap();
    let r = Reader::from_vec(bytes).unwrap();
    r.verify_checksums().unwrap();

    // IPv4 checks
    assert_eq!(
        r.lookup_value(IpAddr::V4(Ipv4Addr::new(8, 8, 8, 8)))
            .unwrap(),
        Some(Value::Map(r_world.clone()))
    );
    assert_eq!(
        r.lookup_value(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5)))
            .unwrap(),
        Some(Value::Map(r_ten.clone()))
    );
    assert_eq!(
        r.lookup_value(IpAddr::V4(Ipv4Addr::new(10, 1, 0, 5)))
            .unwrap(),
        None // explicit /16 hole
    );
    assert_eq!(
        r.lookup_value(IpAddr::V4(Ipv4Addr::new(10, 1, 1, 1)))
            .unwrap(),
        Some(Value::Map(r_host.clone())) // last-insert-wins /32 inside hole
    );
    assert_eq!(
        r.lookup_value(IpAddr::V4(Ipv4Addr::new(10, 2, 0, 1)))
            .unwrap(),
        Some(Value::Map(r_ten.clone()))
    );

    // IPv6 checks
    assert_eq!(
        r.lookup_value(IpAddr::V6("2001:db8::1".parse().unwrap()))
            .unwrap(),
        Some(Value::Map(r_world))
    );
    assert_eq!(
        r.lookup_value(IpAddr::V6("2001:db8:1::1".parse().unwrap()))
            .unwrap(),
        Some(Value::Map(r_ten))
    );
    assert_eq!(
        r.lookup_value(IpAddr::V6("2001:db8::99".parse().unwrap()))
            .unwrap(),
        Some(Value::Map(r_host))
    );
    assert_eq!(
        r.lookup_value(IpAddr::V6("2001:db8::dead".parse().unwrap()))
            .unwrap(),
        None // explicit /128 HostExt hole punching through /32!
    );
}

#[test]
fn test_build_time_pruning_collapses_records_and_transitions() {
    let mut opts = BuildOptions::compact();
    opts.prune = Some(PruneConfig {
        keep_fields: Some(vec!["country.iso_code".into(), "country.name".into()]),
    });

    let mut b = CoipBuilder::new(opts);

    // Two adjacent /24s with DIFFERENT postal codes & geoname_ids, but IDENTICAL country (US) iso_code+name!
    for octet in [0u8, 1u8] {
        let mut m = BTreeMap::new();
        let mut country = BTreeMap::new();
        country.insert("iso_code".into(), Value::Utf8("US".into()));
        country.insert("geoname_id".into(), Value::U32(6252001 + octet as u32));
        country.insert("name".into(), Value::Utf8("United States".into()));
        m.insert("country".into(), Value::Map(country));

        let mut postal = BTreeMap::new();
        postal.insert("code".into(), Value::Utf8(format!("9404{octet}")));
        m.insert("postal".into(), Value::Map(postal));

        b.insert_ipv4_cidr(Ipv4Addr::new(8, 8, octet, 0), 24, m)
            .unwrap();
    }

    let (bytes, stats) = b.build().unwrap();
    // Both /24s collapsed into 1 unique record and 1 contiguous /23 range (+ trailing 0 transition = 2 transitions)!
    assert_eq!(stats.record_count, 1);
    assert_eq!(stats.v4_transitions, 2);

    let r = Reader::from_vec(bytes).unwrap();
    let val = r
        .lookup_value(IpAddr::V4(Ipv4Addr::new(8, 8, 1, 42)))
        .unwrap()
        .unwrap();
    let root = val.as_map().unwrap();
    assert!(!root.contains_key("postal"));
    let c = root["country"].as_map().unwrap();
    assert_eq!(c.get("iso_code"), Some(&Value::Utf8("US".into())));
    assert_eq!(c.get("name"), Some(&Value::Utf8("United States".into())));
    assert!(!c.contains_key("geoname_id"));
}

/// Minimal MMDB v2 encoder helper for deterministic end-to-end `.mmdb -> .coi` tests.
fn mmdb_enc_ctrl(buf: &mut Vec<u8>, typ: u8, size: usize) {
    assert!(size <= 28);
    if typ <= 7 {
        buf.push((typ << 5) | (size as u8));
    } else {
        buf.push(size as u8);
        buf.push(typ - 7);
    }
}

fn mmdb_enc_str(buf: &mut Vec<u8>, s: &str) {
    mmdb_enc_ctrl(buf, 2, s.len());
    buf.extend_from_slice(s.as_bytes());
}

fn mmdb_enc_u16(buf: &mut Vec<u8>, v: u16) {
    if v == 0 {
        mmdb_enc_ctrl(buf, 5, 0);
    } else if v <= 0xFF {
        mmdb_enc_ctrl(buf, 5, 1);
        buf.push(v as u8);
    } else {
        mmdb_enc_ctrl(buf, 5, 2);
        buf.extend_from_slice(&v.to_be_bytes());
    }
}

fn mmdb_enc_u32(buf: &mut Vec<u8>, v: u32) {
    let bytes = v.to_be_bytes();
    let first_nz = bytes.iter().position(|&b| b != 0).unwrap_or(4);
    let slice = &bytes[first_nz..];
    mmdb_enc_ctrl(buf, 6, slice.len());
    buf.extend_from_slice(slice);
}

fn mmdb_enc_map(buf: &mut Vec<u8>, entries: &[(&str, Vec<u8>)]) {
    mmdb_enc_ctrl(buf, 7, entries.len());
    for (k, v_bytes) in entries {
        mmdb_enc_str(buf, k);
        buf.extend_from_slice(v_bytes);
    }
}

fn mmdb_enc_array(buf: &mut Vec<u8>, items: &[Vec<u8>]) {
    mmdb_enc_ctrl(buf, 11, items.len());
    for item in items {
        buf.extend_from_slice(item);
    }
}

fn mmdb_val_str(s: &str) -> Vec<u8> {
    let mut b = Vec::new();
    mmdb_enc_str(&mut b, s);
    b
}

fn mmdb_val_u16(v: u16) -> Vec<u8> {
    let mut b = Vec::new();
    mmdb_enc_u16(&mut b, v);
    b
}

fn mmdb_val_u32(v: u32) -> Vec<u8> {
    let mut b = Vec::new();
    mmdb_enc_u32(&mut b, v);
    b
}

#[test]
fn test_mmdb_to_coi_simplifies_names_to_en_name_and_deduplicates() {
    // Build a minimal valid IPv4 MMDB v2 (record_size=24, node_count=2):
    // - 0.0.0.0/2   -> rec_a: Singapore (en="Singapore", zh-CN="新加坡A")
    // - 64.0.0.0/2  -> rec_b: Singapore (en="Singapore", zh-CN="新加坡B")  [dedups with rec_a!]
    // - 128.0.0.0/1 -> rec_c: city.names has NO "en" (omits city.name), subdivisions[0].names has "en"
    let mut data = Vec::new();

    let off_a = data.len() as u32;
    {
        let mut city_names = Vec::new();
        mmdb_enc_map(
            &mut city_names,
            &[
                ("en", mmdb_val_str("Singapore")),
                ("zh-CN", mmdb_val_str("新加坡A")),
            ],
        );
        let mut city = Vec::new();
        mmdb_enc_map(
            &mut city,
            &[("geoname_id", mmdb_val_u32(1880252)), ("names", city_names)],
        );

        let mut country_names = Vec::new();
        mmdb_enc_map(
            &mut country_names,
            &[
                ("de", mmdb_val_str("Singapur")),
                ("en", mmdb_val_str("Singapore")),
            ],
        );
        let mut country = Vec::new();
        mmdb_enc_map(
            &mut country,
            &[
                ("geoname_id", mmdb_val_u32(1880251)),
                ("iso_code", mmdb_val_str("SG")),
                ("names", country_names),
            ],
        );
        mmdb_enc_map(&mut data, &[("city", city), ("country", country)]);
    }

    let off_b = data.len() as u32;
    {
        let mut city_names = Vec::new();
        mmdb_enc_map(
            &mut city_names,
            &[
                ("en", mmdb_val_str("Singapore")),
                ("zh-CN", mmdb_val_str("新加坡B")),
            ],
        );
        let mut city = Vec::new();
        mmdb_enc_map(
            &mut city,
            &[("geoname_id", mmdb_val_u32(1880252)), ("names", city_names)],
        );

        let mut country_names = Vec::new();
        mmdb_enc_map(
            &mut country_names,
            &[
                ("en", mmdb_val_str("Singapore")),
                ("fr", mmdb_val_str("Singapour")),
            ],
        );
        let mut country = Vec::new();
        mmdb_enc_map(
            &mut country,
            &[
                ("geoname_id", mmdb_val_u32(1880251)),
                ("iso_code", mmdb_val_str("SG")),
                ("names", country_names),
            ],
        );
        mmdb_enc_map(&mut data, &[("city", city), ("country", country)]);
    }

    let off_c = data.len() as u32;
    {
        let mut city_names = Vec::new();
        mmdb_enc_map(&mut city_names, &[("zh-CN", mmdb_val_str("仅中文城市"))]);
        let mut city = Vec::new();
        mmdb_enc_map(
            &mut city,
            &[("geoname_id", mmdb_val_u32(999)), ("names", city_names)],
        );

        let mut sub_names = Vec::new();
        mmdb_enc_map(
            &mut sub_names,
            &[
                ("en", mmdb_val_str("Central")),
                ("zh-CN", mmdb_val_str("中部")),
            ],
        );
        let mut sub0 = Vec::new();
        mmdb_enc_map(
            &mut sub0,
            &[("iso_code", mmdb_val_str("C1")), ("names", sub_names)],
        );
        let mut subs = Vec::new();
        mmdb_enc_array(&mut subs, &[sub0]);

        mmdb_enc_map(&mut data, &[("city", city), ("subdivisions", subs)]);
    }

    let node_count = 2u32;
    let ptr = |off: u32| -> [u8; 3] {
        let v = node_count + 16 + off;
        [(v >> 16) as u8, (v >> 8) as u8, v as u8]
    };

    let mut mmdb = Vec::new();
    // Node 0: left -> node 1, right -> rec_c
    mmdb.extend_from_slice(&[0, 0, 1]);
    mmdb.extend_from_slice(&ptr(off_c));
    // Node 1: left -> rec_a, right -> rec_b
    mmdb.extend_from_slice(&ptr(off_a));
    mmdb.extend_from_slice(&ptr(off_b));
    // 16-byte separator
    mmdb.extend_from_slice(&[0u8; 16]);
    // Data section
    mmdb.extend_from_slice(&data);
    // Metadata marker + metadata map
    mmdb.extend_from_slice(b"\xab\xcd\xefMaxMind.com");
    let mut desc = Vec::new();
    mmdb_enc_map(
        &mut desc,
        &[
            ("en", mmdb_val_str("Test City DB")),
            ("zh-CN", mmdb_val_str("测试城市库")),
        ],
    );
    let mut langs = Vec::new();
    mmdb_enc_array(
        &mut langs,
        &[
            mmdb_val_str("de"),
            mmdb_val_str("en"),
            mmdb_val_str("zh-CN"),
        ],
    );
    mmdb_enc_map(
        &mut mmdb,
        &[
            ("binary_format_major_version", mmdb_val_u16(2)),
            ("binary_format_minor_version", mmdb_val_u16(0)),
            ("database_type", mmdb_val_str("GeoIP2-City")),
            ("description", desc),
            ("ip_version", mmdb_val_u16(4)),
            ("languages", langs),
            ("node_count", mmdb_val_u32(node_count)),
            ("record_size", mmdb_val_u16(24)),
        ],
    );

    let (coi_bytes, stats) = build_from_mmdb_bytes(&mmdb, &BuildOptions::compact()).unwrap();
    // rec_a and rec_b collapsed into 1 unique record -> total 2 unique records!
    assert_eq!(stats.record_count, 2);
    // 0.0.0.0/2 + 64.0.0.0/2 merged into 0.0.0.0/1, plus 128.0.0.0/1 -> only 2 transitions!
    assert_eq!(stats.v4_transitions, 2);

    let reader = Reader::from_vec(coi_bytes).unwrap();
    reader.verify_checksums().unwrap();

    // Metadata omits `languages` and flattens `description` to `"en"` string
    assert!(reader.metadata().get("languages").is_none());
    assert_eq!(
        reader.metadata().get("description"),
        Some(&serde_json::json!("Test City DB"))
    );

    // 1.2.3.4 (rec_a) and 65.2.3.4 (rec_b) produce identical simplified records
    let r1 = reader
        .lookup_value(IpAddr::V4(Ipv4Addr::new(1, 2, 3, 4)))
        .unwrap()
        .unwrap();
    let r2 = reader
        .lookup_value(IpAddr::V4(Ipv4Addr::new(65, 2, 3, 4)))
        .unwrap()
        .unwrap();
    assert!(r1.bit_eq(&r2));
    let m1 = r1.as_map().unwrap();
    let city1 = m1["city"].as_map().unwrap();
    assert!(!city1.contains_key("names"));
    assert_eq!(city1.get("geoname_id"), Some(&Value::U32(1880252)));
    assert_eq!(city1.get("name"), Some(&Value::Utf8("Singapore".into())));
    let country1 = m1["country"].as_map().unwrap();
    assert!(!country1.contains_key("names"));
    assert_eq!(country1.get("iso_code"), Some(&Value::Utf8("SG".into())));
    assert_eq!(country1.get("name"), Some(&Value::Utf8("Singapore".into())));

    // 200.1.2.3 (rec_c): city has no "en" -> no "name" and no "names"; subdivisions[0] gets "name"
    let r3 = reader
        .lookup_value(IpAddr::V4(Ipv4Addr::new(200, 1, 2, 3)))
        .unwrap()
        .unwrap();
    let m3 = r3.as_map().unwrap();
    let city3 = m3["city"].as_map().unwrap();
    assert!(!city3.contains_key("names"));
    assert!(!city3.contains_key("name"));
    assert_eq!(city3.get("geoname_id"), Some(&Value::U32(999)));
    let subs3 = m3["subdivisions"].as_array().unwrap();
    let sub0 = subs3[0].as_map().unwrap();
    assert!(!sub0.contains_key("names"));
    assert_eq!(sub0.get("name"), Some(&Value::Utf8("Central".into())));
}

#[test]
fn test_jsonl_and_csv_import_and_range_scanning() {
    // 1. JSONL with CIDR, single IP, overlapping LPM, and nested objects
    let jsonl = r#"
{"cidr": "192.0.2.0/24", "asn": 64500, "org": "Example Net", "tags": ["isp", "v4"]}
{"cidr": "192.0.2.10", "asn": 64501, "org": "Special Host", "tags": ["vip"]}
{"cidr": "2001:db8:abcd::/48", "asn": 64502, "org": "V6 Corp"}
"#;
    let (jsonl_coi, _) = import_reader(
        jsonl.as_bytes(),
        &ImportOptions {
            format: ImportFormat::Jsonl,
            database_type: Some("Custom-ASN".into()),
            ..ImportOptions::default()
        },
    )
    .unwrap();
    let jr = Reader::from_vec(jsonl_coi).unwrap();
    jr.verify_checksums().unwrap();
    assert_eq!(jr.ipv4_ranges().unwrap().len(), 3); // split around 192.0.2.10!
    assert_eq!(jr.ipv6_ranges().unwrap().len(), 1);
    let v_host = jr
        .lookup_value(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 10)))
        .unwrap()
        .unwrap();
    assert_eq!(
        v_host.as_map().unwrap().get("asn"),
        Some(&Value::I64(64501))
    );
    let v_other = jr
        .lookup_value(IpAddr::V4(Ipv4Addr::new(192, 0, 2, 11)))
        .unwrap()
        .unwrap();
    assert_eq!(
        v_other.as_map().unwrap().get("asn"),
        Some(&Value::I64(64500))
    );

    // 2. CSV with start_ip/end_ip ranges, dot-key unflattening, leading-zero postal preservation, IPv4-only
    let csv_data = "\
start_ip,end_ip,country.iso_code,postal.code,asn,is_proxy,location.latitude
10.0.0.1,10.0.0.10,US,01001,15169,false,42.0654
10.0.0.11,10.0.0.20,US,02108,13335,true,42.3584
";
    let (csv_coi, _) = import_reader(
        csv_data.as_bytes(),
        &ImportOptions {
            format: ImportFormat::Csv,
            ..ImportOptions::default()
        },
    )
    .unwrap();
    let cr = Reader::from_vec(csv_coi).unwrap();
    cr.verify_checksums().unwrap();
    assert!(cr.header().has_ipv4());
    assert!(!cr.header().has_ipv6()); // Pure IPv4-only DB!
    let rec = cr
        .lookup_value(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 5)))
        .unwrap()
        .unwrap();
    let rm = rec.as_map().unwrap();
    assert_eq!(
        rm["postal"].as_map().unwrap().get("code"),
        Some(&Value::Utf8("01001".into())) // Leading zero preserved as Utf8!
    );
    assert_eq!(rm.get("asn"), Some(&Value::U32(15169)));
    assert_eq!(rm.get("is_proxy"), Some(&Value::Bool(false)));
    assert_eq!(
        rm["location"].as_map().unwrap().get("latitude"),
        Some(&Value::F64(42.0654))
    );
    assert_eq!(
        cr.lookup_value(IpAddr::V4(Ipv4Addr::new(10, 0, 0, 21)))
            .unwrap(),
        None
    );
}