wellfriend-document-sdk 1.0.0

Official async Rust SDK for the Wellfriend document API: typed document tools, pipelines, streaming uploads and downloads, retries and webhook verification.
Documentation
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
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;

/// This crate's version, sent in the `User-Agent` header.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// The API base URL used when neither the builder nor `WELLFRIEND_BASE_URL` sets one.
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);

/// The Wellfriend API client.
///
/// Cheap to clone: clones share one connection pool. Create it once and reuse it.
///
/// ```no_run
/// # async fn run() -> wellfriend::Result<()> {
/// use std::time::Duration;
/// use wellfriend::Wellfriend;
///
/// let wf = Wellfriend::builder()
///     .api_key("wf_v2_live_...")
///     .timeout(Duration::from_secs(30))
///     .max_retries(4)
///     .build()?;
/// let page = wf.documents().list(None).await?;
/// println!("{} documents on the first page", page.items.len());
/// # Ok(())
/// # }
/// ```
#[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 {
    /// A client configured from the environment: `WELLFRIEND_API_KEY` and, when set,
    /// `WELLFRIEND_BASE_URL`.
    ///
    /// A missing key is reported by the first request as [`Error::Authentication`].
    ///
    /// # Panics
    ///
    /// Panics if `WELLFRIEND_BASE_URL` is not a valid URL, or if the TLS backend cannot be
    /// initialised. Use [`Wellfriend::builder`] to handle those cases as errors.
    pub fn new() -> Self {
        match Self::builder().build() {
            Ok(client) => client,
            Err(error) => panic!("Wellfriend client could not be created: {error}"),
        }
    }

    /// A builder for a client with explicit settings.
    pub fn builder() -> WellfriendBuilder {
        WellfriendBuilder::default()
    }

    /// The base URL requests are sent to.
    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)
    }

    /// Sends a request with retries and returns the successful response.
    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);
                    // A server that asks for a longer pause than the SDK is willing to sleep gets
                    // its error returned at once, with `retry_after` set.
                    let acceptable_wait =
                        retry_after.map_or(true, |wait| wait <= retry::MAX_RETRY_AFTER);
                    let body = read_error_body(response, timeout).await;
                    // An error the API marks `retryable: false` (for example an exhausted balance,
                    // sent as 429) will not go away by itself, so it is returned at once.
                    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);
        }
    }

    /// Sends a request and decodes its JSON body.
    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)
    }

    /// Sends a request and decodes one field of its JSON body (`{"document": {...}}`).
    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(),
    }
}

/// A new idempotency key (a random UUID v4).
pub(crate) fn new_idempotency_key() -> String {
    uuid::Uuid::new_v4().to_string()
}

/// Serializes a request body, adding `idempotencyKey` when the endpoint takes one in the body.
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>>;

/// A request body that can be produced again for a retry.
#[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)))),
        }
    }
}

/// One API request, before it is sent.
#[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
    }

    /// Marks a request that is safe to repeat although it is a write (for example an upload part).
    pub(crate) fn retry_always(mut self) -> Self {
        self.retry_always = true;
        self
    }
}

/// Settings for one call, applied with `with_options` on any resource handle.
///
/// ```no_run
/// # async fn run() -> wellfriend::Result<()> {
/// use std::time::Duration;
/// use wellfriend::{RequestOptions, Wellfriend};
///
/// let wf = Wellfriend::new();
/// let options = RequestOptions::new()
///     .idempotency_key("invoice-2026-0042-compress")
///     .timeout(Duration::from_secs(120))
///     .max_retries(5);
/// wf.tools().with_options(options).compress_pdf("invoice.pdf", None).await?.save("invoice.min.pdf").await?;
/// # Ok(())
/// # }
/// ```
#[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 {
    /// Options that change nothing.
    pub fn new() -> Self {
        Self::default()
    }

    /// The idempotency key for the call's main write, instead of a generated one. Sending the
    /// same call again with the same key returns the first result instead of repeating the work.
    /// Keys are 8 to 200 characters of letters, digits, `.`, `_`, `:` and `-`.
    pub fn idempotency_key(mut self, key: impl Into<String>) -> Self {
        self.idempotency_key = Some(key.into());
        self
    }

    /// The timeout for connecting and receiving response headers, and for each read of the body.
    /// It never limits a whole streamed upload or download.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// How many times a failed request is retried.
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }

    /// How long tool calls and pipelines wait for their result.
    pub fn wait_timeout(mut self, wait_timeout: Duration) -> Self {
        self.wait_timeout = Some(wait_timeout);
        self
    }

    /// An extra header sent with every request of the call.
    pub fn header(mut self, name: HeaderName, value: HeaderValue) -> Self {
        self.headers.insert(name, value);
        self
    }

    /// The idempotency key to use: the configured one, or a new random key.
    pub(crate) fn key(&self) -> String {
        self.idempotency_key
            .clone()
            .unwrap_or_else(new_idempotency_key)
    }

    /// The configured key with a suffix, for the secondary writes of a multi-step call.
    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)
    }

    /// The same options without the idempotency key, for the reads of a multi-step call.
    pub(crate) fn without_key(&self) -> RequestOptions {
        RequestOptions {
            idempotency_key: None,
            ..self.clone()
        }
    }
}

/// Builds a [`Wellfriend`] client.
#[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 {
    /// The API key. Defaults to the `WELLFRIEND_API_KEY` environment variable.
    pub fn api_key(mut self, api_key: impl Into<String>) -> Self {
        self.api_key = Some(api_key.into());
        self
    }

    /// The API base URL. Defaults to `WELLFRIEND_BASE_URL`, else [`DEFAULT_BASE_URL`].
    pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = Some(base_url.into());
        self
    }

    /// The per-request timeout (default 60 s). It covers connecting and receiving the response
    /// headers, and each read of the body, but never a whole streamed upload or download.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// How many times a failed request is retried (default 2).
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = Some(max_retries);
        self
    }

    /// How long tool calls and pipelines wait for their result (default 15 minutes).
    pub fn wait_timeout(mut self, wait_timeout: Duration) -> Self {
        self.wait_timeout = Some(wait_timeout);
        self
    }

    /// Files above this size use the resumable multipart upload; smaller files go in one
    /// streamed request. The default, and the most one request may carry, is 100 MiB.
    pub fn upload_threshold(mut self, bytes: u64) -> Self {
        self.upload_threshold = Some(bytes);
        self
    }

    /// Your own `reqwest::Client` (for a proxy, custom TLS roots or tracing middleware). Its own
    /// timeouts apply in addition to [`timeout`](Self::timeout).
    pub fn http_client(mut self, client: reqwest::Client) -> Self {
        self.http_client = Some(client);
        self
    }

    /// Headers sent with every request.
    pub fn default_headers(mut self, headers: HeaderMap) -> Self {
        self.default_headers = headers;
        self
    }

    /// Your application's name and version, appended to the `User-Agent` header.
    pub fn app_info(mut self, app: impl Into<String>) -> Self {
        self.app = Some(app.into());
        self
    }

    /// Creates the client.
    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"
            )));
        }
        // The key travels in every request: https:// always, plain http:// only for a loopback
        // host (a local test server).
        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"));
    }
}