artifactize-core 0.27.2

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
Documentation
//! A loopback HTTP server that replays canned provider responses, and the test endpoint rules.

use rig_core::test_utils::MockHttpResponse;
use tokio::{
    io::{AsyncReadExt, AsyncWriteExt},
    net::TcpListener,
};

// Read canned HTTP traffic in 4 KiB chunks without putting the whole request on the
// task's stack; both headers and bodies keep accumulating until their framing is complete.
const READ_CHUNK_BYTES: usize = 4096;

pub(crate) struct Server {
    pub base: String,
}

impl Server {
    /// Run the fixture and exercise together so open sockets are dropped before `run`
    /// returns or unwinds, including if an assertion fails or not all responses are used.
    pub async fn run<T>(
        responses: Vec<MockHttpResponse>,
        exercise: impl AsyncFnOnce(&Self) -> T,
    ) -> T {
        let listener = crate::test_os::tcp::async_loopback_listener();
        let server = Self {
            base: format!("http://{}/v1", listener.local_addr().unwrap()),
        };
        let mut exercise = std::pin::pin!(exercise(&server));
        tokio::select! {
            biased;
            () = server.serve(listener, responses) => exercise.await,
            result = &mut exercise => result,
        }
    }

    async fn serve(&self, listener: TcpListener, responses: Vec<MockHttpResponse>) {
        for response in responses {
            let (mut socket, _) = listener.accept().await.unwrap();
            let mut bytes = Vec::new();
            let end = loop {
                let mut buffer = [0; READ_CHUNK_BYTES];
                let count = socket.read(&mut buffer).await.unwrap();
                assert_ne!(count, 0);
                bytes.extend_from_slice(&buffer[..count]);
                if let Some(end) = bytes.windows(4).position(|part| part == b"\r\n\r\n") {
                    break end + 4;
                }
            };
            let head = String::from_utf8(bytes[..end].to_vec()).unwrap();
            let length = head
                .lines()
                .skip(1)
                .filter_map(|line| line.split_once(':'))
                .find(|(name, _)| name.eq_ignore_ascii_case("content-length"))
                .map(|(_, value)| value.trim().parse::<usize>().unwrap())
                .unwrap_or(0);
            while bytes.len() < end + length {
                let mut buffer = [0; READ_CHUNK_BYTES];
                let count = socket.read(&mut buffer).await.unwrap();
                assert_ne!(count, 0);
                bytes.extend_from_slice(&buffer[..count]);
            }
            let (status, body, content_type) = match response {
                MockHttpResponse::Success(body) => (200, body, "application/json".to_owned()),
                MockHttpResponse::SuccessWithHeaders(body, headers) => (
                    200,
                    body,
                    headers["content-type"].to_str().unwrap().to_owned(),
                ),
                MockHttpResponse::ErrorResponse(status, body) => {
                    (status.as_u16(), body, "application/json".into())
                }
                MockHttpResponse::ErrorWithHeaders(status, body, _) => {
                    (status.as_u16(), body.into(), "application/json".into())
                }
                _ => panic!("unsupported test response"),
            };
            // An empty type omits the header.
            let content_type = match content_type.as_str() {
                "" => String::new(),
                value => format!("Content-Type: {value}\r\n"),
            };
            let header = format!(
                "HTTP/1.1 {status} Test\r\n{content_type}Content-Length: {}\r\nConnection: close\r\n\r\n",
                body.len()
            );
            socket.write_all(header.as_bytes()).await.unwrap();
            socket.write_all(&body).await.unwrap();
        }
    }
}

#[test]
fn http_client_rejects_claude_agent_backend() {
    let root = crate::test_os::tempdir();
    let result = super::Client::new(
        &crate::config::Provider::ClaudeAgent.into(),
        &"test-model".parse().unwrap(),
        &root.path().join("state"),
        root.path(),
    );
    let Err(error) = result else {
        panic!("Claude Agent must not get an HTTP client");
    };
    assert_eq!(error.code, super::Code::AgentError);
    assert!(
        error
            .message
            .contains("Unsupported client backend: claude-agent")
    );
}