basecamp-sdk 0.38.0

Official client for Basecamp - https://basecamp.com
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
//! SPEC ยง3: the client, and the account-scoped client every service hangs off.

use std::fmt;
use std::sync::Arc;
use std::time::{Duration, Instant};

use bytes::Bytes;
use serde::de::DeserializeOwned;
use url::Url;

use crate::auth::{AuthStrategy, BearerAuth, StaticTokenProvider, TokenProvider};
use crate::config::Config;
use crate::deadline::Deadline;
use crate::error::{Error, ErrorCode, parse_retry_after_header};
use crate::hooks::{Hooks, NoopHooks, OperationInfo, OperationResult, RequestInfo, RequestResult};
use crate::http::header::{ACCEPT, CONTENT_TYPE, USER_AGENT};
use crate::http::{
    Body, HeaderMap, HeaderValue, HttpClient, Request, Response as HttpResponse, StatusCode,
};
use crate::operation::Operation;
use crate::pagination::Page;
use crate::retry::{backoff_with_jitter, effective_attempts};
use crate::route::{Representation, Route};
use crate::security::{is_same_origin, require_secure_endpoint};
use crate::services::campfire_index::CampfireIndex;
use crate::version::default_user_agent;

/// A Basecamp client: one identity, one API origin. Derive an [`AccountClient`] with
/// [`Client::for_account`] to reach the services.
///
/// Clients are cheap to clone and share their connection pool, credentials and hooks.
#[derive(Clone)]
pub struct Client {
    shared: Arc<Shared>,
}

/// The client scoped to one account: where every service lives.
#[derive(Clone)]
pub struct AccountClient {
    shared: Arc<Shared>,
    account_id: String,
}

pub(crate) struct Shared {
    pub(crate) config: Config,
    pub(crate) base_url: Url,
    pub(crate) http: Arc<dyn HttpClient>,
    pub(crate) auth: Arc<dyn AuthStrategy>,
    pub(crate) user_agent: String,
    pub(crate) hooks: Arc<dyn Hooks>,
    /// The Campfire discovery caches the recording-summary composite reads chat lines
    /// through (SPEC ยง18). It hangs here, beside the credential it is bound to, so every
    /// [`AccountClient`] derived from one [`Client`] shares one index and a burst of chat
    /// lines costs one listing rather than one per line โ€” and so entries are never shared
    /// across authorization contexts.
    pub(crate) campfires: CampfireIndex,
}

/// What came back from Basecamp, before it is decoded. Its `Debug` form redacts the
/// credential-bearing headers (SPEC ยง9).
#[derive(Clone)]
#[non_exhaustive]
pub struct Response {
    /// The status.
    pub status: StatusCode,
    /// The headers.
    pub headers: HeaderMap,
    /// The body, read whole.
    pub body: Bytes,
    /// The URL the answer came from.
    pub url: Url,
}

impl fmt::Debug for Response {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Response")
            .field("status", &self.status)
            .field("headers", &crate::security::redact_headers(&self.headers))
            .field("body", &self.body)
            .field("url", &self.url)
            .finish()
    }
}

impl Response {
    /// The body decoded as JSON. A body that does not decode as `T` is a statusless,
    /// non-retryable `api_error` (SPEC ยง6) that keeps the request id.
    pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
        serde_json::from_slice(&self.body).map_err(|error| {
            let mut mapped = Error::malformed_response(error.to_string());
            if let Some(request_id) = self.header("x-request-id") {
                mapped = mapped.with_request_id(request_id);
            }
            mapped
        })
    }

    /// One header, when present and readable as text.
    pub fn header(&self, name: &str) -> Option<&str> {
        self.headers.get(name).and_then(|value| value.to_str().ok())
    }
}

/// Builds a [`Client`].
pub struct ClientBuilder {
    config: Config,
    auth: Option<Arc<dyn AuthStrategy>>,
    http: Option<Arc<dyn HttpClient>>,
    user_agent: String,
    hooks: Arc<dyn Hooks>,
    auth_given: u8,
    /// Test-only: the discovery index reads real time unless a test hands it a clock, and
    /// the refresh floor cannot be crossed by waiting in a test.
    #[cfg(all(test, feature = "reqwest"))]
    campfire_clock: Option<crate::services::campfire_index::Clock>,
}

