use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use bytes::Bytes;
use reqwest::header::{
HeaderMap, HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE,
USER_AGENT,
};
use reqwest::{Method, Url};
use serde::de::DeserializeOwned;
use serde::Serialize;
use serde_json::Value;
use crate::error::{ApiError, Error, Result};
use crate::retry;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const DEFAULT_BASE_URL: &str = "https://wellfriend.dev/api/v2";
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
const DEFAULT_MAX_RETRIES: u32 = 2;
const DEFAULT_WAIT_TIMEOUT: Duration = Duration::from_secs(15 * 60);
#[derive(Clone)]
pub struct Wellfriend {
pub(crate) inner: Arc<Inner>,
}
pub(crate) struct Inner {
http: reqwest::Client,
api_key: Option<String>,
base_url: Url,
timeout: Duration,
max_retries: u32,
pub(crate) wait_timeout: Duration,
pub(crate) upload_threshold: u64,
user_agent: HeaderValue,
default_headers: HeaderMap,
}
impl fmt::Debug for Wellfriend {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Wellfriend")
.field("base_url", &self.inner.base_url.as_str())
.field(
"api_key",
&self.inner.api_key.as_ref().map(|_| "<redacted>"),
)
.field("timeout", &self.inner.timeout)
.field("max_retries", &self.inner.max_retries)
.field("wait_timeout", &self.inner.wait_timeout)
.finish_non_exhaustive()
}
}
impl Default for Wellfriend {
fn default() -> Self {
Self::new()
}
}
impl Wellfriend {
pub fn new() -> Self {
match Self::builder().build() {
Ok(client) => client,
Err(error) => panic!("Wellfriend client could not be created: {error}"),
}
}
pub fn builder() -> WellfriendBuilder {
WellfriendBuilder::default()
}
pub fn base_url(&self) -> &str {
self.inner.base_url.as_str()
}
pub(crate) fn url(&self, segments: &[String], query: &[(String, String)]) -> Result<Url> {
let mut url = self.inner.base_url.clone();
{
let mut path = url
.path_segments_mut()
.map_err(|_| Error::InvalidInput("the base URL cannot carry a path".into()))?;
path.pop_if_empty();
for segment in segments {
path.push(segment);
}
}
if !query.is_empty() {
url.query_pairs_mut().extend_pairs(
query
.iter()
.map(|(name, value)| (name.as_str(), value.as_str())),
);
}
Ok(url)
}
pub(crate) async fn send(
&self,
options: &RequestOptions,
request: Request,
) -> Result<reqwest::Response> {
let api_key = self
.inner
.api_key
.as_deref()
.filter(|key| !key.trim().is_empty())
.ok_or_else(Error::missing_api_key)?;
let url = self.url(&request.path, &request.query)?;
let timeout = options.timeout.unwrap_or(self.inner.timeout);
let max_retries = options.max_retries.unwrap_or(self.inner.max_retries);
let retryable = request.retry_always
|| retry::retryable_request(&request.method, request.idempotency_key.is_some());
let mut attempt: u32 = 0;
loop {
let mut builder = self
.inner
.http
.request(request.method.clone(), url.clone())
.headers(self.inner.default_headers.clone())
.header(USER_AGENT, self.inner.user_agent.clone())
.header(AUTHORIZATION, format!("Bearer {}", api_key.trim()))
.header(ACCEPT, "application/json");
if let Some(key) = &request.idempotency_key {
builder = builder.header("Idempotency-Key", key.as_str());
}
builder = builder
.headers(request.headers.clone())
.headers(options.headers.clone());
builder = match request.body.build().await {
Ok(Some((body, content_type, length))) => {
let builder = builder.header(CONTENT_TYPE, content_type).body(body);
match length {
Some(length) => builder.header(CONTENT_LENGTH, length),
None => builder,
}
}
Ok(None) => builder,
Err(error) => return Err(Error::Io(error)),
};
let outcome = tokio::time::timeout(timeout, builder.send()).await;
let failure = match outcome {
Err(_) => Error::Timeout(timeout),
Ok(Err(error)) if error.is_timeout() => Error::Timeout(timeout),
Ok(Err(error)) => Error::connection(error),
Ok(Ok(response)) if response.status().is_success() => return Ok(response),
Ok(Ok(response)) => {
let status = response.status();
let headers = response.headers().clone();
let retry_after = retry::parse_retry_after(&headers);
let acceptable_wait =
retry_after.map_or(true, |wait| wait <= retry::MAX_RETRY_AFTER);
let body = read_error_body(response, timeout).await;
if retryable
&& attempt < max_retries
&& retry::retryable_status(status)
&& acceptable_wait
&& !retry::explicitly_final(&body)
{
tokio::time::sleep(retry::delay(attempt, retry_after)).await;
attempt += 1;
continue;
}
return Err(Error::from_api(ApiError::from_parts(
status.as_u16(),
headers,
&body,
)));
}
};
if retryable && attempt < max_retries {
tokio::time::sleep(retry::backoff(attempt)).await;
attempt += 1;
continue;
}
return Err(failure);
}
}
pub(crate) async fn json<T: DeserializeOwned>(
&self,
options: &RequestOptions,
request: Request,
) -> Result<T> {
let timeout = options.timeout.unwrap_or(self.inner.timeout);
let response = self.send(options, request).await?;
let body = match tokio::time::timeout(timeout, response.bytes()).await {
Err(_) => return Err(Error::Timeout(timeout)),
Ok(Err(error)) if error.is_timeout() => return Err(Error::Timeout(timeout)),
Ok(Err(error)) => return Err(Error::connection(error)),
Ok(Ok(body)) => body,
};
decode_json(&body)
}
pub(crate) async fn json_field<T: DeserializeOwned>(
&self,
options: &RequestOptions,
request: Request,
field: &str,
) -> Result<T> {
let value: Value = self.json(options, request).await?;
crate::util::take_field(value, field)
}
}
pub(crate) fn decode_json<T: DeserializeOwned>(body: &[u8]) -> Result<T> {
let body: &[u8] = if body.iter().all(u8::is_ascii_whitespace) {
b"{}"
} else {
body
};
serde_json::from_slice(body).map_err(|error| {
let snippet: String = String::from_utf8_lossy(body).chars().take(200).collect();
Error::Decode(format!("{error} in {snippet}"))
})
}
async fn read_error_body(response: reqwest::Response, timeout: Duration) -> Bytes {
match tokio::time::timeout(timeout, response.bytes()).await {
Ok(Ok(body)) => body,
_ => Bytes::new(),
}
}
pub(crate) fn new_idempotency_key() -> String {
uuid::Uuid::new_v4().to_string()
}
pub(crate) fn json_body<T: Serialize + ?Sized>(
params: &T,
idempotency_key: Option<&str>,
) -> Result<Bytes> {
let mut value =
serde_json::to_value(params).map_err(|error| Error::InvalidInput(error.to_string()))?;
if value.is_null() {
value = Value::Object(Default::default());
}
if let (Some(key), Value::Object(map)) = (idempotency_key, &mut value) {
map.entry("idempotencyKey")
.or_insert_with(|| Value::from(key));
}
serde_json::to_vec(&value)
.map(Bytes::from)
.map_err(|error| Error::InvalidInput(error.to_string()))
}
pub(crate) type BodyFuture = Pin<Box<dyn Future<Output = std::io::Result<reqwest::Body>> + Send>>;
#[derive(Clone, Default)]
pub(crate) enum RequestBody {
#[default]
Empty,
Bytes {
data: Bytes,
content_type: String,
},
Stream {
open: Arc<dyn Fn() -> BodyFuture + Send + Sync>,
length: u64,
content_type: String,
},
}
impl RequestBody {
async fn build(&self) -> std::io::Result<Option<(reqwest::Body, String, Option<u64>)>> {
match self {
RequestBody::Empty => Ok(None),
RequestBody::Bytes { data, content_type } => Ok(Some((
reqwest::Body::from(data.clone()),
content_type.clone(),
None,
))),
RequestBody::Stream {
open,
length,
content_type,
} => Ok(Some((open().await?, content_type.clone(), Some(*length)))),
}
}
}
#[derive(Clone)]
pub(crate) struct Request {
pub(crate) method: Method,
pub(crate) path: Vec<String>,
pub(crate) query: Vec<(String, String)>,
pub(crate) body: RequestBody,
pub(crate) headers: HeaderMap,
pub(crate) idempotency_key: Option<String>,
pub(crate) retry_always: bool,
}
impl Request {
pub(crate) fn new<I, S>(method: Method, path: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
Request {
method,
path: path.into_iter().map(Into::into).collect(),
query: Vec::new(),
body: RequestBody::Empty,
headers: HeaderMap::new(),
idempotency_key: None,
retry_always: false,
}
}
pub(crate) fn json(mut self, body: Bytes) -> Self {
self.body = RequestBody::Bytes {
data: body,
content_type: "application/json".into(),
};
self
}
pub(crate) fn body(mut self, body: RequestBody) -> Self {
self.body = body;
self
}
pub(crate) fn query<V: ToString>(mut self, name: &str, value: Option<V>) -> Self {
if let Some(value) = value {
self.query.push((name.to_owned(), value.to_string()));
}
self
}
pub(crate) fn header(mut self, name: &'static str, value: &str) -> Self {
if let Ok(value) = HeaderValue::from_str(value) {
self.headers.insert(HeaderName::from_static(name), value);
}
self
}
pub(crate) fn idempotency_key(mut self, key: impl Into<String>) -> Self {
self.idempotency_key = Some(key.into());
self
}
pub(crate) fn retry_always(mut self) -> Self {
self.retry_always = true;
self
}
}
#[derive(Clone, Debug, Default)]
pub struct RequestOptions {
pub(crate) idempotency_key: Option<String>,
pub(crate) timeout: Option<Duration>,
pub(crate) max_retries: Option<u32>,
pub(crate) wait_timeout: Option<Duration>,
pub(crate) headers: HeaderMap,
}
impl RequestOptions {
pub fn new() -> Self {
Self::default()
}
pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
self.idempotency_key = Some(key.into());
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn max_retries(mut self, max_retries: u32) -> Self {
self.max_retries = Some(max_retries);
self
}
pub fn wait_timeout(mut self, wait_timeout: Duration) -> Self {
self.wait_timeout = Some(wait_timeout);
self
}
pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
self.headers.insert(name, value);
self
}
pub(crate) fn key(&self) -> String {
self.idempotency_key
.clone()
.unwrap_or_else(new_idempotency_key)
}
pub(crate) fn derived_key(&self, suffix: &str) -> Option<String> {
self.idempotency_key
.as_ref()
.map(|key| format!("{key}.{suffix}"))
}
pub(crate) fn wait_limit(&self, client: &Wellfriend) -> Duration {
self.wait_timeout.unwrap_or(client.inner.wait_timeout)
}
pub(crate) fn without_key(&self) -> RequestOptions {
RequestOptions {
idempotency_key: None,
..self.clone()
}
}
}
#[derive(Default)]
pub struct WellfriendBuilder {
api_key: Option<String>,
base_url: Option<String>,
timeout: Option<Duration>,
max_retries: Option<u32>,
wait_timeout: Option<Duration>,
upload_threshold: Option<u64>,
http_client: Option<reqwest::Client>,
default_headers: HeaderMap,
app: Option<String>,
}
impl fmt::Debug for WellfriendBuilder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("WellfriendBuilder")
.field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
.field("base_url", &self.base_url)
.field("timeout", &self.timeout)
.field("max_retries", &self.max_retries)
.field("wait_timeout", &self.wait_timeout)
.finish_non_exhaustive()
}
}
impl WellfriendBuilder {
pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
self.api_key = Some(api_key.into());
self
}
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_url = Some(base_url.into());
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
pub fn max_retries(mut self, max_retries: u32) -> Self {
self.max_retries = Some(max_retries);
self
}
pub fn wait_timeout(mut self, wait_timeout: Duration) -> Self {
self.wait_timeout = Some(wait_timeout);
self
}
pub fn upload_threshold(mut self, bytes: u64) -> Self {
self.upload_threshold = Some(bytes);
self
}
pub fn http_client(mut self, client: reqwest::Client) -> Self {
self.http_client = Some(client);
self
}
pub fn default_headers(mut self, headers: HeaderMap) -> Self {
self.default_headers = headers;
self
}
pub fn app_info(mut self, app: impl Into<String>) -> Self {
self.app = Some(app.into());
self
}
pub fn build(self) -> Result<Wellfriend> {
let api_key = self
.api_key
.or_else(|| std::env::var("WELLFRIEND_API_KEY").ok())
.filter(|key| !key.trim().is_empty());
let base = self
.base_url
.or_else(|| {
std::env::var("WELLFRIEND_BASE_URL")
.ok()
.filter(|url| !url.trim().is_empty())
})
.unwrap_or_else(|| DEFAULT_BASE_URL.to_owned());
let base_url = Url::parse(base.trim())
.map_err(|error| Error::InvalidInput(format!("base URL {base:?}: {error}")))?;
if base_url.cannot_be_a_base() {
return Err(Error::InvalidInput(format!(
"base URL {base:?} cannot carry a path"
)));
}
let host = base_url
.host_str()
.unwrap_or_default()
.trim_start_matches('[')
.trim_end_matches(']');
let loopback = host == "localhost"
|| host.ends_with(".localhost")
|| host
.parse::<std::net::IpAddr>()
.is_ok_and(|ip| ip.is_loopback());
if base_url.scheme() != "https" && !(base_url.scheme() == "http" && loopback) {
return Err(Error::InvalidInput(format!(
"base URL {base:?} must use https:// (plain http:// only for a loopback host)"
)));
}
let timeout = self.timeout.unwrap_or(DEFAULT_TIMEOUT);
let http = match self.http_client {
Some(client) => client,
None => reqwest::Client::builder()
.connect_timeout(timeout)
.read_timeout(timeout)
.pool_idle_timeout(Duration::from_secs(90))
.build()
.map_err(Error::connection)?,
};
let mut agent = format!(
"wellfriend-sdk-rust/{VERSION} rustc/{} ({}; {})",
env!("WELLFRIEND_RUSTC_VERSION"),
std::env::consts::OS,
std::env::consts::ARCH
);
if let Some(app) = &self.app {
agent.push(' ');
agent.push_str(app);
}
let user_agent = HeaderValue::from_str(&agent)
.map_err(|_| Error::InvalidInput("app_info must be visible ASCII".into()))?;
Ok(Wellfriend {
inner: Arc::new(Inner {
http,
api_key,
base_url,
timeout,
max_retries: self.max_retries.unwrap_or(DEFAULT_MAX_RETRIES),
wait_timeout: self.wait_timeout.unwrap_or(DEFAULT_WAIT_TIMEOUT),
upload_threshold: self
.upload_threshold
.unwrap_or(crate::uploads::SINGLE_REQUEST_MAX_BYTES)
.clamp(1, crate::uploads::SINGLE_REQUEST_MAX_BYTES),
user_agent,
default_headers: self.default_headers,
}),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builds_urls_with_encoded_segments() {
let wf = Wellfriend::builder()
.api_key("k")
.base_url("https://example.test/api/v2/")
.build()
.unwrap();
let url = wf
.url(
&["documents".into(), "doc 1/x".into()],
&[("limit".into(), "5".into())],
)
.unwrap();
assert_eq!(
url.as_str(),
"https://example.test/api/v2/documents/doc%201%2Fx?limit=5"
);
}
#[test]
fn adds_the_idempotency_key_to_json_bodies() {
let body = json_body(&serde_json::json!({"name": "a"}), Some("key-12345")).unwrap();
let value: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(value["idempotencyKey"], "key-12345");
let body = json_body(
&serde_json::json!({"idempotencyKey": "mine-12345"}),
Some("key-12345"),
)
.unwrap();
let value: Value = serde_json::from_slice(&body).unwrap();
assert_eq!(value["idempotencyKey"], "mine-12345");
}
#[test]
fn refuses_plain_http_except_for_loopback_hosts() {
assert!(Wellfriend::builder()
.api_key("k")
.base_url("http://example.test/api/v2")
.build()
.is_err());
assert!(Wellfriend::builder()
.api_key("k")
.base_url("ftp://example.test/")
.build()
.is_err());
for local in [
"http://127.0.0.1:8091/api/v2",
"http://localhost:3000/api/v2",
"http://[::1]:8091/api/v2",
] {
assert!(
Wellfriend::builder()
.api_key("k")
.base_url(local)
.build()
.is_ok(),
"{local}"
);
}
assert_eq!(
Wellfriend::builder()
.api_key("k")
.build()
.unwrap()
.base_url(),
DEFAULT_BASE_URL
);
}
#[test]
fn debug_output_hides_the_key() {
let wf = Wellfriend::builder()
.api_key("wf_v2_secret")
.build()
.unwrap();
assert!(!format!("{wf:?}").contains("wf_v2_secret"));
}
}