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, http (base) 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 GCP dependency and runs on Python 3.8.

📦 Installation

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

# Base — console/file/http channels + typed events. No GCP deps. Python 3.8+.
# (e.g. the legacy monolith producing via the HTTP channel to the bridge,
#  and/or using the typed DTOs to deserialize events it receives.)
pip install vaitty-eventbus

# + 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) requests console/file/http channels, typed DTOs 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.


🛠 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).

import dataclasses
from vaitty_eventbus import Event

@dataclasses.dataclass
class PolicyEnrolled(Event):
    topic = "core.policy.enrolled"      # class attribute → auto-registered
    policy_id: int
    insured_id: int
    enrolled_at: str                    # ISO 8601

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):
handler.emit(PolicyEnrolled(policy_id=789, insured_id=456, enrolled_at="2026-10-06T14:00:00Z"))

# Raw escape hatch:
handler.emit("core.policy.enrolled", {"policy_id": 789, "insured_id": 456})

# 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_id, event.insured_id)      # 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_id": 789, "insured_id": 456}})

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.


🧭 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 pyproject.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.3

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.3
File Size Uploaded Provenance Actions
vaitty_eventbus-0.2.3.tar.gz 44.7 kB Without provenance Details for vaitty_eventbus-0.2.3.tar.gz

Built distribution (wheel)

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

Total release size: 79.4 kB

Release files / vaitty_eventbus-0.2.3.tar.gz

Download URL vaitty_eventbus-0.2.3.tar.gz
Size 44.7 kB
Tags Source
SHA-256 checksum
How to use checksums
406598fe36d7ad7d86e941ff17e0acaea62f52be02e4197a0b090774f2f6f74a
BLAKE2b-256 checksum
How to use checksums
5aeb7442b1dc20388db6380c5b142796652b95f0628802930eb84556702a8803
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.3-py3-none-any.whl

Download URL vaitty_eventbus-0.2.3-py3-none-any.whl
Size 34.7 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3c6f3875862ad5497b7057bde42b68106ecbe8e6619b52692d8119ba7799c312
BLAKE2b-256 checksum
How to use checksums
369dcfd61c613d0fd66882dc794a369d71c5ce60a6c5c3516392f98a77adc22e
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.3

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