use super::{WaeResult, types::*};
use serde::Serialize;
use std::time::Duration;
#[async_trait::async_trait]
pub trait ProducerBackend: Send + Sync {
async fn send_raw(&self, queue: &str, message: &RawMessage) -> WaeResult<MessageId>;
async fn send_raw_default(&self, message: &RawMessage) -> WaeResult<MessageId>;
async fn send_raw_delayed(&self, queue: &str, message: &RawMessage, delay: Duration) -> WaeResult<MessageId>;
async fn send_raw_batch(&self, queue: &str, messages: &[RawMessage]) -> WaeResult<Vec<MessageId>>;
fn config(&self) -> &ProducerConfig;
}
pub struct MessageProducer {
backend: Box<dyn ProducerBackend>,
}
impl MessageProducer {
pub fn new(backend: Box<dyn ProducerBackend>) -> Self {
Self { backend }
}
pub async fn send<T: Serialize + Send + Sync>(&self, queue: &str, message: &Message<T>) -> WaeResult<MessageId> {
let raw = message.to_raw()?;
self.backend.send_raw(queue, &raw).await
}
pub async fn send_default<T: Serialize + Send + Sync>(&self, message: &Message<T>) -> WaeResult<MessageId> {
let raw = message.to_raw()?;
self.backend.send_raw_default(&raw).await
}
pub async fn send_delayed<T: Serialize + Send + Sync>(
&self,
queue: &str,
message: &Message<T>,
delay: Duration,
) -> WaeResult<MessageId> {
let raw = message.to_raw()?;
self.backend.send_raw_delayed(queue, &raw, delay).await
}
pub async fn send_batch<T: Serialize + Send + Sync>(
&self,
queue: &str,
messages: &[Message<T>],
) -> WaeResult<Vec<MessageId>> {
let raw_messages: Vec<RawMessage> = messages.iter().map(|m| m.to_raw()).collect::<WaeResult<_>>()?;
self.backend.send_raw_batch(queue, &raw_messages).await
}
pub fn config(&self) -> &ProducerConfig {
self.backend.config()
}
}