use super::{
config::{SinkConfig, SourceConfig, redacted, validate_uri},
sink::RabbitMqSink,
source::RabbitMqSource,
};
use crate::error::{Context, Error};
use lapin::{Channel, Connection, ConnectionProperties};
use std::{fmt, sync::Arc};
use tokio::sync::Mutex;
const REPLY_SUCCESS: u16 = 200;
#[derive(Clone)]
pub struct RabbitMq {
shared: Arc<Shared>,
}
struct Shared {
uri: String,
name: String,
consuming: Mutex<Option<Arc<Connection>>>,
publishing: Mutex<Option<Arc<Connection>>>,
}
#[derive(Clone, Copy)]
pub(super) enum Role {
Consume,
Publish,
}
impl RabbitMq {
pub fn new(uri: impl Into<String>) -> Self {
Self::from_parts(uri.into(), "beavers".into())
}
pub fn connection_name(self, name: impl Into<String>) -> Self {
Self::from_parts(self.shared.uri.clone(), name.into())
}
pub fn source<C: Default>(&self, queue: impl Into<String>) -> RabbitMqSource<C> {
self.source_with_codec(C::default(), queue)
}
pub fn source_with_codec<C>(&self, codec: C, queue: impl Into<String>) -> RabbitMqSource<C> {
RabbitMqSource::new(self.clone(), SourceConfig::new(queue.into()), codec)
}
pub fn sink<C: Default>(
&self,
exchange: impl Into<String>,
routing_key: impl Into<String>,
) -> RabbitMqSink<C> {
self.sink_with_codec(C::default(), exchange, routing_key)
}
pub fn sink_with_codec<C>(
&self,
codec: C,
exchange: impl Into<String>,
routing_key: impl Into<String>,
) -> RabbitMqSink<C> {
RabbitMqSink::new(
self.clone(),
SinkConfig::new(exchange.into(), routing_key.into()),
codec,
)
}
pub fn validate(&self) -> Result<(), Error> {
validate_uri(&self.shared.uri)
}
pub(super) async fn channel(&self, role: Role) -> Result<Channel, Error> {
let (slot, role) = match role {
Role::Consume => (&self.shared.consuming, "consumer"),
Role::Publish => (&self.shared.publishing, "publisher"),
};
let mut slot = slot.lock().await;
if let Some(connection) = slot
.as_ref()
.filter(|connection| connection.status().connected())
{
return connection
.create_channel()
.await
.context("opening a RabbitMQ channel");
}
self.validate()?;
let name = format!("{} {role}", self.shared.name);
let properties = ConnectionProperties::default().with_connection_name(name.into());
let connection = Connection::connect(&self.shared.uri, properties)
.await
.context("connecting to RabbitMQ")?;
let channel = connection
.create_channel()
.await
.context("opening a RabbitMQ channel")?;
*slot = Some(Arc::new(connection));
Ok(channel)
}
fn from_parts(uri: String, name: String) -> Self {
Self {
shared: Arc::new(Shared {
uri,
name,
consuming: Mutex::new(None),
publishing: Mutex::new(None),
}),
}
}
}
impl fmt::Debug for RabbitMq {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("RabbitMq")
.field("uri", &redacted(&self.shared.uri))
.field("connection_name", &self.shared.name)
.finish_non_exhaustive()
}
}
pub(super) async fn close(channel: &Channel) -> Result<(), Error> {
if !channel.status().connected() {
return Ok(());
}
channel
.close(REPLY_SUCCESS, "closing".into())
.await
.context("closing the RabbitMQ channel")
}