evx 0.1.0

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

use std::collections::HashMap;
use std::sync::{
    Arc, Mutex,
    atomic::{AtomicBool, Ordering},
};

use async_trait::async_trait;
use fred::clients::RedisClient;
use fred::interfaces::{EventInterface, PubsubInterface};
use tokio::sync::oneshot;

use crate::broker::{Broker, ErasedHandler, HandlerRegistry, SubscriptionId};
use crate::error::EventError;
use crate::event::cloud::CloudEvent;

/// A distributed broker backed by Redis Pub/Sub.
///
/// Channels are named `<prefix>:<event_type>` and use `evx` as the default
/// prefix.
pub struct RedisBroker {
    pub_client: RedisClient,
    sub_client: RedisClient,
    prefix: String,
    handlers: HandlerRegistry,
    subscribed_channels: Arc<tokio::sync::RwLock<HashMap<String, bool>>>,
    pending_requests: Arc<Mutex<HashMap<String, oneshot::Sender<CloudEvent>>>>,
    dispatch_handle: tokio::sync::Mutex<Option<tokio::task::JoinHandle<()>>>,
    shutdown: Arc<AtomicBool>,
}

impl RedisBroker {
    /// Creates a Redis Pub/Sub broker using the default `evx` prefix.
    pub fn new(pub_client: RedisClient, sub_client: RedisClient) -> Self {
        Self::with_prefix(pub_client, sub_client, "evx")
    }

    /// Creates a Redis Pub/Sub broker with a custom channel prefix.
    ///
    /// `pub_client` and `sub_client` must be distinct connected clients.
    pub fn with_prefix(
        pub_client: RedisClient,
        sub_client: RedisClient,
        prefix: impl Into<String>,
    ) -> Self {
        Self {
            pub_client,
            sub_client,
            prefix: prefix.into(),
            handlers: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
            subscribed_channels: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
            pending_requests: Arc::new(Mutex::new(HashMap::new())),
            dispatch_handle: tokio::sync::Mutex::new(None),
            shutdown: Arc::new(AtomicBool::new(false)),
        }
    }

    fn channel_name(&self, event_type: &str) -> String {
        format!("{}:{event_type}", self.prefix)
    }

    async fn ensure_dispatcher(&self) {
        let mut handle = self.dispatch_handle.lock().await;
        if handle.is_none() {
            let sub_client = self.sub_client.clone();
            let handlers = Arc::clone(&self.handlers);
            let pending = Arc::clone(&self.pending_requests);
            let shutdown = Arc::clone(&self.shutdown);

            *handle = Some(tokio::spawn(async move {
                let mut rx = sub_client.message_rx();
                loop {
                    if shutdown.load(Ordering::Relaxed) {
                        break;
                    }
                    match rx.recv().await {
                        Ok(msg) => {
                            let channel = msg.channel.clone();

                            let Some(payload_str) = msg
                                .value
                                .as_bytes()
                                .and_then(|b| std::str::from_utf8(b).ok())
                                .map(String::from)
                            else {
                                continue;
                            };

                            match serde_json::from_str::<CloudEvent>(&payload_str) {
                                Ok(event) => {
                                    // Check for RPC response (_reply.*)
                                    if channel.contains("_reply.")
                                        && let Some(corr) = event
                                            .extensions
                                            .get("correlationid")
                                            .and_then(|v: &serde_json::Value| v.as_str())
                                        && let Some(sender) = pending.lock().unwrap().remove(corr)
                                    {
                                        let _ = sender.send(event);
                                        continue;
                                    }

                                    // Regular event dispatch
                                    let handlers_map = handlers.read().await;
                                    if let Some(handler_list) = handlers_map.get(&event.r#type) {
                                        for (_id, handler) in handler_list {
                                            let h = Arc::clone(handler);
                                            let evt = event.clone();
                                            tokio::spawn(async move {
                                                if let Err(e) = h(evt).await {
                                                    tracing::error!(
                                                        error = %e,
                                                        "RedisBroker handler error"
                                                    );
                                                }
                                            });
                                        }
                                    }
                                }
                                Err(e) => {
                                    let ch = channel.to_string();
                                    tracing::warn!(
                                        error = %e,
                                        channel = %ch,
                                        "RedisBroker failed to deserialize message"
                                    );
                                }
                            }
                        }
                        Err(_) => {
                            if shutdown.load(Ordering::Relaxed) {
                                break;
                            }
                        }
                    }
                }
                tracing::debug!("RedisBroker dispatcher stopped");
            }));
        }
    }
}

