Skip to main content

Universal Inbox-Outbox Pattern Library for Python - reliable message delivery in distributed systems

Project description

Event-Forge (Python)

Python implementation of the Universal Inbox-Outbox Pattern for reliable message delivery in distributed systems.

Installation

pip install event-forge

With RabbitMQ support:

pip install event-forge[rabbitmq]

With MongoDB support:

pip install event-forge[mongodb]

Requirements

  • Python >=3.10
  • SQLAlchemy >= 2.0 (async support)
  • Pydantic >= 2.0

Quick Start

PostgreSQL + SQLAlchemy

from event_forge import OutboxService, CreateOutboxMessageDto, OutboxConfig
from event_forge.repositories.sqlalchemy import (
    SQLAlchemyOutboxRepository,
    Base,
)
from event_forge.publishers.aio_pika_publisher import AioPikaPublisher
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker

# Setup database
engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
session_factory = async_sessionmaker(engine, expire_on_commit=False)

# Create tables
async with engine.begin() as conn:
    await conn.run_sync(Base.metadata.create_all)

# Setup repository and publisher
repository = SQLAlchemyOutboxRepository(session_factory)
publisher = AioPikaPublisher(
    url="amqp://guest:guest@localhost/",
    exchange_name="events",
)

# Create service
outbox = OutboxService(
    repository=repository,
    publisher=publisher,
    config=OutboxConfig(polling_interval=1.0, batch_size=10),
)

# Connect publisher and start polling
await publisher.connect()
outbox.start_polling()

# Create message in transaction
async def create_user_event(session):
    dto = CreateOutboxMessageDto(
        aggregate_type="User",
        aggregate_id="user-123",
        event_type="user.created",
        payload={"email": "user@example.com", "name": "John Doe"},
    )
    return await outbox.create_message(dto, session)

await outbox.with_transaction(create_user_event)

Fire-and-Forget Client

from event_forge import EventForgeAgentClient, OutboxConfig
from event_forge.repositories.sqlalchemy import SQLAlchemyOutboxRepository
from event_forge.publishers.aio_pika_publisher import AioPikaPublisher

client = EventForgeAgentClient(
    repository=SQLAlchemyOutboxRepository(session_factory),
    publisher=AioPikaPublisher(url="amqp://localhost/", exchange_name="events"),
)

await client.start()

# Fire-and-forget
await client.fire(
    aggregate_type="Call",
    aggregate_id="call-123",
    event_type="call.completed",
    payload={"duration": 120, "status": "success"},
)

await client.stop()

Inbox Pattern

from event_forge import InboxService, CreateInboxMessageDto, InboxConfig
from event_forge.repositories.sqlalchemy import SQLAlchemyInboxRepository

# Setup
repository = SQLAlchemyInboxRepository(session_factory)
inbox = InboxService(
    repository=repository,
    config=InboxConfig(enable_retry=True),
)

# Register handler
async def handle_order(message):
    print(f"Processing order: {message.payload}")

inbox.register_handler("order.placed", handle_order)

# Process incoming message (with automatic deduplication)
dto = CreateInboxMessageDto(
    message_id="ext-msg-123",
    source="external-system",
    event_type="order.placed",
    payload={"order_id": "order-456", "amount": 99.99},
)

await inbox.receive_message(dto)

# Start retry polling for failed messages
inbox.start_retry_polling()

RabbitMQ Consumer

from event_forge.consumers import AioPikaConsumer

consumer = AioPikaConsumer(
    url="amqp://guest:guest@localhost/",
    inbox_service=inbox,
    queue_name="my-service-inbox",
    exchange_name="events",
    routing_keys=["Order.*", "User.*"],
)

await consumer.start()

Architecture

Matches the TypeScript implementation with full wire format compatibility:

  • Models: Pydantic v2 models (type-safe DTOs)
  • Repositories: SQLAlchemy async for PostgreSQL (SELECT FOR UPDATE SKIP LOCKED)
  • Services: OutboxService, InboxService with exponential backoff and event emission
  • Publishers: AioPikaPublisher for RabbitMQ (connect_robust, auto-reconnect)
  • Consumers: AioPikaConsumer with inbox recording and deduplication
  • Client: EventForgeAgentClient fire-and-forget facade

Features

  • Transactional Guarantees — Messages created in same transaction as business logic
  • Automatic Retry — Exponential backoff with jitter for failed publishes
  • Duplicate Detection — Inbox pattern prevents duplicate processing
  • Async/Await — Full async support with SQLAlchemy 2.0
  • Type Safety — Pydantic v2 models for validation
  • Wire Format Compatible — camelCase JSON body, AMQP headers match Node.js publisher
  • Auto-Reconnect — aio-pika connect_robust for RabbitMQ resilience
  • Event Emission — SimpleEventEmitter for lifecycle hooks

Node.js Compatibility

For TypeScript/JavaScript projects, use the NPM packages:

  • @prodforcode/event-forge-core
  • @prodforcode/event-forge-typeorm
  • @prodforcode/event-forge-mongoose
  • @prodforcode/event-forge-rabbitmq-publisher
  • @prodforcode/event-forge-nestjs

Documentation

For full documentation, see the main README.

License

MIT

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

event_forge-1.1.0.tar.gz (16.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

event_forge-1.1.0-py3-none-any.whl (26.1 kB view details)

Uploaded Python 3

File details

Details for the file event_forge-1.1.0.tar.gz.

File metadata

  • Download URL: event_forge-1.1.0.tar.gz
  • Upload date:
  • Size: 16.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for event_forge-1.1.0.tar.gz
Algorithm Hash digest
SHA256 125b8edc184cf16e49eb69433525d2f318849e417f810543c2c42406fbbbd32d
MD5 8247f1fbda8029251e70b2dc7a9a5d65
BLAKE2b-256 dc95b65033ad74df675fcd979e43d6581071cdcdf4eaabff9ae4bdd7d7991fba

See more details on using hashes here.

Provenance

The following attestation bundles were made for event_forge-1.1.0.tar.gz:

Publisher: python-release.yml on codeforprod/Event-Forge

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

File details

Details for the file event_forge-1.1.0-py3-none-any.whl.

File metadata

  • Download URL: event_forge-1.1.0-py3-none-any.whl
  • Upload date:
  • Size: 26.1 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for event_forge-1.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 95c61467d47911a35596963494e9bf0caacab3ad1dcc9fb4f2883b06dcc1dace
MD5 b97e90aea6a0fe650ed83731272eb5b6
BLAKE2b-256 5a332aa2511bea908d1fe3cdd82215a1ef8d8b3535eebdcd6f0fcadab790711b

See more details on using hashes here.

Provenance

The following attestation bundles were made for event_forge-1.1.0-py3-none-any.whl:

Publisher: python-release.yml on codeforprod/Event-Forge

Attestations: Values shown here reflect the state when the release was signed and may no longer be current.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page