use crate::{AttributeSetter, Error, Lifecycle, ResourceHandle, RetryPolicy, Supervisor};
use std::{
future::Future,
sync::{Arc, Mutex},
};
pub trait ManagedClientBackend<L: Lifecycle> {
fn execute<F, Fut, T>(
&self,
operation: F,
) -> impl Future<Output = Result<T, Error<L::Error>>> + Send
where
F: FnOnce(Arc<L::Resource>) -> Fut + Send + 'static,
Fut: Future<Output = Result<T, L::Error>> + Send + 'static,
T: Send + 'static;
}
#[cfg(feature = "pool")]
impl<L: Lifecycle> ManagedClientBackend<L> for crate::ManagedResourceProxy<L> {
async fn execute<F, Fut, T>(&self, operation: F) -> Result<T, Error<L::Error>>
where
F: FnOnce(Arc<L::Resource>) -> Fut + Send + 'static,
Fut: Future<Output = Result<T, L::Error>> + Send + 'static,
T: Send + 'static,
{
self.execute(operation).await
}
}
impl<L: Lifecycle> ManagedClientBackend<L> for SupervisedResourceProxy<L> {
async fn execute<F, Fut, T>(&self, operation: F) -> Result<T, Error<L::Error>>
where
F: FnOnce(Arc<L::Resource>) -> Fut + Send + 'static,
Fut: Future<Output = Result<T, L::Error>> + Send + 'static,
T: Send + 'static,
{
self.execute(operation).await
}
}
pub struct SupervisedResourceProxy<L: Lifecycle> {
supervisor: Supervisor<L>,
closed: Arc<Mutex<bool>>,
}
impl<L: Lifecycle> Clone for SupervisedResourceProxy<L> {
fn clone(&self) -> Self {
Self {
supervisor: self.supervisor.clone(),
closed: self.closed.clone(),
}
}
}
impl<L: Lifecycle> SupervisedResourceProxy<L> {
pub fn new(supervisor: Supervisor<L>) -> Self {
Self {
supervisor,
closed: Arc::new(Mutex::new(false)),
}
}
fn begin(&self) -> Result<(), Error<L::Error>> {
let closed = self.closed.lock().unwrap();
if *closed {
return Err(Error::Stopped);
}
self.supervisor.begin();
Ok(())
}
pub async fn connected(&self) -> Result<(), Error<L::Error>> {
self.begin()?;
let mut changed = self.supervisor.subscribe();
let mut stopping = self.supervisor.stopped();
loop {
changed.borrow_and_update();
if *stopping.borrow() {
return Err(Error::Stopped);
}
if let Some(cause) = self.supervisor.failure() {
return Err(Error::Lifecycle(cause));
}
if self.is_connected() {
return Ok(());
}
if let Some(resource) = self.supervisor.current() {
tokio::select! {
biased;
_ = crate::shutdown(&mut stopping) => return Err(Error::Stopped),
_ = changed.changed() => {},
_ = self.supervisor.lifecycle.wait_connected(resource.resource()) => {},
}
} else {
tokio::select! {
biased;
_ = crate::shutdown(&mut stopping) => return Err(Error::Stopped),
_ = changed.changed() => {},
}
}
}
}
pub fn is_connected(&self) -> bool {
!*self.closed.lock().unwrap() && self.supervisor.is_connected()
}
pub fn failure(&self) -> Option<Arc<L::Error>> {
self.supervisor.failure()
}
pub fn reset_failure(&self) -> bool {
let closed = self.closed.lock().unwrap();
!*closed && self.supervisor.reset_failure()
}
pub fn current(&self) -> Option<ResourceHandle<L::Resource>> {
if *self.closed.lock().unwrap() {
None
} else {
self.supervisor.current()
}
}
pub async fn execute<F, Fut, T>(&self, operation: F) -> Result<T, Error<L::Error>>
where
F: FnOnce(Arc<L::Resource>) -> Fut,
Fut: Future<Output = Result<T, L::Error>>,
{
self.begin()?;
self.supervisor.execute_running(operation).await
}
pub async fn execute_with_timeout<F, Fut, T>(
&self,
duration: std::time::Duration,
operation: F,
) -> Result<T, Error<L::Error>>
where
F: FnOnce(Arc<L::Resource>) -> Fut,
Fut: Future<Output = Result<T, L::Error>>,
{
crate::with_call_timeout(duration, self.supervisor.stopped(), async {
self.begin()?;
self.supervisor.execute_running(operation).await
})
.await
}
pub async fn connected_with_timeout(
&self,
duration: std::time::Duration,
) -> Result<(), Error<L::Error>> {
crate::with_call_timeout(duration, self.supervisor.stopped(), self.connected()).await
}
pub async fn execute_with_retry<F, Fut, T, P>(
&self,
policy: RetryPolicy,
operation: F,
retry_if: P,
) -> Result<T, Error<L::Error>>
where
F: FnMut(Arc<L::Resource>) -> Fut,
Fut: Future<Output = Result<T, L::Error>>,
P: FnMut(&L::Error) -> bool,
{
if policy.timeout.is_zero() {
return Err(Error::Timeout);
}
self.begin()?;
self.supervisor
.execute_with_retry_running(policy, operation, retry_if)
.await
}
pub fn set_attribute(&self, name: impl Into<String>, setter: AttributeSetter<L::Resource>) {
self.supervisor.set_attribute(name, setter);
}
pub fn attribute<T>(&self, read: impl FnOnce(&L::Resource) -> T) -> Option<T> {
self.supervisor.with_latest(read)
}
pub fn set_value<T: Clone + Send + Sync + 'static>(
&self,
name: impl Into<String>,
value: T,
apply: impl Fn(&L::Resource, &T) + Send + Sync + 'static,
) {
self.supervisor.set_value(name, value, apply);
}
pub fn value<T: Clone + Send + Sync + 'static>(&self, name: &str) -> Option<T> {
self.supervisor.value(name)
}
pub async fn stop(&self) {
{
let mut closed = self.closed.lock().unwrap();
*closed = true;
self.supervisor.request_stop();
}
self.supervisor.stop().await;
}
}
#[macro_export]
macro_rules! managed_client {
($visibility:vis struct $name:ident for $lifecycle:ty { $($methods:tt)* }) => {
#[derive(Clone)]
$visibility struct $name<B = $crate::SupervisedResourceProxy<$lifecycle>> { pub managed: B }
$crate::managed_client_pool_constructor! { $name; $lifecycle }
impl $name<$crate::SupervisedResourceProxy<$lifecycle>> {
pub fn new(supervisor: $crate::Supervisor<$lifecycle>) -> Self {
Self { managed: $crate::SupervisedResourceProxy::new(supervisor) }
}
pub fn from_supervisor(supervisor: $crate::Supervisor<$lifecycle>) -> Self {
Self::new(supervisor)
}
}
impl<B: $crate::ManagedClientBackend<$lifecycle>> $name<B> {
$crate::managed_client_methods! { $lifecycle; $($methods)* }
}
};
}
#[doc(hidden)]
#[macro_export]
macro_rules! managed_client_methods {
($lifecycle:ty;) => {};
($lifecycle:ty; async fn $method:ident($($argument:ident: $ty:ty),* $(,)?) -> $output:ty; $($rest:tt)*) => {
pub async fn $method(&self, $($argument: $ty),*) -> Result<$output, $crate::Error<<$lifecycle as $crate::Lifecycle>::Error>> {
$crate::ManagedClientBackend::execute(&self.managed, move |resource| async move { resource.$method($($argument),*).await }).await
}
$crate::managed_client_methods! { $lifecycle; $($rest)* }
};
($lifecycle:ty; fn $method:ident($($argument:ident: $ty:ty),* $(,)?) -> $output:ty; $($rest:tt)*) => {
pub async fn $method(&self, $($argument: $ty),*) -> Result<$output, $crate::Error<<$lifecycle as $crate::Lifecycle>::Error>> {
$crate::ManagedClientBackend::execute(&self.managed, move |resource| async move { resource.$method($($argument),*) }).await
}
$crate::managed_client_methods! { $lifecycle; $($rest)* }
};
}
#[cfg(feature = "pool")]
#[doc(hidden)]
#[macro_export]
macro_rules! managed_client_pool_constructor {
($name:ident; $lifecycle:ty) => {
impl $name<$crate::ManagedResourceProxy<$lifecycle>> {
pub fn from_pool(pool: $crate::Pool<$lifecycle>) -> Self {
Self {
managed: $crate::ManagedResourceProxy::new(pool),
}
}
}
};
}
#[cfg(not(feature = "pool"))]
#[doc(hidden)]
#[macro_export]
macro_rules! managed_client_pool_constructor {
($name:ident; $lifecycle:ty) => {};
}