coip-builder 0.1.0

Generic columnar .coi builder and 100% lossless MaxMind .mmdb importer
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
//! Generic JSONL and CSV importers for building arbitrary `.coi` databases from custom data sources.

use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Read};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::Path;

use coip_format::Value;

use crate::builder::{BuildOptions, BuildStats, CoipBuilder};
use crate::error::{BuilderError, Result};

/// Input data format for `coip import`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportFormat {
    Jsonl,
    Csv,
}

/// Configuration options for importing JSONL or CSV datasets into `.coi`.
#[derive(Debug, Clone)]
pub struct ImportOptions {
    pub format: ImportFormat,
    /// Name of the CIDR/IP column or JSON key (defaults to `"cidr"`, or auto-detects `"network"`/`"ip"` in CSV).
    pub cidr_field: Option<String>,
    /// Optional end-IP column/key when input specifies inclusive `[start_ip, end_ip]` ranges instead of CIDRs.
    pub end_ip_field: Option<String>,
    /// Unflatten dot-separated CSV column names (e.g. `country.iso_code`) into nested structs (default `true`).
    pub unflatten_dots: bool,
    /// Optional database_type label stored in Metadata.
    pub database_type: Option<String>,
    /// Build options (profile, compression, pruning, row ordering, etc.).
    pub build_options: BuildOptions,
}

impl Default for ImportOptions {
    fn default() -> Self {
        Self {
            format: ImportFormat::Jsonl,
            cidr_field: None,
            end_ip_field: None,
            unflatten_dots: true,
            database_type: None,
            build_options: BuildOptions::default(),
        }
    }
}

/// Parse either a CIDR (`"1.2.3.0/24"`, `"2001:db8::/32"`) or single IP (`"8.8.8.8"`, `"2001:db8::1"`).
pub fn parse_cidr_or_ip(raw: &str) -> Result<(IpAddr, u8)> {
    let s = raw.trim();
    if let Some((ip_part, len_part)) = s.split_once('/') {
        let addr: IpAddr = ip_part
            .trim()
            .parse()
            .map_err(|_| BuilderError::InvalidInput(format!("invalid IP in CIDR '{s}'")))?;
        let prefix_len: u8 = len_part
            .trim()
            .parse()
            .map_err(|_| BuilderError::InvalidInput(format!("invalid prefix length in '{s}'")))?;
        let max_len = match addr {
            IpAddr::V4(_) => 32,
            IpAddr::V6(_) => 128,
        };
        if prefix_len > max_len {
            return Err(BuilderError::InvalidInput(format!(
                "prefix length {prefix_len} exceeds {max_len} in '{s}'"
            )));
        }
        Ok((addr, prefix_len))
    } else {
        let addr: IpAddr = s
            .parse()
            .map_err(|_| BuilderError::InvalidInput(format!("invalid IP address '{s}'")))?;
        let prefix_len = match addr {
            IpAddr::V4(_) => 32,
            IpAddr::V6(_) => 128,
        };
        Ok((addr, prefix_len))
    }
}

/// Import a JSONL or CSV file on disk directly into a `.coi` file on disk.
pub fn import_file_to_coi(
    src: impl AsRef<Path>,
    dst: impl AsRef<Path>,
    options: &ImportOptions,
) -> Result<BuildStats> {
    let file = std::fs::File::open(src)?;
    let (bytes, stats) = import_reader(file, options)?;
    std::fs::write(dst, &bytes)?;
    Ok(stats)
}

/// Import from any `Read` stream into `.coi` bytes.
pub fn import_reader<R: Read>(reader: R, options: &ImportOptions) -> Result<(Vec<u8>, BuildStats)> {
    match options.format {
        ImportFormat::Jsonl => import_jsonl(reader, options),
        ImportFormat::Csv => import_csv(reader, options),
    }
}

