evx 0.1.0

A type-safe event bus for domain events, CQRS, Redis Pub/Sub, and durable work queues
Documentation
//! Broker abstractions and optional transport implementations.

use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;

use async_trait::async_trait;
use uuid::Uuid;

#[cfg(feature = "redis")]
use std::collections::HashMap;
#[cfg(feature = "redis")]
use tokio::sync::RwLock;

use crate::error::EventError;
use crate::event::cloud::CloudEvent;

#[cfg(feature = "in-process")]
pub mod disruptor;
#[cfg(feature = "redis")]
pub mod redis;

/// A type-erased asynchronous CloudEvent handler.
pub type ErasedHandler = Arc<
    dyn Fn(CloudEvent) -> Pin<Box<dyn Future<Output = Result<(), EventError>> + Send>>
        + Send
        + Sync,
>;

/// A broker-assigned identifier used to cancel a subscription.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct SubscriptionId(
    /// Raw UUID assigned to the subscription.
    pub Uuid,
);

impl SubscriptionId {
    /// Creates a new random subscription identifier.
    pub fn new() -> Self {
        Self(Uuid::new_v4())
    }
}

impl Default for SubscriptionId {
    fn default() -> Self {
        Self::new()
    }
}

/// Handler 注册表。
#[cfg(feature = "redis")]
pub(crate) type HandlerRegistry =
    Arc<RwLock<HashMap<String, Vec<(SubscriptionId, ErasedHandler)>>>>;

/// Transport abstraction used by [`crate::EventBus`].
#[async_trait]
pub trait Broker: Send + Sync {
    /// Publishes an event without waiting for its handlers.
    async fn publish(&self, event: CloudEvent) -> Result<(), EventError>;

    /// Registers a type-erased handler for a message type.
    async fn subscribe(
        &self,
        event_type: &str,
        handler: ErasedHandler,
    ) -> Result<SubscriptionId, EventError>;

    /// Cancels a previously registered subscription.
    async fn unsubscribe(&self, id: SubscriptionId) -> Result<(), EventError>;

    /// Sends a request and waits for its correlated response.
    async fn call(
        &self,
        event: CloudEvent,
        timeout: std::time::Duration,
    ) -> Result<CloudEvent, EventError>;

    /// Shuts down the broker and its background resources.
    async fn shutdown(&self) -> Result<(), EventError>;
}