use std::sync::{Arc, Mutex};
use std::time::Duration;
use bytes::Bytes;
use http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode};
use serde::Serialize;
use serde::de::DeserializeOwned;
use crate::error::{Error, Result};
#[derive(Clone)]
pub struct Client {
base: String,
headers: HeaderMap,
query: Vec<(String, String)>,
timeout: Duration,
retries: u32,
public_only: bool,
inner: reqwest::Client,
}
fn shared() -> reqwest::Client {
static SHARED: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
SHARED
.get_or_init(|| {
reqwest::Client::builder()
.connect_timeout(Duration::from_secs(5))
.user_agent(concat!("Glacier/", env!("CARGO_PKG_VERSION")))
.build()
.unwrap_or_default()
})
.clone()
}
impl Client {
pub fn new(base: &str) -> Self {
Self {
base: base.trim_end_matches('/').to_owned(),
headers: HeaderMap::new(),
query: Vec::new(),
timeout: Duration::from_secs(30),
retries: 0,
public_only: false,
inner: shared(),
}
}
#[must_use]
pub fn bearer(self, token: &str) -> Self {
self.header("authorization", &format!("Bearer {token}"))
}
#[must_use]
pub fn basic(self, username: &str, password: &str) -> Self {
use base64::Engine as _;
let encoded =
base64::engine::general_purpose::STANDARD.encode(format!("{username}:{password}"));
self.header("authorization", &format!("Basic {encoded}"))
}
#[must_use]
pub fn header(mut self, name: &str, value: &str) -> Self {
let name = HeaderName::try_from(name).expect("invalid header name");
let mut value = HeaderValue::try_from(value).expect("invalid header value");
value.set_sensitive(name == http::header::AUTHORIZATION);
self.headers.insert(name, value);
self
}
#[must_use]
pub fn query_auth(mut self, name: &str, value: &str) -> Self {
self.query.push((name.to_owned(), value.to_owned()));
self
}
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn public_only(mut self) -> Self {
static NO_REDIRECTS: std::sync::OnceLock<reqwest::Client> = std::sync::OnceLock::new();
self.public_only = true;
self.inner = NO_REDIRECTS
.get_or_init(|| {
reqwest::Client::builder()
.connect_timeout(Duration::from_secs(5))
.redirect(reqwest::redirect::Policy::none())
.user_agent(concat!("Glacier/", env!("CARGO_PKG_VERSION")))
.build()
.unwrap_or_default()
})
.clone();
self
}
#[must_use]
pub fn retries(mut self, retries: u32) -> Self {
self.retries = retries;
self
}
pub fn get(&self, path: &str) -> Request {
self.request(Method::GET, path)
}
pub fn post(&self, path: &str) -> Request {
self.request(Method::POST, path)
}
pub fn put(&self, path: &str) -> Request {
self.request(Method::PUT, path)
}
pub fn patch(&self, path: &str) -> Request {
self.request(Method::PATCH, path)
}
pub fn delete(&self, path: &str) -> Request {
self.request(Method::DELETE, path)
}
pub fn request(&self, method: Method, path: &str) -> Request {
let url = if path.starts_with("http://")
|| path.starts_with("https://")
|| self.base.is_empty()
{
path.to_owned()
} else {
format!("{}/{}", self.base, path.trim_start_matches('/'))
};
Request {
client: self.clone(),
method,
url,
headers: self.headers.clone(),
query: self.query.clone(),
body: None,
idempotent: false,
fail_on_error: true,
}
}
}
pub struct Request {
client: Client,
method: Method,
url: String,
headers: HeaderMap,
query: Vec<(String, String)>,
body: Option<Bytes>,
idempotent: bool,
fail_on_error: bool,
}
impl Request {
#[must_use]
pub fn query<T: Serialize + ?Sized>(mut self, params: &T) -> Self {
let encoded =
serde_urlencoded::to_string(params).expect("query parameters must be name/value pairs");
self.query.extend(
serde_urlencoded::from_str::<Vec<(String, String)>>(&encoded).unwrap_or_default(),
);
self
}
#[must_use]
pub fn header(mut self, name: &str, value: &str) -> Self {
let name = HeaderName::try_from(name).expect("invalid header name");
self.headers.insert(
name,
HeaderValue::try_from(value).expect("invalid header value"),
);
self
}
#[must_use]
pub fn json<T: Serialize + ?Sized>(mut self, body: &T) -> Self {
self.body = Some(serde_json::to_vec(body).expect("a JSON body").into());
self.headers.insert(
http::header::CONTENT_TYPE,
HeaderValue::from_static("application/json"),
);
self
}
#[must_use]
pub fn form<T: Serialize + ?Sized>(mut self, body: &T) -> Self {
self.body = Some(
serde_urlencoded::to_string(body)
.expect("form fields")
.into(),
);
self.headers.insert(
http::header::CONTENT_TYPE,
HeaderValue::from_static("application/x-www-form-urlencoded"),
);
self
}
#[must_use]
pub fn body(mut self, body: impl Into<Bytes>, content_type: &str) -> Self {
self.body = Some(body.into());
if let Ok(value) = HeaderValue::try_from(content_type) {
self.headers.insert(http::header::CONTENT_TYPE, value);
}
self
}
#[must_use]
pub fn idempotency_key(mut self, key: &str) -> Self {
self = self.header("idempotency-key", key);
self.idempotent = true;
self
}
#[must_use]
pub fn allow_errors(mut self) -> Self {
self.fail_on_error = false;
self
}
pub async fn send(self) -> Result<Response> {
let url = self.full_url();
let target = loggable(&url);
let span = tracing::info_span!(
target: "glacier::client",
"http.client",
otel.name = %format!("{} {}", self.method, target),
otel.kind = "client",
http.request.method = %self.method,
url.full = %target,
http.response.status_code = tracing::field::Empty,
);
let retryable = self.idempotent
|| matches!(
self.method,
Method::GET | Method::HEAD | Method::PUT | Method::DELETE | Method::OPTIONS
);
let attempts = if retryable {
self.client.retries + 1
} else {
1
};
let run = async {
let mut attempt = 0;
loop {
attempt += 1;
let started = std::time::Instant::now();
let outcome = self.send_once(&url).await;
let retry = match &outcome {
Ok(res) => matches!(res.status.as_u16(), 429 | 502 | 503 | 504),
Err(err) => matches!(err.kind, ErrorKind::Timeout | ErrorKind::Connect),
};
if let Ok(res) = &outcome {
tracing::Span::current()
.record("http.response.status_code", i64::from(res.status.as_u16()));
}
tracing::debug!(
target: "glacier::client",
elapsed_ms = started.elapsed().as_millis() as u64,
attempt,
"{} {target}",
self.method
);
if retry && attempt < attempts {
let wait = match &outcome {
Ok(res) => res.retry_after(),
Err(_) => None,
}
.unwrap_or_else(|| backoff(attempt));
tracing::warn!(target: "glacier::client", "{} {target}: retrying in {wait:?}", self.method);
tokio::time::sleep(wait).await;
continue;
}
return match outcome {
Ok(res) if self.fail_on_error && !res.status.is_success() => {
Err(ClientError::from_response(&self.method, &target, &res).into_error())
}
Ok(res) => Ok(res),
Err(err) => Err(err.into_error()),
};
}
};
tracing::Instrument::instrument(run, span).await
}
fn full_url(&self) -> String {
if self.query.is_empty() {
return self.url.clone();
}
let encoded = serde_urlencoded::to_string(&self.query).unwrap_or_default();
let joiner = if self.url.contains('?') { '&' } else { '?' };
format!("{}{joiner}{encoded}", self.url)
}
async fn send_once(&self, url: &str) -> std::result::Result<Response, ClientError> {
if let Some(fake) = fake() {
return fake.answer(self, url);
}
if self.client.public_only {
refuse_private(&self.method, url).await?;
}
let mut builder = self
.client
.inner
.request(self.method.clone(), url)
.headers(self.headers.clone())
.timeout(self.client.timeout);
if let Some(body) = &self.body {
builder = builder.body(body.clone());
}
let target = loggable(url);
let res = builder
.send()
.await
.map_err(|e| ClientError::transport(&self.method, &target, &e))?;
let status = res.status();
let headers = res.headers().clone();
let body = res
.bytes()
.await
.map_err(|e| ClientError::transport(&self.method, &target, &e))?;
Ok(Response {
status,
headers,
body,
})
}
}
fn is_private(ip: std::net::IpAddr) -> bool {
match ip {
std::net::IpAddr::V4(v4) => {
let [a, b, ..] = v4.octets();
v4.is_private()
|| v4.is_loopback()
|| v4.is_link_local()
|| v4.is_unspecified()
|| v4.is_broadcast()
|| v4.is_multicast()
|| (a == 100 && (64..128).contains(&b))
}
std::net::IpAddr::V6(v6) => {
let first = v6.segments()[0];
v6.is_loopback()
|| v6.is_unspecified()
|| v6.is_multicast()
|| (first & 0xfe00) == 0xfc00
|| (first & 0xffc0) == 0xfe80
|| v6
.to_ipv4_mapped()
.is_some_and(|v4| is_private(std::net::IpAddr::V4(v4)))
}
}
}
async fn refuse_private(method: &Method, url: &str) -> std::result::Result<(), ClientError> {
let blocked = |why: String| ClientError {
kind: ErrorKind::Blocked,
status: None,
retry_after: None,
body: String::new(),
message: format!("{method} {}: {why}", loggable(url)),
};
let parsed = reqwest::Url::parse(url).map_err(|e| blocked(format!("not a URL ({e})")))?;
let host = parsed
.host_str()
.ok_or_else(|| blocked("no host".to_owned()))?;
let port = parsed.port_or_known_default().unwrap_or(443);
let host = host.trim_start_matches('[').trim_end_matches(']');
let addresses: Vec<std::net::IpAddr> = match host.parse::<std::net::IpAddr>() {
Ok(ip) => vec![ip],
Err(_) => tokio::net::lookup_host((host, port))
.await
.map_err(|e| blocked(format!("can't resolve it ({e})")))?
.map(|addr| addr.ip())
.collect(),
};
match addresses.into_iter().find(|ip| is_private(*ip)) {
Some(ip) => Err(blocked(format!("{ip} is a private address"))),
None => Ok(()),
}
}
fn loggable(url: &str) -> String {
url.split('?').next().unwrap_or(url).to_owned()
}
fn backoff(attempt: u32) -> Duration {
Duration::from_millis(500 * 2u64.pow(attempt.saturating_sub(1).min(6)))
}
#[derive(Debug, Clone)]
pub struct Response {
pub status: StatusCode,
pub headers: HeaderMap,
pub body: Bytes,
}
impl Response {
pub fn json<T: DeserializeOwned>(&self) -> Result<T> {
serde_json::from_slice(&self.body)
.map_err(|e| Error::new(StatusCode::BAD_GATEWAY, format!("the service's JSON: {e}")))
}
pub fn text(&self) -> String {
String::from_utf8_lossy(&self.body).into_owned()
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.get(name).and_then(|v| v.to_str().ok())
}
pub fn retry_after(&self) -> Option<Duration> {
self.header("retry-after")?
.trim()
.parse()
.ok()
.map(Duration::from_secs)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ErrorKind {
Timeout,
Connect,
BadRequest,
Unauthorized,
Forbidden,
NotFound,
Rejected,
RateLimited,
ServerError,
NotStubbed,
Blocked,
}
#[derive(Debug, Clone)]
pub struct ClientError {
pub kind: ErrorKind,
pub status: Option<StatusCode>,
pub retry_after: Option<Duration>,
pub body: String,
message: String,
}
impl ClientError {
fn from_response(method: &Method, target: &str, res: &Response) -> Self {
let kind = match res.status.as_u16() {
401 => ErrorKind::Unauthorized,
403 => ErrorKind::Forbidden,
404 => ErrorKind::NotFound,
409 | 422 => ErrorKind::Rejected,
429 => ErrorKind::RateLimited,
500..=599 => ErrorKind::ServerError,
_ => ErrorKind::BadRequest,
};
Self {
kind,
status: Some(res.status),
retry_after: res.retry_after(),
body: res.text().chars().take(500).collect(),
message: format!("{method} {target} answered {}", res.status),
}
}
fn transport(method: &Method, target: &str, err: &reqwest::Error) -> Self {
let kind = if err.is_timeout() {
ErrorKind::Timeout
} else {
ErrorKind::Connect
};
Self {
kind,
status: None,
retry_after: None,
body: String::new(),
message: format!("{method} {target}: {err}"),
}
}
}
impl std::fmt::Display for ClientError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ClientError {}
impl ClientError {
fn into_error(self) -> Error {
let status = match self.kind {
ErrorKind::Timeout => StatusCode::GATEWAY_TIMEOUT,
_ => StatusCode::BAD_GATEWAY,
};
Error::with_source(status, self.message.clone(), self)
}
}
struct Stub {
method: Option<Method>,
pattern: String,
status: StatusCode,
headers: HeaderMap,
body: Bytes,
}
#[derive(Debug, Clone)]
pub struct Requested {
pub method: Method,
pub url: String,
pub headers: HeaderMap,
pub body: Bytes,
}
impl Requested {
pub fn json(&self) -> serde_json::Value {
serde_json::from_slice(&self.body).unwrap_or_default()
}
}
#[derive(Default)]
pub(crate) struct Fake {
stubs: Mutex<Vec<Stub>>,
requests: Mutex<Vec<Requested>>,
}
impl Fake {
fn answer(&self, req: &Request, url: &str) -> std::result::Result<Response, ClientError> {
self.requests
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Requested {
method: req.method.clone(),
url: url.to_owned(),
headers: req.headers.clone(),
body: req.body.clone().unwrap_or_default(),
});
let stubs = self.stubs.lock().unwrap_or_else(|e| e.into_inner());
let stub = stubs.iter().rev().find(|stub| {
stub.method.as_ref().is_none_or(|m| *m == req.method)
&& matches_pattern(&stub.pattern, url)
});
match stub {
Some(stub) => Ok(Response {
status: stub.status,
headers: stub.headers.clone(),
body: stub.body.clone(),
}),
None => Err(ClientError {
kind: ErrorKind::NotStubbed,
status: None,
retry_after: None,
body: String::new(),
message: format!(
"{} {url}: tests make no real requests; stub it with \
`stub_request(\"{}\", \"{}\", …)`",
req.method,
req.method,
loggable(url)
),
}),
}
}
}
fn matches_pattern(pattern: &str, url: &str) -> bool {
let url = if pattern.contains('?') {
url
} else {
url.split('?').next().unwrap_or(url)
};
let parts: Vec<&str> = pattern.split('*').collect();
let mut rest = url;
for (i, part) in parts.iter().enumerate() {
if i == 0 {
match rest.strip_prefix(part) {
Some(after) => rest = after,
None => return false,
}
} else if i == parts.len() - 1 {
return rest.ends_with(part);
} else {
match rest.find(part) {
Some(at) => rest = &rest[at + part.len()..],
None => return false,
}
}
}
rest.is_empty()
}
tokio::task_local! {
static FAKE: Arc<Fake>;
}
fn fake() -> Option<Arc<Fake>> {
FAKE.try_with(Arc::clone).ok()
}
#[doc(hidden)]
pub async fn with_fake<F: std::future::Future>(fut: F) -> F::Output {
FAKE.scope(Arc::default(), fut).await
}
pub(crate) fn stub(
method: Option<Method>,
pattern: &str,
status: StatusCode,
body: Bytes,
content_type: &str,
) {
let fake = fake().expect("stub_request works inside a #[glacier::test]");
let mut headers = HeaderMap::new();
if let Ok(value) = HeaderValue::try_from(content_type) {
headers.insert(http::header::CONTENT_TYPE, value);
}
fake.stubs
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(Stub {
method,
pattern: pattern.to_owned(),
status,
headers,
body,
});
}
pub(crate) fn requested() -> Vec<Requested> {
fake()
.map(|fake| {
fake.requests
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
})
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn patterns() {
assert!(matches_pattern(
"https://api.x.com/v1/forms/*/subscribe",
"https://api.x.com/v1/forms/12/subscribe?api_key=k"
));
assert!(matches_pattern(
"https://api.x.com/*",
"https://api.x.com/a/b"
));
assert!(!matches_pattern(
"https://api.x.com/v1/users",
"https://api.x.com/v1/users/1"
));
assert!(matches_pattern(
"https://api.x.com/v1/users?page=2",
"https://api.x.com/v1/users?page=2"
));
assert!(!matches_pattern(
"https://api.x.com/v1/users?page=2",
"https://api.x.com/v1/users?page=3"
));
}
#[test]
fn urls_join_and_logs_drop_queries() {
let client = Client::new("https://api.x.com/v1/").query_auth("api_key", "secret");
let req = client.get("/forms").query(&[("page", "2")]);
assert_eq!(
req.full_url(),
"https://api.x.com/v1/forms?api_key=secret&page=2"
);
assert_eq!(loggable(&req.full_url()), "https://api.x.com/v1/forms");
assert_eq!(client.get("https://other.com/x").url, "https://other.com/x");
}
#[test]
fn private_addresses() {
for ip in [
"127.0.0.1",
"10.1.2.3",
"192.168.0.9",
"172.16.5.4",
"169.254.169.254",
"100.64.0.1",
"::1",
"fd00::1",
"fe80::1",
"::ffff:127.0.0.1",
"0.0.0.0",
] {
assert!(is_private(ip.parse().unwrap()), "{ip}");
}
for ip in ["8.8.8.8", "1.1.1.1", "2606:4700::1111"] {
assert!(!is_private(ip.parse().unwrap()), "{ip}");
}
}
#[tokio::test]
async fn public_only_clients_refuse_private_hosts() {
let client = Client::new("http://127.0.0.1:9").public_only();
let err = client.get("x").send().await.unwrap_err();
assert_eq!(
err.downcast_ref::<ClientError>().unwrap().kind,
ErrorKind::Blocked
);
let err = Client::new("http://localhost:9")
.public_only()
.get("x")
.send()
.await
.unwrap_err();
assert_eq!(
err.downcast_ref::<ClientError>().unwrap().kind,
ErrorKind::Blocked,
"after DNS"
);
}
#[test]
fn backs_off_exponentially() {
assert_eq!(backoff(1), Duration::from_millis(500));
assert_eq!(backoff(3), Duration::from_secs(2));
}
}