use std::time::Duration;
#[derive(Debug, Clone)]
pub struct HttpResponse {
pub status: u16,
pub body: String,
}
impl HttpResponse {
pub fn ok(&self) -> bool {
(200..300).contains(&self.status)
}
}
#[derive(Debug, Clone)]
pub struct BytesResponse {
pub status: u16,
pub body: Vec<u8>,
}
impl BytesResponse {
pub fn ok(&self) -> bool {
(200..300).contains(&self.status)
}
}
const MAX_ARCHIVE_BYTES: u64 = 50 * 1024 * 1024;
pub trait HttpClient {
fn get(&self, url: &str) -> anyhow::Result<HttpResponse>;
fn get_bytes(&self, url: &str, headers: &[(&str, &str)]) -> anyhow::Result<BytesResponse>;
}
pub struct UreqClient {
agent: ureq::Agent,
}
impl UreqClient {
pub fn new() -> Self {
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(10)))
.http_status_as_error(false)
.build()
.into();
Self { agent }
}
}
impl Default for UreqClient {
fn default() -> Self {
Self::new()
}
}
impl HttpClient for UreqClient {
fn get(&self, url: &str) -> anyhow::Result<HttpResponse> {
let mut response = self.agent.get(url).call()?;
let status = response.status().as_u16();
let body = response.body_mut().read_to_string()?;
Ok(HttpResponse { status, body })
}
fn get_bytes(&self, url: &str, headers: &[(&str, &str)]) -> anyhow::Result<BytesResponse> {
let mut request = self.agent.get(url);
for (name, value) in headers {
request = request.header(*name, *value);
}
let mut response = request.call()?;
let status = response.status().as_u16();
let body = response
.body_mut()
.with_config()
.limit(MAX_ARCHIVE_BYTES)
.read_to_vec()?;
Ok(BytesResponse { status, body })
}
}
pub fn encode_uri_component(input: &str) -> String {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
let mut out = String::with_capacity(input.len());
for &b in input.as_bytes() {
let unreserved = b.is_ascii_alphanumeric()
|| matches!(
b,
b'-' | b'_' | b'.' | b'!' | b'~' | b'*' | b'\'' | b'(' | b')'
);
if unreserved {
out.push(b as char);
} else {
out.push('%');
out.push(HEX[(b >> 4) as usize] as char);
out.push(HEX[(b & 0x0f) as usize] as char);
}
}
out
}
#[cfg(test)]
pub mod mock {
use std::collections::HashMap;
use super::{BytesResponse, HttpClient, HttpResponse};
#[derive(Default)]
pub struct MockClient {
responses: HashMap<String, HttpResponse>,
bytes: HashMap<String, BytesResponse>,
}
impl MockClient {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, url: &str, status: u16, body: &str) -> Self {
self.responses.insert(
url.to_string(),
HttpResponse {
status,
body: body.to_string(),
},
);
self
}
pub fn with_bytes(mut self, url: &str, status: u16, body: Vec<u8>) -> Self {
self.bytes
.insert(url.to_string(), BytesResponse { status, body });
self
}
}
impl HttpClient for MockClient {
fn get(&self, url: &str) -> anyhow::Result<HttpResponse> {
self.responses
.get(url)
.cloned()
.ok_or_else(|| anyhow::anyhow!("MockClient: no response registered for {url}"))
}
fn get_bytes(&self, url: &str, _headers: &[(&str, &str)]) -> anyhow::Result<BytesResponse> {
self.bytes.get(url).cloned().ok_or_else(|| {
anyhow::anyhow!("MockClient: no bytes response registered for {url}")
})
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn encode_uri_component_matches_js() {
assert_eq!(encode_uri_component("next"), "next");
assert_eq!(
encode_uri_component("@mastra/client-js"),
"%40mastra%2Fclient-js"
);
assert_eq!(encode_uri_component("a b"), "a%20b");
assert_eq!(encode_uri_component("-_.!~*'()"), "-_.!~*'()");
assert_eq!(encode_uri_component("é"), "%C3%A9");
}
#[test]
fn response_ok_only_for_2xx() {
let mk = |status| HttpResponse {
status,
body: String::new(),
};
assert!(mk(200).ok());
assert!(mk(299).ok());
assert!(!mk(404).ok());
assert!(!mk(500).ok());
assert!(!mk(301).ok());
}
#[test]
fn mock_client_returns_canned_and_errors_on_miss() {
use super::mock::MockClient;
let client = MockClient::new().with("https://x/y", 200, "{\"ok\":true}");
let resp = client.get("https://x/y").unwrap();
assert_eq!(resp.status, 200);
assert!(resp.body.contains("ok"));
assert!(client.get("https://x/other").is_err());
}
}