use super::{
config::{Credential, Settings, SinkConfig, SourceConfig},
connection::Connection,
sink::ServiceBusSink,
source::ServiceBusSource,
};
use crate::error::Error;
use std::{fmt, sync::Arc};
use tokio::sync::Mutex;
#[derive(Clone)]
pub struct ServiceBus {
shared: Arc<Shared>,
}
struct Shared {
settings: Settings,
connection: Mutex<Option<Arc<Connection>>>,
}
impl ServiceBus {
pub fn new(namespace: impl Into<String>) -> Self {
Self::from_settings(Settings::new(namespace.into()))
}
pub fn from_connection_string(connection_string: &str) -> Result<Self, Error> {
Settings::from_connection_string(connection_string).map(Self::from_settings)
}
pub fn shared_access_key(self, name: impl Into<String>, key: impl Into<String>) -> Self {
self.configure(|settings| {
settings.credential = Some(Credential::SharedAccessKey {
name: name.into(),
key: key.into(),
})
})
}
pub fn shared_access_signature(self, signature: impl Into<String>) -> Self {
self.configure(|settings| {
settings.credential = Some(Credential::SharedAccessSignature(signature.into()))
})
}
pub fn emulator(self) -> Self {
self.configure(|settings| settings.emulator = true)
}
pub fn source<C: Default>(&self, entity_path: impl Into<String>) -> ServiceBusSource<C> {
self.source_with_codec(C::default(), entity_path)
}
pub fn source_with_codec<C>(
&self,
codec: C,
entity_path: impl Into<String>,
) -> ServiceBusSource<C> {
ServiceBusSource::new(self.clone(), SourceConfig::new(entity_path.into()), codec)
}
pub fn sink<C: Default>(&self, entity_path: impl Into<String>) -> ServiceBusSink<C> {
self.sink_with_codec(C::default(), entity_path)
}
pub fn sink_with_codec<C>(
&self,
codec: C,
entity_path: impl Into<String>,
) -> ServiceBusSink<C> {
ServiceBusSink::new(self.clone(), SinkConfig::new(entity_path.into()), codec)
}
pub fn validate(&self) -> Result<(), Error> {
self.shared.settings.validate()
}
pub(super) async fn connection(&self, entities: &[String]) -> Result<Arc<Connection>, Error> {
let connection = {
let mut slot = self.shared.connection.lock().await;
match slot.as_ref() {
Some(connection) if !connection.is_lost().await => connection.clone(),
_ => {
self.validate()?;
let connection = Arc::new(Connection::open(&self.shared.settings).await?);
*slot = Some(connection.clone());
connection
}
}
};
connection.authorize(entities).await?;
Ok(connection)
}
fn configure(self, change: impl FnOnce(&mut Settings)) -> Self {
let mut settings = self.shared.settings.clone();
change(&mut settings);
Self::from_settings(settings)
}
fn from_settings(settings: Settings) -> Self {
Self {
shared: Arc::new(Shared {
settings,
connection: Mutex::new(None),
}),
}
}
}
impl fmt::Debug for ServiceBus {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let settings = &self.shared.settings;
f.debug_struct("ServiceBus")
.field("namespace", &settings.namespace)
.field("credential", &settings.credential)
.field("emulator", &settings.emulator)
.finish_non_exhaustive()
}
}