use crate::BusEvent;
use async_trait::async_trait;
use std::collections::HashMap;
use std::fmt::Debug;
#[async_trait]
pub trait EventBusBackend: Send + Sync + 'static + Debug {
fn clone_box(&self) -> Box<dyn EventBusBackend>;
fn as_any(&self) -> &dyn std::any::Any;
fn as_any_mut(&mut self) -> &mut dyn std::any::Any;
async fn connect(&mut self) -> bool;
async fn disconnect(&mut self) -> bool;
fn try_send_serialized(&self, event_json: &[u8], topic: &str) -> bool;
fn try_send_serialized_with_headers(&self, event_json: &[u8], topic: &str, headers: &HashMap<String, String>) -> bool;
async fn receive_serialized(&self, topic: &str) -> Vec<Vec<u8>>;
async fn subscribe(&mut self, topic: &str) -> bool;
async fn unsubscribe(&mut self, topic: &str) -> bool;
}
#[async_trait]
pub trait EventBusBackendExt: EventBusBackend {
fn try_send<T: BusEvent>(&self, event: &T, topic: &str) -> bool {
match serde_json::to_vec(event) {
Ok(serialized) => self.try_send_serialized(&serialized, topic),
Err(_) => false, }
}
fn try_send_with_headers<T: BusEvent>(&self, event: &T, topic: &str, headers: &HashMap<String, String>) -> bool {
match serde_json::to_vec(event) {
Ok(serialized) => self.try_send_serialized_with_headers(&serialized, topic, headers),
Err(_) => false, }
}
async fn receive<T: BusEvent>(&self, topic: &str) -> Vec<T> {
let serialized_messages = self.receive_serialized(topic).await;
let mut result = Vec::with_capacity(serialized_messages.len());
for message in serialized_messages {
if let Ok(deserialized) = serde_json::from_slice(&message) {
result.push(deserialized);
}
}
result
}
}
impl<T: EventBusBackend + ?Sized> EventBusBackendExt for T {}