Skip to main content

vaitty_eventbus

The platform event-bus SDK for Vaitty/Rapihogar: a provider-neutral Python library for decoupled, event-driven communication. Keeps a tiny emit / on / trigger API across a legacy Django 3.8 monolith and modern FastAPI 3.12 services, with GCP Pub/Sub as the default transport in deployed environments.


🚀 Features

  • 🎯 Minimal API: emit (produce), on (subscribe), trigger (dispatch).
  • 🧱 Typed event DTOs — one @dataclass per topic (1 type = 1 topic), auto-registered.
  • 🔌 Pluggable channels: console, file (base, stdlib-only), http (via the [http] extra or your own session) and pubsub (GCP, via the [pubsub] extra).
  • 🧵 Runtime listeners for consumers: SyncListener (Celery/Django) and AsyncListener (FastAPI/asyncio).
  • ✉️ Portable 3-layer envelope (payload · library metadata · channel envelope); metadata (event_id, source, correlation_id, …) travels as Pub/Sub attributes.
  • 🧩 Provider-neutral: the public API never exposes google.cloud.pubsub types. Switching bus = changing the value of EVENTBUS_CHANNEL.
  • 🪶 One package, no forks: sync and async coexist via lazy imports + optional extras. The base install has no mandatory dependency (not even requests) and runs on Python 3.8.

📦 Installation

Install only what the service needs — the extras are additive:

# Base — console/file channels + typed events. No mandatory deps (not even
# requests). Python 3.8+. The http channel also works on base if you pass your
# own `session` (e.g. the legacy monolito, que ya trae su requests, posteando al
# bridge — así no queda forzado a bumpear requests; ver "Customizing the HTTP
# transport").
pip install vaitty-eventbus

# + HTTP channel's default transport (requests) — solo si NO pasás tu propio
#   session. Trae requests>=2.31 (piso por CVE-2023-32681).
pip install 'vaitty-eventbus[http]'

# + GCP Pub/Sub backend — producers and consumers on Pub/Sub. Python 3.9+.
pip install 'vaitty-eventbus[pubsub]'

# + FastAPI — to run the AsyncListener inside a FastAPI lifespan. Python 3.10+.
pip install 'vaitty-eventbus[fastapi]'

# Async service / bridge on Pub/Sub + FastAPI (the usual combo for a modern consumer).
pip install 'vaitty-eventbus[pubsub,fastapi]'

# + Celery — context for the SyncListener in a worker.
pip install 'vaitty-eventbus[celery]'

Pin it in requirements.txt:

vaitty-eventbus[pubsub,fastapi]>=0.2.0
Extra Pulls in For Python
(base) — (stdlib only) console/file channels, typed DTOs, http channel with your own session 3.8+
[http] requests>=2.31 http channel's default transport + egress relay 3.8+
[pubsub] google-cloud-pubsub pubsub channel — emit/consume on GCP 3.9+
[fastapi] fastapi AsyncListener in a FastAPI app 3.10+
[celery] celery SyncListener in a Celery worker 3.9+

The pubsub channel and the async listener are imported lazily: a sync service never parses aio.py, and importing the library without the [pubsub] extra never fails — the factory raises a clear ConfigError only if you actually select the pubsub channel without it. requests is likewise lazy: import vaitty_eventbus and the console/file/pubsub channels never import it. The http channel imports it only when you don't pass your own session (so a service with its own requests isn't forced to bump it; install [http] for the default).


🛠 Configuration

Configure through environment variables (or a dict passed to EventHandlerFactory.from_config). The full surface is deliberately tiny:

Variable Scope What Default
EVENTBUS_CHANNEL all console · file · http · pubsub · custom console
EVENTBUS_SOURCE all identity of the producing service (bare service name, e.g. connect-service) — goes into source and derives subscription names ""
GOOGLE_CLOUD_PROJECT pubsub GCP project of the environment (used to build topic/subscription paths) (required for pubsub)
EVENTBUS_FILE file log file path events.log
EVENTBUS_HTTP_ENDPOINT http target URL http://example.com/events
EVENTBUS_HTTP_METHOD http HTTP method POST
EVENTBUS_HTTP_TIMEOUT http per-request timeout (s) (none)

