coip-reader 0.1.0

High-performance read-only reader for COI (.coi) columnar IP databases with projection, LRU caching, and serde support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
//! High-level `.coi` database reader (`Reader`).

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};

/// Configuration options for opening a `.coi` database.
#[derive(Debug, Clone)]
pub struct ReaderOptions {
    /// Maximum number of decoded IPv4 granule blocks kept in LRU cache (default 256 ≈ 4 MB max).
    pub ipv4_block_cache_capacity: usize,
    /// Maximum number of decoded IPv6 granule blocks kept in LRU cache (default 128 ≈ 3 MB max).
    pub ipv6_block_cache_capacity: usize,
    /// Maximum number of decoded ColumnTable RowGroup chunks kept in LRU cache (default 256).
    pub chunk_cache_capacity: usize,
    /// Maximum number of decoded blocks per large chunked FlatDict (default 32).
    pub flat_dict_cache_capacity: usize,
    /// Whether to verify CRC32C checksums of all sections upon opening (default `false`;
    /// Header + Section Directory CRCs are always verified).
    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,
        }
    }
}

/// High-level read-only reader for `.coi` columnar IP databases.
///
/// Thread-safe (`Send + Sync`): share across threads with `Arc<Reader<'static>>`.
pub struct Reader<'a> {
    backing: Backing<'a>,
    header: FileHeader,
    sections: Vec<SectionEntry>,
    metadata: serde_json::Value,
    schema: Schema,
    /// Precomputed `(crc32c, raw_dict_bytes)` for `Section 3: ZstdDicts`.
    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> {
    /// Open a `.coi` file from disk (uses memory mapping when `mmap` feature is enabled, else `File`).
    pub fn open(path: impl AsRef<Path>) -> Result<Self> {
        Self::open_with_options(path, ReaderOptions::default())
    }

    /// Open a `.coi` file with custom cache/verification options.
    pub fn open_with_options(path: impl AsRef<Path>, options: ReaderOptions) -> Result<Self> {
        #[cfg(feature = "mmap")]
        {
            let file = File::open(path)?;
            // SAFETY: `.coi` files are read-only immutable databases.
            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)
        }
    }

    /// Open a `.coi` file using explicit `File` positioned I/O (no `mmap`).
    pub fn open_file(path: impl AsRef<Path>) -> Result<Self> {
        Self::open_file_with_options(path, ReaderOptions::default())
    }

    /// Open a `.coi` file using `File` I/O with custom options.
    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,
        )
    }

    /// Open a `.coi` database from an owned byte buffer.
    pub fn from_vec(bytes: Vec<u8>) -> Result<Self> {
        Self::from_vec_with_options(bytes, ReaderOptions::default())
    }

    /// Open from an owned `Vec<u8>` with custom options.
    pub fn from_vec_with_options(bytes: Vec<u8>, options: ReaderOptions) -> Result<Self> {
        Self::from_backing(Backing::Owned(bytes), options)
    }
}

impl<'a> Reader<'a> {
    /// Open a `.coi` database directly from a borrowed byte slice (zero-copy).
    pub fn from_bytes(bytes: &'a [u8]) -> Result<Self> {
        Self::from_bytes_with_options(bytes, ReaderOptions::default())
    }

    /// Open from a borrowed byte slice with custom options.
    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());
        }

        // 1. Parse and verify Header + Footer + Section Directory
        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 &sections {
                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())
        };

        // 2. Metadata
        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())
        };

        // 3. Schema
        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)?;

        // 3b. ZstdDicts (optional)
        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()
        };

        // 4. Ipv6Aliases
        let ipv6_aliases = if let Some(sec) = find_section(SectionKind::Ipv6Aliases) {
            let bytes = read_small_section(sec)?;
            Ipv6Aliases::decode(&bytes)?
        } else {
            Ipv6Aliases::default()
        };

        // 5. Ipv6HostExt
        let ipv6_host_ext = if let Some(sec) = find_section(SectionKind::Ipv6HostExt) {
            let bytes = read_small_section(sec)?;
            Ipv6HostExt::decode(&bytes)?
        } else {
            Ipv6HostExt::default()
        };

        // 6. Ipv4Index & Ipv6Index
        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
        };

        // 7. RecordColumns & DictTables
        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)
    }

    /// Return all IPv4 merged transition points `(start_u32, record_id)` in ascending order.
    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()),
        }
    }

    /// Return all native IPv6 `/64` merged transition points `(start_hi64, record_id)` in ascending order.
    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()),
        }
    }

    /// Return all populated inclusive IPv4 ranges `(start_u32, end_u32, record_id)` (`record_id > 0`).
    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)
    }

    /// Return all populated inclusive IPv6 `/64` ranges `(start_hi64, end_hi64, record_id)` (`record_id > 0`).
    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()
    }

    /// Verify CRC32C checksums of every section in the `.coi` file.
    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(())
    }

    /// Clear all LRU caches (useful for benchmarking cold lookups).
    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();
        }
    }

    /// Compile a column projection once at startup for fast projected lookups.
    pub fn compile_projection<I, S>(&self, paths: I) -> Result<Projection>
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        Projection::from_paths(paths)
    }

    /// Resolve an `IpAddr` to its internal 1-based `record_id` (`0` = NotFound).
    #[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);
        // 1. Check IPv6 -> IPv4 aliases first
        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),
            };
        }
        // 2. Check > /64 host overrides (authoritative, including explicit 0 holes)
        if let Some(rid) = self.ipv6_host_ext.lookup(ip_be) {
            return Ok(rid);
        }
        // 3. Check native /64 IPv6 index
        let Some(v6) = &self.ipv6_index else {
            return Ok(0);
        };
        v6.lookup(&self.backing, &self.zstd_dicts, (ip_be >> 64) as u64)
    }

    /// Materialize a unique record directly by 1-based `record_id` (`1..=record_count`).
    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,
        )
    }

    /// Look up an IP address and return its full dynamic record (`BTreeMap<String, Value>`).
    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))
    }

    /// Look up an IP address and materialize ONLY the fields selected by `projection`.
    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))
    }

    /// Look up an IP address and deserialize the full record directly into a typed `serde` struct `T`
    /// without constructing any intermediate `BTreeMap` or `Value`.
    #[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,
        )
    }

    /// Look up an IP address using a compiled `Projection` and deserialize directly into `T`
    /// (zero intermediate `BTreeMap` / `Value` allocation).
    #[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,
        )
    }
}