coip-cli 0.2.0

CLI for converting, importing, exporting, diffing, inspecting, querying, verifying, and benchmarking COI (.coi) IP databases
# coip — Columnar IP Database Format (`.coi`)

[![Crates.io (coip-reader)](https://img.shields.io/crates/v/coip-reader?label=coip-reader)](https://crates.io/crates/coip-reader)
[![Crates.io (coip-cli)](https://img.shields.io/crates/v/coip-cli?label=coip-cli)](https://crates.io/crates/coip-cli)
[![Docs.rs](https://img.shields.io/docsrs/coip-reader)](https://docs.rs/coip-reader)
[![CI](https://github.com/netkn001/coip/actions/workflows/ci.yml/badge.svg)](https://github.com/netkn001/coip/actions/workflows/ci.yml)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)

English | [简体中文](README.zh-CN.md)

**`coip`** is a modern, open-source, read-only **columnar IP database format (`.coi`)** with a Rust toolkit, an offline Web UI server (`coip-web`), and a zero-cgo pure-Go reader. It stores arbitrary structured IP→Record databases (including MaxMind `.mmdb` files such as GeoIP2/GeoLite2 City, Country, ASN, ISP, Enterprise, DB-IP, IPinfo, or custom CSV/JSONL feeds) at **~5× smaller on-disk size** (`GeoIP2-City.mmdb` 104.27 MB → **20.98 MB**), while providing **microsecond random point-lookups**, compile-once **column projection**, and build-time `--keep-fields` pruning.

## Key Features

- **Exact Type Fidelity & Simplified MMDB Import**: Preserves numeric widths, IEEE-754 `f64` bit patterns, `None` vs `false`/`0`/`""` optionality, and IPv6→IPv4 DAG alias semantics. When converting `.mmdb -> .coi`, multi-language `names` maps are automatically removed and flattened into a single English `name` field (strictly taking `en`; omitted if `en` is absent).
- **Self-Describing 6-Primitive Schema**: No hardcoded GeoIP fields; supports arbitrary schemas, dynamic inspection, build-time `--keep-fields` pruning, and compile-once **Column Projection**.
- **Two Tuned Profiles**:
  - **`Compact`** (Zstd + `Section 3: ZstdDicts` + `ZeroSkipDelta` / `LocalDictSplit`): **4.97×** smaller than `.mmdb` (**20.98 MB**).
  - **`UltraFast`** (pure-Rust LZ4): **3.52×** smaller than `.mmdb` (**29.62 MB**), **21.2 µs** cold 5-field lookup, **1.07 µs** warm 5-field lookup (**1.65× faster than `maxminddb`**), and **3.06M QPS** across 8 threads.
- **Zero-C Pure-Rust & Pure-Go Readers**: `coip-reader` defaults to pure-Rust `ruzstd` + `lz4_flex` (optional `zstd-c` feature); [`bindings/go`](bindings/go/) provides a standalone `CGO_ENABLED=0` pure-Go COI v1.0 reader.
- **CLI & Standalone Intranet Web UI**: `coip` supports persistent `coip bind` config, Nushell-style rounded tables, `coip <IP>` shorthand, and stdin piping; [`crates/coip-web`](crates/coip-web) embeds a zero-dependency Web UI & HTTP API server with batch IP extraction and hot reload.
- **Open Binary Specification**: Byte-level specification in [`docs/SPEC.md`](docs/SPEC.md) ([中文导读](docs/SPEC.zh-CN.md)), detailed benchmark report in [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) ([中文压测报告](docs/BENCHMARKS.zh-CN.md)), and cross-language golden vectors in [`test-vectors/`](test-vectors/).

## Simplified MMDB Output Format

Converting any MaxMind `.mmdb` to `.coi` replaces every nested multi-language `names` map (`city`, `continent`, `country`, `registered_country`, `represented_country`, `subdivisions[*]`) with a flat English `name` string:

```json
{
  "city": {
    "geoname_id": 1880252,
    "name": "Singapore"
  },
  "continent": {
    "code": "AS",
    "geoname_id": 6255147,
    "name": "Asia"
  },
  "country": {
    "geoname_id": 1880251,
    "iso_code": "SG",
    "name": "Singapore"
  },
  "location": {
    "accuracy_radius": 10,
    "latitude": 1.2872,
    "longitude": 103.8507,
    "time_zone": "Asia/Singapore"
  },
  "postal": {
    "code": "17"
  },
  "registered_country": {
    "geoname_id": 1880251,
    "iso_code": "SG",
    "name": "Singapore"
  }
}
```

## Real-World Benchmark (`GeoIP2-City.mmdb`, 672,963 unique records, simplified `en` `name`)

Measured on Intel Core i7-13700 (Windows x64, `coip bench` with `zstd-c`). Full section breakdown and Go benchmarks are in [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md).

| Format / Profile | File Size | Ratio vs MMDB | Cold 5-Field (`serde`) | Warm 5-Field (1T) | Warm 8-Thread QPS |
| --- | ---: | ---: | ---: | ---: | ---: |
| MaxMind `GeoIP2-City.mmdb` (`maxminddb` 5-field) | 104.27 MB | 1.00× | 2.06–2.24 µs | 1.77–1.88 µs | 2.98–3.12M QPS |
| MaxMind `GeoIP2-City.mmdb` (`maxminddb` full) | 104.27 MB | 1.00× | 2.93–3.56 µs | 2.32–2.49 µs | — |
| `coip` **Compact** (Zstd + 4 `ZstdDicts`) | **20.98 MB** | **4.97×** | 95.4 µs | **1.22 µs** (822K QPS) | **2.94M QPS** |
| `coip` **UltraFast** (pure-Rust LZ4) | **29.62 MB** | **3.52×** | **21.2 µs** | **1.07 µs** (937K QPS) | **3.06M QPS** |
| `coip` **Country-only pruned** (`--keep-fields`) | **1.06 MB** | **98.65×** | 26.1 µs | **0.35 µs** (2.86M QPS) | **6.43M QPS** |

## Workspace Layout

| Path | Description |
| --- | --- |
| [`docs/SPEC.md`](docs/SPEC.md) / [`docs/SPEC.zh-CN.md`](docs/SPEC.zh-CN.md) | Canonical COI v1.0 binary format specification (EN & ZH-CN) |
| [`docs/BENCHMARKS.md`](docs/BENCHMARKS.md) / [`docs/BENCHMARKS.zh-CN.md`](docs/BENCHMARKS.zh-CN.md) | Compression evolution, section breakdown, latency/QPS & architecture analysis |
| [`crates/coip-format`](crates/coip-format) | Header, Footer, Section Directory, Schema, Varint, CRC32C (`no_std` + `alloc`) |
| [`crates/coip-builder`](crates/coip-builder) | Generic `.coi` builder, simplified `.mmdb` importer (`names -> name`), LPM resolver, `--keep-fields` pruning, CSV/JSONL import |
| [`crates/coip-reader`](crates/coip-reader) | `mmap` / `&[u8]` / `File` reader, sharded LRU caches, Column Projection, streaming `serde` |
| [`crates/coip-cli`](crates/coip-cli) | CLI: `coip bind \| convert \| import \| export \| diff \| lookup \| query \| inspect \| verify \| bench` |
| [`crates/coip-web`](crates/coip-web) | Standalone offline intranet Web UI & HTTP API server (single & batch lookup, log IP extraction, hot reload) |
| [`bindings/go`](bindings/go) | Standalone pure-Go (`CGO_ENABLED=0`) COI v1.0 reader ([中文文档](bindings/go/README.zh-CN.md)) |
| [`test-vectors/`](test-vectors) | Cross-language golden `.coi` test vectors (`Compact` + `UltraFast`) and expected JSON |
| [`benches/`](benches) | Criterion benchmark suite comparing `coip-reader` vs `maxminddb` |

## Installation

### CLI (`coip`)

```bash
# Pure-Rust build (zero C dependencies)
cargo install coip-cli

# Optional: link system/bundled libzstd for faster Compact cold lookups
cargo install coip-cli --features zstd-c
```

### Rust Libraries (crates.io)

| Crate | Crates.io | Docs | Purpose |
| --- | --- | --- | --- |
| `coip-reader` | [![crates.io](https://img.shields.io/crates/v/coip-reader.svg)](https://crates.io/crates/coip-reader) | [docs.rs](https://docs.rs/coip-reader) | High-performance read-only `.coi` reader (`mmap`, LRU cache, Column Projection, streaming `serde`) |
| `coip-builder` | [![crates.io](https://img.shields.io/crates/v/coip-builder.svg)](https://crates.io/crates/coip-builder) | [docs.rs](https://docs.rs/coip-builder) | Generic `.coi` builder, simplified `.mmdb` (`names -> name`) / CSV / JSONL importer, LPM & pruning |
| `coip-format` | [![crates.io](https://img.shields.io/crates/v/coip-format.svg)](https://crates.io/crates/coip-format) | [docs.rs](https://docs.rs/coip-format) | Core binary format, schema, varint, CRC32C (`no_std` + `alloc`) |
| `coip-cli` | [![crates.io](https://img.shields.io/crates/v/coip-cli.svg)](https://crates.io/crates/coip-cli) | [docs.rs](https://docs.rs/coip-cli) | `coip` CLI binary |

```bash
cargo add coip-reader
# Optional: if building or converting .coi databases in Rust
cargo add coip-builder
```

## CLI Quick Start

Once installed via `cargo install coip-cli`, run `coip` directly (or `cargo run --release -p coip-cli -- ...` from this repo):

```bash
# Convert an MMDB file to .coi (automatically simplifies `names` -> English `name`; Compact Zstd + ZstdDicts, 4.97x smaller)
coip convert GeoIP2-City.mmdb GeoIP2-City.coi

# Convert with UltraFast profile (pure-Rust LZ4, 21.2 µs cold / 1.07 µs warm, 3.52x smaller)
coip convert GeoIP2-City.mmdb GeoIP2-City-fast.coi --profile ultrafast

# Build-time field pruning or .coi -> .coi repacking (no .mmdb needed!)
coip convert GeoIP2-City.coi GeoIP2-Country.coi \
  --keep-fields continent,country,registered_country

# Import any custom JSONL or CSV IP dataset (supports overlapping LPM CIDRs & IP ranges)
coip import custom_ips.csv custom.coi --profile compact

# Export a .coi database as canonical CIDR + JSONL (with optional projection)
coip export GeoIP2-City.coi --fields country.iso_code,country.name,location.time_zone --limit 100

# Diff two .coi databases (exact dual-stack IP additions, removals, and changes)
coip diff GeoIP2-City-old.coi GeoIP2-City-new.coi

# Inspect schema, dictionaries, ZstdDicts, and section sizes
coip inspect GeoIP2-City.coi

# Bind a default database once (saved to ~/.coip/config.toml; supports aliases & default --format)
coip bind GeoIP2-City.coi

# Direct top-level IP lookup (defaults to Nushell-style rounded table; uses bound DB, COIP_DB, or single .coi/.coip in cwd)
coip 8.8.8.8
coip 8.8.8.8 1.1.1.1 --fields country.iso_code,country.name,location.time_zone --json
echo "8.8.8.8 1.1.1.1" | coip query

# Or specify a file/alias explicitly (table by default; --json for pure JSON; --line for `ip => json`)
coip lookup GeoIP2-City.coi 8.8.8.8
coip query -d GeoIP2-City 8.8.8.8 \
  --fields country.iso_code,country.name,location.latitude,location.longitude,location.time_zone --json

# Exhaustively verify exact equivalence against source MMDB (with simplified English `name`)
coip verify GeoIP2-City.mmdb GeoIP2-City.coi

# Benchmark cold / warm / multi-threaded concurrent lookups vs maxminddb
coip bench GeoIP2-City.mmdb GeoIP2-City.coi

# Start the offline Web UI & HTTP API server (auto-loads ~/.coip/config.toml & ~/.coip/*.coi(p))
coip-web --listen 0.0.0.0:8090
```

## Rust Library Example

```rust
use std::net::IpAddr;
use coip_reader::Reader;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct GeoRecord {
    country: Option<Country>,
    location: Option<Location>,
}

#[derive(Debug, Deserialize)]
struct Country {
    iso_code: Option<String>,
    name: Option<String>,
}

#[derive(Debug, Deserialize)]
struct Location {
    latitude: Option<f64>,
    longitude: Option<f64>,
    time_zone: Option<String>,
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let reader = Reader::open("GeoIP2-City.coi")?;
    let proj = reader.compile_projection([
        "country.iso_code",
        "country.name",
        "location.latitude",
        "location.longitude",
        "location.time_zone",
    ])?;

    let ip: IpAddr = "8.8.8.8".parse()?;
    let rec: Option<GeoRecord> = reader.lookup_with_projection(ip, &proj)?;
    println!("{rec:#?}");
    Ok(())
}
```

See full runnable examples in [`crates/coip-reader/examples/basic_lookup.rs`](crates/coip-reader/examples/basic_lookup.rs) and [`crates/coip-builder/examples/custom_db.rs`](crates/coip-builder/examples/custom_db.rs):

```bash
cargo run -p coip-builder --example custom_db
cargo run -p coip-reader --example basic_lookup
```

## Pure-Go Reader (`bindings/go`)

```go
import coip "github.com/netkn001/coip/bindings/go"

r, err := coip.Open("GeoIP2-City.coi")
if err != nil {
    log.Fatal(err)
}
defer r.Close()

proj, _ := coip.CompileProjection("country.iso_code", "country.name", "location.latitude", "location.longitude")
rec, found, err := r.LookupProjectedString("8.8.8.8", proj)
```

See [`bindings/go/README.md`](bindings/go/README.md) ([简体中文](bindings/go/README.zh-CN.md)) for full Go documentation.

## License

MIT License — see [`LICENSE`](LICENSE).