There is no provider-named key (EVENTBUS_PUBSUB_* is forbidden) and no secret: on GKE, credentials come from Workload Identity. GOOGLE_CLOUD_PROJECT is a standard Google var and must be set per environment (GKE does not inject it) — without it, Pub/Sub publishes fail with project=None.

from vaitty_eventbus import EventHandlerFactory

handler = EventHandlerFactory.from_env()  # reads EVENTBUS_* from os.environ
# or
handler = EventHandlerFactory.from_config(
    {"EVENTBUS_CHANNEL": "pubsub", "EVENTBUS_SOURCE": "connect-service"}
)

🧱 Typed events (DTOs)

A typed event is a @dataclass subclass of Event that declares its topic as a class attribute (no annotation, so dataclass does not treat it as a field). Defining it auto-registers the bijective topic ↔ class mapping (1 type = 1 topic).

Platform DTOs ship in the library, under vaitty_eventbus.catalog — producer and consumer import the same class, so the payload shape can't drift between the two ends of the bus (flat payload, ADR-047). Importing the catalog auto-registers its topics.

from vaitty_eventbus.catalog import PolicyDisenrolled, PolicyEnrolled

# Flat payload (no wrapper). Dates are ISO-8601 **with timezone**, carried as
# strings — the SDK never parses them, it only preserves the contract.
evt = PolicyEnrolled(
    policy_number="900001",
    type="property",
    product_id=137,
    city_id=100,
    address="Av. Siempre Viva",
    issue_date="2026-08-03T10:30:00-03:00",
    valid_from="2026-09-02T00:00:00-03:00",
    valid_until="2027-09-02T23:59:59-03:00",
)

To define your own, subclass Event and declare topic as a class attribute:

import dataclasses
from vaitty_eventbus import Event


@dataclasses.dataclass
class VisitConfirmed(Event):
    topic = "core.visit.confirmed"  # class attribute → auto-registered
    visit_id: int
    confirmed_at: str  # ISO-8601 with tz

The raw form Event("core.policy.enrolled", {...}) stays valid as an escape hatch. DTOs live in the base package (pure dataclasses, no GCP dep), so a legacy 3.8 service can install the base library just to deserialize what it receives.


🌿 Producing: emit

emit accepts a typed DTO or the raw (topic, payload) form. It builds the library metadata (envelope) and sends through the configured channel.

handler = EventHandlerFactory.from_env()  # EVENTBUS_CHANNEL=pubsub

# Typed (preferred) — `evt` is a catalog DTO (see "Typed events"):
handler.emit(evt)

# Raw escape hatch:
handler.emit("core.policy.enrolled", {"policy_number": "900001", "type": "property"})

# Optional envelope metadata as kwargs:
handler.emit(evt, correlation_id="corr-xyz", tenant_id="t1")

On the pubsub channel this publishes to the topic named after the event type (core.policy.enrolled); data + occurred_at go to the message body, the rest of the metadata to attributes. emit waits for the publish to be confirmed (at-least-once on the producer side) and returns the EventMessage.


🎧 Consuming: on + trigger

on(pattern, callback) registers a handler for a topic or wildcard (core.policy.*, *). trigger(incoming) resolves the typed DTO from the registry and calls each matching callback with the typed event instance (not the raw payload):

def on_enrolled(event: PolicyEnrolled):
    print(event.policy_number, event.type)  # typed fields


handler.on("core.policy.enrolled", on_enrolled)

# `incoming` may be an Event, an EventMessage, or a dict envelope:
handler.trigger(
    {"type": "core.policy.enrolled", "data": {"policy_number": "900001", "type": "property"}}
)

