use std::collections::{BTreeMap, HashMap};
use std::io::Write;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::path::Path;
use coip_format::{
AliasRule, Codec, FORMAT_MAJOR, FORMAT_MINOR, FileFooter, FileHeader, HEADER_SIZE, Ipv6Aliases,
SECTION_ENTRY_SIZE, SectionEntry, SectionKind, Value, ZstdDicts, align8, crc32c, header_flags,
range_to_cidrs_v4, range_to_cidrs_v6,
};
use crate::column_writer::compress_with_codec;
use crate::error::{BuilderError, Result};
use crate::index_writer::{
build_host_ext, encode_ipv4_index, encode_ipv6_index, merge_v4_transitions,
merge_v6_transitions,
};
use crate::lpm::{resolve_lpm_v4, resolve_lpm_v6, resolve_lpm_v6_host};
use crate::mmdb::{V4Interval, V6HostInterval, V6Interval, extract_mmdb};
use crate::prune::{PruneConfig, apply_pruning};
use crate::schema_infer::{ColumnarBuildConfig, RowOrderStrategy, infer_and_encode_records};
#[derive(Debug, Clone)]
pub struct BuildOptions {
pub profile_codec: Codec,
pub zstd_level: i32,
pub train_zstd_dicts: bool,
pub index_block_size: u32,
pub ipv4_l1_bits: u8,
pub ipv6_l1_bits: u8,
pub row_group_size: u32,
pub struct_dict_row_group_size: u32,
pub dict_block_size: u32,
pub row_order: RowOrderStrategy,
pub prune: Option<PruneConfig>,
}
impl BuildOptions {
pub fn compact() -> Self {
Self {
profile_codec: Codec::Zstd,
zstd_level: 9,
train_zstd_dicts: true,
index_block_size: 2048,
ipv4_l1_bits: 16,
ipv6_l1_bits: 0,
row_group_size: 4096,
struct_dict_row_group_size: 2048,
dict_block_size: 4096,
row_order: RowOrderStrategy::GeoLocality,
prune: None,
}
}
pub fn ultrafast() -> Self {
Self {
profile_codec: Codec::Lz4,
zstd_level: 1,
train_zstd_dicts: false,
index_block_size: 512,
ipv4_l1_bits: 16,
ipv6_l1_bits: 0,
row_group_size: 1024,
struct_dict_row_group_size: 512,
dict_block_size: 1024,
row_order: RowOrderStrategy::GeoLocality,
prune: None,
}
}
}
impl Default for BuildOptions {
fn default() -> Self {
Self::compact()
}
}
#[derive(Debug, Clone)]
pub struct BuildStats {
pub total_bytes: u64,
pub record_count: u64,
pub v4_transitions: usize,
pub v6_transitions: usize,
pub v6_host_ext_entries: usize,
pub ipv6_alias_count: usize,
pub dict_count: usize,
pub section_sizes: Vec<(SectionKind, u64)>,
}
pub struct CoipBuilder {
options: BuildOptions,
build_epoch: u64,
metadata: serde_json::Map<String, serde_json::Value>,
ipv6_aliases: Vec<AliasRule>,
v4_intervals: Vec<V4Interval>,
v6_intervals: Vec<V6Interval>,
v6_host_ext: Vec<V6HostInterval>,
record_dedup: HashMap<BTreeMap<String, Value>, u32>,
unique_records: Vec<BTreeMap<String, Value>>,
}
impl CoipBuilder {
pub fn new(options: BuildOptions) -> Self {
let mut metadata = serde_json::Map::new();
metadata.insert(
"generator".into(),
serde_json::Value::String(format!("coip-builder {}", env!("CARGO_PKG_VERSION"))),
);
Self {
options,
build_epoch: 0,
metadata,
ipv6_aliases: Vec::new(),
v4_intervals: Vec::new(),
v6_intervals: Vec::new(),
v6_host_ext: Vec::new(),
record_dedup: HashMap::new(),
unique_records: Vec::new(),
}
}
pub fn set_build_epoch(&mut self, epoch: u64) -> &mut Self {
self.build_epoch = epoch;
self.metadata
.insert("build_epoch".into(), serde_json::Value::from(epoch));
self
}
pub fn set_metadata_field(
&mut self,
key: impl Into<String>,
val: serde_json::Value,
) -> &mut Self {
self.metadata.insert(key.into(), val);
self
}
pub fn add_ipv6_alias(&mut self, rule: AliasRule) -> &mut Self {
self.ipv6_aliases.push(rule);
self
}
fn intern_record(&mut self, record: BTreeMap<String, Value>) -> u32 {
if let Some(&id) = self.record_dedup.get(&record) {
return id;
}
let id = (self.unique_records.len() + 1) as u32;
self.record_dedup.insert(record.clone(), id);
self.unique_records.push(record);
id
}
pub fn insert_ipv4_cidr(
&mut self,
addr: Ipv4Addr,
prefix_len: u8,
record: BTreeMap<String, Value>,
) -> Result<&mut Self> {
let rid = self.intern_record(record);
self.push_ipv4_cidr_rid(addr, prefix_len, rid)
}
pub fn delete_ipv4_cidr(&mut self, addr: Ipv4Addr, prefix_len: u8) -> Result<&mut Self> {
self.push_ipv4_cidr_rid(addr, prefix_len, 0)
}
fn push_ipv4_cidr_rid(
&mut self,
addr: Ipv4Addr,
prefix_len: u8,
rid: u32,
) -> Result<&mut Self> {
if prefix_len > 32 {
return Err(BuilderError::InvalidInput(format!(
"invalid IPv4 prefix length {prefix_len}"
)));
}
let ip = u32::from(addr);
let (start, end) = if prefix_len == 0 {
(0u32, u32::MAX)
} else if prefix_len == 32 {
(ip, ip)
} else {
let mask = !((1u32 << (32 - prefix_len)) - 1);
let s = ip & mask;
let e = s | !mask;
(s, e)
};
self.v4_intervals.push(V4Interval {
start,
end,
record_idx: rid,
});
Ok(self)
}
pub fn insert_ipv4_range(
&mut self,
start: Ipv4Addr,
end: Ipv4Addr,
record: BTreeMap<String, Value>,
) -> Result<&mut Self> {
let s = u32::from(start);
let e = u32::from(end);
if s > e {
return Err(BuilderError::InvalidInput(format!(
"IPv4 start {start} > end {end}"
)));
}
let rid = self.intern_record(record);
for (net, plen) in range_to_cidrs_v4(s, e) {
self.push_ipv4_cidr_rid(Ipv4Addr::from(net), plen, rid)?;
}
Ok(self)
}
pub fn insert_ipv6_cidr(
&mut self,
addr: Ipv6Addr,
prefix_len: u8,
record: BTreeMap<String, Value>,
) -> Result<&mut Self> {
let rid = self.intern_record(record);
self.push_ipv6_cidr_rid(addr, prefix_len, rid)
}
pub fn delete_ipv6_cidr(&mut self, addr: Ipv6Addr, prefix_len: u8) -> Result<&mut Self> {
self.push_ipv6_cidr_rid(addr, prefix_len, 0)
}
fn push_ipv6_cidr_rid(
&mut self,
addr: Ipv6Addr,
prefix_len: u8,
rid: u32,
) -> Result<&mut Self> {
if prefix_len > 128 {
return Err(BuilderError::InvalidInput(format!(
"invalid IPv6 prefix length {prefix_len}"
)));
}
let ip = u128::from(addr);
if prefix_len <= 64 {
let hi = (ip >> 64) as u64;
let (start, end) = if prefix_len == 0 {
(0u64, u64::MAX)
} else if prefix_len == 64 {
(hi, hi)
} else {
let mask = !((1u64 << (64 - prefix_len)) - 1);
let s = hi & mask;
let e = s | !mask;
(s, e)
};
self.v6_intervals.push(V6Interval {
start,
end,
record_idx: rid,
});
} else {
let (start, end) = if prefix_len == 128 {
(ip, ip)
} else {
let mask = !((1u128 << (128 - prefix_len)) - 1);
let s = ip & mask;
let e = s | !mask;
(s, e)
};
self.v6_host_ext.push(V6HostInterval {
start,
end,
record_idx: rid,
});
}
Ok(self)
}
pub fn insert_ipv6_range(
&mut self,
start: Ipv6Addr,
end: Ipv6Addr,
record: BTreeMap<String, Value>,
) -> Result<&mut Self> {
let s = u128::from(start);
let e = u128::from(end);
if s > e {
return Err(BuilderError::InvalidInput(format!(
"IPv6 start {start} > end {end}"
)));
}
let rid = self.intern_record(record);
for (net, plen) in range_to_cidrs_v6(s, e) {
self.push_ipv6_cidr_rid(Ipv6Addr::from(net), plen, rid)?;
}
Ok(self)
}
pub fn insert_cidr_str(
&mut self,
cidr: &str,
record: BTreeMap<String, Value>,
) -> Result<&mut Self> {
let (addr, plen) = crate::import::parse_cidr_or_ip(cidr)?;
match addr {
std::net::IpAddr::V4(v4) => self.insert_ipv4_cidr(v4, plen, record),
std::net::IpAddr::V6(v6) => self.insert_ipv6_cidr(v6, plen, record),
}
}
pub fn build(self) -> Result<(Vec<u8>, BuildStats)> {
assemble_coi(
&self.options,
self.build_epoch,
serde_json::Value::Object(self.metadata),
self.ipv6_aliases,
self.v4_intervals,
self.v6_intervals,
self.v6_host_ext,
self.unique_records,
)
}
}
#[allow(clippy::too_many_arguments)]
pub fn build_from_parts(
options: &BuildOptions,
build_epoch: u64,
metadata_json: serde_json::Value,
ipv6_aliases: Vec<AliasRule>,
v4_intervals: Vec<V4Interval>,
v6_intervals: Vec<V6Interval>,
v6_host_ext: Vec<V6HostInterval>,
unique_records: Vec<BTreeMap<String, Value>>,
) -> Result<(Vec<u8>, BuildStats)> {
assemble_coi(
options,
build_epoch,
metadata_json,
ipv6_aliases,
v4_intervals,
v6_intervals,
v6_host_ext,
unique_records,
)
}
pub fn convert_mmdb_file(
src_mmdb: impl AsRef<Path>,
dst_coi: impl AsRef<Path>,
options: &BuildOptions,
) -> Result<BuildStats> {
let mmdb_bytes = std::fs::read(src_mmdb)?;
let (coi_bytes, stats) = build_from_mmdb_bytes(&mmdb_bytes, options)?;
let mut f = std::fs::File::create(dst_coi)?;
f.write_all(&coi_bytes)?;
f.flush()?;
Ok(stats)
}
pub fn build_from_mmdb_bytes(
mmdb_bytes: &[u8],
options: &BuildOptions,
) -> Result<(Vec<u8>, BuildStats)> {
let extracted = extract_mmdb(mmdb_bytes)?;
let mut meta = serde_json::Map::new();
meta.insert(
"database_type".into(),
serde_json::Value::String(extracted.metadata.database_type.clone()),
);
meta.insert(
"description".into(),
serde_json::to_value(&extracted.metadata.description)?,
);
meta.insert(
"languages".into(),
serde_json::to_value(&extracted.metadata.languages)?,
);
meta.insert(
"build_epoch".into(),
serde_json::Value::from(extracted.metadata.build_epoch),
);
meta.insert(
"ip_version".into(),
serde_json::Value::from(extracted.metadata.ip_version),
);
meta.insert(
"source_format".into(),
serde_json::Value::String(format!(
"mmdb-{}.{}",
extracted.metadata.binary_format_major_version,
extracted.metadata.binary_format_minor_version
)),
);
meta.insert(
"generator".into(),
serde_json::Value::String(format!("coip-builder {}", env!("CARGO_PKG_VERSION"))),
);
assemble_coi(
options,
extracted.metadata.build_epoch,
serde_json::Value::Object(meta),
extracted.ipv6_aliases,
extracted.v4_intervals,
extracted.v6_intervals,
extracted.v6_host_ext,
extracted.unique_records,
)
}
#[allow(clippy::too_many_arguments)]
fn assemble_coi(
options: &BuildOptions,
build_epoch: u64,
mut metadata_json: serde_json::Value,
ipv6_aliases: Vec<AliasRule>,
v4_intervals: Vec<V4Interval>,
v6_intervals: Vec<V6Interval>,
v6_host_ext: Vec<V6HostInterval>,
mut unique_records: Vec<BTreeMap<String, Value>>,
) -> Result<(Vec<u8>, BuildStats)> {
let codec = options.profile_codec;
let zstd_level = options.zstd_level;
let mut v4_intervals = resolve_lpm_v4(v4_intervals);
let mut v6_intervals = resolve_lpm_v6(v6_intervals);
let mut v6_host_ext = resolve_lpm_v6_host(v6_host_ext);
if let Some(ref prune) = options.prune {
unique_records = apply_pruning(
prune,
unique_records,
&mut v4_intervals,
&mut v6_intervals,
&mut v6_host_ext,
&mut metadata_json,
)?;
}
let mut ip_first_pos = vec![u64::MAX; unique_records.len()];
let mut seq = 0u64;
for iv in &v4_intervals {
let idx = (iv.record_idx as usize).saturating_sub(1);
if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
ip_first_pos[idx] = seq;
}
seq += 1;
}
for iv in &v6_intervals {
let idx = (iv.record_idx as usize).saturating_sub(1);
if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
ip_first_pos[idx] = seq;
}
seq += 1;
}
for iv in &v6_host_ext {
let idx = (iv.record_idx as usize).saturating_sub(1);
if iv.record_idx > 0 && ip_first_pos[idx] == u64::MAX {
ip_first_pos[idx] = seq;
}
seq += 1;
}
let col_cfg = ColumnarBuildConfig {
row_group_size: options.row_group_size,
struct_dict_row_group_size: options.struct_dict_row_group_size,
dict_block_size: options.dict_block_size,
codec,
zstd_level,
row_order: options.row_order,
};
let built_cols = infer_and_encode_records(&unique_records, &ip_first_pos, &col_cfg)?;
for iv in &mut v4_intervals {
iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
}
for iv in &mut v6_intervals {
iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
}
for iv in &mut v6_host_ext {
iv.record_idx = built_cols.old_to_new_rid[iv.record_idx as usize];
}
let v4_transitions = merge_v4_transitions(&v4_intervals);
let v6_transitions = merge_v6_transitions(&v6_intervals);
let host_ext = build_host_ext(&v6_host_ext);
let has_ipv4 = !v4_transitions.is_empty();
let has_ipv6 =
!v6_transitions.is_empty() || !ipv6_aliases.is_empty() || !host_ext.entries.is_empty();
let has_host_ext = !host_ext.entries.is_empty();
let mut trained_zstd_dicts: Vec<Vec<u8>> = Vec::new();
let v4_blob = if has_ipv4 {
Some(
encode_ipv4_index(
&v4_transitions,
options.index_block_size,
options.ipv4_l1_bits,
codec,
zstd_level,
options.train_zstd_dicts,
&mut trained_zstd_dicts,
)?
.bytes,
)
} else {
None
};
let v6_blob = if !v6_transitions.is_empty() {
Some(
encode_ipv6_index(
&v6_transitions,
options.index_block_size,
options.ipv6_l1_bits,
codec,
zstd_level,
options.train_zstd_dicts,
&mut trained_zstd_dicts,
)?
.bytes,
)
} else {
None
};
let has_zstd_dicts = !trained_zstd_dicts.is_empty();
struct PendingSection {
kind: SectionKind,
flags: u16,
bytes: Vec<u8>,
uncompressed_len: u64,
}
let mut sections: Vec<PendingSection> = Vec::new();
let push_small_section =
|sections: &mut Vec<PendingSection>, kind: SectionKind, raw: Vec<u8>| -> Result<()> {
let uncompressed_len = raw.len() as u64;
if codec != Codec::None && raw.len() > 32 {
let comp = compress_with_codec(codec, &raw, zstd_level, None)?;
if comp.len() < raw.len() {
sections.push(PendingSection {
kind,
flags: codec as u16,
bytes: comp,
uncompressed_len,
});
return Ok(());
}
}
sections.push(PendingSection {
kind,
flags: Codec::None as u16,
bytes: raw,
uncompressed_len,
});
Ok(())
};
let meta_raw = serde_json::to_vec(&metadata_json)?;
push_small_section(&mut sections, SectionKind::Metadata, meta_raw)?;
let schema_raw = built_cols.schema.encode();
push_small_section(&mut sections, SectionKind::Schema, schema_raw)?;
if has_zstd_dicts {
let zd_raw = ZstdDicts {
dicts: trained_zstd_dicts,
}
.encode();
push_small_section(&mut sections, SectionKind::ZstdDicts, zd_raw)?;
}
if !ipv6_aliases.is_empty() {
let alias_raw = Ipv6Aliases {
rules: ipv6_aliases.clone(),
}
.encode();
push_small_section(&mut sections, SectionKind::Ipv6Aliases, alias_raw)?;
}
if let Some(blob) = v4_blob {
let len = blob.len() as u64;
sections.push(PendingSection {
kind: SectionKind::Ipv4Index,
flags: 0,
bytes: blob,
uncompressed_len: len,
});
}
if let Some(blob) = v6_blob {
let len = blob.len() as u64;
sections.push(PendingSection {
kind: SectionKind::Ipv6Index,
flags: 0,
bytes: blob,
uncompressed_len: len,
});
}
if has_host_ext {
let he_raw = host_ext.encode();
push_small_section(&mut sections, SectionKind::Ipv6HostExt, he_raw)?;
}
{
let len = built_cols.record_columns_blob.len() as u64;
sections.push(PendingSection {
kind: SectionKind::RecordColumns,
flags: 0,
bytes: built_cols.record_columns_blob,
uncompressed_len: len,
});
}
if !built_cols.dict_blobs.is_empty() {
let dict_section = encode_dict_tables_section(&built_cols.dict_blobs);
let len = dict_section.len() as u64;
sections.push(PendingSection {
kind: SectionKind::DictTables,
flags: 0,
bytes: dict_section,
uncompressed_len: len,
});
}
let section_count = sections.len();
let section_dir_offset = HEADER_SIZE as u64;
let dir_bytes_len = (section_count * SECTION_ENTRY_SIZE) as u64;
let mut cur_offset = align8(section_dir_offset + dir_bytes_len);
let mut dir_entries = Vec::with_capacity(section_count);
let mut section_sizes = Vec::with_capacity(section_count);
for sec in §ions {
let offset = align8(cur_offset);
let length = sec.bytes.len() as u64;
let checksum = crc32c(&sec.bytes);
dir_entries.push(SectionEntry {
kind: sec.kind,
flags: sec.flags,
crc32c: checksum,
offset,
length,
uncompressed_length: sec.uncompressed_len,
});
section_sizes.push((sec.kind, length));
cur_offset = offset + length;
}
let footer_offset = align8(cur_offset);
let file_size = footer_offset + (coip_format::FOOTER_SIZE as u64);
let mut dir_buf = Vec::with_capacity(dir_bytes_len as usize);
for entry in &dir_entries {
entry.encode(&mut dir_buf);
}
let dir_crc = crc32c(&dir_buf);
let mut flags = 0u32;
if has_ipv4 {
flags |= header_flags::HAS_IPV4;
}
if has_ipv6 {
flags |= header_flags::HAS_IPV6;
}
if has_host_ext {
flags |= header_flags::HAS_IPV6_HOST_EXT;
}
if has_zstd_dicts {
flags |= header_flags::HAS_ZSTD_DICTS;
}
let header = FileHeader {
format_major: FORMAT_MAJOR,
format_minor: FORMAT_MINOR,
flags,
profile_codec: options.profile_codec,
section_count: section_count as u8,
header_ext_len: 0,
build_epoch,
record_count: unique_records.len() as u64,
section_dir_offset,
file_size,
header_crc32c: 0,
};
let footer = FileFooter {
dir_crc32c: dir_crc,
section_dir_offset,
};
let mut out = Vec::with_capacity(file_size as usize);
out.extend_from_slice(&header.encode());
out.extend_from_slice(&dir_buf);
for (sec, entry) in sections.iter().zip(dir_entries.iter()) {
out.resize(entry.offset as usize, 0);
out.extend_from_slice(&sec.bytes);
}
out.resize(footer_offset as usize, 0);
out.extend_from_slice(&footer.encode());
debug_assert_eq!(out.len() as u64, file_size);
let stats = BuildStats {
total_bytes: file_size,
record_count: unique_records.len() as u64,
v4_transitions: v4_transitions.len(),
v6_transitions: v6_transitions.len(),
v6_host_ext_entries: host_ext.entries.len(),
ipv6_alias_count: ipv6_aliases.len(),
dict_count: built_cols.schema.dicts.len(),
section_sizes,
};
Ok((out, stats))
}
fn encode_dict_tables_section(dict_blobs: &[Vec<u8>]) -> Vec<u8> {
let count = dict_blobs.len();
let mut cur_off = 0u64;
let mut entries: Vec<(u64, u64)> = Vec::with_capacity(count);
for blob in dict_blobs {
let aligned = align8(cur_off);
entries.push((aligned, blob.len() as u64));
cur_off = aligned + blob.len() as u64;
}
let header_len = 8 + count * 16;
let mut out = Vec::with_capacity(header_len + cur_off as usize);
out.extend_from_slice(&(count as u16).to_le_bytes());
out.extend_from_slice(&[0u8; 6]);
for &(off, len) in &entries {
out.extend_from_slice(&off.to_le_bytes());
out.extend_from_slice(&len.to_le_bytes());
}
for (blob, &(off, _)) in dict_blobs.iter().zip(entries.iter()) {
out.resize(header_len + off as usize, 0);
out.extend_from_slice(blob);
}
out
}