atpmcp 0.15.0

AT Protocol MCP server (Model Context Protocol 2026-07-28)
//! Shared fixtures for tool and resource tests.
//!
//! None of these touch the network. The resolver is constructed but never
//! reached in the tests that use it: every case here fails argument validation
//! or is served from a seeded cache, which is deliberate — a unit test that
//! depends on `plc.directory` being up is a unit test that fails for reasons
//! unrelated to the code it covers.

use std::sync::Arc;

use atproto_identity::resolve::{HickoryDnsResolver, InnerIdentityResolver};
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;

use crate::cache::BlobCache;
use crate::context::{Limits, ServerContext};
use crate::proto::RequestKey;
use crate::proto::serve::RequestCtx;
use crate::proto::writer;

/// A resolver pointed at the default PLC directory, around the client the
/// server itself uses for identity resolution.
#[must_use]
pub fn create_test_resolver() -> InnerIdentityResolver {
    InnerIdentityResolver {
        dns_resolver: Arc::new(HickoryDnsResolver::create_resolver(&[])),
        http_client: crate::context::identity_client(&test_guard()).expect("identity client"),
        plc_hostname: "plc.directory".to_string(),
    }
}

/// The client the server uses for every other JSON request.
#[must_use]
/// The address guard the test clients carry: off, as for the waived
/// [`Limits`](crate::context::Limits) these tests use, so a test server on a
/// name that resolves to loopback is reachable.
pub fn test_guard() -> crate::context::AddressGuard {
    crate::context::AddressGuard::for_config(true, "plc.directory")
}

pub fn test_request_client() -> reqwest::Client {
    crate::context::request_client(&test_guard()).expect("request client")
}

/// Limits with a small inline ceiling, so the size rules are testable without
/// allocating megabytes.
#[must_use]
pub fn test_limits() -> Limits {
    Limits {
        blob_max_inline_bytes: 1024,
        // These tests point tools at `https://127.0.0.1:1/`, an address chosen
        // because nothing listens there: the case under test is what happens
        // before or instead of a connection. The endpoint policy refuses an
        // address literal, which is the whole point of it, so the waiver an
        // operator would use for a local server is what makes them runnable.
        allow_insecure_endpoints: true,
        ..Limits::default()
    }
}

/// A context with caching disabled.
#[must_use]
pub fn test_context() -> Arc<ServerContext> {
    build_context(Arc::new(BlobCache::new(None, 0)), test_limits())
}

/// A context with a cache in a directory unique to this test run.
#[must_use]
pub fn test_context_with_cache() -> Arc<ServerContext> {
    test_context_with_cache_and_limits(test_limits())
}

/// [`test_context_with_cache`], under `limits` rather than [`test_limits`].
#[must_use]
pub fn test_context_with_cache_and_limits(limits: Limits) -> Arc<ServerContext> {
    test_context_with_cache_budget(limits, crate::context::DEFAULT_BLOB_CACHE_MAX_BYTES)
}

/// [`test_context_with_cache_and_limits`], with the cache pruned to
/// `cache_max_bytes` rather than the default budget. Zero is a cache that
/// stores nothing, as `ATPMCP_BLOB_CACHE_MAX_BYTES=0` is.
#[must_use]
pub fn test_context_with_cache_budget(limits: Limits, cache_max_bytes: u64) -> Arc<ServerContext> {
    // A counter, not a timestamp: `SystemTime::now()` is only
    // microsecond-resolution on some platforms, and parallel tests that landed
    // in the same microsecond shared a directory and deleted each other's
    // files.
    use std::sync::atomic::{AtomicU64, Ordering};
    static COUNTER: AtomicU64 = AtomicU64::new(0);
    let dir = std::env::temp_dir().join(format!(
        "atpmcp-test-{}-{}",
        std::process::id(),
        COUNTER.fetch_add(1, Ordering::Relaxed)
    ));
    build_context(Arc::new(BlobCache::new(Some(dir), cache_max_bytes)), limits)
}

fn build_context(cache: Arc<BlobCache>, limits: Limits) -> Arc<ServerContext> {
    // The receiver is deliberately leaked rather than dropped: a closed
    // channel would make every progress notification fail, which is harmless
    // but noisy, and keeping it open exercises the real send path.
    let (tx, rx) = mpsc::channel::<writer::Outgoing>(writer::CHANNEL_CAPACITY);
    std::mem::forget(rx);

    Arc::new(
        ServerContext::new(Arc::new(create_test_resolver()), cache, limits, tx).expect("context"),
    )
}

/// A request context with no progress reporting and nothing cancelled.
#[must_use]
pub fn test_request() -> RequestCtx {
    RequestCtx {
        key: RequestKey::Num(1),
        id: serde_json::json!(1),
        meta: crate::proto::meta::Meta {
            protocol_version: crate::proto::PROTOCOL_VERSION.to_string(),
            client_capabilities: serde_json::json!({}),
            client_info: None,
            progress_token: None,
        },
        cancel: CancellationToken::new(),
        progress: None,
    }
}