get_matching_callbacks(event) is available if you want to drive dispatch yourself (each callback is yielded once even if several patterns match).


🧵 Runtime listeners (consumers on Pub/Sub)

For services that pull from Pub/Sub, the SDK ships two listeners. The set of subscriptions is derived from the on() registrations — you never write subscription names.

Async (FastAPI / asyncio) — [pubsub,fastapi]:

from contextlib import asynccontextmanager
from fastapi import FastAPI
from vaitty_eventbus import EventHandlerFactory
from vaitty_eventbus.runtime import AsyncListener


@asynccontextmanager
async def lifespan(app):
    handler = EventHandlerFactory.from_env()  # EVENTBUS_CHANNEL=pubsub
    handler.on("core.policy.enrolled", on_enrolled)
    listener = AsyncListener(handler, handler.channel, source=handler.source, concurrency=10)
    await listener.start()  # validates its subscriptions, then pulls
    try:
        yield
    finally:
        await listener.stop()


app = FastAPI(lifespan=lifespan)

AsyncListener awaits the dispatch and acks only after success (nack → redelivery/DLQ), with bounded concurrency. Only start it when there is at least one on() — an empty listener has nothing to consume.

Sync (Celery / Django 3.9+) — [pubsub] (+[celery]):

from vaitty_eventbus.runtime import SyncListener

listener = SyncListener(handler, handler.channel, source=handler.source, concurrency=1)
listener.run()  # blocking loop; or start()/stop() to run in a daemon thread

Both are imported lazily (vaitty_eventbus.runtime.__getattr__): importing runtime does not parse aio.py, so a sync service never drags async code in.


🧾 Delivery metadata in the handler (current_delivery)

The handler receives the payload as the typed DTO. The envelope metadata — who emitted it, when, under which schema version — is read on the side via current_delivery(), without changing the handler signature. It is populated while a listener is dispatching a message (outside dispatch it returns None):

from vaitty_eventbus.runtime import current_delivery


def on_enrolled(event: PolicyEnrolled):
    ctx = current_delivery()  # DeliveryContext for the message in flight (or None)
    log.info(
        "policy=%s occurred_at=%s source=%s schema_v=%s corr=%s attempt=%s",
        event.policy_number,
        ctx.occurred_at,  # logical event time (from the envelope) — use to order
        ctx.source,  # producing service
        ctx.schema_version,  # payload contract version (forward-compat)
        ctx.correlation_id,  # end-to-end trace id
        ctx.delivery_attempt,  # redelivery counter
    )

DeliveryContext carries delivery_attempt, event_id, received_at (when this listener received it), occurred_at (logical event time, for ordering/idempotency — ADR-039), source, schema_version and correlation_id. It is read-only and scoped to the message being dispatched (contextvars: isolated per task/thread, safe under concurrency).


🧭 Topics, subscriptions & provisioning

  • Topic name: <domain>.<entity>.<past-verb> (e.g. core.policy.enrolled, core.visit.confirmed).
  • Subscription name: <service>--<topic> — the prefix is the consumer's bare service name (EVENTBUS_SOURCE), e.g. connect-service--core.policy.enrolled. The library computes it to validate/bind; infra (Terraform) computes the same name to provision it.
  • Provisioning model (ADR-004): topics and subscriptions are provisioned by infra (Terraform). The SDK validates them at startup (fail-fast with EVENTBUS_RESOURCE_NOT_FOUND) and does not create them. A producer needs only the topic; a consumer needs the topic plus its subscription (in Pub/Sub you consume from a subscription, not the topic).
  • Dead-letter / retry / ordering / TTL are declared as neutral policy; the DLQ topic, backoff and retention are infra. See specs/cross-cutting/delivery-policy.spec.md.

The full event catalog and envelope live under specs/ (events-catalog.asyncapi.yaml, event-envelope.yaml).


