use super::{
config::{ClientConfig, SourceConfig, SqsCredentials},
sink::SqsSink,
source::SqsSource,
};
use crate::error::{BoxError, Error};
use aws_config::{BehaviorVersion, Region};
use aws_sdk_sqs::{Client, config::Credentials};
use std::sync::Arc;
use tokio::sync::OnceCell;
#[derive(Clone, Debug)]
pub struct Sqs {
shared: Arc<Shared>,
}
#[derive(Debug)]
struct Shared {
config: ClientConfig,
client: OnceCell<Client>,
}
impl Sqs {
pub fn new() -> Self {
Self::from_config(ClientConfig::default())
}
pub fn region(self, region: impl Into<String>) -> Self {
self.configure(|config| config.region = Some(region.into()))
}
pub fn endpoint_url(self, endpoint_url: impl Into<String>) -> Self {
self.configure(|config| config.endpoint_url = Some(endpoint_url.into()))
}
pub fn credentials(self, credentials: SqsCredentials) -> Self {
self.configure(|config| config.credentials = Some(credentials))
}
pub fn source<C: Default>(&self, queue_url: impl Into<String>) -> SqsSource<C> {
self.source_with_codec(C::default(), queue_url)
}
pub fn source_with_codec<C>(&self, codec: C, queue_url: impl Into<String>) -> SqsSource<C> {
SqsSource::new(self.clone(), SourceConfig::new(queue_url.into()), codec)
}
pub fn sink<C: Default>(&self, queue_url: impl Into<String>) -> SqsSink<C> {
self.sink_with_codec(C::default(), queue_url)
}
pub fn sink_with_codec<C>(&self, codec: C, queue_url: impl Into<String>) -> SqsSink<C> {
SqsSink::new(self.clone(), queue_url.into(), codec)
}
pub fn validate(&self) -> Result<(), Error> {
self.shared.config.validate()
}
pub(super) async fn client(&self) -> Result<&Client, BoxError> {
self.shared
.client
.get_or_try_init(|| async {
self.validate()?;
let config = &self.shared.config;
let mut loader = aws_config::defaults(BehaviorVersion::latest());
if let Some(region) = &config.region {
loader = loader.region(Region::new(region.clone()));
}
if let Some(url) = &config.endpoint_url {
loader = loader.endpoint_url(url);
}
if let Some(credentials) = &config.credentials {
loader = loader.credentials_provider(Credentials::new(
&credentials.access_key_id,
&credentials.secret_access_key,
credentials.session_token.clone(),
None,
"beavers",
));
}
Ok::<_, BoxError>(Client::new(&loader.load().await))
})
.await
}
fn configure(self, change: impl FnOnce(&mut ClientConfig)) -> Self {
let mut config = self.shared.config.clone();
change(&mut config);
Self::from_config(config)
}
fn from_config(config: ClientConfig) -> Self {
Self {
shared: Arc::new(Shared {
config,
client: OnceCell::new(),
}),
}
}
}
impl Default for Sqs {
fn default() -> Self {
Self::new()
}
}