merry 0.1.3

Rust SDK facade for the Merry coding agent runtime (CLI available as `merry-cli`).
Documentation
//! Single-consumer async lease primitive for foreign-language bindings.
//!
//! Ensures at most one async stream operation holds mutable access to an owned
//! run or interactive stream at a time without holding a `std::sync::Mutex`
//! guard across `.await`, while allowing cooperative `cancel`/`close` to wait
//! reliably (without lost wakeups) for the active lease to restore.

use std::sync::{Arc, Mutex};
use tokio::sync::Notify;

/// Exclusive single-consumer container for an owned binding resource.
///
/// Operations borrow mutable ownership temporarily through [`StateLease`].
#[derive(Debug)]
pub struct ExclusiveState<T> {
    label: &'static str,
    inner: Mutex<Option<T>>,
    changed: Notify,
}

impl<T> ExclusiveState<T> {
    /// Creates a new exclusive state holding `value` and tagged with `label`
    /// for diagnostics.
    #[must_use]
    pub fn new(label: &'static str, value: T) -> Self {
        Self {
            label,
            inner: Mutex::new(Some(value)),
            changed: Notify::new(),
        }
    }
}

/// RAII lease granting temporary exclusive access to the value inside an
/// [`ExclusiveState`].
///
/// Dropping a lease without calling [`StateLease::restore`] automatically
/// returns the owned value and notifies any waiting `cancel`/`close` callers.
#[derive(Debug)]
pub struct StateLease<T> {
    state: Arc<ExclusiveState<T>>,
    value: Option<T>,
}

impl<T> StateLease<T> {
    /// Non-blocking lease acquisition used by ordinary stream operations.
    ///
    /// Fails immediately if another operation already holds the lease.
    pub fn try_take(state: Arc<ExclusiveState<T>>) -> Result<Self, String> {
        let value = state
            .inner
            .lock()
            .map_err(|_| format!("{} state is poisoned", state.label))?
            .take()
            .ok_or_else(|| format!("{} operation is already in progress", state.label))?;
        Ok(Self {
            state,
            value: Some(value),
        })
    }

    /// Cooperative blocking lease acquisition used by terminal `cancel`/`close`.
    ///
    /// Registers the waiter before acquiring the mutex (`enable()`) so a
    /// concurrent [`StateLease::restore`] between lock release and `.await`
    /// never causes a lost wakeup.
    pub async fn wait_take(state: Arc<ExclusiveState<T>>) -> Result<Self, String> {
        let value = loop {
            let notified = state.changed.notified();
            tokio::pin!(notified);
            notified.as_mut().enable();
            let taken = state
                .inner
                .lock()
                .map_err(|_| format!("{} state is poisoned", state.label))?
                .take();
            if let Some(value) = taken {
                break value;
            }
            notified.await;
        };
        Ok(Self {
            state,
            value: Some(value),
        })
    }

    /// Borrows the leased value mutably.
    pub fn value_mut(&mut self) -> Result<&mut T, String> {
        self.value
            .as_mut()
            .ok_or_else(|| format!("{} lease has already been restored", self.state.label))
    }

    /// Explicitly restores the leased value and surfaces any state violation.
    pub fn restore(mut self) -> Result<(), String> {
        let Some(value) = self.value.take() else {
            return Ok(());
        };
        restore_value(&self.state, value)
    }
}

impl<T> Drop for StateLease<T> {
    fn drop(&mut self) {
        let Some(value) = self.value.take() else {
            return;
        };
        let _ = restore_value(&self.state, value);
    }
}

fn restore_value<T>(state: &ExclusiveState<T>, value: T) -> Result<(), String> {
    let mut guard = state
        .inner
        .lock()
        .map_err(|_| format!("{} state is poisoned", state.label))?;
    if guard.is_some() {
        return Err(format!("{} state was restored more than once", state.label));
    }
    *guard = Some(value);
    state.changed.notify_waiters();
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::{ExclusiveState, StateLease};
    use std::sync::Arc;

    #[tokio::test(flavor = "current_thread")]
    async fn try_take_rejects_concurrent_consumer_and_wait_take_wakes_on_restore() {
        let state = Arc::new(ExclusiveState::new("test run", 1usize));
        let mut lease = StateLease::try_take(Arc::clone(&state)).expect("first take succeeds");
        let err = StateLease::try_take(Arc::clone(&state)).expect_err("second take rejects");
        assert!(err.contains("already in progress"));

        *lease.value_mut().expect("mutable borrow") += 1;
        let waiter_state = Arc::clone(&state);
        let waiter = tokio::spawn(async move {
            let mut next = StateLease::wait_take(waiter_state)
                .await
                .expect("wait_take acquires after restore");
            let value = *next.value_mut().expect("value");
            next.restore().expect("restore");
            value
        });
        tokio::task::yield_now().await;
        lease.restore().expect("first restore");

        let observed = waiter.await.expect("waiter completes");
        assert_eq!(observed, 2);
    }

    #[tokio::test(flavor = "current_thread")]
    async fn dropping_lease_restores_value_for_subsequent_waiter() {
        let state = Arc::new(ExclusiveState::new("drop test", "ok".to_owned()));
        let lease = StateLease::try_take(Arc::clone(&state)).expect("take");
        drop(lease);
        let mut next = StateLease::wait_take(Arc::clone(&state))
            .await
            .expect("value restored on drop");
        assert_eq!(next.value_mut().expect("value").as_str(), "ok");
    }
}