1use std::collections::BTreeMap;
4use std::fs::File;
5use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
6use std::path::Path;
7use std::sync::Mutex;
8
9use coip_format::{
10 Cursor, FOOTER_SIZE, FileFooter, FileHeader, FormatError, HEADER_SIZE, Ipv6Aliases,
11 Ipv6HostExt, SECTION_ENTRY_SIZE, Schema, SectionEntry, SectionKind, Value, ZstdDicts, crc32c,
12};
13
14use crate::codec::decompress;
15use crate::error::{ReaderError, Result};
16use crate::index_reader::{Ipv4IndexReader, Ipv6IndexReader};
17use crate::projection::{Projection, ProjectionNode};
18use crate::source::Backing;
19use crate::table_reader::{ChunkCache, ColumnTableReader, DictTablesReader, read_struct_row};
20
21#[derive(Debug, Clone)]
23pub struct ReaderOptions {
24 pub ipv4_block_cache_capacity: usize,
26 pub ipv6_block_cache_capacity: usize,
28 pub chunk_cache_capacity: usize,
30 pub flat_dict_cache_capacity: usize,
32 pub verify_all_checksums_on_open: bool,
35}
36
37impl Default for ReaderOptions {
38 fn default() -> Self {
39 Self {
40 ipv4_block_cache_capacity: 256,
41 ipv6_block_cache_capacity: 128,
42 chunk_cache_capacity: 256,
43 flat_dict_cache_capacity: 32,
44 verify_all_checksums_on_open: false,
45 }
46 }
47}
48
49pub struct Reader<'a> {
53 backing: Backing<'a>,
54 header: FileHeader,
55 sections: Vec<SectionEntry>,
56 metadata: serde_json::Value,
57 schema: Schema,
58 zstd_dicts: Vec<(u32, Vec<u8>)>,
60 ipv6_aliases: Ipv6Aliases,
61 ipv6_host_ext: Ipv6HostExt,
62 ipv4_index: Option<Ipv4IndexReader>,
63 ipv6_index: Option<Ipv6IndexReader>,
64 record_columns: ColumnTableReader,
65 dict_tables: DictTablesReader,
66 chunk_cache: ChunkCache,
67}
68
69impl Reader<'static> {
70 pub fn open(path: impl AsRef<Path>) -> Result<Self> {
72 Self::open_with_options(path, ReaderOptions::default())
73 }
74
75 pub fn open_with_options(path: impl AsRef<Path>, options: ReaderOptions) -> Result<Self> {
77 #[cfg(feature = "mmap")]
78 {
79 let file = File::open(path)?;
80 let mmap = unsafe { memmap2::Mmap::map(&file)? };
82 Self::from_backing(Backing::Mmap(mmap), options)
83 }
84 #[cfg(not(feature = "mmap"))]
85 {
86 Self::open_file_with_options(path, options)
87 }
88 }
89
90 pub fn open_file(path: impl AsRef<Path>) -> Result<Self> {
92 Self::open_file_with_options(path, ReaderOptions::default())
93 }
94
95 pub fn open_file_with_options(path: impl AsRef<Path>, options: ReaderOptions) -> Result<Self> {
97 let file = File::open(path)?;
98 let len = file.metadata()?.len();
99 Self::from_backing(
100 Backing::File {
101 file: Mutex::new(file),
102 len,
103 },
104 options,
105 )
106 }
107
108 pub fn from_vec(bytes: Vec<u8>) -> Result<Self> {
110 Self::from_vec_with_options(bytes, ReaderOptions::default())
111 }
112
113 pub fn from_vec_with_options(bytes: Vec<u8>, options: ReaderOptions) -> Result<Self> {
115 Self::from_backing(Backing::Owned(bytes), options)
116 }
117}
118
119impl<'a> Reader<'a> {
120 pub fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
122 Self::from_bytes_with_options(bytes, ReaderOptions::default())
123 }
124
125 pub fn from_bytes_with_options(bytes: &'a [u8], options: ReaderOptions) -> Result<Self> {
127 Self::from_backing(Backing::Slice(bytes), options)
128 }
129
130 fn from_backing(backing: Backing<'a>, options: ReaderOptions) -> Result<Self> {
131 let total_len = backing.len();
132 if total_len < (HEADER_SIZE + FOOTER_SIZE) as u64 {
133 return Err(FormatError::UnexpectedEof.into());
134 }
135
136 let hdr_bytes = backing.read_slice(0, HEADER_SIZE)?;
138 let header = FileHeader::decode(&hdr_bytes)?;
139 if header.file_size != total_len {
140 return Err(ReaderError::Corrupt(format!(
141 "header file_size {} != actual {}",
142 header.file_size, total_len
143 )));
144 }
145
146 let footer_bytes = backing.read_slice(total_len - (FOOTER_SIZE as u64), FOOTER_SIZE)?;
147 let footer = FileFooter::decode(&footer_bytes)?;
148 if footer.section_dir_offset != header.section_dir_offset {
149 return Err(ReaderError::Corrupt(
150 "footer section_dir_offset mismatch".into(),
151 ));
152 }
153
154 let dir_len = (header.section_count as usize) * SECTION_ENTRY_SIZE;
155 let dir_bytes = backing.read_slice(header.section_dir_offset, dir_len)?;
156 let actual_dir_crc = crc32c(&dir_bytes);
157 if actual_dir_crc != footer.dir_crc32c {
158 return Err(FormatError::InvalidCrc {
159 expected: footer.dir_crc32c,
160 actual: actual_dir_crc,
161 }
162 .into());
163 }
164
165 let mut dc = Cursor::new(&dir_bytes);
166 let mut sections = Vec::with_capacity(header.section_count as usize);
167 for _ in 0..header.section_count {
168 let entry = SectionEntry::decode(&mut dc)?;
169 if entry
170 .offset
171 .checked_add(entry.length)
172 .is_none_or(|e| e > total_len)
173 {
174 return Err(FormatError::OutOfBounds("section range exceeds file size").into());
175 }
176 sections.push(entry);
177 }
178
179 if options.verify_all_checksums_on_open {
180 for sec in §ions {
181 let raw = backing.read_slice(sec.offset, sec.length as usize)?;
182 let actual = crc32c(&raw);
183 if actual != sec.crc32c {
184 return Err(FormatError::InvalidCrc {
185 expected: sec.crc32c,
186 actual,
187 }
188 .into());
189 }
190 }
191 }
192
193 let find_section = |kind: SectionKind| -> Option<SectionEntry> {
194 sections.iter().copied().find(|s| s.kind == kind)
195 };
196
197 let read_small_section = |sec: SectionEntry| -> Result<Vec<u8>> {
198 let raw = backing.read_slice(sec.offset, sec.length as usize)?;
199 let codec = sec.codec()?;
200 let dec = decompress(codec, &raw, Some(sec.uncompressed_length as usize))?;
201 Ok(dec.into_owned())
202 };
203
204 let metadata = if let Some(sec) = find_section(SectionKind::Metadata) {
206 let bytes = read_small_section(sec)?;
207 serde_json::from_slice(&bytes)?
208 } else {
209 serde_json::Value::Object(serde_json::Map::new())
210 };
211
212 let schema_sec =
214 find_section(SectionKind::Schema).ok_or(ReaderError::MissingSection("Schema"))?;
215 let schema_bytes = read_small_section(schema_sec)?;
216 let schema = Schema::decode(&schema_bytes)?;
217
218 let zstd_dicts = if let Some(sec) = find_section(SectionKind::ZstdDicts) {
220 let bytes = read_small_section(sec)?;
221 let zd = ZstdDicts::decode(&bytes)?;
222 zd.dicts.into_iter().map(|d| (crc32c(&d), d)).collect()
223 } else {
224 Vec::new()
225 };
226
227 let ipv6_aliases = if let Some(sec) = find_section(SectionKind::Ipv6Aliases) {
229 let bytes = read_small_section(sec)?;
230 Ipv6Aliases::decode(&bytes)?
231 } else {
232 Ipv6Aliases::default()
233 };
234
235 let ipv6_host_ext = if let Some(sec) = find_section(SectionKind::Ipv6HostExt) {
237 let bytes = read_small_section(sec)?;
238 Ipv6HostExt::decode(&bytes)?
239 } else {
240 Ipv6HostExt::default()
241 };
242
243 let ipv4_index = if let Some(sec) = find_section(SectionKind::Ipv4Index) {
245 Some(Ipv4IndexReader::parse(
246 &backing,
247 sec.offset,
248 sec.length,
249 options.ipv4_block_cache_capacity,
250 )?)
251 } else {
252 None
253 };
254 let ipv6_index = if let Some(sec) = find_section(SectionKind::Ipv6Index) {
255 Some(Ipv6IndexReader::parse(
256 &backing,
257 sec.offset,
258 sec.length,
259 options.ipv6_block_cache_capacity,
260 )?)
261 } else {
262 None
263 };
264
265 let rec_sec = find_section(SectionKind::RecordColumns)
267 .ok_or(ReaderError::MissingSection("RecordColumns"))?;
268 let record_columns = ColumnTableReader::parse(
269 0,
270 &backing,
271 rec_sec.offset,
272 rec_sec.length,
273 &schema.root,
274 schema.dicts.len(),
275 )?;
276
277 let dict_tables = if let Some(sec) = find_section(SectionKind::DictTables) {
278 DictTablesReader::parse(
279 &backing,
280 sec.offset,
281 sec.length,
282 &schema,
283 options.flat_dict_cache_capacity,
284 )?
285 } else {
286 DictTablesReader::empty()
287 };
288
289 Ok(Self {
290 backing,
291 header,
292 sections,
293 metadata,
294 schema,
295 zstd_dicts,
296 ipv6_aliases,
297 ipv6_host_ext,
298 ipv4_index,
299 ipv6_index,
300 record_columns,
301 dict_tables,
302 chunk_cache: ChunkCache::new(options.chunk_cache_capacity),
303 })
304 }
305
306 pub fn header(&self) -> &FileHeader {
307 &self.header
308 }
309
310 pub fn sections(&self) -> &[SectionEntry] {
311 &self.sections
312 }
313
314 pub fn metadata(&self) -> &serde_json::Value {
315 &self.metadata
316 }
317
318 pub fn schema(&self) -> &Schema {
319 &self.schema
320 }
321
322 pub fn zstd_dict_count(&self) -> usize {
323 self.zstd_dicts.len()
324 }
325
326 pub fn ipv6_aliases(&self) -> &Ipv6Aliases {
327 &self.ipv6_aliases
328 }
329
330 pub fn ipv6_host_ext(&self) -> &Ipv6HostExt {
331 &self.ipv6_host_ext
332 }
333
334 pub fn ipv4_entry_count(&self) -> u64 {
335 self.ipv4_index
336 .as_ref()
337 .map_or(0, Ipv4IndexReader::entry_count)
338 }
339
340 pub fn ipv6_entry_count(&self) -> u64 {
341 self.ipv6_index
342 .as_ref()
343 .map_or(0, Ipv6IndexReader::entry_count)
344 }
345
346 pub fn ipv4_transitions(&self) -> Result<Vec<(u32, u64)>> {
348 match &self.ipv4_index {
349 Some(v4) => v4.collect_transitions(&self.backing, &self.zstd_dicts),
350 None => Ok(Vec::new()),
351 }
352 }
353
354 pub fn ipv6_transitions(&self) -> Result<Vec<(u64, u64)>> {
356 match &self.ipv6_index {
357 Some(v6) => v6.collect_transitions(&self.backing, &self.zstd_dicts),
358 None => Ok(Vec::new()),
359 }
360 }
361
362 pub fn ipv4_ranges(&self) -> Result<Vec<(u32, u32, u64)>> {
364 let trans = self.ipv4_transitions()?;
365 let mut out = Vec::with_capacity(trans.len());
366 for i in 0..trans.len() {
367 let (start, rid) = trans[i];
368 if rid == 0 {
369 continue;
370 }
371 let end = if i + 1 < trans.len() {
372 trans[i + 1].0 - 1
373 } else {
374 u32::MAX
375 };
376 out.push((start, end, rid));
377 }
378 Ok(out)
379 }
380
381 pub fn ipv6_ranges(&self) -> Result<Vec<(u64, u64, u64)>> {
383 let trans = self.ipv6_transitions()?;
384 let mut out = Vec::with_capacity(trans.len());
385 for i in 0..trans.len() {
386 let (start, rid) = trans[i];
387 if rid == 0 {
388 continue;
389 }
390 let end = if i + 1 < trans.len() {
391 trans[i + 1].0 - 1
392 } else {
393 u64::MAX
394 };
395 out.push((start, end, rid));
396 }
397 Ok(out)
398 }
399
400 pub fn dict_entry_counts(&self) -> Vec<(String, u64)> {
401 self.schema
402 .dicts
403 .iter()
404 .zip(self.dict_tables.dicts.iter())
405 .map(|(s, d)| (s.name.clone(), d.entry_count()))
406 .collect()
407 }
408
409 pub fn verify_checksums(&self) -> Result<()> {
411 for sec in &self.sections {
412 let raw = self.backing.read_slice(sec.offset, sec.length as usize)?;
413 let actual = crc32c(&raw);
414 if actual != sec.crc32c {
415 return Err(FormatError::InvalidCrc {
416 expected: sec.crc32c,
417 actual,
418 }
419 .into());
420 }
421 }
422 Ok(())
423 }
424
425 pub fn clear_caches(&self) {
427 if let Some(v4) = &self.ipv4_index {
428 v4.clear_cache();
429 }
430 if let Some(v6) = &self.ipv6_index {
431 v6.clear_cache();
432 }
433 self.chunk_cache.clear();
434 for d in &self.dict_tables.dicts {
435 d.clear_cache();
436 }
437 }
438
439 pub fn compile_projection<I, S>(&self, paths: I) -> Result<Projection>
441 where
442 I: IntoIterator<Item = S>,
443 S: AsRef<str>,
444 {
445 Projection::from_paths(paths)
446 }
447
448 #[inline]
450 pub fn lookup_record_id(&self, ip: IpAddr) -> Result<u64> {
451 match ip {
452 IpAddr::V4(v4) => self.lookup_ipv4_record_id(v4),
453 IpAddr::V6(v6) => self.lookup_ipv6_record_id(v6),
454 }
455 }
456
457 #[inline]
458 pub fn lookup_ipv4_record_id(&self, ip: Ipv4Addr) -> Result<u64> {
459 let Some(v4) = &self.ipv4_index else {
460 return Ok(0);
461 };
462 v4.lookup(&self.backing, &self.zstd_dicts, u32::from(ip))
463 }
464
465 #[inline]
466 pub fn lookup_ipv6_record_id(&self, ip: Ipv6Addr) -> Result<u64> {
467 let ip_be = u128::from(ip);
468 if let Some(v4_u32) = self.ipv6_aliases.match_ipv6(ip_be) {
470 return match &self.ipv4_index {
471 Some(v4) => v4.lookup(&self.backing, &self.zstd_dicts, v4_u32),
472 None => Ok(0),
473 };
474 }
475 if let Some(rid) = self.ipv6_host_ext.lookup(ip_be) {
477 return Ok(rid);
478 }
479 let Some(v6) = &self.ipv6_index else {
481 return Ok(0);
482 };
483 v6.lookup(&self.backing, &self.zstd_dicts, (ip_be >> 64) as u64)
484 }
485
486 pub fn get_record_by_id(
488 &self,
489 record_id: u64,
490 projection: Option<&Projection>,
491 ) -> Result<Option<BTreeMap<String, Value>>> {
492 if record_id == 0 || record_id > self.header.record_count {
493 return Ok(None);
494 }
495 let row_idx = (record_id - 1) as usize;
496 let (rg, row_in_rg, rows_in_rg) = self.record_columns.row_group_of(row_idx);
497 let proj = projection.map_or(&ProjectionNode::All, |p| &p.root);
498 read_struct_row(
499 &self.backing,
500 &self.record_columns,
501 &self.dict_tables,
502 &self.chunk_cache,
503 &self.schema.root.root,
504 rg,
505 row_in_rg,
506 rows_in_rg,
507 proj,
508 )
509 }
510
511 pub fn lookup_value(&self, ip: IpAddr) -> Result<Option<Value>> {
513 let rid = self.lookup_record_id(ip)?;
514 if rid == 0 {
515 return Ok(None);
516 }
517 Ok(self.get_record_by_id(rid, None)?.map(Value::Map))
518 }
519
520 pub fn lookup_projected(&self, ip: IpAddr, projection: &Projection) -> Result<Option<Value>> {
522 let rid = self.lookup_record_id(ip)?;
523 if rid == 0 {
524 return Ok(None);
525 }
526 Ok(self
527 .get_record_by_id(rid, Some(projection))?
528 .map(Value::Map))
529 }
530
531 #[cfg(feature = "serde")]
534 pub fn lookup<T: for<'de> serde::Deserialize<'de>>(&self, ip: IpAddr) -> Result<Option<T>> {
535 let rid = self.lookup_record_id(ip)?;
536 if rid == 0 || rid > self.header.record_count {
537 return Ok(None);
538 }
539 let row_idx = (rid - 1) as usize;
540 let (rg, row_in_rg, rows_in_rg) = self.record_columns.row_group_of(row_idx);
541 crate::serde_de::deserialize_struct_row(
542 &self.backing,
543 &self.record_columns,
544 &self.dict_tables,
545 &self.chunk_cache,
546 &self.schema.root.root,
547 rg,
548 row_in_rg,
549 rows_in_rg,
550 &ProjectionNode::All,
551 )
552 }
553
554 #[cfg(feature = "serde")]
557 pub fn lookup_with_projection<T: for<'de> serde::Deserialize<'de>>(
558 &self,
559 ip: IpAddr,
560 projection: &Projection,
561 ) -> Result<Option<T>> {
562 let rid = self.lookup_record_id(ip)?;
563 if rid == 0 || rid > self.header.record_count {
564 return Ok(None);
565 }
566 let row_idx = (rid - 1) as usize;
567 let (rg, row_in_rg, rows_in_rg) = self.record_columns.row_group_of(row_idx);
568 crate::serde_de::deserialize_struct_row(
569 &self.backing,
570 &self.record_columns,
571 &self.dict_tables,
572 &self.chunk_cache,
573 &self.schema.root.root,
574 rg,
575 row_in_rg,
576 rows_in_rg,
577 &projection.root,
578 )
579 }
580}