use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
#[async_trait]
pub trait HttpClient: Send + Sync + Clone {
type Error: std::error::Error + Send + Sync + 'static;
async fn post(&self, url: &str, body: &str) -> Result<u16, Self::Error>;
async fn get(&self, url: &str) -> Result<(u16, Vec<u8>), Self::Error>;
}
#[async_trait]
pub trait ToolsetCache: Send + Sync {
type Error: std::error::Error + Send + Sync + 'static;
async fn get_cached(&self, cache_key: &str) -> Result<Option<String>, Self::Error>;
async fn put_cache(&self, cache_key: &str, json: &str) -> Result<(), Self::Error>;
}
#[derive(Debug)]
pub struct SimpleHttpError(String);
impl std::fmt::Display for SimpleHttpError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for SimpleHttpError {}
#[derive(Clone)]
pub struct SimpleHttpClient {
client: reqwest::Client,
}
impl Default for SimpleHttpClient {
fn default() -> Self {
Self::new()
}
}
impl SimpleHttpClient {
pub fn new() -> Self {
Self {
client: reqwest::Client::new(),
}
}
}
#[async_trait]
impl HttpClient for SimpleHttpClient {
type Error = SimpleHttpError;
async fn post(&self, url: &str, body: &str) -> Result<u16, SimpleHttpError> {
let resp = self
.client
.post(url)
.header("content-type", "application/json")
.body(body.to_owned())
.send()
.await
.map_err(|e| SimpleHttpError(e.to_string()))?;
Ok(resp.status().as_u16())
}
async fn get(&self, url: &str) -> Result<(u16, Vec<u8>), SimpleHttpError> {
let resp = self
.client
.get(url)
.header("accept", "application/json")
.send()
.await
.map_err(|e| SimpleHttpError(e.to_string()))?;
let status = resp.status().as_u16();
let bytes = resp
.bytes()
.await
.map_err(|e| SimpleHttpError(e.to_string()))?;
Ok((status, bytes.to_vec()))
}
}
#[derive(Debug)]
pub struct CacheError(String);
impl std::fmt::Display for CacheError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl std::error::Error for CacheError {}
pub struct InMemoryToolsetCache {
store: Arc<Mutex<HashMap<String, String>>>,
}
impl Default for InMemoryToolsetCache {
fn default() -> Self {
Self::new()
}
}
impl InMemoryToolsetCache {
pub fn new() -> Self {
Self {
store: Arc::new(Mutex::new(HashMap::new())),
}
}
}
#[async_trait]
impl ToolsetCache for InMemoryToolsetCache {
type Error = CacheError;
async fn get_cached(&self, key: &str) -> Result<Option<String>, CacheError> {
Ok(self
.store
.lock()
.expect("bug: cache mutex poisoned")
.get(key)
.cloned())
}
async fn put_cache(&self, key: &str, json: &str) -> Result<(), CacheError> {
self.store
.lock()
.expect("bug: cache mutex poisoned")
.insert(key.to_owned(), json.to_owned());
Ok(())
}
}