etherbird 0.2.3

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;
}

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 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()
    }
    /// 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.
    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
    }
    /// 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;
    }
}