impl ClientBuilder {
    /// A builder over a configuration.
    pub fn new(config: Config) -> ClientBuilder {
        ClientBuilder {
            config,
            auth: None,
            http: None,
            user_agent: default_user_agent(),
            hooks: Arc::new(NoopHooks),
            auth_given: 0,
            #[cfg(all(test, feature = "reqwest"))]
            campfire_clock: None,
        }
    }

    /// The clock the Campfire discovery index ages its entries by. Test-only: nothing
    /// outside this crate's own tests can move it, and the shipped client always reads
    /// [`std::time::Instant::now`].
    #[cfg(all(test, feature = "reqwest"))]
    pub(crate) fn campfire_clock(
        mut self,
        clock: crate::services::campfire_index::Clock,
    ) -> ClientBuilder {
        self.campfire_clock = Some(clock);
        self
    }

    /// A fixed bearer token โ€” a personal access token, say.
    pub fn access_token(self, token: impl Into<String>) -> ClientBuilder {
        self.token_provider(StaticTokenProvider::new(token.into()))
    }

    /// Bearer authentication over a [`TokenProvider`], refreshed on 401 where the provider
    /// supports it.
    pub fn token_provider(self, provider: impl TokenProvider + 'static) -> ClientBuilder {
        self.auth_strategy(BearerAuth::new(provider))
    }

    /// Any [`AuthStrategy`]. Exactly one of this, [`ClientBuilder::access_token`] or
    /// [`ClientBuilder::token_provider`] must be given.
    pub fn auth_strategy(mut self, strategy: impl AuthStrategy + 'static) -> ClientBuilder {
        self.auth_given += 1;
        self.auth = Some(Arc::new(strategy));
        self
    }

    /// Replaces the HTTP client every request goes out on. It must not follow redirects;
    /// see [`HttpClient`]. The configured timeout then has no effect โ€” a timeout belongs to
    /// the client that can enforce it.
    pub fn http_client(mut self, http: impl HttpClient + 'static) -> ClientBuilder {
        self.http = Some(Arc::new(http));
        self
    }

    /// Another `User-Agent`.
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> ClientBuilder {
        self.user_agent = user_agent.into();
        self
    }

    /// Reports every operation and every request the client makes. Several sets of hooks
    /// go on as one with [`crate::hooks::ChainHooks`].
    pub fn hooks(mut self, hooks: impl Hooks + 'static) -> ClientBuilder {
        self.hooks = Arc::new(hooks);
        self
    }

    /// The whole-operation deadline; see [`Config::operation_deadline`].
    pub fn operation_deadline(mut self, deadline: Duration) -> ClientBuilder {
        self.config.operation_deadline = Some(deadline);
        self
    }

    /// Validates the configuration (SPEC ยง2) and builds the client.
    pub fn build(self) -> Result<Client, Error> {
        if self.auth_given > 1 {
            return Err(Error::usage(
                "Provide either auth or access_token, not both",
            ));
        }
        let auth = self
            .auth
            .ok_or_else(|| Error::usage("Either auth or access_token is required"))?;
        let base_url = parse_base_url(&self.config.base_url)?;
        self.config.validate()?;
        let http = match self.http {
            Some(http) => http,
            None => shipped_http_client(self.config.timeout)?,
        };
        #[cfg(all(test, feature = "reqwest"))]
        let campfires = match self.campfire_clock {
            Some(clock) => CampfireIndex::with_clock(clock),
            None => CampfireIndex::new(),
        };
        #[cfg(not(all(test, feature = "reqwest")))]
        let campfires = CampfireIndex::new();
        Ok(Client {
            shared: Arc::new(Shared {
                config: self.config,
                base_url,
                http,
                auth,
                user_agent: self.user_agent,
                hooks: self.hooks,
                campfires,
            }),
        })
    }
}

impl Client {
    /// A builder over a configuration.
    pub fn builder(config: Config) -> ClientBuilder {
        ClientBuilder::new(config)
    }

    /// The configuration the client was built with.
    pub fn config(&self) -> &Config {
        &self.shared.config
    }

    /// The API origin.
    pub fn base_url(&self) -> &Url {
        &self.shared.base_url
    }

    /// The client scoped to one account. Every account-scoped path is prefixed with the id.
    pub fn for_account(&self, account_id: impl Into<String>) -> AccountClient {
        AccountClient {
            shared: self.shared.clone(),
            account_id: account_id.into(),
        }
    }
}

impl fmt::Debug for Client {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Client")
            .field("base_url", &self.shared.base_url)
            .finish_non_exhaustive()
    }
}

