Skip to main content

rap_client/
http.rs

1/// HTTP and caching abstractions for RAP client operations.
2use async_trait::async_trait;
3use std::collections::HashMap;
4use std::sync::{Arc, Mutex};
5
6/// Abstraction over HTTP client for RAP tool invocation and toolset discovery.
7#[async_trait]
8pub trait HttpClient: Send + Sync + Clone {
9    /// Error type returned by HTTP operations.
10    type Error: std::error::Error + Send + Sync + 'static;
11
12    /// POST a JSON body to the given URL. Returns the HTTP status code.
13    async fn post(&self, url: &str, body: &str) -> Result<u16, Self::Error>;
14    /// GET the given URL. Returns the HTTP status code and response body.
15    async fn get(&self, url: &str) -> Result<(u16, Vec<u8>), Self::Error>;
16}
17
18/// Abstraction over toolset manifest caching.
19#[async_trait]
20pub trait ToolsetCache: Send + Sync {
21    /// Error type returned by cache operations.
22    type Error: std::error::Error + Send + Sync + 'static;
23
24    /// Look up a cached value by key.
25    async fn get_cached(&self, cache_key: &str) -> Result<Option<String>, Self::Error>;
26    /// Store a value in the cache.
27    async fn put_cache(&self, cache_key: &str, json: &str) -> Result<(), Self::Error>;
28}
29
30// ── SimpleHttpClient ──
31
32/// Error type for [`SimpleHttpClient`].
33#[derive(Debug)]
34pub struct SimpleHttpError(String);
35impl std::fmt::Display for SimpleHttpError {
36    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
37        write!(f, "{}", self.0)
38    }
39}
40impl std::error::Error for SimpleHttpError {}
41
42/// Plain reqwest-based [`HttpClient`] with no authentication.
43#[derive(Clone)]
44pub struct SimpleHttpClient {
45    client: reqwest::Client,
46}
47
48impl Default for SimpleHttpClient {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl SimpleHttpClient {
55    /// Create a new client with default settings.
56    pub fn new() -> Self {
57        Self {
58            client: reqwest::Client::new(),
59        }
60    }
61}
62
63#[async_trait]
64impl HttpClient for SimpleHttpClient {
65    type Error = SimpleHttpError;
66
67    async fn post(&self, url: &str, body: &str) -> Result<u16, SimpleHttpError> {
68        let resp = self
69            .client
70            .post(url)
71            .header("content-type", "application/json")
72            .body(body.to_owned())
73            .send()
74            .await
75            .map_err(|e| SimpleHttpError(e.to_string()))?;
76        Ok(resp.status().as_u16())
77    }
78
79    async fn get(&self, url: &str) -> Result<(u16, Vec<u8>), SimpleHttpError> {
80        let resp = self
81            .client
82            .get(url)
83            .header("accept", "application/json")
84            .send()
85            .await
86            .map_err(|e| SimpleHttpError(e.to_string()))?;
87        let status = resp.status().as_u16();
88        let bytes = resp
89            .bytes()
90            .await
91            .map_err(|e| SimpleHttpError(e.to_string()))?;
92        Ok((status, bytes.to_vec()))
93    }
94}
95
96// ── InMemoryToolsetCache ──
97
98/// Error type for [`InMemoryToolsetCache`].
99#[derive(Debug)]
100pub struct CacheError(String);
101impl std::fmt::Display for CacheError {
102    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
103        write!(f, "{}", self.0)
104    }
105}
106impl std::error::Error for CacheError {}
107
108/// In-memory [`ToolsetCache`] backed by a `HashMap`. Useful for testing and CLI usage.
109pub struct InMemoryToolsetCache {
110    store: Arc<Mutex<HashMap<String, String>>>,
111}
112
113impl Default for InMemoryToolsetCache {
114    fn default() -> Self {
115        Self::new()
116    }
117}
118
119impl InMemoryToolsetCache {
120    /// Create a new empty cache.
121    pub fn new() -> Self {
122        Self {
123            store: Arc::new(Mutex::new(HashMap::new())),
124        }
125    }
126}
127
128#[async_trait]
129impl ToolsetCache for InMemoryToolsetCache {
130    type Error = CacheError;
131
132    async fn get_cached(&self, key: &str) -> Result<Option<String>, CacheError> {
133        Ok(self
134            .store
135            .lock()
136            .expect("bug: cache mutex poisoned")
137            .get(key)
138            .cloned())
139    }
140
141    async fn put_cache(&self, key: &str, json: &str) -> Result<(), CacheError> {
142        self.store
143            .lock()
144            .expect("bug: cache mutex poisoned")
145            .insert(key.to_owned(), json.to_owned());
146        Ok(())
147    }
148}