use std::sync::Arc;
use super::consumer::InMemoryConsumer;
use super::producer::InMemoryProducer;
use super::state::PublishState;
use crate::message::Message;
#[derive(Debug, Clone)]
pub struct InMemoryBroker<T: Clone + Send + Sync + 'static> {
pub(super) state: Arc<PublishState<T>>,
}
impl<T: Clone + Send + Sync + 'static> InMemoryBroker<T> {
pub fn new(capacity: usize) -> Self {
let limit = capacity.max(1);
Self {
state: Arc::new(PublishState::new(limit, limit)),
}
}
pub fn producer(&self) -> InMemoryProducer<T> {
InMemoryProducer {
state: self.state.clone(),
}
}
#[must_use]
pub fn with_history_limit(capacity: usize, history_limit: usize) -> Self {
Self {
state: Arc::new(PublishState::new(capacity, history_limit)),
}
}
pub fn consumer(&self) -> InMemoryConsumer<T> {
InMemoryConsumer::new(self.state.subscribe())
}
pub async fn messages(&self, topic: &str) -> Vec<Message<T>> {
self.state.messages(topic).await
}
pub async fn all_messages(&self) -> Vec<Message<T>> {
self.state.all_messages().await
}
pub async fn message_count(&self, topic: &str) -> usize {
self.state.message_count(topic).await
}
pub async fn reset(&self) {
self.state.reset().await;
}
pub async fn create_topic(&self, topic: &str) {
self.state.create_topic(topic).await;
}
pub async fn topic_names(&self) -> Vec<String> {
self.state.topic_names().await
}
pub(super) async fn notified(&self) {
self.state.notified().await;
}
}
impl<T: Clone + Send + Sync + 'static> Default for InMemoryBroker<T> {
fn default() -> Self {
Self::new(256)
}
}