1use std::fmt;
2use std::future::Future;
3use std::pin::Pin;
4use std::sync::Arc;
5use std::time::Duration;
6
7use bytes::Bytes;
8use reqwest::header::{
9 HeaderMap, HeaderName, HeaderValue, ACCEPT, AUTHORIZATION, CONTENT_LENGTH, CONTENT_TYPE,
10 USER_AGENT,
11};
12use reqwest::{Method, Url};
13use serde::de::DeserializeOwned;
14use serde::Serialize;
15use serde_json::Value;
16
17use crate::error::{ApiError, Error, Result};
18use crate::retry;
19
20pub const VERSION: &str = env!("CARGO_PKG_VERSION");
22
23pub const DEFAULT_BASE_URL: &str = "https://wellfriend.dev/api/v2";
25
26const DEFAULT_TIMEOUT: Duration = Duration::from_secs(60);
27const DEFAULT_MAX_RETRIES: u32 = 2;
28const DEFAULT_WAIT_TIMEOUT: Duration = Duration::from_secs(15 * 60);
29
30#[derive(Clone)]
50pub struct Wellfriend {
51 pub(crate) inner: Arc<Inner>,
52}
53
54pub(crate) struct Inner {
55 http: reqwest::Client,
56 api_key: Option<String>,
57 base_url: Url,
58 timeout: Duration,
59 max_retries: u32,
60 pub(crate) wait_timeout: Duration,
61 pub(crate) upload_threshold: u64,
62 user_agent: HeaderValue,
63 default_headers: HeaderMap,
64}
65
66impl fmt::Debug for Wellfriend {
67 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68 f.debug_struct("Wellfriend")
69 .field("base_url", &self.inner.base_url.as_str())
70 .field(
71 "api_key",
72 &self.inner.api_key.as_ref().map(|_| "<redacted>"),
73 )
74 .field("timeout", &self.inner.timeout)
75 .field("max_retries", &self.inner.max_retries)
76 .field("wait_timeout", &self.inner.wait_timeout)
77 .finish_non_exhaustive()
78 }
79}
80
81impl Default for Wellfriend {
82 fn default() -> Self {
83 Self::new()
84 }
85}
86
87impl Wellfriend {
88 pub fn new() -> Self {
98 match Self::builder().build() {
99 Ok(client) => client,
100 Err(error) => panic!("Wellfriend client could not be created: {error}"),
101 }
102 }
103
104 pub fn builder() -> WellfriendBuilder {
106 WellfriendBuilder::default()
107 }
108
109 pub fn base_url(&self) -> &str {
111 self.inner.base_url.as_str()
112 }
113
114 pub(crate) fn url(&self, segments: &[String], query: &[(String, String)]) -> Result<Url> {
115 let mut url = self.inner.base_url.clone();
116 {
117 let mut path = url
118 .path_segments_mut()
119 .map_err(|_| Error::InvalidInput("the base URL cannot carry a path".into()))?;
120 path.pop_if_empty();
121 for segment in segments {
122 path.push(segment);
123 }
124 }
125 if !query.is_empty() {
126 url.query_pairs_mut().extend_pairs(
127 query
128 .iter()
129 .map(|(name, value)| (name.as_str(), value.as_str())),
130 );
131 }
132 Ok(url)
133 }
134
135 pub(crate) async fn send(
137 &self,
138 options: &RequestOptions,
139 request: Request,
140 ) -> Result<reqwest::Response> {
141 let api_key = self
142 .inner
143 .api_key
144 .as_deref()
145 .filter(|key| !key.trim().is_empty())
146 .ok_or_else(Error::missing_api_key)?;
147 let url = self.url(&request.path, &request.query)?;
148 let timeout = options.timeout.unwrap_or(self.inner.timeout);
149 let max_retries = options.max_retries.unwrap_or(self.inner.max_retries);
150 let retryable = request.retry_always
151 || retry::retryable_request(&request.method, request.idempotency_key.is_some());
152 let mut attempt: u32 = 0;
153 loop {
154 let mut builder = self
155 .inner
156 .http
157 .request(request.method.clone(), url.clone())
158 .headers(self.inner.default_headers.clone())
159 .header(USER_AGENT, self.inner.user_agent.clone())
160 .header(AUTHORIZATION, format!("Bearer {}", api_key.trim()))
161 .header(ACCEPT, "application/json");
162 if let Some(key) = &request.idempotency_key {
163 builder = builder.header("Idempotency-Key", key.as_str());
164 }
165 builder = builder
166 .headers(request.headers.clone())
167 .headers(options.headers.clone());
168 builder = match request.body.build().await {
169 Ok(Some((body, content_type, length))) => {
170 let builder = builder.header(CONTENT_TYPE, content_type).body(body);
171 match length {
172 Some(length) => builder.header(CONTENT_LENGTH, length),
173 None => builder,
174 }
175 }
176 Ok(None) => builder,
177 Err(error) => return Err(Error::Io(error)),
178 };
179 let outcome = tokio::time::timeout(timeout, builder.send()).await;
180 let failure = match outcome {
181 Err(_) => Error::Timeout(timeout),
182 Ok(Err(error)) if error.is_timeout() => Error::Timeout(timeout),
183 Ok(Err(error)) => Error::connection(error),
184 Ok(Ok(response)) if response.status().is_success() => return Ok(response),
185 Ok(Ok(response)) => {
186 let status = response.status();
187 let headers = response.headers().clone();
188 let retry_after = retry::parse_retry_after(&headers);
189 let acceptable_wait =
192 retry_after.map_or(true, |wait| wait <= retry::MAX_RETRY_AFTER);
193 let body = read_error_body(response, timeout).await;
194 if retryable
197 && attempt < max_retries
198 && retry::retryable_status(status)
199 && acceptable_wait
200 && !retry::explicitly_final(&body)
201 {
202 tokio::time::sleep(retry::delay(attempt, retry_after)).await;
203 attempt += 1;
204 continue;
205 }
206 return Err(Error::from_api(ApiError::from_parts(
207 status.as_u16(),
208 headers,
209 &body,
210 )));
211 }
212 };
213 if retryable && attempt < max_retries {
214 tokio::time::sleep(retry::backoff(attempt)).await;
215 attempt += 1;
216 continue;
217 }
218 return Err(failure);
219 }
220 }
221
222 pub(crate) async fn json<T: DeserializeOwned>(
224 &self,
225 options: &RequestOptions,
226 request: Request,
227 ) -> Result<T> {
228 let timeout = options.timeout.unwrap_or(self.inner.timeout);
229 let response = self.send(options, request).await?;
230 let body = match tokio::time::timeout(timeout, response.bytes()).await {
231 Err(_) => return Err(Error::Timeout(timeout)),
232 Ok(Err(error)) if error.is_timeout() => return Err(Error::Timeout(timeout)),
233 Ok(Err(error)) => return Err(Error::connection(error)),
234 Ok(Ok(body)) => body,
235 };
236 decode_json(&body)
237 }
238
239 pub(crate) async fn json_field<T: DeserializeOwned>(
241 &self,
242 options: &RequestOptions,
243 request: Request,
244 field: &str,
245 ) -> Result<T> {
246 let value: Value = self.json(options, request).await?;
247 crate::util::take_field(value, field)
248 }
249}
250
251pub(crate) fn decode_json<T: DeserializeOwned>(body: &[u8]) -> Result<T> {
252 let body: &[u8] = if body.iter().all(u8::is_ascii_whitespace) {
253 b"{}"
254 } else {
255 body
256 };
257 serde_json::from_slice(body).map_err(|error| {
258 let snippet: String = String::from_utf8_lossy(body).chars().take(200).collect();
259 Error::Decode(format!("{error} in {snippet}"))
260 })
261}
262
263async fn read_error_body(response: reqwest::Response, timeout: Duration) -> Bytes {
264 match tokio::time::timeout(timeout, response.bytes()).await {
265 Ok(Ok(body)) => body,
266 _ => Bytes::new(),
267 }
268}
269
270pub(crate) fn new_idempotency_key() -> String {
272 uuid::Uuid::new_v4().to_string()
273}
274
275pub(crate) fn json_body<T: Serialize + ?Sized>(
277 params: &T,
278 idempotency_key: Option<&str>,
279) -> Result<Bytes> {
280 let mut value =
281 serde_json::to_value(params).map_err(|error| Error::InvalidInput(error.to_string()))?;
282 if value.is_null() {
283 value = Value::Object(Default::default());
284 }
285 if let (Some(key), Value::Object(map)) = (idempotency_key, &mut value) {
286 map.entry("idempotencyKey")
287 .or_insert_with(|| Value::from(key));
288 }
289 serde_json::to_vec(&value)
290 .map(Bytes::from)
291 .map_err(|error| Error::InvalidInput(error.to_string()))
292}
293
294pub(crate) type BodyFuture = Pin<Box<dyn Future<Output = std::io::Result<reqwest::Body>> + Send>>;
295
296#[derive(Clone, Default)]
298pub(crate) enum RequestBody {
299 #[default]
300 Empty,
301 Bytes {
302 data: Bytes,
303 content_type: String,
304 },
305 Stream {
306 open: Arc<dyn Fn() -> BodyFuture + Send + Sync>,
307 length: u64,
308 content_type: String,
309 },
310}
311
312impl RequestBody {
313 async fn build(&self) -> std::io::Result<Option<(reqwest::Body, String, Option<u64>)>> {
314 match self {
315 RequestBody::Empty => Ok(None),
316 RequestBody::Bytes { data, content_type } => Ok(Some((
317 reqwest::Body::from(data.clone()),
318 content_type.clone(),
319 None,
320 ))),
321 RequestBody::Stream {
322 open,
323 length,
324 content_type,
325 } => Ok(Some((open().await?, content_type.clone(), Some(*length)))),
326 }
327 }
328}
329
330#[derive(Clone)]
332pub(crate) struct Request {
333 pub(crate) method: Method,
334 pub(crate) path: Vec<String>,
335 pub(crate) query: Vec<(String, String)>,
336 pub(crate) body: RequestBody,
337 pub(crate) headers: HeaderMap,
338 pub(crate) idempotency_key: Option<String>,
339 pub(crate) retry_always: bool,
340}
341
342impl Request {
343 pub(crate) fn new<I, S>(method: Method, path: I) -> Self
344 where
345 I: IntoIterator<Item = S>,
346 S: Into<String>,
347 {
348 Request {
349 method,
350 path: path.into_iter().map(Into::into).collect(),
351 query: Vec::new(),
352 body: RequestBody::Empty,
353 headers: HeaderMap::new(),
354 idempotency_key: None,
355 retry_always: false,
356 }
357 }
358
359 pub(crate) fn json(mut self, body: Bytes) -> Self {
360 self.body = RequestBody::Bytes {
361 data: body,
362 content_type: "application/json".into(),
363 };
364 self
365 }
366
367 pub(crate) fn body(mut self, body: RequestBody) -> Self {
368 self.body = body;
369 self
370 }
371
372 pub(crate) fn query<V: ToString>(mut self, name: &str, value: Option<V>) -> Self {
373 if let Some(value) = value {
374 self.query.push((name.to_owned(), value.to_string()));
375 }
376 self
377 }
378
379 pub(crate) fn header(mut self, name: &'static str, value: &str) -> Self {
380 if let Ok(value) = HeaderValue::from_str(value) {
381 self.headers.insert(HeaderName::from_static(name), value);
382 }
383 self
384 }
385
386 pub(crate) fn idempotency_key(mut self, key: impl Into<String>) -> Self {
387 self.idempotency_key = Some(key.into());
388 self
389 }
390
391 pub(crate) fn retry_always(mut self) -> Self {
393 self.retry_always = true;
394 self
395 }
396}
397
398#[derive(Clone, Debug, Default)]
415pub struct RequestOptions {
416 pub(crate) idempotency_key: Option<String>,
417 pub(crate) timeout: Option<Duration>,
418 pub(crate) max_retries: Option<u32>,
419 pub(crate) wait_timeout: Option<Duration>,
420 pub(crate) headers: HeaderMap,
421}
422
423impl RequestOptions {
424 pub fn new() -> Self {
426 Self::default()
427 }
428
429 pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
433 self.idempotency_key = Some(key.into());
434 self
435 }
436
437 pub fn timeout(mut self, timeout: Duration) -> Self {
440 self.timeout = Some(timeout);
441 self
442 }
443
444 pub fn max_retries(mut self, max_retries: u32) -> Self {
446 self.max_retries = Some(max_retries);
447 self
448 }
449
450 pub fn wait_timeout(mut self, wait_timeout: Duration) -> Self {
452 self.wait_timeout = Some(wait_timeout);
453 self
454 }
455
456 pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
458 self.headers.insert(name, value);
459 self
460 }
461
462 pub(crate) fn key(&self) -> String {
464 self.idempotency_key
465 .clone()
466 .unwrap_or_else(new_idempotency_key)
467 }
468
469 pub(crate) fn derived_key(&self, suffix: &str) -> Option<String> {
471 self.idempotency_key
472 .as_ref()
473 .map(|key| format!("{key}.{suffix}"))
474 }
475
476 pub(crate) fn wait_limit(&self, client: &Wellfriend) -> Duration {
477 self.wait_timeout.unwrap_or(client.inner.wait_timeout)
478 }
479
480 pub(crate) fn without_key(&self) -> RequestOptions {
482 RequestOptions {
483 idempotency_key: None,
484 ..self.clone()
485 }
486 }
487}
488
489#[derive(Default)]
491pub struct WellfriendBuilder {
492 api_key: Option<String>,
493 base_url: Option<String>,
494 timeout: Option<Duration>,
495 max_retries: Option<u32>,
496 wait_timeout: Option<Duration>,
497 upload_threshold: Option<u64>,
498 http_client: Option<reqwest::Client>,
499 default_headers: HeaderMap,
500 app: Option<String>,
501}
502
503impl fmt::Debug for WellfriendBuilder {
504 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
505 f.debug_struct("WellfriendBuilder")
506 .field("api_key", &self.api_key.as_ref().map(|_| "<redacted>"))
507 .field("base_url", &self.base_url)
508 .field("timeout", &self.timeout)
509 .field("max_retries", &self.max_retries)
510 .field("wait_timeout", &self.wait_timeout)
511 .finish_non_exhaustive()
512 }
513}
514
515impl WellfriendBuilder {
516 pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
518 self.api_key = Some(api_key.into());
519 self
520 }
521
522 pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
524 self.base_url = Some(base_url.into());
525 self
526 }
527
528 pub fn timeout(mut self, timeout: Duration) -> Self {
531 self.timeout = Some(timeout);
532 self
533 }
534
535 pub fn max_retries(mut self, max_retries: u32) -> Self {
537 self.max_retries = Some(max_retries);
538 self
539 }
540
541 pub fn wait_timeout(mut self, wait_timeout: Duration) -> Self {
543 self.wait_timeout = Some(wait_timeout);
544 self
545 }
546
547 pub fn upload_threshold(mut self, bytes: u64) -> Self {
550 self.upload_threshold = Some(bytes);
551 self
552 }
553
554 pub fn http_client(mut self, client: reqwest::Client) -> Self {
557 self.http_client = Some(client);
558 self
559 }
560
561 pub fn default_headers(mut self, headers: HeaderMap) -> Self {
563 self.default_headers = headers;
564 self
565 }
566
567 pub fn app_info(mut self, app: impl Into<String>) -> Self {
569 self.app = Some(app.into());
570 self
571 }
572
573 pub fn build(self) -> Result<Wellfriend> {
575 let api_key = self
576 .api_key
577 .or_else(|| std::env::var("WELLFRIEND_API_KEY").ok())
578 .filter(|key| !key.trim().is_empty());
579 let base = self
580 .base_url
581 .or_else(|| {
582 std::env::var("WELLFRIEND_BASE_URL")
583 .ok()
584 .filter(|url| !url.trim().is_empty())
585 })
586 .unwrap_or_else(|| DEFAULT_BASE_URL.to_owned());
587 let base_url = Url::parse(base.trim())
588 .map_err(|error| Error::InvalidInput(format!("base URL {base:?}: {error}")))?;
589 if base_url.cannot_be_a_base() {
590 return Err(Error::InvalidInput(format!(
591 "base URL {base:?} cannot carry a path"
592 )));
593 }
594 let host = base_url
597 .host_str()
598 .unwrap_or_default()
599 .trim_start_matches('[')
600 .trim_end_matches(']');
601 let loopback = host == "localhost"
602 || host.ends_with(".localhost")
603 || host
604 .parse::<std::net::IpAddr>()
605 .is_ok_and(|ip| ip.is_loopback());
606 if base_url.scheme() != "https" && !(base_url.scheme() == "http" && loopback) {
607 return Err(Error::InvalidInput(format!(
608 "base URL {base:?} must use https:// (plain http:// only for a loopback host)"
609 )));
610 }
611 let timeout = self.timeout.unwrap_or(DEFAULT_TIMEOUT);
612 let http = match self.http_client {
613 Some(client) => client,
614 None => reqwest::Client::builder()
615 .connect_timeout(timeout)
616 .read_timeout(timeout)
617 .pool_idle_timeout(Duration::from_secs(90))
618 .build()
619 .map_err(Error::connection)?,
620 };
621 let mut agent = format!(
622 "wellfriend-sdk-rust/{VERSION} rustc/{} ({}; {})",
623 env!("WELLFRIEND_RUSTC_VERSION"),
624 std::env::consts::OS,
625 std::env::consts::ARCH
626 );
627 if let Some(app) = &self.app {
628 agent.push(' ');
629 agent.push_str(app);
630 }
631 let user_agent = HeaderValue::from_str(&agent)
632 .map_err(|_| Error::InvalidInput("app_info must be visible ASCII".into()))?;
633 Ok(Wellfriend {
634 inner: Arc::new(Inner {
635 http,
636 api_key,
637 base_url,
638 timeout,
639 max_retries: self.max_retries.unwrap_or(DEFAULT_MAX_RETRIES),
640 wait_timeout: self.wait_timeout.unwrap_or(DEFAULT_WAIT_TIMEOUT),
641 upload_threshold: self
642 .upload_threshold
643 .unwrap_or(crate::uploads::SINGLE_REQUEST_MAX_BYTES)
644 .clamp(1, crate::uploads::SINGLE_REQUEST_MAX_BYTES),
645 user_agent,
646 default_headers: self.default_headers,
647 }),
648 })
649 }
650}
651
652#[cfg(test)]
653mod tests {
654 use super::*;
655
656 #[test]
657 fn builds_urls_with_encoded_segments() {
658 let wf = Wellfriend::builder()
659 .api_key("k")
660 .base_url("https://example.test/api/v2/")
661 .build()
662 .unwrap();
663 let url = wf
664 .url(
665 &["documents".into(), "doc 1/x".into()],
666 &[("limit".into(), "5".into())],
667 )
668 .unwrap();
669 assert_eq!(
670 url.as_str(),
671 "https://example.test/api/v2/documents/doc%201%2Fx?limit=5"
672 );
673 }
674
675 #[test]
676 fn adds_the_idempotency_key_to_json_bodies() {
677 let body = json_body(&serde_json::json!({"name": "a"}), Some("key-12345")).unwrap();
678 let value: Value = serde_json::from_slice(&body).unwrap();
679 assert_eq!(value["idempotencyKey"], "key-12345");
680 let body = json_body(
681 &serde_json::json!({"idempotencyKey": "mine-12345"}),
682 Some("key-12345"),
683 )
684 .unwrap();
685 let value: Value = serde_json::from_slice(&body).unwrap();
686 assert_eq!(value["idempotencyKey"], "mine-12345");
687 }
688
689 #[test]
690 fn refuses_plain_http_except_for_loopback_hosts() {
691 assert!(Wellfriend::builder()
692 .api_key("k")
693 .base_url("http://example.test/api/v2")
694 .build()
695 .is_err());
696 assert!(Wellfriend::builder()
697 .api_key("k")
698 .base_url("ftp://example.test/")
699 .build()
700 .is_err());
701 for local in [
702 "http://127.0.0.1:8091/api/v2",
703 "http://localhost:3000/api/v2",
704 "http://[::1]:8091/api/v2",
705 ] {
706 assert!(
707 Wellfriend::builder()
708 .api_key("k")
709 .base_url(local)
710 .build()
711 .is_ok(),
712 "{local}"
713 );
714 }
715 assert_eq!(
716 Wellfriend::builder()
717 .api_key("k")
718 .build()
719 .unwrap()
720 .base_url(),
721 DEFAULT_BASE_URL
722 );
723 }
724
725 #[test]
726 fn debug_output_hides_the_key() {
727 let wf = Wellfriend::builder()
728 .api_key("wf_v2_secret")
729 .build()
730 .unwrap();
731 assert!(!format!("{wf:?}").contains("wf_v2_secret"));
732 }
733}