The official client for GenesisDB. Synchronous and asynchronous clients, fully typed, one dependency (httpx), Python 3.9+.
pip install genesisdb-clientQuick start
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
# 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.
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.
for event in db.subscribe("/order", interval=0.5):
print(event.type, event.data)
if should_stop:
breakinterval 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 runs on the server. Results come back as rows, a bare aggregate as a single-element list.
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 {}.
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 tokenInline payloads are immutable. erase on a subject without reference payloads raises UnprocessableError (422).
Schemas
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
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.
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
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)
)