Metadata-Version: 2.5
Name: genesisdb-client
Version: 2.0.0
Summary: The official Python client for GenesisDB, the open source event sourcing database
Project-URL: Homepage, https://www.genesisdb.io
Project-URL: Documentation, https://docs.genesisdb.io
Project-URL: Repository, https://github.com/genesisdb-io/genesisdb-io-client-python
Author-email: Patric Eckhart <mail@genesisdb.io>
License: MIT
License-File: LICENSE
Keywords: client,cloudevents,cqrs,database,event-sourcing,event-store,genesisdb
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
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 :: Database
Classifier: Typing :: Typed
Requires-Python: >=3.9
Requires-Dist: httpx>=0.24
Provides-Extra: dev
Requires-Dist: pytest-asyncio>=0.21; extra == 'dev'
Requires-Dist: pytest>=7; extra == 'dev'
Requires-Dist: respx>=0.20; extra == 'dev'
Description-Content-Type: text/markdown

# GenesisDB client for Python

The official client for [GenesisDB](https://www.genesisdb.io), the open source event sourcing database. Synchronous and asynchronous clients, fully typed, one dependency (`httpx`), Python 3.9+.

> **Version 2.0.0 targets GenesisDB 2.0 and is not compatible with GenesisDB 1.x servers or with the 1.x client API.** Routes, configuration, type names and method signatures have changed. Keep a 1.x client for a 1.x server.
>
> Existing 1.x clients keep working against a GenesisDB 2.0 server, which still serves the unchanged 1.x API under `/api/v1`, so the server can be upgraded first and the clients at your own pace. New 2.0 features (stored events returned by commit, upper bounds, schemas, typed errors) need this 2.0.0 client.

```bash
pip install genesisdb-client
```

## Quick start

```python
import os
from genesisdb import Client

db = Client(url="http://localhost:8080", token=os.environ["GENESISDB_AUTH_TOKEN"])

db.commit([
    {"source": "io.example.shop", "subject": "/customer/42", "type": "io.example.shop.customer-registered", "data": {"name": "Bruce Wayne"}},
])

events = db.fetch("/customer/42")
```

`url` and `token` fall back to `GENESISDB_URL` and `GENESISDB_AUTH_TOKEN`, so `Client()` works in an environment that sets both. The client is a context manager, `with Client() as db:` closes the connection pool on exit.

## Events

```python
# Commit a batch atomically. The server assigns ID, time and hashes and returns the stored events.
stored = db.commit([
    {"source": "io.example.shop", "subject": "/order/1", "type": "io.example.shop.order-placed", "data": {"total": 99.5}},
    {"source": "io.example.shop", "subject": "/order/1/item/1", "type": "io.example.shop.item-added", "data": {"sku": "A1", "qty": 2}},
])
stored[0].id    # "3f2c..."
stored[0].hash  # "a9b1..."
stored[0].time  # datetime with timezone

# A subject with one segment gets a generated ID appended.
db.commit([{"source": "io.example.shop", "subject": "/customer", "type": "io.example.shop.customer-registered", "data": {"name": "Selina"}}])

# Fetch a subject with all descendants, in commit order.
all_events = db.fetch("/order/1")

# Resume after a known event, or stop at one.
since = db.fetch("/order", {"lowerBound": last_seen_id, "includeLowerBoundEvent": False})
until = db.fetch("/order", {"upperBound": some_id, "includeUpperBoundEvent": True})

# Only the newest event of a type below the subject.
latest = db.fetch("/order/1", {"latestByEventType": "io.example.shop.order-placed"})
```

Events are frozen dataclasses with the CloudEvents attribute names (`source`, `subject`, `type`, `id`, `time`, `data`, `hash`, `predecessorhash`, ...).

## Preconditions

Preconditions are checked atomically with the commit. A failed precondition raises `PreconditionFailedError` and writes nothing.

```python
from genesisdb import PreconditionFailedError, is_subject_new, is_query_result_true

try:
    db.commit(
        [{"source": "io.example.shop", "subject": "/customer/42", "type": "io.example.shop.customer-registered", "data": {"email": "bruce@example.com"}}],
        [
            is_subject_new("/customer/42"),
            is_query_result_true("STREAM e FROM events WHERE e.data.email == 'bruce@example.com' MAP COUNT() == 0"),
        ],
    )
except PreconditionFailedError as error:
    print(error.precondition_type, error.reason)  # "isSubjectNew" "subject /customer/42 already has events"
```

Helpers: `is_subject_new`, `is_subject_existing`, `is_query_result_true`.

## Subscriptions

`subscribe` is a generator over Server-Sent Events. It yields the existing history first, then new events as they are committed, and runs until you stop iterating.

```python
for event in db.subscribe("/order", interval=0.5):
    print(event.type, event.data)
    if should_stop:
        break
```

`interval` is the poll interval in seconds (default 1). The bound options of `fetch` work here as well, so a consumer that persists the last processed event ID resumes with `options={"lowerBound": ...}`.

## Queries

[GDBQL](https://github.com/genesisdb-io/genesisdb/blob/main/docs/gdbql.md) runs on the server. Results come back as rows, a bare aggregate as a single-element list.

```python
rows = db.query("STREAM e FROM events WHERE e.subject UNDER '/customer' MAP { name: e.data.name, total: e.data.total }")

[count] = db.query("STREAM e FROM events WHERE e.type == 'io.example.shop.order-placed' MAP COUNT()")

by_category = db.query(
    "STREAM e FROM events WHERE e.type == 'io.example.shop.item-added' GROUP BY e.data.category "
    "MAP { category: e.data.category, items: COUNT(), revenue: SUM(e.data.total) }"
)
```

## GDPR: reference payloads and erasure

Store a payload as reference data and it can be erased later. The event, its hash and the chain stay intact, the payload becomes `{}`.

```python
db.commit([
    {
        "source": "io.example.shop",
        "subject": "/customer/42",
        "type": "io.example.shop.customer-registered",
        "data": {"name": "Bruce", "email": "bruce@example.com"},
        "options": {"storeDataAsReference": True},
    },
])

db.erase("/customer/42")  # administrator token
```

Inline payloads are immutable. `erase` on a subject without reference payloads raises `UnprocessableError` (422).

## Schemas

```python
db.register_schema("io.example.shop.order-placed", {
    "type": "object",
    "properties": {"total": {"type": "number"}, "currency": {"type": "string"}},
    "required": ["total"],
})

schemas = db.schemas()
```

Commits of that type are validated. A violation raises `GenesisDBError` with status 400.

## Catalog, status, administration

```python
db.subjects()          # ["/customer", "/order"]
db.types()             # ["io.example.shop.customer-registered", ...]
db.status()            # Status(version=..., event_count=..., ready=True, ...)
db.ping()              # "Pong", no token required

db.audit()             # "Audit passed. All 1234 events integrity checks succeeded."
```

Audit, erase and schema registration need the administrator token. Everything else works with a reader token (`GENESISDB_READ_TOKEN`), commit additionally with a writer token.

## Async

`AsyncClient` has the same methods, awaited. `subscribe` is an async generator.

```python
import asyncio
from genesisdb import AsyncClient

async def main():
    async with AsyncClient() as db:
        await db.commit([{"source": "app", "subject": "/order/1", "type": "order.placed", "data": {"total": 10}}])
        async for event in db.subscribe("/order"):
            print(event.id)

asyncio.run(main())
```

## Errors

Every non-2xx answer raises `GenesisDBError` with `status`, `body` and `operation`. Subclasses: `PreconditionFailedError` (412, with `precondition_type` and `reason`), `AuthenticationError` (401, 403), `NotFoundError` (404), `ConflictError` (409), `UnprocessableError` (422), `NotReadyError` (503). A subscription that the server ends with an error raises `GenesisDBError` from the generator.

## Configuration

```python
Client(
    url="http://localhost:8080",  # or GENESISDB_URL
    token="...",                  # or GENESISDB_AUTH_TOKEN
    timeout=30.0,                 # seconds, for non-streaming calls, None disables
    http=httpx.Client(...),       # optional, bring your own httpx client (proxies, TLS, retries)
)
```

## Development

```bash
python -m venv .venv && . .venv/bin/activate
pip install -e ".[dev]"
pytest tests/test_client.py                                                  # unit tests against a mocked server
GENESISDB_URL=http://localhost:8080 GENESISDB_AUTH_TOKEN=... pytest tests/test_integration.py   # against a running GenesisDB
```

## License

MIT