fn import_jsonl<R: Read>(reader: R, options: &ImportOptions) -> Result<(Vec<u8>, BuildStats)> {
    let mut builder = CoipBuilder::new(options.build_options.clone());
    builder.set_metadata_field("source_format", serde_json::Value::String("jsonl".into()));
    if let Some(db_type) = &options.database_type {
        builder.set_metadata_field("database_type", serde_json::Value::String(db_type.clone()));
    }

    let cidr_key = options.cidr_field.as_deref().unwrap_or("cidr");
    let end_key = options.end_ip_field.as_deref();

    let buf = BufReader::new(reader);
    for (line_no, line_res) in buf.lines().enumerate() {
        let line = line_res?;
        let trimmed = line.trim();
        if trimmed.is_empty() || trimmed.starts_with('#') {
            continue;
        }
        let val: serde_json::Value = serde_json::from_str(trimmed)
            .map_err(|e| BuilderError::InvalidInput(format!("JSONL line {}: {e}", line_no + 1)))?;
        let mut obj = match val {
            serde_json::Value::Object(m) => m,
            _ => {
                return Err(BuilderError::InvalidInput(format!(
                    "JSONL line {} is not a JSON object",
                    line_no + 1
                )));
            }
        };

        let start_str = obj
            .remove(cidr_key)
            .and_then(|v| v.as_str().map(str::to_owned))
            .ok_or_else(|| {
                BuilderError::InvalidInput(format!(
                    "JSONL line {} missing string key '{cidr_key}'",
                    line_no + 1
                ))
            })?;

        let end_str = match end_key {
            Some(ek) => obj.remove(ek).and_then(|v| v.as_str().map(str::to_owned)),
            None => None,
        };

        let mut rec = BTreeMap::new();
        for (k, v) in obj {
            if !v.is_null() {
                rec.insert(k, json_to_coi_value(v));
            }
        }

        if let Some(es) = end_str {
            insert_ip_range_str(&mut builder, &start_str, &es, rec)?;
        } else {
            let (addr, prefix_len) = parse_cidr_or_ip(&start_str)?;
            match addr {
                IpAddr::V4(v4) => {
                    builder.insert_ipv4_cidr(v4, prefix_len, rec)?;
                }
                IpAddr::V6(v6) => {
                    builder.insert_ipv6_cidr(v6, prefix_len, rec)?;
                }
            }
        }
    }

    builder.build()
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum CsvColKind {
    Bool,
    U32,
    I64,
    F64,
    Utf8,
}

fn has_leading_zero_number(s: &str) -> bool {
    let digits = s.strip_prefix('-').unwrap_or(s);
    digits.len() > 1 && digits.starts_with('0') && !digits.starts_with("0.")
}

fn infer_csv_col_kind(cells: &[&str]) -> CsvColKind {
    let mut non_empty = 0usize;
    let mut all_bool = true;
    let mut all_u32 = true;
    let mut all_i64 = true;
    let mut all_f64 = true;

    for &raw in cells {
        let s = raw.trim();
        if s.is_empty() {
            continue;
        }
        non_empty += 1;
        if all_bool && !matches!(s, "true" | "false" | "TRUE" | "FALSE") {
            all_bool = false;
        }
        if has_leading_zero_number(s) {
            all_u32 = false;
            all_i64 = false;
            all_f64 = false;
        } else {
            if all_u32 && s.parse::<u32>().is_err() {
                all_u32 = false;
            }
            if all_i64 && s.parse::<i64>().is_err() {
                all_i64 = false;
            }
            if all_f64 {
                match s.parse::<f64>() {
                    Ok(v) if v.is_finite() => {}
                    _ => all_f64 = false,
                }
            }
        }
    }

    if non_empty == 0 {
        return CsvColKind::Utf8;
    }
    if all_bool {
        CsvColKind::Bool
    } else if all_u32 {
        CsvColKind::U32
    } else if all_i64 {
        CsvColKind::I64
    } else if all_f64 {
        CsvColKind::F64
    } else {
        CsvColKind::Utf8
    }
}

fn import_csv<R: Read>(reader: R, options: &ImportOptions) -> Result<(Vec<u8>, BuildStats)> {
    let mut rdr = csv::ReaderBuilder::new()
        .has_headers(true)
        .flexible(true)
        .from_reader(reader);

    let headers: Vec<String> = rdr
        .headers()
        .map_err(|e| BuilderError::InvalidInput(format!("CSV header error: {e}")))?
        .iter()
        .map(|s| s.trim().trim_start_matches('\u{feff}').to_owned())
        .collect();
    if headers.is_empty() {
        return Err(BuilderError::InvalidInput(
            "CSV has empty header row".into(),
        ));
    }

    // Locate CIDR/start_ip column
    let cidr_idx = if let Some(ref name) = options.cidr_field {
        headers.iter().position(|h| h == name).ok_or_else(|| {
            BuilderError::InvalidInput(format!("CSV missing CIDR column '{name}'"))
        })?
    } else {
        headers
            .iter()
            .position(|h| matches!(h.as_str(), "cidr" | "network" | "ip" | "start_ip"))
            .unwrap_or(0)
    };

    let end_idx = match &options.end_ip_field {
        Some(name) => Some(headers.iter().position(|h| h == name).ok_or_else(|| {
            BuilderError::InvalidInput(format!("CSV missing end_ip column '{name}'"))
        })?),
        None => headers.iter().position(|h| h == "end_ip"),
    };

    // Read all rows so we can infer homogeneous column types cleanly across the entire CSV.
    let mut rows: Vec<csv::StringRecord> = Vec::new();
    for rec in rdr.records() {
        let r = rec.map_err(|e| BuilderError::InvalidInput(format!("CSV row error: {e}")))?;
        rows.push(r);
    }

    let mut col_kinds = vec![CsvColKind::Utf8; headers.len()];
    for (col, kind_slot) in col_kinds.iter_mut().enumerate().take(headers.len()) {
        if col == cidr_idx || Some(col) == end_idx {
            continue;
        }
        let cells: Vec<&str> = rows.iter().map(|r| r.get(col).unwrap_or("")).collect();
        *kind_slot = infer_csv_col_kind(&cells);
    }

    let mut builder = CoipBuilder::new(options.build_options.clone());
    builder.set_metadata_field("source_format", serde_json::Value::String("csv".into()));
    if let Some(db_type) = &options.database_type {
        builder.set_metadata_field("database_type", serde_json::Value::String(db_type.clone()));
    }

    for (row_no, row) in rows.iter().enumerate() {
        let start_str = row.get(cidr_idx).unwrap_or("").trim();
        if start_str.is_empty() {
            continue;
        }
        let end_str = end_idx.map(|i| row.get(i).unwrap_or("").trim());

        let mut rec = BTreeMap::new();
        for (col, hname) in headers.iter().enumerate() {
            if col == cidr_idx || Some(col) == end_idx || hname.is_empty() {
                continue;
            }
            let cell = row.get(col).unwrap_or("").trim();
            if cell.is_empty() {
                continue;
            }
            let val = match col_kinds[col] {
                CsvColKind::Bool => Value::Bool(matches!(cell, "true" | "TRUE")),
                CsvColKind::U32 => Value::U32(cell.parse::<u32>().unwrap()),
                CsvColKind::I64 => Value::I64(cell.parse::<i64>().unwrap()),
                CsvColKind::F64 => Value::F64(cell.parse::<f64>().unwrap()),
                CsvColKind::Utf8 => Value::Utf8(cell.to_owned()),
            };
            if options.unflatten_dots && hname.contains('.') {
                let segs: Vec<&str> = hname.split('.').collect();
                insert_nested_field(&mut rec, &segs, val);
            } else {
                rec.insert(hname.clone(), val);
            }
        }

        if let Some(es) = end_str.filter(|s| !s.is_empty()) {
            insert_ip_range_str(&mut builder, start_str, es, rec)
                .map_err(|e| BuilderError::InvalidInput(format!("CSV row {}: {e}", row_no + 2)))?;
        } else {
            let (addr, prefix_len) = parse_cidr_or_ip(start_str)
                .map_err(|e| BuilderError::InvalidInput(format!("CSV row {}: {e}", row_no + 2)))?;
            match addr {
                IpAddr::V4(v4) => {
                    builder.insert_ipv4_cidr(v4, prefix_len, rec)?;
                }
                IpAddr::V6(v6) => {
                    builder.insert_ipv6_cidr(v6, prefix_len, rec)?;
                }
            }
        }
    }

    builder.build()
}

fn insert_ip_range_str(
    builder: &mut CoipBuilder,
    start_str: &str,
    end_str: &str,
    rec: BTreeMap<String, Value>,
) -> Result<()> {
    let s_addr: IpAddr = start_str
        .trim()
        .parse()
        .map_err(|_| BuilderError::InvalidInput(format!("invalid start_ip '{start_str}'")))?;
    let e_addr: IpAddr = end_str
        .trim()
        .parse()
        .map_err(|_| BuilderError::InvalidInput(format!("invalid end_ip '{end_str}'")))?;
    match (s_addr, e_addr) {
        (IpAddr::V4(s), IpAddr::V4(e)) => {
            builder.insert_ipv4_range(s, e, rec)?;
            Ok(())
        }
        (IpAddr::V6(s), IpAddr::V6(e)) => {
            builder.insert_ipv6_range(s, e, rec)?;
            Ok(())
        }
        _ => Err(BuilderError::InvalidInput(format!(
            "mismatched IP versions in range '{start_str}'..='{end_str}'"
        ))),
    }
}

fn insert_nested_field(map: &mut BTreeMap<String, Value>, segs: &[&str], val: Value) {
    if segs.len() == 1 {
        map.insert(segs[0].to_owned(), val);
        return;
    }
    let entry = map
        .entry(segs[0].to_owned())
        .or_insert_with(|| Value::Map(BTreeMap::new()));
    if let Value::Map(sub) = entry {
        insert_nested_field(sub, &segs[1..], val);
    }
}

fn json_to_coi_value(v: serde_json::Value) -> Value {
    match v {
        serde_json::Value::Null => Value::Null,
        serde_json::Value::Bool(b) => Value::Bool(b),
        serde_json::Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                Value::I64(i)
            } else if let Some(u) = n.as_u64() {
                Value::U64(u)
            } else {
                Value::F64(n.as_f64().unwrap_or(0.0))
            }
        }
        serde_json::Value::String(s) => Value::Utf8(s),
        serde_json::Value::Array(arr) => {
            Value::Array(arr.into_iter().map(json_to_coi_value).collect())
        }
        serde_json::Value::Object(m) => {
            let mut out = BTreeMap::new();
            for (k, val) in m {
                if !val.is_null() {
                    out.insert(k, json_to_coi_value(val));
                }
            }
            Value::Map(out)
        }
    }
}

/// Convenience helper for `Ipv4Addr` / `Ipv6Addr` exports.
pub fn format_cidr_v4(net: u32, prefix_len: u8) -> String {
    format!("{}/{prefix_len}", Ipv4Addr::from(net))
}

pub fn format_cidr_v6(net: u128, prefix_len: u8) -> String {
    format!("{}/{prefix_len}", Ipv6Addr::from(net))
}