#[async_trait]
impl Broker for RedisBroker {
    async fn publish(&self, event: CloudEvent) -> Result<(), EventError> {
        let channel = self.channel_name(&event.r#type);
        let payload = event.to_json()?;
        self.pub_client
            .publish::<i64, String, String>(channel, payload)
            .await
            .map_err(|e| EventError::Publish(format!("redis publish failed: {e}")))?;
        Ok(())
    }

    async fn subscribe(
        &self,
        event_type: &str,
        handler: ErasedHandler,
    ) -> Result<SubscriptionId, EventError> {
        let id = SubscriptionId::new();
        let channel = self.channel_name(event_type);

        {
            let mut handlers = self.handlers.write().await;
            handlers
                .entry(event_type.to_string())
                .or_default()
                .push((id, handler));
        }

        // Subscribe to Redis channel if not already subscribed
        let mut channels = self.subscribed_channels.write().await;
        if !channels.contains_key(event_type) {
            self.sub_client
                .subscribe(&channel)
                .await
                .map_err(|e| EventError::Subscription(format!("redis subscribe failed: {e}")))?;
            channels.insert(event_type.to_string(), true);
        }
        drop(channels);

        self.ensure_dispatcher().await;
        Ok(id)
    }

    async fn unsubscribe(&self, id: SubscriptionId) -> Result<(), EventError> {
        let mut handlers = self.handlers.write().await;
        for list in handlers.values_mut() {
            list.retain(|(sid, _)| *sid != id);
        }
        Ok(())
    }

    async fn call(
        &self,
        event: CloudEvent,
        timeout: std::time::Duration,
    ) -> Result<CloudEvent, EventError> {
        let correlation_id = uuid::Uuid::new_v4().to_string();
        let reply_channel = format!("_reply.{correlation_id}");
        let reply_channel_full = self.channel_name(&reply_channel);

        let (tx, rx) = oneshot::channel();

        // Store pending request
        self.pending_requests
            .lock()
            .unwrap()
            .insert(correlation_id.clone(), tx);

        // Set correlation metadata
        let mut event = event;
        event.extensions.insert(
            "correlationid".into(),
            serde_json::Value::String(correlation_id.clone()),
        );
        event
            .extensions
            .insert("reply_to".into(), serde_json::Value::String(reply_channel));

        let channel = self.channel_name(&event.r#type);
        let payload = event.to_json()?;

        // Subscribe to reply channel BEFORE publishing to avoid race
        self.sub_client
            .subscribe(&reply_channel_full)
            .await
            .map_err(|e| EventError::Subscription(format!("redis subscribe failed: {e}")))?;
        self.ensure_dispatcher().await;

        // Publish request
        self.pub_client
            .publish::<i64, String, String>(channel, payload)
            .await
            .map_err(|e| EventError::Publish(format!("redis publish failed: {e}")))?;

        // Wait for response
        let result = match tokio::time::timeout(timeout, rx).await {
            Ok(Ok(event)) => Ok(event),
            Ok(Err(_)) => {
                self.pending_requests
                    .lock()
                    .unwrap()
                    .remove(&correlation_id);
                Err(EventError::Publish("response channel closed".into()))
            }
            Err(_) => {
                self.pending_requests
                    .lock()
                    .unwrap()
                    .remove(&correlation_id);
                Err(EventError::Timeout("call timed out".into()))
            }
        };

        // Cleanup reply subscription
        let _ = self.sub_client.unsubscribe(&reply_channel_full).await;

        result
    }

    async fn shutdown(&self) -> Result<(), EventError> {
        self.shutdown.store(true, Ordering::Relaxed);

        // Unsubscribe from all channels
        let channels: Vec<String> = {
            let subscribed = self.subscribed_channels.read().await;
            subscribed.keys().map(|k| self.channel_name(k)).collect()
        };
        for channel in &channels {
            let _ = self.sub_client.unsubscribe(channel).await;
        }

        if let Some(handle) = self.dispatch_handle.lock().await.take() {
            handle.abort();
        }
        Ok(())
    }
}