/// A one-shot raw HTTP server for exercising the streamed fetch against a
/// real socket. Accepts exactly one connection, drains the request, and
/// writes back a fixed status/body. `declare_length: false` omits
/// `Content-Length` and relies on `Connection: close` instead -- the
/// shape a peer that wants to under-declare its size would use, so it is
/// the running-total check and not the header that has to catch it.
///
/// It serves `application/octet-stream`, as -04 §11.8 lets a host serve any
/// blob; [`one_shot_server_typed`] serves another type or none.
pub async fn one_shot_server(status: u16, body: Vec<u8>, declare_length: bool) -> String {
    one_shot_server_typed(
        status,
        body,
        declare_length,
        Some("application/octet-stream"),
    )
    .await
}

/// [`one_shot_server`], answering with `content_type` as its `Content-Type`,
/// or with no `Content-Type` at all for `None`.
pub async fn one_shot_server_typed(
    status: u16,
    body: Vec<u8>,
    declare_length: bool,
    content_type: Option<&str>,
) -> String {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
    let addr = listener.local_addr().expect("addr");

    let content_type = content_type.map(str::to_string);
    tokio::spawn(async move {
        let Ok((mut socket, _)) = listener.accept().await else {
            return;
        };

        let mut raw = Vec::new();
        let mut buffer = [0u8; 4096];
        loop {
            let Ok(read) = socket.read(&mut buffer).await else {
                return;
            };
            if read == 0 {
                break;
            }
            raw.extend_from_slice(&buffer[..read]);
            if raw.windows(4).any(|w| w == b"\r\n\r\n") {
                break;
            }
        }

        let mut response = format!("HTTP/1.1 {status} X\r\n");
        if let Some(content_type) = &content_type {
            response.push_str(&format!("Content-Type: {content_type}\r\n"));
        }
        if declare_length {
            response.push_str(&format!("Content-Length: {}\r\n", body.len()));
        }
        response.push_str("Connection: close\r\n\r\n");

        let _ = socket.write_all(response.as_bytes()).await;
        let _ = socket.write_all(&body).await;
        let _ = socket.shutdown().await;
    });

    format!("http://{addr}")
}

/// One answer of a [`route_server`].
#[derive(Clone)]
pub struct Route {
    /// The request path it answers, with any query (`/page?x=1`).
    pub path: &'static str,
    /// The status line's code.
    pub status: u16,
    /// Headers beyond `Content-Length` and `Connection`.
    pub headers: Vec<(&'static str, String)>,
    /// The body.
    pub body: Vec<u8>,
}

impl Route {
    /// A `200` with `content_type` and `body`.
    #[must_use]
    pub fn ok(path: &'static str, content_type: &str, body: impl Into<Vec<u8>>) -> Self {
        Self {
            path,
            status: 200,
            headers: vec![("Content-Type", content_type.to_string())],
            body: body.into(),
        }
    }
}

/// A raw HTTP server answering every connection from a fixed table of
/// routes until the test ends, and `404` for a path not in it. Returns its
/// base URL, `http://127.0.0.1:<port>`.
///
/// For the fetches that make more than one request -- a page, then the image
/// it names -- where [`one_shot_server`] answers only the first.
pub async fn route_server(routes: Vec<Route>) -> String {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::net::TcpListener;

    let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind");
    let addr = listener.local_addr().expect("addr");
    let routes = Arc::new(routes);

    tokio::spawn(async move {
        while let Ok((mut socket, _)) = listener.accept().await {
            let routes = Arc::clone(&routes);
            tokio::spawn(async move {
                let mut raw = Vec::new();
                let mut buffer = [0u8; 4096];
                loop {
                    let Ok(read) = socket.read(&mut buffer).await else {
                        return;
                    };
                    if read == 0 {
                        break;
                    }
                    raw.extend_from_slice(&buffer[..read]);
                    if raw.windows(4).any(|w| w == b"\r\n\r\n") {
                        break;
                    }
                }
                let request = String::from_utf8_lossy(&raw);
                let path = request.split_whitespace().nth(1).unwrap_or("/");
                let route = routes.iter().find(|route| route.path == path);

                let (status, headers, body) = match route {
                    Some(route) => (route.status, route.headers.clone(), route.body.clone()),
                    None => (404, Vec::new(), b"not found".to_vec()),
                };
                let mut response = format!("HTTP/1.1 {status} X\r\n");
                for (name, value) in headers {
                    response.push_str(&format!("{name}: {value}\r\n"));
                }
                response.push_str(&format!(
                    "Content-Length: {}\r\nConnection: close\r\n\r\n",
                    body.len()
                ));
                let _ = socket.write_all(response.as_bytes()).await;
                let _ = socket.write_all(&body).await;
                let _ = socket.shutdown().await;
            });
        }
    });

    format!("http://{addr}")
}