1use std::sync::Arc;
5
6use async_trait::async_trait;
7use axum::Router;
8use axum::body::Body;
9use axum::http::{HeaderMap, HeaderValue, Request, header};
10use bytes::Bytes;
11use tower::util::ServiceExt;
12
13pub const MAX_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
15
16#[derive(Debug, Clone)]
18pub struct Fetched {
19 pub status: u16,
21 pub headers: HeaderMap,
23 pub body: Bytes,
25}
26
27impl Fetched {
28 pub fn media_type(&self) -> Option<String> {
30 self.headers
31 .get(header::CONTENT_TYPE)
32 .and_then(|value| value.to_str().ok())
33 .map(|value| value.split(';').next().unwrap_or_default().trim().to_ascii_lowercase())
34 }
35
36 pub fn header(&self, name: &str) -> Option<&str> {
38 self.headers.get(name).and_then(|value| value.to_str().ok())
39 }
40}
41
42#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
44#[error("GET {url} failed: {reason}")]
45pub struct FetchError {
46 pub url: String,
48 pub reason: String,
50}
51
52#[async_trait]
54pub trait Fetcher: Send + Sync {
55 async fn get(&self, url: &str, headers: &HeaderMap) -> Result<Fetched, FetchError>;
61}
62
63#[async_trait]
65pub trait RequestSigner: Send + Sync {
66 async fn sign(&self, url: &str, headers: &mut HeaderMap) -> Result<(), String>;
72}
73
74#[derive(Clone)]
77pub struct HttpFetcher {
78 client: reqwest::Client,
79 signer: Option<Arc<dyn RequestSigner>>,
80}
81
82impl std::fmt::Debug for HttpFetcher {
83 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
84 f.debug_struct("HttpFetcher").field("signed", &self.signer.is_some()).finish()
85 }
86}
87
88impl HttpFetcher {
89 pub fn new() -> Result<Self, FetchError> {
95 let client = reqwest::Client::builder()
96 .redirect(reqwest::redirect::Policy::none())
97 .timeout(std::time::Duration::from_secs(30))
98 .user_agent(concat!("adk-awp-verify/", env!("CARGO_PKG_VERSION")))
99 .build()
100 .map_err(|error| FetchError { url: String::new(), reason: error.to_string() })?;
101 Ok(Self { client, signer: None })
102 }
103
104 pub fn with_signer(mut self, signer: Arc<dyn RequestSigner>) -> Self {
106 self.signer = Some(signer);
107 self
108 }
109}
110
111#[async_trait]
112impl Fetcher for HttpFetcher {
113 async fn get(&self, url: &str, headers: &HeaderMap) -> Result<Fetched, FetchError> {
114 let failed = |reason: String| FetchError { url: url.to_owned(), reason };
115 let mut headers = headers.clone();
116 if let Some(signer) = &self.signer {
117 signer.sign(url, &mut headers).await.map_err(failed)?;
118 }
119 let response = self
120 .client
121 .get(url)
122 .headers(headers)
123 .send()
124 .await
125 .map_err(|error| failed(error.to_string()))?;
126 let status = response.status().as_u16();
127 let mut response_headers = HeaderMap::new();
128 for (name, value) in response.headers() {
129 response_headers.append(name.clone(), value.clone());
130 }
131 let body = response.bytes().await.map_err(|error| failed(error.to_string()))?;
132 if body.len() > MAX_RESPONSE_BYTES {
133 return Err(failed("the response is too large".to_owned()));
134 }
135 Ok(Fetched { status, headers: response_headers, body })
136 }
137}
138
139#[derive(Clone)]
142pub struct RouterFetcher {
143 router: Router,
144}
145
146impl std::fmt::Debug for RouterFetcher {
147 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
148 f.debug_struct("RouterFetcher").finish_non_exhaustive()
149 }
150}
151
152impl RouterFetcher {
153 pub fn new(router: Router) -> Self {
155 Self { router }
156 }
157}
158
159#[async_trait]
160impl Fetcher for RouterFetcher {
161 async fn get(&self, url: &str, headers: &HeaderMap) -> Result<Fetched, FetchError> {
162 let failed = |reason: &str| FetchError { url: url.to_owned(), reason: reason.to_owned() };
163 let rest = url.strip_prefix("https://").ok_or_else(|| failed("only https URLs"))?;
164 let (host, path) = rest
165 .split_once('/')
166 .map_or((rest, "/".to_owned()), |(host, path)| (host, format!("/{path}")));
167 let mut request = Request::get(path).body(Body::empty()).map_err(|_| failed("bad URL"))?;
168 *request.headers_mut() = headers.clone();
169 let host = HeaderValue::from_str(host).map_err(|_| failed("bad host"))?;
170 request.headers_mut().insert(header::HOST, host);
171 let response =
172 self.router.clone().oneshot(request).await.map_err(|_| failed("router failed"))?;
173 let status = response.status().as_u16();
174 let headers = response.headers().clone();
175 let body = axum::body::to_bytes(response.into_body(), MAX_RESPONSE_BYTES)
176 .await
177 .map_err(|_| failed("the response is too large"))?;
178 Ok(Fetched { status, headers, body })
179 }
180}