Skip to content

About

Snodra messaging for Python: commands, queries, events, sagas and processors over Snodra Server

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Snodra Messaging for Python mascot

Snodra Messaging (Python)

Commands, queries, events, streams, scatter-gathers, subscriptions, sagas and idempotent external calls for asyncio services, routed by Snodra Server.

ci PyPI Python docs license


What it is

One package, snodra, that gives an asyncio service what it needs to send and serve requests in a Snodra system, with the same wire protocol as services written with any Snodra library: you write async functions, the library keeps the hub streams, permits, retries and timeouts.

  • Commands and queries through Snodra Server, with deadlines, retries and routing keys. A command or a query that is not shared, of a type the service handles itself, is answered in-process by its own handler, without the hub; Settings(always_route_through_hub=True) sends it through the hub like any other request. Settings(hub_enabled=False) (SNODRA_SERVER_ENABLED=false) runs the service without a hub: every command and point query of a type it handles, a shared one included, is answered in-process, any other type fails as no handler, and a scatter-gather, stream or subscription needs a hub. always_route_through_hub together with it is refused at startup, from code and from the environment alike.
  • Every query mode: point, scatter-gather, streaming and subscription; streams and updates are async iterables (async for).
  • Message contracts: @snodra.message_type("orders.PlaceOrder", version=2) names the version of a message type, and the library generates the JSON Schema of every handled request, reply, stream item, subscription type and consumed event from the dataclasses with the standard library alone (schema= and response_schema= replace a generated document with a checked-in one; a type it cannot describe raises snodra.InvalidContract before the app connects). Register declares one contract per handled type and one per consumed event type, so Snodra Server 0.8's schema catalogue lists them, and a changed schema at the same version is refused by the hub with FAILED_PRECONDITION (App.rejection). Every request carries snodra-schema-version and snodra-response-schema-version, in every mode, in-process answers and the saga relay included, and the hub routes it only to an instance serving exactly that contract. Every published event carries snodra-schema-version, and a consumer skips and acknowledges a record of another version of a type it handles.
  • Events through the outbox: publish inside the same transaction as the service's own writes; a relay publishes what the outbox holds, at least once, and event handlers commit their processed-event marker with their work.
  • Event processors and their status: handlers run in the default processor or in a named one (processor="orders"), each with one subscription, <prefix>.<processor> (the prefix is Settings.subscription_prefix, SNODRA_EVENTS_SUBSCRIPTION_PREFIX, the service name by default), and processor:<processor>:<eventId> markers, so a redelivery is skipped and one processor's failure does not hold another's. Every started processor reports its state, segments, counters and dead-letter count to the hub.
  • Processor control: the dashboard, or app.pause_processor and app.resume_processor from code, pauses and resumes a processor persistently on every instance; a leased reset stops its subscription, runs the @app.reset_handler handlers before anything is deleted or replayed, deletes the replayed range's markers, and replays from earliest, latest, timestamp or explicit positions. A handler declared with replay=False stays out of a replay, and control runs off the hub read loop.
  • Dead letters: Settings.dead_letter_mode (SNODRA_EVENTS_DEAD_LETTER_MODE) parks a record that exhausts its attempts in collection (the message store's dead letters, with list, retry, retry-all and discard from the dashboard or from code through app.dead_letters), publishes it to the <source>.dlt source with the snodra-dlt-* headers in event-store (when the store declares native-dead-letter), or logs it and moves on in log. Settings.dead_letter_retention (SNODRA_EVENTS_DEAD_LETTER_RETENTION_MS, 30 days by default) is how long a collected letter is kept.
  • Sagas: @app.saga("payment") classes with @saga_start, @saga_event and @saga_command_failed handlers, associations, a start key that keeps one live instance per order, an optimistic state version and parked failures, which app.saga_failures lists, retries (applied once) and discards. A handler records through SagaContext (send, publish, associate_with, end) inside the saga's transaction; a relay dispatches each saga's commands and events after it commits, in order under the saga's lease, renewed before each entry and while a send runs. A send is waited for at most its send timeout, and through the hub never less than the hub's bound for the command type. A command the relay gives up on comes back as the local SagaCommandFailed notice; a store failure leaves an event entry for the next poll, while an event the outbox refuses is given up as INVALID. A record whose saga stage alone failed is logged and skipped after the consumer's attempts, never a dead letter. Settings carries the saga attempts, the relay's poll (0.5 s), lease (30 s), attempts, backoff and send timeout, the deadline scheduler's poll and lease, and the external-call lease (SNODRA_SAGAS_*, SNODRA_DEADLINES_*, SNODRA_EXTERNAL_CALLS_LEASE_MS); sagas_enabled=False (SNODRA_SAGAS_ENABLED) runs no saga.
  • Saga deadlines: ctx.schedule(...) records a deadline and returns its id; ctx.cancel_deadline(id) and ctx.cancel_deadlines(name) cancel one or every deadline of a name, and @saga_deadline("charge-timeout", end=True) handles it. A leased scheduler claims the due deadlines, up to 100 a poll, runs each handler and marks it fired in one transaction.
  • Testing: snodra.testing.SagaFixture drives one saga class with events, command failures and time on the in-memory stores, using the real saga runtime with one attempt and firing due deadlines in order, so a test reads as one given…/when…/expect… chain. snodra.testing.InMemory runs a whole service without a hub, a broker or a database: it publishes events into the service, reads what it published and what its processors parked, and waits for processed-event markers. snodra.testing.InProcessHub serves a hub of its own on a free loopback port, for a test of two or more services together over their real gRPC streams: commands, point and scatter-gather queries, streams and subscriptions route between the apps, registered() lists the connected instances, and control() sends a processor control to one of them. It routes by the exact message contract (the type and both version headers) and refuses a type another service owns. It is a test helper, not the server: no permit queue, routing-key affinity, heartbeat eviction, stream or subscription duration, byte caps, access control or topology discovery, and no without_catalogue mode (the catalogue is always on, so a contract-less Register needs the scripted hub of the library's own suite). All three need nothing beyond the standard library and snodra.
from dataclasses import dataclass

from snodra import App, message_type
from snodra.testing import InMemory


@message_type("orders.Note")
@dataclass
class Note:
    text: str


async def test_a_note_is_handled() -> None:
    def register(app: App) -> None:
        @app.event_handler
        async def on_note(note: Note) -> None:
            pass

    async with InMemory("audit", register=register) as memory:
        event_id = await memory.publish(Note("hello"))
        await memory.await_processed(event_id)
from dataclasses import dataclass

from snodra import App, Settings, message_type
from snodra.testing import InProcessHub


@message_type("orders.Note")
@dataclass
class Note:
    text: str


async def test_a_note_reaches_the_other_service() -> None:
    async with InProcessHub() as hub:
        service = App(Settings(service="audit", hubs=(hub.address,)))
        caller = App(Settings(service="api", hubs=(hub.address,)))

        @service.query_handler
        async def echo(note: Note) -> Note:
            return note

        async with service, caller:
            await caller.ready(5)
            assert await caller.query(Note("hello"), Note) == Note("hello")
            assert hub.registered() == sorted([caller.instance_id, service.instance_id])
  • Idempotent external calls: @app.idempotent_command_handler and @app.idempotent_event_handler record each call in external_calls under its key before the body runs: the idempotency-key header, or key=lambda message, info: ... derived from the message. The first call wins, a repeat after success returns the first reply, a permanent failure is replayed, and a lapsed call is given up as unknown (or taken over with external_idempotent=True); a body cancelled with its caller leaves the call in progress until its lease lapses. Retryable and UnknownOutcome write the two reserved Error.details markers, which is_retryable and is_unknown_outcome read locally and from a hub; the saga relay owns the backoff.
  • Events from outside: snodra.verify_webhook checks a partner's webhook against a shared secret (the secret itself in X-Snodra-Webhook-Secret, or the HMAC-SHA256 of the raw body in X-Snodra-Signature; the previous secret during a rotation; constant-time comparisons), and app.accept_external(source, dedupe_key, event) applies the event once by the partner's delivery id: the service's event handlers, then its sagas, before it returns, never the event store. A repeat answers IngressResult.DUPLICATE; a handler failure is raised, so the partner retries.
  • A partner's topic: @app.external_source(name, provider) registers a translator from a partner's records to the service's own events, and snodra_kafka.KafkaExternalSource reads a partner's Kafka topic in a consumer group of its own (<service>.external.<name>, earliest or latest for a new group, TLS or SASL through the consumer's options), never creating the topic. Each record is applied once, locally, by the partner's key or its partition and offset, then acknowledged; a record that keeps failing is retried, logged and skipped, never dead-lettered.
  • Event and message stores: Kafka or RabbitMQ Streams for events; MongoDB, PostgreSQL or MySQL for the outbox, the processed-event markers, the dead letters and the processor control state. Each store is a separate package, selected when the service is built, with a from_env() of its own: the message stores read the retentions (SNODRA_OUTBOX_RETENTION_MS, SNODRA_IDEMPOTENCY_RETENTION_MS and the saga, deadline and external-call ones), and the RabbitMQ Streams store reads a password file, TLS with the CA its nodes are verified against, a load balancer in front of the nodes and the management API's own login and CA. A value an add-on cannot read is refused, naming its variable, and a printed configuration shows no password.
  • The hub connection: registration, heartbeats, reconnects, flow control, several hubs and an ordered shutdown. await app.ready() returns once every hub acknowledged the registration and fails at once with RegistrationRejected (its rejection names the hub, code and reason) when one refuses it; app.rejection keeps the latest refusal of any hub; await app.handlers_idle() waits for the handlers in flight to end, and app.handlers_in_flight counts them.
  • Connection status and contracts: app.auth_status reads how the instance authenticates (none, a static token, an access token with its expiry, fetch count and last error, or a client certificate with its fingerprint, end and rotations) and how many credential refreshes were sent, with no token or key in it. app.contracts() returns the message and event contracts the app declares (type, kind, version, JSON Schema of payload and answer) before or after it starts.
  • Credentials and identity: a token (static, or a file read again), an OAuth2 JWT (renewed) or a client certificate (rolled over to a renewed pair); the caller's token verified against the issuer's keys, and guards on handlers (authenticated(), role(), caller_matches()), or message_matches() for a rule that reads the decoded message too.
  • Telemetry behind an interface, with an OpenTelemetry implementation in the separate snodra-messaging-observability package: the hub client's calls, connections and credentials; every outbox send attempt and the outbox's backlog; each consumed record's final outcome per processor and its handlers' time; each processor's state, lag per segment and dead letters; sagas started and ended, each saga event's outcome, live sagas, pending saga dispatch entries, fired and overdue deadlines, saga command failures nothing handled, and each idempotent external call's outcome. Every label comes from a bounded set (an event type a processor does not handle is other).
  • Checked by tests anyone can run: the 39 checks of the conformance runner, the event-store and message-store kits on every add-on, and an interop run in which one saga continues across services on shared stores.

Install

pip install 'snodra-messaging~=0.21.0'
pip install 'snodra-messaging-observability~=0.21.0'   # optional: OpenTelemetry
pip install 'snodra-messaging-kafka~=0.21.0'           # or snodra-messaging-rabbitmq
pip install 'snodra-messaging-mongo~=0.21.0'           # or snodra-messaging-sql

The packages are on PyPI and need Python 3.12 or later; the core depends only on grpcio, protobuf and cryptography. An add-on pins the core version it was released with.

A handler

@app.command_handler
async def place_order(cmd: PlaceOrder) -> OrderReceipt:
    # A request sent while a request is handled carries its correlation id, the caller's token and the trace on.
    stock = await app.query(CheckStock(items=cmd.items), Stock)
    if not stock.available:
        raise snodra.HandlerError("out of stock", details={"orderId": cmd.order_id})
    return OrderReceipt(order_id=cmd.order_id, total=42)

A message is a dataclass with @snodra.message_type("..."); its payload is JSON by default (see snodra.Codec). A handler's return annotation is its response in the contract its Register declares to the hub (-> None for no content, AsyncIterator[Item] for a stream handler); a handler without one is refused when it is registered. Settings are dataclass options, and snodra.Settings.from_env() reads the SNODRA_* variables; keyword arguments win over the environment (Settings.from_env(subscription_prefix="orders-v2") subscribes every processor as orders-v2.<processor>).

An event

An event is a message type too. Build the service with one event store and one message store, publish inside the transaction that holds the service's own writes, and handle it in the processor that owns the subscription:

@snodra.message_type("orders.OrderPlaced")
@dataclass
class OrderPlaced:
    order_id: str
    total: int


@app.event_handler(processor="orders")
async def on_order_placed(event: OrderPlaced) -> None:
    await project_order(event)


async with store.transaction():
    await app.publish(OrderPlaced(order_id=cmd.order_id, total=cmd.total), key=cmd.order_id)

The relay publishes what the outbox holds, at least once; a redelivered event finds its processor:orders:<eventId> marker and is skipped. A handler without processor= runs in default.

A service's own admin endpoints work the dead letters, the parked saga events and the pause from code, as the hub's dashboard does: await app.dead_letters.retry(letter_id) answers Retried, Failed, Blocked (behind its key's head) and so on, await app.saga_failures.retry(failure_id) applies a parked saga event once, and await app.pause_processor("orders") pauses the processor on every instance.

Documentation

The hub must be Snodra Server 0.8 or later, whose schema catalogue is on by default and refuses a Register without contracts (this library declares them). Python generates its own schemas and the generators of the libraries differ, so a service in another language that serves the same type must declare the same checked-in schema as this one (Services in different languages). Quick start, the settings map, the API and testing: https://snodra.damoreira.com/docs/messaging/python/. A complete service is examples/quickstart. The library speaks the Snodra protocol (snodra.hub.v1). Where the specification is silent, SPEC-GAPS.md records what this library does. Counterparts: https://snodra.damoreira.com/.

Contributing

Branches off main, conventional commits, a pull request with a green workflow.

Releases

Versions are cut by CI from the commit subjects since the last tag, in Conventional Commits: a feat cuts the next minor, a fix or a perf the next patch, and docs, test, chore, ci, refactor, build and style cut nothing. Below 1.0.0 a ! or a BREAKING CHANGE: footer counts as a minor; 1.0.0 is declared by hand. Nobody pushes a tag: only the workflow makes tags.

All six published distributions carry one version and one tag, vX.Y.Z. The release commit, release: X.Y.Z, writes that version into the six pyproject.toml files of packages/, makes each add-on require snodra-messaging==X.Y.Z, and records them in uv.lock (scripts/bump-version.sh).

That commit is pushed only after scripts/release-check.sh X.Y.Z has built the six sdists and the six wheels, run twine check --strict on them, installed all six wheels on Python 3.12 and 3.14, imported every distribution and run the tests there. It is the check to run by hand when a release commit is in doubt, and it refuses a version PyPI already has.

Pull before you push: git pull --rebase first, because a release leaves a commit by the workflow's bot on main.

A failed release is finished, never repeated. Re-run failed jobs on the run: the version, the commit and the tag are already recorded, and the later jobs continue from them; the GitHub release on its own is recreated with the release workflow and the tag. PyPI keeps a version forever, so a wrong release is fixed by the next one, never by publishing the same version again.

License

Apache-2.0 © 2026 Guilherme D'Amoreira.

About

Snodra messaging for Python: commands, queries, events, sagas and processors over Snodra Server

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages