nstreams-core 0.3.1

Generic versioned event stream handler with history replay
Documentation
use async_trait::async_trait;

use crate::namespace::Namespace;
use crate::stream::WriteQueueBackend;

/// Publishes events to the write-side queue for durable processing.
#[derive(Clone)]
pub struct EventPublisher<Q: WriteQueueBackend> {
    queue: Q,
}

impl<Q: WriteQueueBackend> EventPublisher<Q> {
    pub fn new(queue: Q) -> Self {
        Self { queue }
    }

    pub async fn publish<N: Namespace>(
        &self,
        namespace: &N,
        payload: &[u8],
        filter_value: Option<&str>,
    ) -> crate::Result<()> {
        self.queue.publish(namespace, payload, filter_value).await
    }
}

/// Convenience trait for typed publishing.
#[async_trait]
pub trait TypedPublisher: Send + Sync {
    async fn publish_typed<N, C>(&self, namespace: &N, codec: &C, event: &C::Event) -> crate::Result<()>
    where
        N: Namespace,
        C: crate::event::EventCodec + ?Sized;
}

#[async_trait]
impl<Q: WriteQueueBackend> TypedPublisher for EventPublisher<Q> {
    async fn publish_typed<N, C>(&self, namespace: &N, codec: &C, event: &C::Event) -> crate::Result<()>
    where
        N: Namespace,
        C: crate::event::EventCodec + ?Sized,
    {
        let payload = codec.encode(event)?;
        self.publish(namespace, &payload, None).await
    }
}