impl fmt::Debug for AccountClient {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("AccountClient")
            .field("base_url", &self.shared.base_url)
            .field("account_id", &self.account_id)
            .finish_non_exhaustive()
    }
}

impl AccountClient {
    /// The account this client is scoped to.
    pub fn account_id(&self) -> &str {
        &self.account_id
    }

    /// The configuration the client was built with.
    pub fn config(&self) -> &Config {
        &self.shared.config
    }

    /// The API origin.
    pub fn base_url(&self) -> &Url {
        &self.shared.base_url
    }

    /// How many pages an auto-paginating read follows.
    pub fn max_pages(&self) -> usize {
        self.shared.config.max_pages
    }

    pub(crate) fn shared(&self) -> &Arc<Shared> {
        &self.shared
    }

    /// The Campfire discovery index, shared with every other account client derived from
    /// the same [`Client`].
    pub(crate) fn campfire_index(&self) -> &CampfireIndex {
        &self.shared.campfires
    }

    /// The account-independent client this was derived from.
    pub fn client(&self) -> Client {
        Client {
            shared: self.shared.clone(),
        }
    }

    /// Starts a request for one of the modelled routes. Generated service methods call
    /// this; reach for it directly only to add a query parameter they do not expose.
    pub fn operation(&self, route: &'static Route, params: &[&dyn fmt::Display]) -> Operation {
        Operation::for_route(route, params)
    }

    /// Sends an operation and decodes its JSON body.
    pub async fn send<T: DeserializeOwned>(&self, operation: Operation) -> Result<T, Error> {
        self.run(operation, |response| response.json()).await
    }

    /// The whole-operation deadline, started now (SPEC ยง2's `operation_deadline`).
    pub(crate) fn deadline(&self) -> Deadline {
        Deadline::starting_now(self.shared.config.operation_deadline)
    }

    /// Sends an operation whose answer carries no body worth reading.
    pub async fn send_unit(&self, operation: Operation) -> Result<(), Error> {
        self.run(operation, |_| Ok(())).await
    }

    /// Sends a paginated read and keeps the cursor Basecamp answered with.
    pub async fn send_page<T: DeserializeOwned>(
        &self,
        operation: Operation,
    ) -> Result<Page<T>, Error> {
        let route = operation.route;
        let info = operation.info.clone();
        let pinned = operation.pins_a_page();
        self.run(operation, |response| {
            Ok(Page::new(response.json()?, &response, route, info, pinned))
        })
        .await
    }

    /// Sends an operation and reads its answer with `decode`, so a body that does not decode
    /// ends the operation as a failure in the hooks' eyes too (SPEC ยง12).
    pub async fn run<T>(
        &self,
        operation: Operation,
        decode: impl FnOnce(Response) -> Result<T, Error>,
    ) -> Result<T, Error> {
        let deadline = self.deadline();
        self.observe(&operation, async {
            self.dispatch(&operation, &deadline).await.and_then(decode)
        })
        .await
    }

    /// The follow-on read for a `Link` target: the same route and hook identity as the
    /// page it follows, the target checked against the origin the walk started on
    /// (SPEC ยง8).
    pub(crate) fn follow_up<T>(&self, page: &Page<T>, next: &Url) -> Result<Operation, Error> {
        self.follow_up_at(page.route(), page.info(), page.origin(), next)
    }

    #[allow(clippy::unused_self)]
    pub(crate) fn follow_up_at(
        &self,
        route: &'static Route,
        info: &OperationInfo,
        origin: &Url,
        next: &Url,
    ) -> Result<Operation, Error> {
        if !is_same_origin(next, origin) {
            return Err(Error::usage(format!(
                "pagination Link header points to a different origin: {}",
                crate::security::redact_url(next)
            )));
        }
        Ok(Operation::at(route, info.clone(), next.clone()))
    }

    /// Sends an operation: applies credentials and account scope, retries transient
    /// failures under SPEC ยง7's three gates, resends once after a refreshed 401, and maps
    /// every non-2xx status onto an [`Error`].
    pub async fn execute(&self, operation: Operation) -> Result<Response, Error> {
        let deadline = self.deadline();
        self.observe(&operation, self.dispatch(&operation, &deadline))
            .await
    }

