use crate::{error::Result, processor::Processor, Exchange};
use std::fmt::{Debug, Formatter, Result as FmtResult};
#[derive(Clone, Default)]
pub struct CorrelationInitializer {
mirror_header: Option<String>,
}
impl CorrelationInitializer {
pub fn with_mirror<H: Into<String>>(header: H) -> Self {
Self {
mirror_header: Some(header.into()),
}
}
}
impl Debug for CorrelationInitializer {
fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
f.debug_struct("CorrelationInitializer")
.field("mirror_header", &self.mirror_header)
.finish()
}
}
#[async_trait::async_trait]
impl Processor for CorrelationInitializer {
async fn process(&self, exchange: &mut Exchange) -> Result<()> {
if exchange.in_msg.header("correlation_id").is_none() {
let cid = uuid::Uuid::new_v4().to_string();
exchange.in_msg.set_header("correlation_id", &cid);
if let Some(mh) = &self.mirror_header {
exchange.in_msg.set_header(mh, &cid);
}
} else if let Some(mh) = &self.mirror_header {
if exchange.in_msg.header(mh).is_none() {
if let Some(cid_val) = exchange
.in_msg
.header("correlation_id")
.map(|s| s.to_string())
{
exchange.in_msg.set_header(mh, &cid_val);
}
}
}
Ok(())
}
}