1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
use {
goods::AssetNotFound,
reqwest::{Client, IntoUrl, StatusCode},
std::future::Future,
};
#[cfg(target_arch = "wasm32")]
use futures_core::future::LocalBoxFuture;
#[cfg(not(target_arch = "wasm32"))]
use futures_core::future::BoxFuture;
#[derive(Debug, Default)]
pub struct ReqwestSource {
client: Client,
}
impl ReqwestSource {
pub fn new() -> Self {
ReqwestSource::default()
}
pub fn with_client(client: Client) -> Self {
ReqwestSource { client }
}
}
#[cfg(not(target_arch = "wasm32"))]
impl goods::AutoLocalSource for ReqwestSource {}
impl ReqwestSource {
async fn read_impl(
&self,
request: impl Future<Output = Result<reqwest::Response, reqwest::Error>>,
) -> eyre::Result<Box<[u8]>> {
let response = request.await.map_err(|_err| {
#[cfg(feature = "trace")]
tracing::debug!("Error fetching asset: {}", _err);
AssetNotFound
})?;
let status = response.status();
match status {
StatusCode::OK => {
let bytes = response.bytes().await?;
Ok(bytes.as_ref().into())
}
StatusCode::NO_CONTENT | StatusCode::MOVED_PERMANENTLY | StatusCode::NOT_FOUND => {
Err(AssetNotFound.into())
}
_ => {
#[cfg(feature = "trace")]
tracing::warn!("Unexpected status: {}", status);
Err(AssetNotFound.into())
}
}
}
}
#[cfg(target_arch = "wasm32")]
impl<U> goods::LocalSource<U> for ReqwestSource
where
U: IntoUrl + Clone + 'static,
{
fn read_local(&self, url: &U) -> LocalBoxFuture<'_, eyre::Result<Box<[u8]>>> {
let request = self.client.get(url.clone()).send();
Box::pin(self.read_impl(request))
}
}
#[cfg(not(target_arch = "wasm32"))]
impl<U> goods::Source<U> for ReqwestSource
where
U: IntoUrl + Clone + 'static,
{
fn read(&self, url: &U) -> BoxFuture<'_, eyre::Result<Box<[u8]>>> {
let request = self.client.get(url.clone()).send();
Box::pin(self.read_impl(request))
}
}