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};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ImportFormat {
Jsonl,
Csv,
}
#[derive(Debug, Clone)]
pub struct ImportOptions {
pub format: ImportFormat,
pub cidr_field: Option<String>,
pub end_ip_field: Option<String>,
pub unflatten_dots: bool,
pub database_type: Option<String>,
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(),
}
}
}
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))
}
}
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)
}
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(),
));
}
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"),
};
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)
}
}
}
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))
}