evx 0.1.0

A type-safe event bus for domain events, CQRS, Redis Pub/Sub, and durable work queues
Documentation

evx

简体中文

evx is a type-safe asynchronous event bus for Rust applications. It combines domain-event fan-out, CQRS request-response messaging, in-process dispatch, Redis Pub/Sub, and Redis Stream work queues behind one API. Messages crossing a transport boundary use CloudEvents 1.0-style envelopes.

Features

Cargo feature Default Provides
in-process yes InProcessBroker, backed by a disruptor ring buffer
redis no RedisBroker and RedisStreamQueue

The core message, broker, queue, and EventBus abstractions are available with default-features = false.

[dependencies]
evx = "0.1"

# Add Redis Pub/Sub and Redis Stream support.
# evx = { version = "0.1", features = ["redis"] }

Evx requires Rust 1.88 or newer. Redis-backed queues require Redis or Valkey 6.2 or newer because stale pending jobs are recovered with XAUTOCLAIM.

Message model

Every message implements Message, which defines its stable wire type, source, and routing scope:

  • EventScope::Process uses the process broker.
  • EventScope::App uses the application broker, normally Redis Pub/Sub.

Domain events implement DomainEvent. Commands and queries implement RequestMessage plus CommandMessage or QueryMessage; their response type is selected at compile time.

use evx::{CommandMessage, EventScope, Message, RequestMessage};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, Serialize)]
struct CreateUser {
    email: String,
}

#[derive(Clone, Debug, Deserialize, Serialize)]
struct CreateUserResponse {
    user_id: String,
}

impl Message for CreateUser {
    fn message_type() -> &'static str { "com.example.user.cmd.create" }
    fn source() -> &'static str { "/example/users" }
    fn scope() -> EventScope { EventScope::Process }
}

impl RequestMessage for CreateUser {
    type Response = CreateUserResponse;
}

impl CommandMessage for CreateUser {}

impl Message for CreateUserResponse {
    fn message_type() -> &'static str { "com.example.user.res.create" }
    fn source() -> &'static str { "/example/users" }
    fn scope() -> EventScope { EventScope::Process }
}

Use stable reverse-domain message types. Renaming a type after deployment breaks compatibility between producers and consumers.

In-process commands and queries

An EventBus has a process broker and an application broker. A local-only application can use in-process brokers for both scopes:

use std::sync::Arc;
use std::time::Duration;

use evx::{EventBus, InProcessBroker};

let runtime = tokio::runtime::Handle::current();
let eventbus = Arc::new(EventBus::new(
    Arc::new(InProcessBroker::new(1024, runtime.clone())),
    Arc::new(InProcessBroker::new(1024, runtime)),
));

eventbus
    .handle::<CreateUser, _, _>(|command| async move {
        let user_id = create_user(command.email).await?;
        Ok(CreateUserResponse { user_id })
    })
    .await?;

let response = eventbus
    .call(
        &CreateUser { email: "dev@example.com".into() },
        Duration::from_secs(5),
    )
    .await?;

Process-scoped calls use direct typed dispatch when a handler is registered, avoiding a CloudEvent serialization round trip. Calls return EventError::Timeout when their deadline expires.

handle and subscribe return a SubscriptionId. Cancel the registration with eventbus.unsubscribe(id).await.

Domain events

Domain events describe facts that already happened and use fire-and-forget fan-out:

use evx::{DomainEvent, EventScope, Message};
use serde::{Deserialize, Serialize};

#[derive(Clone, Debug, Deserialize, Serialize)]
struct UserCreated {
    user_id: String,
}

impl Message for UserCreated {
    fn message_type() -> &'static str { "com.example.user.created" }
    fn source() -> &'static str { "/example/users" }
    fn scope() -> EventScope { EventScope::App }
    fn subject(&self) -> Option<String> { Some(self.user_id.clone()) }
}

impl DomainEvent for UserCreated {}

eventbus
    .subscribe::<UserCreated, _, _>(|event| async move {
        update_search_index(&event.user_id).await?;
        Ok(())
    })
    .await?;

eventbus.publish(&UserCreated { user_id }).await?;

A successful publish means the broker accepted the event. Subscriber failures are logged and are not returned to the publisher. Redis Pub/Sub is not durable; offline subscribers do not receive earlier events.

Redis Pub/Sub and cross-node calls

Enable the redis feature and provide separate, connected fred clients for publishing and subscribing:

use std::sync::Arc;

use evx::{EventBus, InProcessBroker, RedisBroker};

let process = Arc::new(InProcessBroker::new(
    1024,
    tokio::runtime::Handle::current(),
));
let application = Arc::new(RedisBroker::new(pub_client, sub_client));
let eventbus = Arc::new(EventBus::new(process, application));

RedisBroker::new uses the evx channel prefix. Use RedisBroker::with_prefix to isolate applications or environments. App-scoped commands use correlation IDs and temporary Redis reply channels, so the caller and handler may run on different nodes.

Durable work queues

Configure a queue backend when constructing the EventBus:

use std::sync::Arc;

use evx::{EventBus, RedisStreamQueue};

let queue = Arc::new(RedisStreamQueue::new(queue_client));
let eventbus = Arc::new(EventBus::new_with_queue(
    process_broker,
    application_broker,
    queue,
));

Then implement QueuedCommand and start a worker:

use evx::{QueuePolicy, QueuedCommand};

impl QueuedCommand for CreateUser {
    fn queue_policy() -> QueuePolicy {
        QueuePolicy {
            queue: "user.create",
            consumer_group: "user-workers",
            max_attempts: 3,
            max_in_flight: 8,
            block_ms: 1_000,
            claim_idle_ms: 300_000,
        }
    }
}

let job_id = eventbus.enqueue(&CreateUser {
    email: "dev@example.com".into(),
}).await?;

let worker = eventbus
    .work::<CreateUser, _, _>("worker-1", |command| async move {
        let user_id = create_user(command.email).await?;
        Ok(CreateUserResponse { user_id })
    })
    .await?;

// During application shutdown:
worker.abort();

Each consumer instance needs a unique name. Successful jobs are acknowledged. Failures are re-enqueued immediately until max_attempts, then written to a dead-letter stream. Jobs left pending by a crashed worker become claimable after claim_idle_ms.

The default Redis keys are:

  • queue: evx:queue:<queue>
  • dead letter: evx:dlq:<queue>

Use RedisStreamQueue::with_prefix for a different namespace. Delivery can be duplicated when a worker completes a side effect but stops before acknowledging the job, so queued handlers must be idempotent. Evx does not currently apply a retry backoff.

CloudEvent envelopes

Business code normally works only with typed messages. For custom transports or external integrations, CloudEvent::from_message, into_message, to_json, and from_json expose the wire envelope. Evx uses the reply_to and correlationid extension attributes for request-response messaging.

Shutdown

Call eventbus.shutdown().await to stop both brokers. Queue workers are separate Tokio tasks; retain their JoinHandles and stop them as part of application shutdown.

License

Licensed under either of

at your option.