use async_trait::async_trait;
use bevy::prelude::*;
use serde::{Serialize, de::DeserializeOwned};
use std::collections::HashMap;
use std::time::Duration;
use crate::{BusEvent, EventBusBackend, EventBusError};
#[derive(Clone)]
pub struct KafkaConfig {
pub brokers: Vec<String>,
pub client_id: String,
pub group_id: String,
pub timeout: Duration,
pub properties: HashMap<String, String>,
}
impl Default for KafkaConfig {
fn default() -> Self {
Self {
brokers: vec!["localhost:9092".to_string()],
client_id: "bevy_event_bus".to_string(),
group_id: "bevy_event_bus_consumer".to_string(),
timeout: Duration::from_secs(10),
properties: HashMap::new(),
}
}
}
pub struct KafkaEventBusBackend {
config: KafkaConfig,
connected: bool,
subscriptions: Vec<String>,
}
#[async_trait]
impl EventBusBackend for KafkaEventBusBackend {
type Config = KafkaConfig;
fn new(config: Self::Config) -> Self {
Self {
config,
connected: false,
subscriptions: Vec::new(),
}
}
async fn connect(&mut self) -> Result<(), EventBusError> {
info!("Connecting to Kafka brokers: {:?}", self.config.brokers);
self.connected = true;
Ok(())
}
async fn disconnect(&mut self) -> Result<(), EventBusError> {
info!("Disconnecting from Kafka");
self.connected = false;
Ok(())
}
async fn send<T: BusEvent>(&self, event: &T, topic: &str) -> Result<(), EventBusError> {
if !self.connected {
return Err(EventBusError::NotConfigured("Kafka not connected".to_string()));
}
info!("Sending event to Kafka topic: {}", topic);
Ok(())
}
async fn receive<T: BusEvent>(&self, topic: &str) -> Result<Vec<T>, EventBusError> {
if !self.connected {
return Err(EventBusError::NotConfigured("Kafka not connected".to_string()));
}
if !self.subscriptions.contains(&topic.to_string()) {
return Err(EventBusError::Topic(format!("Not subscribed to topic: {}", topic)));
}
info!("Polling Kafka topic for messages: {}", topic);
Ok(Vec::new())
}
async fn subscribe(&mut self, topic: &str) -> Result<(), EventBusError> {
if !self.connected {
return Err(EventBusError::NotConfigured("Kafka not connected".to_string()));
}
info!("Subscribing to Kafka topic: {}", topic);
if !self.subscriptions.contains(&topic.to_string()) {
self.subscriptions.push(topic.to_string());
}
Ok(())
}
async fn unsubscribe(&mut self, topic: &str) -> Result<(), EventBusError> {
if !self.connected {
return Err(EventBusError::NotConfigured("Kafka not connected".to_string()));
}
info!("Unsubscribing from Kafka topic: {}", topic);
self.subscriptions.retain(|t| t != topic);
Ok(())
}
}