    /// Runs `work` inside the operation hook lifecycle. The operation deadline is applied
    /// inside `work`, at each await, so a request the deadline cuts short still reports
    /// its end to the request hooks before the operation ends.
    pub(crate) async fn observe<T>(
        &self,
        operation: &Operation,
        work: impl std::future::Future<Output = Result<T, Error>>,
    ) -> Result<T, Error> {
        let started = Instant::now();
        let hooks = self.shared.hooks.clone();
        crate::hooks::guarded(|| hooks.on_operation_start(&operation.info));
        let outcome = work.await;
        let result = OperationResult {
            error: outcome.as_ref().err(),
            duration: started.elapsed(),
        };
        crate::hooks::guarded(|| hooks.on_operation_end(&operation.info, &result));
        outcome
    }

    #[cfg(feature = "tracing")]
    async fn dispatch(
        &self,
        operation: &Operation,
        deadline: &Deadline,
    ) -> Result<Response, Error> {
        use tracing::Instrument;
        let span = tracing::info_span!(
            "basecamp.operation",
            operation = operation.route.id,
            service = operation.route.service,
            http.status = tracing::field::Empty,
            request_id = tracing::field::Empty,
        );
        self.attempts(operation, deadline).instrument(span).await
    }

    #[cfg(not(feature = "tracing"))]
    async fn dispatch(
        &self,
        operation: &Operation,
        deadline: &Deadline,
    ) -> Result<Response, Error> {
        self.attempts(operation, deadline).await
    }

