eclipse-core 0.14.0

Core library for eclipse: providers, tools, sessions, config, runtime
Documentation
//! Cooperative cancellation for a run.
//!
//! A [`Cancel`] is a cloneable flag plus a wakeup. The caller (a CLI signal handler, the
//! dashboard) sets it; the agent checks it at its own boundaries — before each provider
//! request, before each tool call, and between iterations — and returns
//! [`Error::Cancelled`](crate::Error::Cancelled) when it sees the flag.
//!
//! It is cooperative on purpose: the run stops at the next check point rather than being
//! aborted mid-write, so a cancelled run never leaves half-written records behind. What
//! has already been written (the user message, any completed tool results) stays in the
//! session, and the next run repairs an unanswered tool call.

use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::Notify;

#[derive(Clone, Debug, Default)]
pub struct Cancel {
    inner: Arc<Inner>,
}

#[derive(Debug, Default)]
struct Inner {
    flag: AtomicBool,
    notify: Notify,
}

impl Cancel {
    pub fn new() -> Self {
        Self::default()
    }

    /// Request cancellation. Calling it more than once, or after the run finished, is
    /// harmless.
    pub fn cancel(&self) {
        self.inner.flag.store(true, Ordering::SeqCst);
        self.inner.notify.notify_waiters();
    }

    pub fn is_cancelled(&self) -> bool {
        self.inner.flag.load(Ordering::SeqCst)
    }

    /// Resolves as soon as [`cancel`](Self::cancel) has been called; immediately if it
    /// already was, and never if it is not.
    pub async fn cancelled(&self) {
        // Registered before the check: a `cancel` between the two cannot be missed.
        let notified = self.inner.notify.notified();
        if self.is_cancelled() {
            return;
        }
        notified.await;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn starts_uncancelled_and_latches() {
        let c = Cancel::new();
        assert!(!c.is_cancelled());
        c.cancel();
        assert!(c.is_cancelled());
        c.cancel();
        assert!(c.is_cancelled());
    }

    #[test]
    fn clones_share_one_flag() {
        let a = Cancel::new();
        let b = a.clone();
        b.cancel();
        assert!(a.is_cancelled());
    }

    #[tokio::test]
    async fn cancelled_wakes_a_waiter() {
        let c = Cancel::new();
        let woken = {
            let c = c.clone();
            tokio::spawn(async move { c.cancelled().await })
        };
        tokio::time::sleep(Duration::from_millis(20)).await;
        assert!(!woken.is_finished());
        c.cancel();
        tokio::time::timeout(Duration::from_secs(1), woken)
            .await
            .expect("waiter should wake")
            .unwrap();
    }

    #[tokio::test]
    async fn cancelled_returns_at_once_when_already_set() {
        let c = Cancel::new();
        c.cancel();
        tokio::time::timeout(Duration::from_millis(200), c.cancelled())
            .await
            .expect("an already-cancelled token must not wait");
    }
}