🔮 Extensibility

  1. Subclass EventChannel.
  2. Register it: EventHandlerFactory.register_channel("mychannel", MyChannel).
  3. Select it via EVENTBUS_CHANNEL=mychannel.

Customizing the HTTP transport

For pooled sessions, retries or dynamic auth headers, build HttpEventChannel directly:

import requests
from vaitty_eventbus import EventHandler, HttpEventChannel

channel = HttpEventChannel(
    endpoint="http://event-bus-bridge.event-bus-bridge.svc.cluster.local/events",
    session=requests.Session(),
    headers_provider=lambda: {"Authorization": f"Bearer {token_cache.get()}"},
    timeout=5,
)
handler = EventHandler(channel, source="rapihogarweb")

session accepts anything exposing .request(method, url, json=, headers=, timeout=) (requests.Session, httpx.Client, …). headers_provider is merged on top of headers on every send, so short-lived tokens stay fresh.


🧪 Development

git clone git@bitbucket.org:rapihogar/event-bus.git
cd event-bus
python -m venv .venv && source .venv/bin/activate
pip install -e '.[pubsub,fastapi,test,dev,publish]'
pre-commit install
pytest

Lint/format are enforced by ruff (config in ruff.toml); pre-commit runs ruff check --fix and ruff format on every commit.

🚢 Releasing a new version

Releases are tag-driven: Jenkins publishes to PyPI when a tag matching v[0-9]+.[0-9]+.[0-9]+ is pushed and its version equals pyproject.toml's version.

# From a clean `main`, in sync with origin/main:
scripts/release.sh patch          # 0.2.0 → 0.2.1
scripts/release.sh minor          # 0.2.0 → 0.3.0
scripts/release.sh major          # 0.2.0 → 1.0.0
scripts/release.sh 0.2.3          # explicit version
scripts/release.sh patch --dry-run

The script bumps pyproject.toml, commits chore(release): vX.Y.Z on main, creates the annotated tag, pushes both, and back-merges main into develop.

Step Where Action
1 Feature branch PR feature/x → develop. CI: lint + test matrix (Python 3.8–3.14) + coverage gate.
2 develop PR develop → main. CI runs again on the merge commit.
3 main (local) scripts/release.sh {patch|minor|major|X.Y.Z} — push is automatic.
4 Jenkins The tag build runs the Publish stage and uploads to PyPI (trigger the tag build if the multibranch job does not start it on its own).

Metadata

Release files for vaitty-eventbus 0.2.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for vaitty-eventbus 0.2.4
File Size Uploaded Provenance Actions
vaitty_eventbus-0.2.4.tar.gz 49.0 kB Without provenance Details for vaitty_eventbus-0.2.4.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for vaitty-eventbus 0.2.4
File Interpreter ABI Platform Actions
vaitty_eventbus-0.2.4-py3-none-any.whl Python 3 none any Details for vaitty_eventbus-0.2.4-py3-none-any.whl

Total release size: 86.6 kB

Release files / vaitty_eventbus-0.2.4.tar.gz

Download URL vaitty_eventbus-0.2.4.tar.gz
Size 49.0 kB
Tags Source
SHA-256 checksum
How to use checksums
5dbf7dbd7780613f970606fe6c09ba9c90306ad26ec7f1633e3c00b959bc2b6f
BLAKE2b-256 checksum
How to use checksums
c002f8f0838e4b10532f57603bfa21a57499aad5c6f6268cb75b42b5fb7f4404
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Release files / vaitty_eventbus-0.2.4-py3-none-any.whl

Download URL vaitty_eventbus-0.2.4-py3-none-any.whl
Size 37.6 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f4111f85523cd9a1cd26e44939d3ae32ca9662fba9965f2e4c28e83273d58e3b
BLAKE2b-256 checksum
How to use checksums
74cd07ca430244ceb817ce2d430a32fc1f950ee8f5dece8bedf4a389f94ddefe
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.15

Security for vaitty-eventbus 0.2.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page