atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
//! The in-flight request registry.
//!
//! On stdio there is no per-request stream to close, so a client cancels by
//! sending `notifications/cancelled`. Two requirements shape this registry:
//! a server **SHOULD** stop processing a cancelled request and free its
//! resources, and it **MUST NOT** send a response for one.
//!
//! Both are met by making removal the decision point. Cancelling *removes*
//! the entry and fires the token; a handler that finishes normally removes its
//! own entry and sends only if the removal succeeded. Whichever happens first
//! wins, under one lock, with no window in between.

use std::collections::HashMap;
use std::sync::Mutex;

use tokio_util::sync::CancellationToken;

use crate::proto::RequestKey;

/// Requests currently being handled, keyed by JSON-RPC id.
#[derive(Debug, Default)]
pub struct Registry {
    entries: Mutex<HashMap<RequestKey, CancellationToken>>,
}

impl Registry {
    /// An empty registry.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Register a request and return its cancellation token.
    ///
    /// Called before the handler is spawned, which closes the race where a
    /// cancellation arrives before the handler has announced itself.
    pub fn register(&self, key: RequestKey) -> CancellationToken {
        let token = CancellationToken::new();
        self.lock().insert(key, token.clone());
        token
    }

    /// Take a request out of the registry, if it is still there.
    ///
    /// Returns `None` when the request was already cancelled, which is the
    /// signal to drop its response rather than send it.
    pub fn take(&self, key: &RequestKey) -> Option<CancellationToken> {
        self.lock().remove(key)
    }

    /// Cancel a request by id.
    ///
    /// Returns whether anything was cancelled. An unknown id is not an error:
    /// cancellations race with completion, and the specification says to
    /// ignore one for a request that is unknown or already finished.
    pub fn cancel(&self, key: &RequestKey) -> bool {
        match self.lock().remove(key) {
            Some(token) => {
                token.cancel();
                true
            }
            None => false,
        }
    }

    /// Cancel everything, for shutdown.
    pub fn cancel_all(&self) {
        for (_, token) in self.lock().drain() {
            token.cancel();
        }
    }

    /// How many requests are in flight.
    pub fn len(&self) -> usize {
        self.lock().len()
    }

    /// Whether nothing is in flight.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<RequestKey, CancellationToken>> {
        // A poisoned lock means a thread panicked while holding it. The map is
        // a plain HashMap with no invariant a panic could break mid-update, so
        // recovering is strictly better than propagating the panic into every
        // later request.
        self.entries.lock().unwrap_or_else(|poisoned| {
            tracing::warn!("In-flight registry lock was poisoned; recovering.");
            poisoned.into_inner()
        })
    }
}

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

    fn key(n: i64) -> RequestKey {
        RequestKey::Num(n)
    }

    #[test]
    fn register_then_take_yields_the_token() {
        let registry = Registry::new();
        let token = registry.register(key(1));
        assert!(!token.is_cancelled());
        assert!(registry.take(&key(1)).is_some());
        assert!(registry.is_empty());
    }

    #[test]
    fn cancel_fires_the_token_and_removes_the_entry() {
        let registry = Registry::new();
        let token = registry.register(key(1));
        assert!(registry.cancel(&key(1)));
        assert!(token.is_cancelled());
        // The handler's own removal now fails, which is what tells it to drop
        // the response instead of sending one.
        assert!(registry.take(&key(1)).is_none());
    }

    #[test]
    fn cancelling_an_unknown_id_is_ignored() {
        let registry = Registry::new();
        assert!(!registry.cancel(&key(99)));
    }

    #[test]
    fn cancelling_a_completed_request_is_ignored() {
        let registry = Registry::new();
        registry.register(key(1));
        assert!(registry.take(&key(1)).is_some());
        assert!(!registry.cancel(&key(1)));
    }

    #[test]
    fn string_and_numeric_ids_do_not_collide() {
        let registry = Registry::new();
        let numeric = registry.register(RequestKey::Num(1));
        let textual = registry.register(RequestKey::Str("1".to_string()));
        assert!(registry.cancel(&RequestKey::Num(1)));
        assert!(numeric.is_cancelled());
        assert!(!textual.is_cancelled());
    }

    #[test]
    fn cancel_all_drains_everything() {
        let registry = Registry::new();
        let a = registry.register(key(1));
        let b = registry.register(key(2));
        registry.cancel_all();
        assert!(a.is_cancelled());
        assert!(b.is_cancelled());
        assert!(registry.is_empty());
    }
}