use super::{
config::{SinkConfig, SourceConfig, validate_endpoint},
sink::PubSubSink,
source::PubSubSource,
};
use crate::error::{BoxError, Context, Error};
use google_cloud_auth::credentials::{
Builder as DefaultCredentials, Credentials, anonymous::Builder as Anonymous,
};
use google_cloud_pubsub::client::{Publisher, Subscriber};
use std::{fmt, sync::Arc, time::Duration};
use tokio::sync::OnceCell;
#[derive(Clone)]
pub struct PubSub {
shared: Arc<Shared>,
}
#[derive(Clone, Debug, Default)]
struct Settings {
endpoint: Option<String>,
anonymous: bool,
}
struct Shared {
settings: Settings,
credentials: OnceCell<Credentials>,
subscriber: OnceCell<Subscriber>,
}
impl PubSub {
pub fn new() -> Self {
Self::from_settings(Settings::default())
}
pub fn endpoint(self, endpoint: impl Into<String>) -> Self {
self.configure(|settings| settings.endpoint = Some(endpoint.into()))
}
pub fn anonymous(self) -> Self {
self.configure(|settings| settings.anonymous = true)
}
pub fn source<C: Default>(&self, subscription: impl Into<String>) -> PubSubSource<C> {
self.source_with_codec(C::default(), subscription)
}
pub fn source_with_codec<C>(
&self,
codec: C,
subscription: impl Into<String>,
) -> PubSubSource<C> {
PubSubSource::new(self.clone(), SourceConfig::new(subscription.into()), codec)
}
pub fn sink<C: Default>(&self, topic: impl Into<String>) -> PubSubSink<C> {
self.sink_with_codec(C::default(), topic)
}
pub fn sink_with_codec<C>(&self, codec: C, topic: impl Into<String>) -> PubSubSink<C> {
PubSubSink::new(self.clone(), SinkConfig::new(topic.into()), codec)
}
pub fn validate(&self) -> Result<(), Error> {
match &self.shared.settings.endpoint {
Some(url) => validate_endpoint(url),
None => Ok(()),
}
}
pub(super) async fn subscriber(&self) -> Result<&Subscriber, BoxError> {
self.shared
.subscriber
.get_or_try_init(|| async {
let mut builder =
Subscriber::builder().with_credentials(self.credentials().await?.clone());
if let Some(url) = &self.shared.settings.endpoint {
builder = builder.with_endpoint(url);
}
Ok::<_, BoxError>(
builder
.build()
.await
.context("creating the Pub/Sub subscriber client")?,
)
})
.await
}
pub(super) async fn publisher(
&self,
topic: &str,
batch_delay: Duration,
) -> Result<Publisher, BoxError> {
let mut builder = Publisher::builder(topic)
.set_delay_threshold(batch_delay)
.with_credentials(self.credentials().await?.clone());
if let Some(url) = &self.shared.settings.endpoint {
builder = builder.with_endpoint(url);
}
Ok(builder
.build()
.await
.context("creating the Pub/Sub publisher client")?)
}
async fn credentials(&self) -> Result<&Credentials, BoxError> {
self.shared
.credentials
.get_or_try_init(|| async {
self.validate()?;
if self.shared.settings.anonymous {
return Ok(Anonymous::new().build());
}
Ok::<_, BoxError>(
DefaultCredentials::default()
.build()
.context("resolving Google Cloud credentials")?,
)
})
.await
}
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,
credentials: OnceCell::new(),
subscriber: OnceCell::new(),
}),
}
}
}
impl Default for PubSub {
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for PubSub {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("PubSub")
.field("endpoint", &self.shared.settings.endpoint)
.field("anonymous", &self.shared.settings.anonymous)
.finish_non_exhaustive()
}
}