    /// SPEC ยง7's loop, written out in the order the specification states it.
    #[allow(clippy::too_many_lines)]
    async fn attempts(
        &self,
        operation: &Operation,
        deadline: &Deadline,
    ) -> Result<Response, Error> {
        let route = operation.route;
        let retry = &route.metadata.retry;
        let eligible = route.retry_eligible();
        // The transient-retry ceiling (SPEC ยง7), and the budget the replay after a
        // refreshed 401 draws on (SPEC ยง4): the same ceiling on a retry-eligible route, the
        // caller's cap alone on one the gates make single-attempt, which otherwise could
        // never replay.
        let attempts = if eligible {
            effective_attempts(self.shared.config.max_retries, retry.max_attempts)
        } else {
            1
        };
        let budget = if eligible {
            attempts
        } else {
            effective_attempts(self.shared.config.max_retries, u32::MAX)
        };
        let url = self.url_for(operation)?;
        let hooks = &self.shared.hooks;
        let mut refreshed = false;
        let mut attempt: u32 = 1;
        let mut retry_index: u32 = 0;

        loop {
            // Read before authenticating: a stamp older than the credentials shares the
            // verdict of the refresh that produced them, where a newer one would refresh
            // again.
            let generation = self.shared.auth.generation();
            let request = deadline.bound(self.prepare(operation, &url)).await?;
            let info = RequestInfo {
                method: operation.method.clone(),
                url: url.clone(),
                attempt,
            };
            crate::hooks::guarded(|| hooks.on_request_start(&info));
            let sent_at = Instant::now();
            let sent = deadline.bound(self.shared.http.send(request)).await;
            let duration = sent_at.elapsed();

            match sent {
                Err(error) => {
                    crate::hooks::guarded(|| {
                        hooks.on_request_end(
                            &info,
                            &RequestResult {
                                status: None,
                                duration,
                                error: Some(&error),
                                retry_after: None,
                            },
                        );
                    });
                    // A timed-out attempt spent its whole per-attempt budget; another
                    // would spend another on the same slowness (SPEC ยง14).
                    if eligible
                        && attempt < attempts
                        && !error.is_timeout()
                        && !error.is_deadline_exceeded()
                    {
                        let delay =
                            backoff_with_jitter(retry, retry_index, self.shared.config.max_jitter);
                        crate::hooks::guarded(|| hooks.on_retry(&info, attempt + 1, &error, delay));
                        deadline.wait(delay).await?;
                        retry_index += 1;
                        attempt += 1;
                    } else {
                        return Err(error);
                    }
                }
                Ok(response) => {
                    let status = response.status();
                    let retry_after =
                        parse_retry_after_header(response.headers(), jiff::Timestamp::now());
                    #[cfg(feature = "tracing")]
                    {
                        let span = tracing::Span::current();
                        span.record("http.status", status.as_u16());
                        if let Some(id) = response
                            .headers()
                            .get("x-request-id")
                            .and_then(|v| v.to_str().ok())
                        {
                            span.record("request_id", id);
                        }
                    }
                    if status == StatusCode::UNAUTHORIZED
                        && !refreshed
                        && attempt < budget
                        && self.shared.auth.refreshable()
                    {
                        let cause = Error::from_response(status, response.headers(), &[]);
                        crate::hooks::guarded(|| {
                            hooks.on_request_end(
                                &info,
                                &RequestResult {
                                    status: Some(status),
                                    duration,
                                    error: Some(&cause),
                                    retry_after,
                                },
                            );
                        });
                        refreshed = true;
                        let renewed =
                            match deadline.bound(self.shared.auth.refresh(generation)).await {
                                Ok(renewed) => renewed,
                                Err(cause) if cause.is_deadline_exceeded() => return Err(cause),
                                Err(cause) => {
                                    return Err(Error::new(
                                        ErrorCode::AuthRequired,
                                        "credentials could not be refreshed",
                                    )
                                    .with_status(401)
                                    .with_source(cause));
                                }
                            };
                        if renewed {
                            crate::hooks::guarded(|| {
                                hooks.on_retry(&info, attempt + 1, &cause, Duration::ZERO);
                            });
                            attempt += 1;
                            continue;
                        }
                        return Err(self.finish_failure(operation, response, deadline).await);
                    }
                    if eligible && attempt < attempts && retry.retry_on.contains(&status.as_u16()) {
                        let cause = Error::from_response(status, response.headers(), &[]);
                        crate::hooks::guarded(|| {
                            hooks.on_request_end(
                                &info,
                                &RequestResult {
                                    status: Some(status),
                                    duration,
                                    error: Some(&cause),
                                    retry_after,
                                },
                            );
                        });
                        let delay = match retry_after {
                            Some(seconds) => Duration::from_secs(u64::from(seconds)),
                            None => backoff_with_jitter(
                                retry,
                                retry_index,
                                self.shared.config.max_jitter,
                            ),
                        };
                        crate::hooks::guarded(|| hooks.on_retry(&info, attempt + 1, &cause, delay));
                        deadline.wait(delay).await?;
                        retry_index += 1;
                        attempt += 1;
                        continue;
                    }
                    let finished = self
                        .finish(operation, url.clone(), response, deadline)
                        .await;
                    crate::hooks::guarded(|| {
                        hooks.on_request_end(
                            &info,
                            &RequestResult {
                                status: Some(status),
                                duration,
                                error: finished.as_ref().err(),
                                retry_after,
                            },
                        );
                    });
                    // A connection that broke while the body was streaming is the same
                    // transport failure as one that broke before the status arrived, and
                    // is retried the same way; a decode or size refusal is not.
                    match finished {
                        Err(error)
                            if eligible
                                && attempt < attempts
                                && error.code() == ErrorCode::Network
                                && !error.is_timeout()
                                && !error.is_deadline_exceeded() =>
                        {
                            let delay = backoff_with_jitter(
                                retry,
                                retry_index,
                                self.shared.config.max_jitter,
                            );
                            crate::hooks::guarded(|| {
                                hooks.on_retry(&info, attempt + 1, &error, delay);
                            });
                            deadline.wait(delay).await?;
                            retry_index += 1;
                            attempt += 1;
                        }
                        finished => return finished,
                    }
                }
            }
        }
    }

    /// SPEC ยง3's `buildURL`: an absolute same-origin URL as given; else the base URL โ€”
    /// any path it carries included โ€” the account id and the path.
    pub(crate) fn url_for(&self, operation: &Operation) -> Result<Url, Error> {
        let mut url = if let Some(url) = &operation.url {
            if !is_same_origin(url, &self.shared.base_url) {
                return Err(Error::usage("absolute URL must be same-origin as base_url"));
            }
            url.clone()
        } else {
            let path = operation.path.trim_start_matches('/');
            let mut url = self.shared.base_url.clone();
            let prefix = self.shared.base_url.path().trim_end_matches('/');
            let account = account_segment(&self.account_id)?;
            url.set_path(&format!("{prefix}/{account}/{path}"));
            url
        };
        if !operation.query.is_empty() {
            url.query_pairs_mut().extend_pairs(&operation.query);
        }
        Ok(url)
    }

