Skip to main content

coip_builder/
import.rs

1//! Generic JSONL and CSV importers for building arbitrary `.coi` databases from custom data sources.
2
3use std::collections::BTreeMap;
4use std::io::{BufRead, BufReader, Read};
5use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
6use std::path::Path;
7
8use coip_format::Value;
9
10use crate::builder::{BuildOptions, BuildStats, CoipBuilder};
11use crate::error::{BuilderError, Result};
12
13/// Input data format for `coip import`.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ImportFormat {
16    Jsonl,
17    Csv,
18}
19
20/// Configuration options for importing JSONL or CSV datasets into `.coi`.
21#[derive(Debug, Clone)]
22pub struct ImportOptions {
23    pub format: ImportFormat,
24    /// Name of the CIDR/IP column or JSON key (defaults to `"cidr"`, or auto-detects `"network"`/`"ip"` in CSV).
25    pub cidr_field: Option<String>,
26    /// Optional end-IP column/key when input specifies inclusive `[start_ip, end_ip]` ranges instead of CIDRs.
27    pub end_ip_field: Option<String>,
28    /// Unflatten dot-separated CSV column names (e.g. `country.iso_code`) into nested structs (default `true`).
29    pub unflatten_dots: bool,
30    /// Optional database_type label stored in Metadata.
31    pub database_type: Option<String>,
32    /// Build options (profile, compression, pruning, row ordering, etc.).
33    pub build_options: BuildOptions,
34}
35
36impl Default for ImportOptions {
37    fn default() -> Self {
38        Self {
39            format: ImportFormat::Jsonl,
40            cidr_field: None,
41            end_ip_field: None,
42            unflatten_dots: true,
43            database_type: None,
44            build_options: BuildOptions::default(),
45        }
46    }
47}
48
49/// Parse either a CIDR (`"1.2.3.0/24"`, `"2001:db8::/32"`) or single IP (`"8.8.8.8"`, `"2001:db8::1"`).
50pub fn parse_cidr_or_ip(raw: &str) -> Result<(IpAddr, u8)> {
51    let s = raw.trim();
52    if let Some((ip_part, len_part)) = s.split_once('/') {
53        let addr: IpAddr = ip_part
54            .trim()
55            .parse()
56            .map_err(|_| BuilderError::InvalidInput(format!("invalid IP in CIDR '{s}'")))?;
57        let prefix_len: u8 = len_part
58            .trim()
59            .parse()
60            .map_err(|_| BuilderError::InvalidInput(format!("invalid prefix length in '{s}'")))?;
61        let max_len = match addr {
62            IpAddr::V4(_) => 32,
63            IpAddr::V6(_) => 128,
64        };
65        if prefix_len > max_len {
66            return Err(BuilderError::InvalidInput(format!(
67                "prefix length {prefix_len} exceeds {max_len} in '{s}'"
68            )));
69        }
70        Ok((addr, prefix_len))
71    } else {
72        let addr: IpAddr = s
73            .parse()
74            .map_err(|_| BuilderError::InvalidInput(format!("invalid IP address '{s}'")))?;
75        let prefix_len = match addr {
76            IpAddr::V4(_) => 32,
77            IpAddr::V6(_) => 128,
78        };
79        Ok((addr, prefix_len))
80    }
81}
82
83/// Import a JSONL or CSV file on disk directly into a `.coi` file on disk.
84pub fn import_file_to_coi(
85    src: impl AsRef<Path>,
86    dst: impl AsRef<Path>,
87    options: &ImportOptions,
88) -> Result<BuildStats> {
89    let file = std::fs::File::open(src)?;
90    let (bytes, stats) = import_reader(file, options)?;
91    std::fs::write(dst, &bytes)?;
92    Ok(stats)
93}
94
95/// Import from any `Read` stream into `.coi` bytes.
96pub fn import_reader<R: Read>(reader: R, options: &ImportOptions) -> Result<(Vec<u8>, BuildStats)> {
97    match options.format {
98        ImportFormat::Jsonl => import_jsonl(reader, options),
99        ImportFormat::Csv => import_csv(reader, options),
100    }
101}
102
103fn import_jsonl<R: Read>(reader: R, options: &ImportOptions) -> Result<(Vec<u8>, BuildStats)> {
104    let mut builder = CoipBuilder::new(options.build_options.clone());
105    builder.set_metadata_field("source_format", serde_json::Value::String("jsonl".into()));
106    if let Some(db_type) = &options.database_type {
107        builder.set_metadata_field("database_type", serde_json::Value::String(db_type.clone()));
108    }
109
110    let cidr_key = options.cidr_field.as_deref().unwrap_or("cidr");
111    let end_key = options.end_ip_field.as_deref();
112
113    let buf = BufReader::new(reader);
114    for (line_no, line_res) in buf.lines().enumerate() {
115        let line = line_res?;
116        let trimmed = line.trim();
117        if trimmed.is_empty() || trimmed.starts_with('#') {
118            continue;
119        }
120        let val: serde_json::Value = serde_json::from_str(trimmed)
121            .map_err(|e| BuilderError::InvalidInput(format!("JSONL line {}: {e}", line_no + 1)))?;
122        let mut obj = match val {
123            serde_json::Value::Object(m) => m,
124            _ => {
125                return Err(BuilderError::InvalidInput(format!(
126                    "JSONL line {} is not a JSON object",
127                    line_no + 1
128                )));
129            }
130        };
131
132        let start_str = obj
133            .remove(cidr_key)
134            .and_then(|v| v.as_str().map(str::to_owned))
135            .ok_or_else(|| {
136                BuilderError::InvalidInput(format!(
137                    "JSONL line {} missing string key '{cidr_key}'",
138                    line_no + 1
139                ))
140            })?;
141
142        let end_str = match end_key {
143            Some(ek) => obj.remove(ek).and_then(|v| v.as_str().map(str::to_owned)),
144            None => None,
145        };
146
147        let mut rec = BTreeMap::new();
148        for (k, v) in obj {
149            if !v.is_null() {
150                rec.insert(k, json_to_coi_value(v));
151            }
152        }
153
154        if let Some(es) = end_str {
155            insert_ip_range_str(&mut builder, &start_str, &es, rec)?;
156        } else {
157            let (addr, prefix_len) = parse_cidr_or_ip(&start_str)?;
158            match addr {
159                IpAddr::V4(v4) => {
160                    builder.insert_ipv4_cidr(v4, prefix_len, rec)?;
161                }
162                IpAddr::V6(v6) => {
163                    builder.insert_ipv6_cidr(v6, prefix_len, rec)?;
164                }
165            }
166        }
167    }
168
169    builder.build()
170}
171
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173enum CsvColKind {
174    Bool,
175    U32,
176    I64,
177    F64,
178    Utf8,
179}
180
181fn has_leading_zero_number(s: &str) -> bool {
182    let digits = s.strip_prefix('-').unwrap_or(s);
183    digits.len() > 1 && digits.starts_with('0') && !digits.starts_with("0.")
184}
185
186fn infer_csv_col_kind(cells: &[&str]) -> CsvColKind {
187    let mut non_empty = 0usize;
188    let mut all_bool = true;
189    let mut all_u32 = true;
190    let mut all_i64 = true;
191    let mut all_f64 = true;
192
193    for &raw in cells {
194        let s = raw.trim();
195        if s.is_empty() {
196            continue;
197        }
198        non_empty += 1;
199        if all_bool && !matches!(s, "true" | "false" | "TRUE" | "FALSE") {
200            all_bool = false;
201        }
202        if has_leading_zero_number(s) {
203            all_u32 = false;
204            all_i64 = false;
205            all_f64 = false;
206        } else {
207            if all_u32 && s.parse::<u32>().is_err() {
208                all_u32 = false;
209            }
210            if all_i64 && s.parse::<i64>().is_err() {
211                all_i64 = false;
212            }
213            if all_f64 {
214                match s.parse::<f64>() {
215                    Ok(v) if v.is_finite() => {}
216                    _ => all_f64 = false,
217                }
218            }
219        }
220    }
221
222    if non_empty == 0 {
223        return CsvColKind::Utf8;
224    }
225    if all_bool {
226        CsvColKind::Bool
227    } else if all_u32 {
228        CsvColKind::U32
229    } else if all_i64 {
230        CsvColKind::I64
231    } else if all_f64 {
232        CsvColKind::F64
233    } else {
234        CsvColKind::Utf8
235    }
236}
237
238fn import_csv<R: Read>(reader: R, options: &ImportOptions) -> Result<(Vec<u8>, BuildStats)> {
239    let mut rdr = csv::ReaderBuilder::new()
240        .has_headers(true)
241        .flexible(true)
242        .from_reader(reader);
243
244    let headers: Vec<String> = rdr
245        .headers()
246        .map_err(|e| BuilderError::InvalidInput(format!("CSV header error: {e}")))?
247        .iter()
248        .map(|s| s.trim().trim_start_matches('\u{feff}').to_owned())
249        .collect();
250    if headers.is_empty() {
251        return Err(BuilderError::InvalidInput(
252            "CSV has empty header row".into(),
253        ));
254    }
255
256    // Locate CIDR/start_ip column
257    let cidr_idx = if let Some(ref name) = options.cidr_field {
258        headers.iter().position(|h| h == name).ok_or_else(|| {
259            BuilderError::InvalidInput(format!("CSV missing CIDR column '{name}'"))
260        })?
261    } else {
262        headers
263            .iter()
264            .position(|h| matches!(h.as_str(), "cidr" | "network" | "ip" | "start_ip"))
265            .unwrap_or(0)
266    };
267
268    let end_idx = match &options.end_ip_field {
269        Some(name) => Some(headers.iter().position(|h| h == name).ok_or_else(|| {
270            BuilderError::InvalidInput(format!("CSV missing end_ip column '{name}'"))
271        })?),
272        None => headers.iter().position(|h| h == "end_ip"),
273    };
274
275    // Read all rows so we can infer homogeneous column types cleanly across the entire CSV.
276    let mut rows: Vec<csv::StringRecord> = Vec::new();
277    for rec in rdr.records() {
278        let r = rec.map_err(|e| BuilderError::InvalidInput(format!("CSV row error: {e}")))?;
279        rows.push(r);
280    }
281
282    let mut col_kinds = vec![CsvColKind::Utf8; headers.len()];
283    for (col, kind_slot) in col_kinds.iter_mut().enumerate().take(headers.len()) {
284        if col == cidr_idx || Some(col) == end_idx {
285            continue;
286        }
287        let cells: Vec<&str> = rows.iter().map(|r| r.get(col).unwrap_or("")).collect();
288        *kind_slot = infer_csv_col_kind(&cells);
289    }
290
291    let mut builder = CoipBuilder::new(options.build_options.clone());
292    builder.set_metadata_field("source_format", serde_json::Value::String("csv".into()));
293    if let Some(db_type) = &options.database_type {
294        builder.set_metadata_field("database_type", serde_json::Value::String(db_type.clone()));
295    }
296
297    for (row_no, row) in rows.iter().enumerate() {
298        let start_str = row.get(cidr_idx).unwrap_or("").trim();
299        if start_str.is_empty() {
300            continue;
301        }
302        let end_str = end_idx.map(|i| row.get(i).unwrap_or("").trim());
303
304        let mut rec = BTreeMap::new();
305        for (col, hname) in headers.iter().enumerate() {
306            if col == cidr_idx || Some(col) == end_idx || hname.is_empty() {
307                continue;
308            }
309            let cell = row.get(col).unwrap_or("").trim();
310            if cell.is_empty() {
311                continue;
312            }
313            let val = match col_kinds[col] {
314                CsvColKind::Bool => Value::Bool(matches!(cell, "true" | "TRUE")),
315                CsvColKind::U32 => Value::U32(cell.parse::<u32>().unwrap()),
316                CsvColKind::I64 => Value::I64(cell.parse::<i64>().unwrap()),
317                CsvColKind::F64 => Value::F64(cell.parse::<f64>().unwrap()),
318                CsvColKind::Utf8 => Value::Utf8(cell.to_owned()),
319            };
320            if options.unflatten_dots && hname.contains('.') {
321                let segs: Vec<&str> = hname.split('.').collect();
322                insert_nested_field(&mut rec, &segs, val);
323            } else {
324                rec.insert(hname.clone(), val);
325            }
326        }
327
328        if let Some(es) = end_str.filter(|s| !s.is_empty()) {
329            insert_ip_range_str(&mut builder, start_str, es, rec)
330                .map_err(|e| BuilderError::InvalidInput(format!("CSV row {}: {e}", row_no + 2)))?;
331        } else {
332            let (addr, prefix_len) = parse_cidr_or_ip(start_str)
333                .map_err(|e| BuilderError::InvalidInput(format!("CSV row {}: {e}", row_no + 2)))?;
334            match addr {
335                IpAddr::V4(v4) => {
336                    builder.insert_ipv4_cidr(v4, prefix_len, rec)?;
337                }
338                IpAddr::V6(v6) => {
339                    builder.insert_ipv6_cidr(v6, prefix_len, rec)?;
340                }
341            }
342        }
343    }
344
345    builder.build()
346}
347
348fn insert_ip_range_str(
349    builder: &mut CoipBuilder,
350    start_str: &str,
351    end_str: &str,
352    rec: BTreeMap<String, Value>,
353) -> Result<()> {
354    let s_addr: IpAddr = start_str
355        .trim()
356        .parse()
357        .map_err(|_| BuilderError::InvalidInput(format!("invalid start_ip '{start_str}'")))?;
358    let e_addr: IpAddr = end_str
359        .trim()
360        .parse()
361        .map_err(|_| BuilderError::InvalidInput(format!("invalid end_ip '{end_str}'")))?;
362    match (s_addr, e_addr) {
363        (IpAddr::V4(s), IpAddr::V4(e)) => {
364            builder.insert_ipv4_range(s, e, rec)?;
365            Ok(())
366        }
367        (IpAddr::V6(s), IpAddr::V6(e)) => {
368            builder.insert_ipv6_range(s, e, rec)?;
369            Ok(())
370        }
371        _ => Err(BuilderError::InvalidInput(format!(
372            "mismatched IP versions in range '{start_str}'..='{end_str}'"
373        ))),
374    }
375}
376
377fn insert_nested_field(map: &mut BTreeMap<String, Value>, segs: &[&str], val: Value) {
378    if segs.len() == 1 {
379        map.insert(segs[0].to_owned(), val);
380        return;
381    }
382    let entry = map
383        .entry(segs[0].to_owned())
384        .or_insert_with(|| Value::Map(BTreeMap::new()));
385    if let Value::Map(sub) = entry {
386        insert_nested_field(sub, &segs[1..], val);
387    }
388}
389
390fn json_to_coi_value(v: serde_json::Value) -> Value {
391    match v {
392        serde_json::Value::Null => Value::Null,
393        serde_json::Value::Bool(b) => Value::Bool(b),
394        serde_json::Value::Number(n) => {
395            if let Some(i) = n.as_i64() {
396                Value::I64(i)
397            } else if let Some(u) = n.as_u64() {
398                Value::U64(u)
399            } else {
400                Value::F64(n.as_f64().unwrap_or(0.0))
401            }
402        }
403        serde_json::Value::String(s) => Value::Utf8(s),
404        serde_json::Value::Array(arr) => {
405            Value::Array(arr.into_iter().map(json_to_coi_value).collect())
406        }
407        serde_json::Value::Object(m) => {
408            let mut out = BTreeMap::new();
409            for (k, val) in m {
410                if !val.is_null() {
411                    out.insert(k, json_to_coi_value(val));
412                }
413            }
414            Value::Map(out)
415        }
416    }
417}
418
419/// Convenience helper for `Ipv4Addr` / `Ipv6Addr` exports.
420pub fn format_cidr_v4(net: u32, prefix_len: u8) -> String {
421    format!("{}/{prefix_len}", Ipv4Addr::from(net))
422}
423
424pub fn format_cidr_v6(net: u128, prefix_len: u8) -> String {
425    format!("{}/{prefix_len}", Ipv6Addr::from(net))
426}