etherbird 0.4.2

Stable async clients with connection recovery and session restoration
Documentation
use crate::{AttributeSetter, Error, Lifecycle, ResourceHandle, RetryPolicy, Supervisor};
use std::{
    future::Future,
    sync::{Arc, Mutex},
};

/// Execution backend for methods generated by [`crate::managed_client!`].
/// Implementations select whether calls require exclusive pooled access or can
/// execute concurrently. Dispatch is static and does not box operation futures.
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
    }
}

/// Stable proxy for a single resource supporting concurrent operations.
///
/// Calls wait for lifecycle readiness but do not acquire an exclusive lease or
/// enter a pool queue. Operation futures are polled by their callers: dropping a
/// call cancels it, and shutdown is observed when the caller next polls. Unlike
/// a pool, this proxy does not drain an unpolled operation before teardown.
/// Resource-specific cancellation safety remains the adapter's responsibility.
///
/// Clones share configuration and permanent shutdown. Do not independently
/// restart retained clones of the supplied supervisor while using this proxy.
/// Named setters and stored values are replayed before replacement setup.
/// Generate the same application methods as a pooled client with
/// [`crate::managed_client!`] and select this backend with `Client::from_supervisor`.
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> {
    /// Wrap without starting tasks; the first call starts supervision.
    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);
        }
        // Serialize startup with permanent shutdown. Acquisition/operations below
        // never implicitly restart, even if shutdown races after this check.
        self.supervisor.begin();
        Ok(())
    }
    /// Start supervision if needed and wait for setup and the live connection
    /// indicator, following replacements. Returns [`Error::Stopped`] after shutdown.
    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() => {},
                }
            }
        }
    }
    /// Query readiness and the resource's live connection indicator without starting tasks.
    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()
    }
    /// Reset a suspended lifecycle without reopening a permanently closed client.
    pub fn reset_failure(&self) -> bool {
        let closed = self.closed.lock().unwrap();
        !*closed && self.supervisor.reset_failure()
    }
    /// Snapshot the published generation, or `None` during recovery or after shutdown.
    /// The handle does not reserve exclusive access or keep that generation ready.
    pub fn current(&self) -> Option<ResourceHandle<L::Resource>> {
        if *self.closed.lock().unwrap() {
            None
        } else {
            self.supervisor.current()
        }
    }
    /// Run once, concurrently with other calls; failures request recovery by default.
    /// The adapter's operation policy can retain a healthy resource instead.
    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
    }
    /// Run once with an overall timeout including readiness and failure teardown.
    /// Zero does not start work. Shutdown takes precedence; expiry drops the
    /// caller-owned future without replay. Protocol cancellation safety remains
    /// the adapter's responsibility, as with `execute`.
    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
    }
    /// Wait for live readiness within an overall timeout. Zero does not start
    /// supervision; shutdown takes precedence over expiry.
    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
    }
    /// Explicitly retry a replay-safe call after replacement readiness.
    /// See [`Supervisor::execute_with_retry`] for deadlines and replay semantics.
    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)
    }
    /// Permanently close every proxy clone. Cleanup runs independently of this
    /// future, but caller-owned operations are not joined by this method.
    pub async fn stop(&self) {
        {
            let mut closed = self.closed.lock().unwrap();
            *closed = true;
            self.supervisor.request_stop();
        }
        self.supervisor.stop().await;
    }
}

/// Generate a typed proxy with ordinary async client methods returning owned results.
/// Methods must return the lifecycle error type. Borrowed/streaming results need a manual wrapper.
/// `Client::new(supervisor)` selects direct supervision for a concurrency-safe
/// resource; `from_supervisor` is an alias. This is the default backend.
/// With the `pool` feature, `Client::from_pool(pool)` selects exclusive dispatch
/// with type `Client<ManagedResourceProxy<Hooks>>`. Both expose the same generated
/// methods and configuration access through `managed`.
/// Direct calls are caller-owned and do not promise the pool's independent
/// shutdown drain. See [`crate::SupervisedResourceProxy`] for cancellation semantics.
///
/// ```
/// # use etherbird::{Config, Lifecycle, Supervisor, async_trait};
/// # use std::convert::Infallible;
/// # struct Resource;
/// # impl Resource { fn identifier(&self) -> Result<usize, Infallible> { Ok(7) } }
/// # struct Hooks;
/// # #[async_trait]
/// # impl Lifecycle for Hooks {
/// #     type Resource = Resource;
/// #     type Error = Infallible;
/// #     async fn create(&self) -> Result<Resource, Infallible> { Ok(Resource) }
/// #     async fn connect(&self, _: &Resource) -> Result<(), Infallible> { Ok(()) }
/// #     async fn disconnect(&self, _: &Resource) -> Result<(), Infallible> { Ok(()) }
/// # }
/// etherbird::managed_client! {
///     struct Client for Hooks {
///         fn identifier() -> usize;
///     }
/// }
/// # async fn run() -> Result<(), etherbird::Error<Infallible>> {
/// let direct = Client::new(Supervisor::new(Hooks, Config::default()));
/// assert_eq!(direct.identifier().await?, 7);
/// direct.managed.stop().await;
///
/// # #[cfg(feature = "pool")]
/// # {
/// # use etherbird::{Pool, PoolConfig};
/// let pool = Pool::new(
///     || Supervisor::new(Hooks, Config::default()),
///     PoolConfig::default(),
/// );
/// let pooled = Client::from_pool(pool);
/// assert_eq!(pooled.identifier().await?, 7);
/// pooled.managed.stop().await;
/// # }
/// # Ok(())
/// # }
/// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap()
/// #     .block_on(run()).unwrap();
/// ```
#[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>> {
            /// Wrap a concurrency-safe resource without exclusive pool dispatch.
            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)* }
    };
}

// Select at library compile time, not with a cfg in the consuming crate.
#[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) => {};
}