use async_trait::async_trait;
use thiserror::Error;
use crate::{coords::WorldTileCoords, io::source_type::SourceType};
pub type HTTPClientFactory<HC> = dyn Fn() -> HC;
#[cfg_attr(not(feature = "thread-safe-futures"), async_trait(?Send))]
#[cfg_attr(feature = "thread-safe-futures", async_trait)]
pub trait HttpClient: Clone + Sync + Send + 'static {
async fn fetch(&self, url: &str) -> Result<Vec<u8>, SourceFetchError>;
}
#[derive(Clone)]
pub struct HttpSourceClient<HC>
where
HC: HttpClient,
{
inner_client: HC,
}
#[derive(Error, Debug)]
#[error("failed to fetch from source")]
pub struct SourceFetchError(#[source] pub Box<dyn std::error::Error>);
#[derive(Clone)]
pub struct SourceClient<HC>
where
HC: HttpClient,
{
http: HttpSourceClient<HC>,
}
impl<HC> SourceClient<HC>
where
HC: HttpClient,
{
pub fn new(http: HttpSourceClient<HC>) -> Self {
Self { http }
}
pub async fn fetch(
&self,
coords: &WorldTileCoords,
source_type: &SourceType,
) -> Result<Vec<u8>, SourceFetchError> {
self.http.fetch(coords, source_type).await
}
}
impl<HC> HttpSourceClient<HC>
where
HC: HttpClient,
{
pub fn new(http_client: HC) -> Self {
Self {
inner_client: http_client,
}
}
pub async fn fetch(
&self,
coords: &WorldTileCoords,
source_type: &SourceType,
) -> Result<Vec<u8>, SourceFetchError> {
self.inner_client
.fetch(source_type.format(coords).as_str())
.await
}
}