use std::collections::BTreeMap;
use std::fs::File;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use std::path::Path;
use std::sync::Mutex;
use coip_format::{
Cursor, FOOTER_SIZE, FileFooter, FileHeader, FormatError, HEADER_SIZE, Ipv6Aliases,
Ipv6HostExt, SECTION_ENTRY_SIZE, Schema, SectionEntry, SectionKind, Value, ZstdDicts, crc32c,
};
use crate::codec::decompress;
use crate::error::{ReaderError, Result};
use crate::index_reader::{Ipv4IndexReader, Ipv6IndexReader};
use crate::projection::{Projection, ProjectionNode};
use crate::source::Backing;
use crate::table_reader::{ChunkCache, ColumnTableReader, DictTablesReader, read_struct_row};
#[derive(Debug, Clone)]
pub struct ReaderOptions {
pub ipv4_block_cache_capacity: usize,
pub ipv6_block_cache_capacity: usize,
pub chunk_cache_capacity: usize,
pub flat_dict_cache_capacity: usize,
pub verify_all_checksums_on_open: bool,
}
impl Default for ReaderOptions {
fn default() -> Self {
Self {
ipv4_block_cache_capacity: 256,
ipv6_block_cache_capacity: 128,
chunk_cache_capacity: 256,
flat_dict_cache_capacity: 32,
verify_all_checksums_on_open: false,
}
}
}
pub struct Reader<'a> {
backing: Backing<'a>,
header: FileHeader,
sections: Vec<SectionEntry>,
metadata: serde_json::Value,
schema: Schema,
zstd_dicts: Vec<(u32, Vec<u8>)>,
ipv6_aliases: Ipv6Aliases,
ipv6_host_ext: Ipv6HostExt,
ipv4_index: Option<Ipv4IndexReader>,
ipv6_index: Option<Ipv6IndexReader>,
record_columns: ColumnTableReader,
dict_tables: DictTablesReader,
chunk_cache: ChunkCache,
}
impl Reader<'static> {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
Self::open_with_options(path, ReaderOptions::default())
}
pub fn open_with_options(path: impl AsRef<Path>, options: ReaderOptions) -> Result<Self> {
#[cfg(feature = "mmap")]
{
let file = File::open(path)?;
let mmap = unsafe { memmap2::Mmap::map(&file)? };
Self::from_backing(Backing::Mmap(mmap), options)
}
#[cfg(not(feature = "mmap"))]
{
Self::open_file_with_options(path, options)
}
}
pub fn open_file(path: impl AsRef<Path>) -> Result<Self> {
Self::open_file_with_options(path, ReaderOptions::default())
}
pub fn open_file_with_options(path: impl AsRef<Path>, options: ReaderOptions) -> Result<Self> {
let file = File::open(path)?;
let len = file.metadata()?.len();
Self::from_backing(
Backing::File {
file: Mutex::new(file),
len,
},
options,
)
}
pub fn from_vec(bytes: Vec<u8>) -> Result<Self> {
Self::from_vec_with_options(bytes, ReaderOptions::default())
}
pub fn from_vec_with_options(bytes: Vec<u8>, options: ReaderOptions) -> Result<Self> {
Self::from_backing(Backing::Owned(bytes), options)
}
}
impl<'a> Reader<'a> {
pub fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
Self::from_bytes_with_options(bytes, ReaderOptions::default())
}
pub fn from_bytes_with_options(bytes: &'a [u8], options: ReaderOptions) -> Result<Self> {
Self::from_backing(Backing::Slice(bytes), options)
}
fn from_backing(backing: Backing<'a>, options: ReaderOptions) -> Result<Self> {
let total_len = backing.len();
if total_len < (HEADER_SIZE + FOOTER_SIZE) as u64 {
return Err(FormatError::UnexpectedEof.into());
}
let hdr_bytes = backing.read_slice(0, HEADER_SIZE)?;
let header = FileHeader::decode(&hdr_bytes)?;
if header.file_size != total_len {
return Err(ReaderError::Corrupt(format!(
"header file_size {} != actual {}",
header.file_size, total_len
)));
}
let footer_bytes = backing.read_slice(total_len - (FOOTER_SIZE as u64), FOOTER_SIZE)?;
let footer = FileFooter::decode(&footer_bytes)?;
if footer.section_dir_offset != header.section_dir_offset {
return Err(ReaderError::Corrupt(
"footer section_dir_offset mismatch".into(),
));
}
let dir_len = (header.section_count as usize) * SECTION_ENTRY_SIZE;
let dir_bytes = backing.read_slice(header.section_dir_offset, dir_len)?;
let actual_dir_crc = crc32c(&dir_bytes);
if actual_dir_crc != footer.dir_crc32c {
return Err(FormatError::InvalidCrc {
expected: footer.dir_crc32c,
actual: actual_dir_crc,
}
.into());
}
let mut dc = Cursor::new(&dir_bytes);
let mut sections = Vec::with_capacity(header.section_count as usize);
for _ in 0..header.section_count {
let entry = SectionEntry::decode(&mut dc)?;
if entry
.offset
.checked_add(entry.length)
.is_none_or(|e| e > total_len)
{
return Err(FormatError::OutOfBounds("section range exceeds file size").into());
}
sections.push(entry);
}
if options.verify_all_checksums_on_open {
for sec in §ions {
let raw = backing.read_slice(sec.offset, sec.length as usize)?;
let actual = crc32c(&raw);
if actual != sec.crc32c {
return Err(FormatError::InvalidCrc {
expected: sec.crc32c,
actual,
}
.into());
}
}
}
let find_section = |kind: SectionKind| -> Option<SectionEntry> {
sections.iter().copied().find(|s| s.kind == kind)
};
let read_small_section = |sec: SectionEntry| -> Result<Vec<u8>> {
let raw = backing.read_slice(sec.offset, sec.length as usize)?;
let codec = sec.codec()?;
let dec = decompress(codec, &raw, Some(sec.uncompressed_length as usize))?;
Ok(dec.into_owned())
};
let metadata = if let Some(sec) = find_section(SectionKind::Metadata) {
let bytes = read_small_section(sec)?;
serde_json::from_slice(&bytes)?
} else {
serde_json::Value::Object(serde_json::Map::new())
};
let schema_sec =
find_section(SectionKind::Schema).ok_or(ReaderError::MissingSection("Schema"))?;
let schema_bytes = read_small_section(schema_sec)?;
let schema = Schema::decode(&schema_bytes)?;
let zstd_dicts = if let Some(sec) = find_section(SectionKind::ZstdDicts) {
let bytes = read_small_section(sec)?;
let zd = ZstdDicts::decode(&bytes)?;
zd.dicts.into_iter().map(|d| (crc32c(&d), d)).collect()
} else {
Vec::new()
};
let ipv6_aliases = if let Some(sec) = find_section(SectionKind::Ipv6Aliases) {
let bytes = read_small_section(sec)?;
Ipv6Aliases::decode(&bytes)?
} else {
Ipv6Aliases::default()
};
let ipv6_host_ext = if let Some(sec) = find_section(SectionKind::Ipv6HostExt) {
let bytes = read_small_section(sec)?;
Ipv6HostExt::decode(&bytes)?
} else {
Ipv6HostExt::default()
};
let ipv4_index = if let Some(sec) = find_section(SectionKind::Ipv4Index) {
Some(Ipv4IndexReader::parse(
&backing,
sec.offset,
sec.length,
options.ipv4_block_cache_capacity,
)?)
} else {
None
};
let ipv6_index = if let Some(sec) = find_section(SectionKind::Ipv6Index) {
Some(Ipv6IndexReader::parse(
&backing,
sec.offset,
sec.length,
options.ipv6_block_cache_capacity,
)?)
} else {
None
};
let rec_sec = find_section(SectionKind::RecordColumns)
.ok_or(ReaderError::MissingSection("RecordColumns"))?;
let record_columns = ColumnTableReader::parse(
0,
&backing,
rec_sec.offset,
rec_sec.length,
&schema.root,
schema.dicts.len(),
)?;
let dict_tables = if let Some(sec) = find_section(SectionKind::DictTables) {
DictTablesReader::parse(
&backing,
sec.offset,
sec.length,
&schema,
options.flat_dict_cache_capacity,
)?
} else {
DictTablesReader::empty()
};
Ok(Self {
backing,
header,
sections,
metadata,
schema,
zstd_dicts,
ipv6_aliases,
ipv6_host_ext,
ipv4_index,
ipv6_index,
record_columns,
dict_tables,
chunk_cache: ChunkCache::new(options.chunk_cache_capacity),
})
}
pub fn header(&self) -> &FileHeader {
&self.header
}
pub fn sections(&self) -> &[SectionEntry] {
&self.sections
}
pub fn metadata(&self) -> &serde_json::Value {
&self.metadata
}
pub fn schema(&self) -> &Schema {
&self.schema
}
pub fn zstd_dict_count(&self) -> usize {
self.zstd_dicts.len()
}
pub fn ipv6_aliases(&self) -> &Ipv6Aliases {
&self.ipv6_aliases
}
pub fn ipv6_host_ext(&self) -> &Ipv6HostExt {
&self.ipv6_host_ext
}
pub fn ipv4_entry_count(&self) -> u64 {
self.ipv4_index
.as_ref()
.map_or(0, Ipv4IndexReader::entry_count)
}
pub fn ipv6_entry_count(&self) -> u64 {
self.ipv6_index
.as_ref()
.map_or(0, Ipv6IndexReader::entry_count)
}
pub fn ipv4_transitions(&self) -> Result<Vec<(u32, u64)>> {
match &self.ipv4_index {
Some(v4) => v4.collect_transitions(&self.backing, &self.zstd_dicts),
None => Ok(Vec::new()),
}
}
pub fn ipv6_transitions(&self) -> Result<Vec<(u64, u64)>> {
match &self.ipv6_index {
Some(v6) => v6.collect_transitions(&self.backing, &self.zstd_dicts),
None => Ok(Vec::new()),
}
}
pub fn ipv4_ranges(&self) -> Result<Vec<(u32, u32, u64)>> {
let trans = self.ipv4_transitions()?;
let mut out = Vec::with_capacity(trans.len());
for i in 0..trans.len() {
let (start, rid) = trans[i];
if rid == 0 {
continue;
}
let end = if i + 1 < trans.len() {
trans[i + 1].0 - 1
} else {
u32::MAX
};
out.push((start, end, rid));
}
Ok(out)
}
pub fn ipv6_ranges(&self) -> Result<Vec<(u64, u64, u64)>> {
let trans = self.ipv6_transitions()?;
let mut out = Vec::with_capacity(trans.len());
for i in 0..trans.len() {
let (start, rid) = trans[i];
if rid == 0 {
continue;
}
let end = if i + 1 < trans.len() {
trans[i + 1].0 - 1
} else {
u64::MAX
};
out.push((start, end, rid));
}
Ok(out)
}
pub fn dict_entry_counts(&self) -> Vec<(String, u64)> {
self.schema
.dicts
.iter()
.zip(self.dict_tables.dicts.iter())
.map(|(s, d)| (s.name.clone(), d.entry_count()))
.collect()
}
pub fn verify_checksums(&self) -> Result<()> {
for sec in &self.sections {
let raw = self.backing.read_slice(sec.offset, sec.length as usize)?;
let actual = crc32c(&raw);
if actual != sec.crc32c {
return Err(FormatError::InvalidCrc {
expected: sec.crc32c,
actual,
}
.into());
}
}
Ok(())
}
pub fn clear_caches(&self) {
if let Some(v4) = &self.ipv4_index {
v4.clear_cache();
}
if let Some(v6) = &self.ipv6_index {
v6.clear_cache();
}
self.chunk_cache.clear();
for d in &self.dict_tables.dicts {
d.clear_cache();
}
}
pub fn compile_projection<I, S>(&self, paths: I) -> Result<Projection>
where
I: IntoIterator<Item = S>,
S: AsRef<str>,
{
Projection::from_paths(paths)
}
#[inline]
pub fn lookup_record_id(&self, ip: IpAddr) -> Result<u64> {
match ip {
IpAddr::V4(v4) => self.lookup_ipv4_record_id(v4),
IpAddr::V6(v6) => self.lookup_ipv6_record_id(v6),
}
}
#[inline]
pub fn lookup_ipv4_record_id(&self, ip: Ipv4Addr) -> Result<u64> {
let Some(v4) = &self.ipv4_index else {
return Ok(0);
};
v4.lookup(&self.backing, &self.zstd_dicts, u32::from(ip))
}
#[inline]
pub fn lookup_ipv6_record_id(&self, ip: Ipv6Addr) -> Result<u64> {
let ip_be = u128::from(ip);
if let Some(v4_u32) = self.ipv6_aliases.match_ipv6(ip_be) {
return match &self.ipv4_index {
Some(v4) => v4.lookup(&self.backing, &self.zstd_dicts, v4_u32),
None => Ok(0),
};
}
if let Some(rid) = self.ipv6_host_ext.lookup(ip_be) {
return Ok(rid);
}
let Some(v6) = &self.ipv6_index else {
return Ok(0);
};
v6.lookup(&self.backing, &self.zstd_dicts, (ip_be >> 64) as u64)
}
pub fn get_record_by_id(
&self,
record_id: u64,
projection: Option<&Projection>,
) -> Result<Option<BTreeMap<String, Value>>> {
if record_id == 0 || record_id > self.header.record_count {
return Ok(None);
}
let row_idx = (record_id - 1) as usize;
let (rg, row_in_rg, rows_in_rg) = self.record_columns.row_group_of(row_idx);
let proj = projection.map_or(&ProjectionNode::All, |p| &p.root);
read_struct_row(
&self.backing,
&self.record_columns,
&self.dict_tables,
&self.chunk_cache,
&self.schema.root.root,
rg,
row_in_rg,
rows_in_rg,
proj,
)
}
pub fn lookup_value(&self, ip: IpAddr) -> Result<Option<Value>> {
let rid = self.lookup_record_id(ip)?;
if rid == 0 {
return Ok(None);
}
Ok(self.get_record_by_id(rid, None)?.map(Value::Map))
}
pub fn lookup_projected(&self, ip: IpAddr, projection: &Projection) -> Result<Option<Value>> {
let rid = self.lookup_record_id(ip)?;
if rid == 0 {
return Ok(None);
}
Ok(self
.get_record_by_id(rid, Some(projection))?
.map(Value::Map))
}
#[cfg(feature = "serde")]
pub fn lookup<T: for<'de> serde::Deserialize<'de>>(&self, ip: IpAddr) -> Result<Option<T>> {
let rid = self.lookup_record_id(ip)?;
if rid == 0 || rid > self.header.record_count {
return Ok(None);
}
let row_idx = (rid - 1) as usize;
let (rg, row_in_rg, rows_in_rg) = self.record_columns.row_group_of(row_idx);
crate::serde_de::deserialize_struct_row(
&self.backing,
&self.record_columns,
&self.dict_tables,
&self.chunk_cache,
&self.schema.root.root,
rg,
row_in_rg,
rows_in_rg,
&ProjectionNode::All,
)
}
#[cfg(feature = "serde")]
pub fn lookup_with_projection<T: for<'de> serde::Deserialize<'de>>(
&self,
ip: IpAddr,
projection: &Projection,
) -> Result<Option<T>> {
let rid = self.lookup_record_id(ip)?;
if rid == 0 || rid > self.header.record_count {
return Ok(None);
}
let row_idx = (rid - 1) as usize;
let (rg, row_in_rg, rows_in_rg) = self.record_columns.row_group_of(row_idx);
crate::serde_de::deserialize_struct_row(
&self.backing,
&self.record_columns,
&self.dict_tables,
&self.chunk_cache,
&self.schema.root.root,
rg,
row_in_rg,
rows_in_rg,
&projection.root,
)
}
}