Metadata-Version: 2.4
Name: o192
Version: 0.2.2
Summary: ORION-192: ordered, resilient, independent, URL-safe 192-bit IDs for distributed systems.
Project-URL: Homepage, https://github.com/lh0x00/orion-192
Project-URL: Repository, https://github.com/lh0x00/orion-192
Project-URL: Issues, https://github.com/lh0x00/orion-192/issues
Project-URL: Changelog, https://github.com/lh0x00/orion-192/blob/main/CHANGELOG.md
Author: Lam Hieu and contributors
License-Expression: MIT
License-File: LICENSE
Keywords: csprng,distributed-systems,id,ksuid,monotonic,snowflake,sortable-id,uid,ulid,uuid
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.9
Provides-Extra: dev
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8.0; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Description-Content-Type: text/markdown

# o192 — Python

[![PyPI](https://img.shields.io/pypi/v/o192.svg)](https://pypi.org/project/o192/)
[![Python versions](https://img.shields.io/pypi/pyversions/o192.svg)](https://pypi.org/project/o192/)
[![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](./LICENSE)
[![Spec: v0](https://img.shields.io/badge/spec-v0-orange.svg)](https://github.com/lh0x00/orion-192/blob/main/SPEC.md)

Python reference implementation of [**ORION-192**](https://github.com/lh0x00/orion-192) — **O**rdered, **R**esilient, **I**ndependent, **O**paque-ish, **N**on-coordinated 192-bit identifiers for distributed systems.

ORION-192 produces fixed-width, URL-safe, lexicographically sortable IDs without a central coordinator, worker ID, or machine identity in the wire format. This package is byte-compatible with the [JavaScript](../javascript) and [Rust](../rust) reference implementations.

## Highlights

- **Zero runtime dependencies.** The CSPRNG comes from the standard library (`os.urandom` / `secrets`).
- **Fully typed**, ships a [`py.typed`](https://peps.python.org/pep-0561/) marker, and is `mypy --strict` clean.
- Supports **CPython 3.9+** and **PyPy**; pure-Python source, no native build step.
- **Strictly monotonic** within a generator instance, including across clock rollback.
- **Wire-compatible** with the JavaScript and Rust packages — same 24-byte layout, same 32-character canonical form.

## Install

```bash
python -m pip install o192
```

## Quick start

```python
from o192 import orionid, OrionIdGenerator, parse, is_valid

# 1. One-shot helper
print(orionid())  # → "0Pu_iDKVO9012BwIEM28oFojPMWLWeLU"

# 2. Long-lived generator (recommended for sustained throughput)
gen = OrionIdGenerator(epoch_ms=1_735_689_600_000)  # 2025-01-01 UTC
a, b = gen.next(), gen.next()
assert a < b  # strictly monotonic per generator

# 3. Parse and inspect
if is_valid(a):
    view = parse(a, epoch_ms=1_735_689_600_000)
    print(view.unix_datetime, view.fraction4096, view.counter)
```

## Command-line

The package installs an `o192` console entry point:

```bash
o192            # prints a single ORION-192 id
python -m o192  # equivalent
```

## API

### Top-level helpers

```python
def orionid() -> str: ...
def parse(identifier: str, *, epoch_ms: int = 0) -> ParsedOrionId: ...
def is_valid(identifier: str) -> bool: ...
def encode_sortable64(data: bytes | bytearray | memoryview) -> str: ...
def decode_sortable64(identifier: str) -> bytes: ...
```

### `OrionIdGenerator`

```python
OrionIdGenerator(
    *,
    epoch_ms: int = 0,                                   # private epoch in ms
    random_pool_bytes: int = 65_536,                     # 14 .. 16 MiB
    clock: Callable[[], int] | None = None,              # test-only
    random_bytes: Callable[[int], bytes] | None = None,  # test-only
)

generator.next() -> str                       # 32-char canonical string
generator.next_bytes() -> bytes               # 24-byte binary form
generator.parse(identifier: str) -> ParsedOrionId

# Read-only telemetry
generator.epoch_ms: int
generator.last_time_key: int                  # -1 before the first call
generator.counter: int                        # 20-bit counter
generator.clock_rollbacks: int                # observed backward jumps
generator.synthetic_ticks: int                # counter-overflow advances
```

### `ParsedOrionId`

```python
@dataclass(frozen=True, slots=True)
class ParsedOrionId:
    id: str                       # original canonical string
    binary: bytes                 # 24-byte binary form
    unix_ms: int                  # relative_ms + epoch_ms
    unix_datetime: datetime | None
    relative_ms: int              # 48-bit ms field
    fraction4096: int             # 12-bit sub-ms fraction
    approx_sub_ms: float          # fraction4096 / 4096, in ms
    counter: int                  # 20-bit counter
    random_hex: str               # 14-byte tail as lower-case hex
```

### Errors

```python
class OrionIdError(ValueError):
    code: str
    # One of: INVALID_LENGTH, INVALID_CHARACTER, INVALID_OPTION,
    #         TIMESTAMP_OVERFLOW, COUNTER_OVERFLOW, RANDOM_FAILURE
```

`OrionIdError` subclasses `ValueError`, so existing `except ValueError` handlers continue to work. Inspect `error.code` for programmatic handling.

## Performance

A single `OrionIdGenerator` produces roughly **400 k – 1 M IDs/second** on a modern laptop under CPython, and noticeably more under PyPy. Numbers are indicative — run the bundled benchmark on your target hardware:

```bash
python ../../benchmarks/python_bench.py
```

## Status

ORION-192 is at **spec `v0`** — implementation-complete, cross-language conformant, and **wire-frozen**. See the [project status](https://github.com/lh0x00/orion-192#status) for the full stability statement.

## Specification & related

- [Specification (`SPEC.md`)](https://github.com/lh0x00/orion-192/blob/main/SPEC.md) — normative wire format and algorithm.
- [Design rationale (`docs/RATIONALE.md`)](https://github.com/lh0x00/orion-192/blob/main/docs/RATIONALE.md) — why 192 bits, why this layout.
- [Storage guide (`docs/DATABASE.md`)](https://github.com/lh0x00/orion-192/blob/main/docs/DATABASE.md) — column types, collation, indexing.
- [Security policy (`SECURITY.md`)](https://github.com/lh0x00/orion-192/blob/main/SECURITY.md) — threat model and disclosure process.
- Sibling implementations: [JavaScript](https://www.npmjs.com/package/orion-192) · [Rust](https://crates.io/crates/o192).

## License

Licensed under the [MIT License](./LICENSE) — Copyright © 2026 Lam Hieu and contributors.
