use std::collections::HashMap;
use std::time::{
Duration,
SystemTime,
};
use crate::{
Acknowledgement,
EventBusError,
EventBusResult,
EventEnvelope,
Topic,
};
use super::event_envelope::generate_event_id;
#[derive(Debug)]
pub struct EventEnvelopeBuilder<T: 'static> {
pub(crate) id: String,
pub(crate) topic: Option<Topic<T>>,
pub(crate) payload: Option<T>,
pub(crate) headers: HashMap<String, String>,
pub(crate) ordering_key: Option<String>,
pub(crate) timestamp: SystemTime,
pub(crate) delay: Option<Duration>,
pub(crate) acknowledgement: Option<Acknowledgement>,
pub(crate) dead_letter: bool,
}
impl<T: 'static> EventEnvelopeBuilder<T> {
pub(crate) fn new() -> Self {
Self {
id: generate_event_id(),
topic: None,
payload: None,
headers: HashMap::new(),
ordering_key: None,
timestamp: SystemTime::now(),
delay: None,
acknowledgement: None,
dead_letter: false,
}
}
pub fn id(mut self, id: impl Into<String>) -> Self {
self.id = id.into();
self
}
pub fn topic(mut self, topic: Topic<T>) -> Self {
self.topic = Some(topic);
self
}
pub fn payload(mut self, payload: T) -> Self {
self.payload = Some(payload);
self
}
pub fn header(mut self, key: impl Into<String>, value: impl ToString) -> Self {
self.headers.insert(key.into(), value.to_string());
self
}
pub fn headers(mut self, headers: HashMap<String, String>) -> Self {
self.headers.extend(headers);
self
}
pub fn ordering_key(mut self, ordering_key: impl Into<String>) -> Self {
self.ordering_key = Some(ordering_key.into());
self
}
pub fn timestamp(mut self, timestamp: SystemTime) -> Self {
self.timestamp = timestamp;
self
}
pub fn delay(mut self, delay: Duration) -> Self {
self.delay = Some(delay);
self
}
pub fn acknowledgement(mut self, acknowledgement: Acknowledgement) -> Self {
self.acknowledgement = Some(acknowledgement);
self
}
pub fn dead_letter(mut self, dead_letter: bool) -> Self {
self.dead_letter = dead_letter;
self
}
pub fn build(self) -> EventBusResult<EventEnvelope<T>> {
if self.id.trim().is_empty() {
return Err(EventBusError::invalid_argument(
"id",
"event id must not be blank",
));
}
if self.topic.is_none() {
return Err(EventBusError::missing_field("topic"));
}
if self.payload.is_none() {
return Err(EventBusError::missing_field("payload"));
}
Ok(EventEnvelope::from_builder(self))
}
}