    async fn prepare(&self, operation: &Operation, url: &Url) -> Result<Request<Bytes>, Error> {
        let mut request = Request::builder()
            .method(operation.method.clone())
            .uri(url.as_str())
            .body(Bytes::new())
            .map_err(|error| Error::usage(format!("request could not be built: {error}")))?;
        let headers = request.headers_mut();
        headers.insert(USER_AGENT, header_value(&self.shared.user_agent)?);
        headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
        if let Some(body) = &operation.body {
            headers.insert(CONTENT_TYPE, header_value(&body.content_type)?);
            *request.body_mut() = body.bytes.clone();
        }
        self.shared.auth.authenticate(&mut request).await?;
        Ok(request)
    }

    async fn finish(
        &self,
        operation: &Operation,
        url: Url,
        response: HttpResponse<Body>,
        deadline: &Deadline,
    ) -> Result<Response, Error> {
        let status = response.status();
        if !status.is_success() {
            return Err(self.finish_failure(operation, response, deadline).await);
        }
        let headers = response.headers().clone();
        let limit = self.shared.config.max_response_body_bytes;
        let body = deadline
            .bound(
                response
                    .into_body()
                    .collect(limit, || Error::response_too_large(limit)),
            )
            .await?;
        if operation.route.response == Representation::Json
            && body.is_empty()
            && status != StatusCode::NO_CONTENT
        {
            let mut error = Error::malformed_response("empty body");
            if let Some(id) = headers.get("x-request-id").and_then(|v| v.to_str().ok()) {
                error = error.with_request_id(id);
            }
            return Err(error);
        }
        Ok(Response {
            status,
            headers,
            body,
            url,
        })
    }

    /// The error a non-2xx response maps to, its body read under the deadline: a body
    /// that stalls past it is the deadline error, and one that fails to read is the
    /// status alone.
    async fn finish_failure(
        &self,
        _operation: &Operation,
        response: HttpResponse<Body>,
        deadline: &Deadline,
    ) -> Error {
        let status = response.status();
        let headers = response.headers().clone();
        let read = response
            .into_body()
            .collect(crate::error::MAX_ERROR_BODY_BYTES, || {
                Error::response_too_large(crate::error::MAX_ERROR_BODY_BYTES)
            });
        match deadline.bound(read).await {
            Ok(body) => Error::from_response(status, &headers, &body),
            Err(error) if error.is_deadline_exceeded() => error,
            Err(_) => Error::from_response(status, &headers, &[]),
        }
    }
}

#[cfg(feature = "reqwest")]
fn shipped_http_client(timeout: Duration) -> Result<Arc<dyn HttpClient>, Error> {
    Ok(Arc::new(crate::http::ReqwestClient::with_timeout(timeout)?))
}

#[cfg(not(feature = "reqwest"))]
fn shipped_http_client(_timeout: Duration) -> Result<Arc<dyn HttpClient>, Error> {
    Err(Error::usage(
        "no HTTP client: supply one with ClientBuilder::http_client, or enable the reqwest feature",
    ))
}

/// The account id as one path segment: percent-encoded, and never a segment that the URL
/// parser would fold away (`.`, `..`, nothing at all), which would put the request outside
/// the account's scope.
fn account_segment(account_id: &str) -> Result<String, Error> {
    let trimmed = account_id.trim_matches('.');
    if account_id.is_empty() || trimmed.is_empty() {
        return Err(Error::usage(format!(
            "account id {account_id:?} is not a path segment"
        )));
    }
    Ok(percent_encoding::utf8_percent_encode(account_id, ACCOUNT_SEGMENT).to_string())
}

const ACCOUNT_SEGMENT: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
    .remove(b'-')
    .remove(b'_')
    .remove(b'.')
    .remove(b'~');

fn parse_base_url(base_url: &str) -> Result<Url, Error> {
    let mut url = Url::parse(base_url.trim_end_matches('/'))
        .map_err(|error| Error::usage(format!("base URL {base_url}: {error}")))?;
    if url.cannot_be_a_base() || url.host_str().is_none() {
        return Err(Error::usage(format!("base URL {base_url} has no host")));
    }
    require_secure_endpoint(&url).map_err(|_| Error::usage("base URL must use HTTPS"))?;
    url.set_query(None);
    url.set_fragment(None);
    Ok(url)
}

pub(crate) fn header_value(value: &str) -> Result<HeaderValue, Error> {
    HeaderValue::from_str(value)
        .map_err(|_| Error::usage(format!("{value:?} is not a valid header value")))
}

impl From<ErrorCode> for Error {
    fn from(code: ErrorCode) -> Error {
        Error::new(code, code.as_str())
    }
}