Skip to main content

basecamp_sdk/
client.rs

1//! SPEC §3: the client, and the account-scoped client every service hangs off.
2
3use std::fmt;
4use std::sync::Arc;
5use std::time::{Duration, Instant};
6
7use bytes::Bytes;
8use serde::de::DeserializeOwned;
9use url::Url;
10
11use crate::auth::{AuthStrategy, BearerAuth, StaticTokenProvider, TokenProvider};
12use crate::config::Config;
13use crate::deadline::Deadline;
14use crate::error::{Error, ErrorCode, parse_retry_after_header};
15use crate::hooks::{Hooks, NoopHooks, OperationInfo, OperationResult, RequestInfo, RequestResult};
16use crate::http::header::{ACCEPT, CONTENT_TYPE, USER_AGENT};
17use crate::http::{
18    Body, HeaderMap, HeaderValue, HttpClient, Request, Response as HttpResponse, StatusCode,
19};
20use crate::operation::Operation;
21use crate::pagination::Page;
22use crate::retry::{backoff_with_jitter, effective_attempts};
23use crate::route::{Representation, Route};
24use crate::security::{is_same_origin, require_secure_endpoint};
25use crate::services::campfire_index::CampfireIndex;
26use crate::version::default_user_agent;
27
28/// A Basecamp client: one identity, one API origin. Derive an [`AccountClient`] with
29/// [`Client::for_account`] to reach the services.
30///
31/// Clients are cheap to clone and share their connection pool, credentials and hooks.
32#[derive(Clone)]
33pub struct Client {
34    shared: Arc<Shared>,
35}
36
37/// The client scoped to one account: where every service lives.
38#[derive(Clone)]
39pub struct AccountClient {
40    shared: Arc<Shared>,
41    account_id: String,
42}
43
44pub(crate) struct Shared {
45    pub(crate) config: Config,
46    pub(crate) base_url: Url,
47    pub(crate) http: Arc<dyn HttpClient>,
48    pub(crate) auth: Arc<dyn AuthStrategy>,
49    pub(crate) user_agent: String,
50    pub(crate) hooks: Arc<dyn Hooks>,
51    /// The Campfire discovery caches the recording-summary composite reads chat lines
52    /// through (SPEC §18). It hangs here, beside the credential it is bound to, so every
53    /// [`AccountClient`] derived from one [`Client`] shares one index and a burst of chat
54    /// lines costs one listing rather than one per line — and so entries are never shared
55    /// across authorization contexts.
56    pub(crate) campfires: CampfireIndex,
57}
58
59/// What came back from Basecamp, before it is decoded. Its `Debug` form redacts the
60/// credential-bearing headers (SPEC §9).
61#[derive(Clone)]
62#[non_exhaustive]
63pub struct Response {
64    /// The status.
65    pub status: StatusCode,
66    /// The headers.
67    pub headers: HeaderMap,
68    /// The body, read whole.
69    pub body: Bytes,
70    /// The URL the answer came from.
71    pub url: Url,
72}
73
74impl fmt::Debug for Response {
75    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76        f.debug_struct("Response")
77            .field("status", &self.status)
78            .field("headers", &crate::security::redact_headers(&self.headers))
79            .field("body", &self.body)
80            .field("url", &self.url)
81            .finish()
82    }
83}
84
85impl Response {
86    /// The body decoded as JSON. A body that does not decode as `T` is a statusless,
87    /// non-retryable `api_error` (SPEC §6) that keeps the request id.
88    pub fn json<T: DeserializeOwned>(&self) -> Result<T, Error> {
89        serde_json::from_slice(&self.body).map_err(|error| {
90            let mut mapped = Error::malformed_response(error.to_string());
91            if let Some(request_id) = self.header("x-request-id") {
92                mapped = mapped.with_request_id(request_id);
93            }
94            mapped
95        })
96    }
97
98    /// One header, when present and readable as text.
99    pub fn header(&self, name: &str) -> Option<&str> {
100        self.headers.get(name).and_then(|value| value.to_str().ok())
101    }
102}
103
104/// Builds a [`Client`].
105pub struct ClientBuilder {
106    config: Config,
107    auth: Option<Arc<dyn AuthStrategy>>,
108    http: Option<Arc<dyn HttpClient>>,
109    user_agent: String,
110    hooks: Arc<dyn Hooks>,
111    auth_given: u8,
112    /// Test-only: the discovery index reads real time unless a test hands it a clock, and
113    /// the refresh floor cannot be crossed by waiting in a test.
114    #[cfg(all(test, feature = "reqwest"))]
115    campfire_clock: Option<crate::services::campfire_index::Clock>,
116}
117
118impl ClientBuilder {
119    /// A builder over a configuration.
120    pub fn new(config: Config) -> ClientBuilder {
121        ClientBuilder {
122            config,
123            auth: None,
124            http: None,
125            user_agent: default_user_agent(),
126            hooks: Arc::new(NoopHooks),
127            auth_given: 0,
128            #[cfg(all(test, feature = "reqwest"))]
129            campfire_clock: None,
130        }
131    }
132
133    /// The clock the Campfire discovery index ages its entries by. Test-only: nothing
134    /// outside this crate's own tests can move it, and the shipped client always reads
135    /// [`std::time::Instant::now`].
136    #[cfg(all(test, feature = "reqwest"))]
137    pub(crate) fn campfire_clock(
138        mut self,
139        clock: crate::services::campfire_index::Clock,
140    ) -> ClientBuilder {
141        self.campfire_clock = Some(clock);
142        self
143    }
144
145    /// A fixed bearer token — a personal access token, say.
146    pub fn access_token(self, token: impl Into<String>) -> ClientBuilder {
147        self.token_provider(StaticTokenProvider::new(token.into()))
148    }
149
150    /// Bearer authentication over a [`TokenProvider`], refreshed on 401 where the provider
151    /// supports it.
152    pub fn token_provider(self, provider: impl TokenProvider + 'static) -> ClientBuilder {
153        self.auth_strategy(BearerAuth::new(provider))
154    }
155
156    /// Any [`AuthStrategy`]. Exactly one of this, [`ClientBuilder::access_token`] or
157    /// [`ClientBuilder::token_provider`] must be given.
158    pub fn auth_strategy(mut self, strategy: impl AuthStrategy + 'static) -> ClientBuilder {
159        self.auth_given += 1;
160        self.auth = Some(Arc::new(strategy));
161        self
162    }
163
164    /// Replaces the HTTP client every request goes out on. It must not follow redirects;
165    /// see [`HttpClient`]. The configured timeout then has no effect — a timeout belongs to
166    /// the client that can enforce it.
167    pub fn http_client(mut self, http: impl HttpClient + 'static) -> ClientBuilder {
168        self.http = Some(Arc::new(http));
169        self
170    }
171
172    /// Another `User-Agent`.
173    pub fn user_agent(mut self, user_agent: impl Into<String>) -> ClientBuilder {
174        self.user_agent = user_agent.into();
175        self
176    }
177
178    /// Reports every operation and every request the client makes. Several sets of hooks
179    /// go on as one with [`crate::hooks::ChainHooks`].
180    pub fn hooks(mut self, hooks: impl Hooks + 'static) -> ClientBuilder {
181        self.hooks = Arc::new(hooks);
182        self
183    }
184
185    /// The whole-operation deadline; see [`Config::operation_deadline`].
186    pub fn operation_deadline(mut self, deadline: Duration) -> ClientBuilder {
187        self.config.operation_deadline = Some(deadline);
188        self
189    }
190
191    /// Validates the configuration (SPEC §2) and builds the client.
192    pub fn build(self) -> Result<Client, Error> {
193        if self.auth_given > 1 {
194            return Err(Error::usage(
195                "Provide either auth or access_token, not both",
196            ));
197        }
198        let auth = self
199            .auth
200            .ok_or_else(|| Error::usage("Either auth or access_token is required"))?;
201        let base_url = parse_base_url(&self.config.base_url)?;
202        self.config.validate()?;
203        let http = match self.http {
204            Some(http) => http,
205            None => shipped_http_client(self.config.timeout)?,
206        };
207        #[cfg(all(test, feature = "reqwest"))]
208        let campfires = match self.campfire_clock {
209            Some(clock) => CampfireIndex::with_clock(clock),
210            None => CampfireIndex::new(),
211        };
212        #[cfg(not(all(test, feature = "reqwest")))]
213        let campfires = CampfireIndex::new();
214        Ok(Client {
215            shared: Arc::new(Shared {
216                config: self.config,
217                base_url,
218                http,
219                auth,
220                user_agent: self.user_agent,
221                hooks: self.hooks,
222                campfires,
223            }),
224        })
225    }
226}
227
228impl Client {
229    /// A builder over a configuration.
230    pub fn builder(config: Config) -> ClientBuilder {
231        ClientBuilder::new(config)
232    }
233
234    /// The configuration the client was built with.
235    pub fn config(&self) -> &Config {
236        &self.shared.config
237    }
238
239    /// The API origin.
240    pub fn base_url(&self) -> &Url {
241        &self.shared.base_url
242    }
243
244    /// The client scoped to one account. Every account-scoped path is prefixed with the id.
245    pub fn for_account(&self, account_id: impl Into<String>) -> AccountClient {
246        AccountClient {
247            shared: self.shared.clone(),
248            account_id: account_id.into(),
249        }
250    }
251}
252
253impl fmt::Debug for Client {
254    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
255        f.debug_struct("Client")
256            .field("base_url", &self.shared.base_url)
257            .finish_non_exhaustive()
258    }
259}
260
261impl fmt::Debug for AccountClient {
262    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
263        f.debug_struct("AccountClient")
264            .field("base_url", &self.shared.base_url)
265            .field("account_id", &self.account_id)
266            .finish_non_exhaustive()
267    }
268}
269
270impl AccountClient {
271    /// The account this client is scoped to.
272    pub fn account_id(&self) -> &str {
273        &self.account_id
274    }
275
276    /// The configuration the client was built with.
277    pub fn config(&self) -> &Config {
278        &self.shared.config
279    }
280
281    /// The API origin.
282    pub fn base_url(&self) -> &Url {
283        &self.shared.base_url
284    }
285
286    /// How many pages an auto-paginating read follows.
287    pub fn max_pages(&self) -> usize {
288        self.shared.config.max_pages
289    }
290
291    pub(crate) fn shared(&self) -> &Arc<Shared> {
292        &self.shared
293    }
294
295    /// The Campfire discovery index, shared with every other account client derived from
296    /// the same [`Client`].
297    pub(crate) fn campfire_index(&self) -> &CampfireIndex {
298        &self.shared.campfires
299    }
300
301    /// The account-independent client this was derived from.
302    pub fn client(&self) -> Client {
303        Client {
304            shared: self.shared.clone(),
305        }
306    }
307
308    /// Starts a request for one of the modelled routes. Generated service methods call
309    /// this; reach for it directly only to add a query parameter they do not expose.
310    pub fn operation(&self, route: &'static Route, params: &[&dyn fmt::Display]) -> Operation {
311        Operation::for_route(route, params)
312    }
313
314    /// Sends an operation and decodes its JSON body.
315    pub async fn send<T: DeserializeOwned>(&self, operation: Operation) -> Result<T, Error> {
316        self.run(operation, |response| response.json()).await
317    }
318
319    /// The whole-operation deadline, started now (SPEC §2's `operation_deadline`).
320    pub(crate) fn deadline(&self) -> Deadline {
321        Deadline::starting_now(self.shared.config.operation_deadline)
322    }
323
324    /// Sends an operation whose answer carries no body worth reading.
325    pub async fn send_unit(&self, operation: Operation) -> Result<(), Error> {
326        self.run(operation, |_| Ok(())).await
327    }
328
329    /// Sends a paginated read and keeps the cursor Basecamp answered with.
330    pub async fn send_page<T: DeserializeOwned>(
331        &self,
332        operation: Operation,
333    ) -> Result<Page<T>, Error> {
334        let route = operation.route;
335        let info = operation.info.clone();
336        let pinned = operation.pins_a_page();
337        self.run(operation, |response| {
338            Ok(Page::new(response.json()?, &response, route, info, pinned))
339        })
340        .await
341    }
342
343    /// Sends an operation and reads its answer with `decode`, so a body that does not decode
344    /// ends the operation as a failure in the hooks' eyes too (SPEC §12).
345    pub async fn run<T>(
346        &self,
347        operation: Operation,
348        decode: impl FnOnce(Response) -> Result<T, Error>,
349    ) -> Result<T, Error> {
350        let deadline = self.deadline();
351        self.observe(&operation, async {
352            self.dispatch(&operation, &deadline).await.and_then(decode)
353        })
354        .await
355    }
356
357    /// The follow-on read for a `Link` target: the same route and hook identity as the
358    /// page it follows, the target checked against the origin the walk started on
359    /// (SPEC §8).
360    pub(crate) fn follow_up<T>(&self, page: &Page<T>, next: &Url) -> Result<Operation, Error> {
361        self.follow_up_at(page.route(), page.info(), page.origin(), next)
362    }
363
364    #[allow(clippy::unused_self)]
365    pub(crate) fn follow_up_at(
366        &self,
367        route: &'static Route,
368        info: &OperationInfo,
369        origin: &Url,
370        next: &Url,
371    ) -> Result<Operation, Error> {
372        if !is_same_origin(next, origin) {
373            return Err(Error::usage(format!(
374                "pagination Link header points to a different origin: {}",
375                crate::security::redact_url(next)
376            )));
377        }
378        Ok(Operation::at(route, info.clone(), next.clone()))
379    }
380
381    /// Sends an operation: applies credentials and account scope, retries transient
382    /// failures under SPEC §7's three gates, resends once after a refreshed 401, and maps
383    /// every non-2xx status onto an [`Error`].
384    pub async fn execute(&self, operation: Operation) -> Result<Response, Error> {
385        let deadline = self.deadline();
386        self.observe(&operation, self.dispatch(&operation, &deadline))
387            .await
388    }
389
390    /// Runs `work` inside the operation hook lifecycle. The operation deadline is applied
391    /// inside `work`, at each await, so a request the deadline cuts short still reports
392    /// its end to the request hooks before the operation ends.
393    pub(crate) async fn observe<T>(
394        &self,
395        operation: &Operation,
396        work: impl std::future::Future<Output = Result<T, Error>>,
397    ) -> Result<T, Error> {
398        let started = Instant::now();
399        let hooks = self.shared.hooks.clone();
400        crate::hooks::guarded(|| hooks.on_operation_start(&operation.info));
401        let outcome = work.await;
402        let result = OperationResult {
403            error: outcome.as_ref().err(),
404            duration: started.elapsed(),
405        };
406        crate::hooks::guarded(|| hooks.on_operation_end(&operation.info, &result));
407        outcome
408    }
409
410    #[cfg(feature = "tracing")]
411    async fn dispatch(
412        &self,
413        operation: &Operation,
414        deadline: &Deadline,
415    ) -> Result<Response, Error> {
416        use tracing::Instrument;
417        let span = tracing::info_span!(
418            "basecamp.operation",
419            operation = operation.route.id,
420            service = operation.route.service,
421            http.status = tracing::field::Empty,
422            request_id = tracing::field::Empty,
423        );
424        self.attempts(operation, deadline).instrument(span).await
425    }
426
427    #[cfg(not(feature = "tracing"))]
428    async fn dispatch(
429        &self,
430        operation: &Operation,
431        deadline: &Deadline,
432    ) -> Result<Response, Error> {
433        self.attempts(operation, deadline).await
434    }
435
436    /// SPEC §7's loop, written out in the order the specification states it.
437    #[allow(clippy::too_many_lines)]
438    async fn attempts(
439        &self,
440        operation: &Operation,
441        deadline: &Deadline,
442    ) -> Result<Response, Error> {
443        let route = operation.route;
444        let retry = &route.metadata.retry;
445        let eligible = route.retry_eligible();
446        // The transient-retry ceiling (SPEC §7), and the budget the replay after a
447        // refreshed 401 draws on (SPEC §4): the same ceiling on a retry-eligible route, the
448        // caller's cap alone on one the gates make single-attempt, which otherwise could
449        // never replay.
450        let attempts = if eligible {
451            effective_attempts(self.shared.config.max_retries, retry.max_attempts)
452        } else {
453            1
454        };
455        let budget = if eligible {
456            attempts
457        } else {
458            effective_attempts(self.shared.config.max_retries, u32::MAX)
459        };
460        let url = self.url_for(operation)?;
461        let hooks = &self.shared.hooks;
462        let mut refreshed = false;
463        let mut attempt: u32 = 1;
464        let mut retry_index: u32 = 0;
465
466        loop {
467            // Read before authenticating: a stamp older than the credentials shares the
468            // verdict of the refresh that produced them, where a newer one would refresh
469            // again.
470            let generation = self.shared.auth.generation();
471            let request = deadline.bound(self.prepare(operation, &url)).await?;
472            let info = RequestInfo {
473                method: operation.method.clone(),
474                url: url.clone(),
475                attempt,
476            };
477            crate::hooks::guarded(|| hooks.on_request_start(&info));
478            let sent_at = Instant::now();
479            let sent = deadline.bound(self.shared.http.send(request)).await;
480            let duration = sent_at.elapsed();
481
482            match sent {
483                Err(error) => {
484                    crate::hooks::guarded(|| {
485                        hooks.on_request_end(
486                            &info,
487                            &RequestResult {
488                                status: None,
489                                duration,
490                                error: Some(&error),
491                                retry_after: None,
492                            },
493                        );
494                    });
495                    // A timed-out attempt spent its whole per-attempt budget; another
496                    // would spend another on the same slowness (SPEC §14).
497                    if eligible
498                        && attempt < attempts
499                        && !error.is_timeout()
500                        && !error.is_deadline_exceeded()
501                    {
502                        let delay =
503                            backoff_with_jitter(retry, retry_index, self.shared.config.max_jitter);
504                        crate::hooks::guarded(|| hooks.on_retry(&info, attempt + 1, &error, delay));
505                        deadline.wait(delay).await?;
506                        retry_index += 1;
507                        attempt += 1;
508                    } else {
509                        return Err(error);
510                    }
511                }
512                Ok(response) => {
513                    let status = response.status();
514                    let retry_after =
515                        parse_retry_after_header(response.headers(), chrono::Utc::now());
516                    #[cfg(feature = "tracing")]
517                    {
518                        let span = tracing::Span::current();
519                        span.record("http.status", status.as_u16());
520                        if let Some(id) = response
521                            .headers()
522                            .get("x-request-id")
523                            .and_then(|v| v.to_str().ok())
524                        {
525                            span.record("request_id", id);
526                        }
527                    }
528                    if status == StatusCode::UNAUTHORIZED
529                        && !refreshed
530                        && attempt < budget
531                        && self.shared.auth.refreshable()
532                    {
533                        let cause = Error::from_response(status, response.headers(), &[]);
534                        crate::hooks::guarded(|| {
535                            hooks.on_request_end(
536                                &info,
537                                &RequestResult {
538                                    status: Some(status),
539                                    duration,
540                                    error: Some(&cause),
541                                    retry_after,
542                                },
543                            );
544                        });
545                        refreshed = true;
546                        let renewed =
547                            match deadline.bound(self.shared.auth.refresh(generation)).await {
548                                Ok(renewed) => renewed,
549                                Err(cause) if cause.is_deadline_exceeded() => return Err(cause),
550                                Err(cause) => {
551                                    return Err(Error::new(
552                                        ErrorCode::AuthRequired,
553                                        "credentials could not be refreshed",
554                                    )
555                                    .with_status(401)
556                                    .with_source(cause));
557                                }
558                            };
559                        if renewed {
560                            crate::hooks::guarded(|| {
561                                hooks.on_retry(&info, attempt + 1, &cause, Duration::ZERO);
562                            });
563                            attempt += 1;
564                            continue;
565                        }
566                        return Err(self.finish_failure(operation, response, deadline).await);
567                    }
568                    if eligible && attempt < attempts && retry.retry_on.contains(&status.as_u16()) {
569                        let cause = Error::from_response(status, response.headers(), &[]);
570                        crate::hooks::guarded(|| {
571                            hooks.on_request_end(
572                                &info,
573                                &RequestResult {
574                                    status: Some(status),
575                                    duration,
576                                    error: Some(&cause),
577                                    retry_after,
578                                },
579                            );
580                        });
581                        let delay = match retry_after {
582                            Some(seconds) => Duration::from_secs(u64::from(seconds)),
583                            None => backoff_with_jitter(
584                                retry,
585                                retry_index,
586                                self.shared.config.max_jitter,
587                            ),
588                        };
589                        crate::hooks::guarded(|| hooks.on_retry(&info, attempt + 1, &cause, delay));
590                        deadline.wait(delay).await?;
591                        retry_index += 1;
592                        attempt += 1;
593                        continue;
594                    }
595                    let finished = self
596                        .finish(operation, url.clone(), response, deadline)
597                        .await;
598                    crate::hooks::guarded(|| {
599                        hooks.on_request_end(
600                            &info,
601                            &RequestResult {
602                                status: Some(status),
603                                duration,
604                                error: finished.as_ref().err(),
605                                retry_after,
606                            },
607                        );
608                    });
609                    // A connection that broke while the body was streaming is the same
610                    // transport failure as one that broke before the status arrived, and
611                    // is retried the same way; a decode or size refusal is not.
612                    match finished {
613                        Err(error)
614                            if eligible
615                                && attempt < attempts
616                                && error.code() == ErrorCode::Network
617                                && !error.is_timeout()
618                                && !error.is_deadline_exceeded() =>
619                        {
620                            let delay = backoff_with_jitter(
621                                retry,
622                                retry_index,
623                                self.shared.config.max_jitter,
624                            );
625                            crate::hooks::guarded(|| {
626                                hooks.on_retry(&info, attempt + 1, &error, delay);
627                            });
628                            deadline.wait(delay).await?;
629                            retry_index += 1;
630                            attempt += 1;
631                        }
632                        finished => return finished,
633                    }
634                }
635            }
636        }
637    }
638
639    /// SPEC §3's `buildURL`: an absolute same-origin URL as given; else the base URL —
640    /// any path it carries included — the account id and the path.
641    pub(crate) fn url_for(&self, operation: &Operation) -> Result<Url, Error> {
642        let mut url = if let Some(url) = &operation.url {
643            if !is_same_origin(url, &self.shared.base_url) {
644                return Err(Error::usage("absolute URL must be same-origin as base_url"));
645            }
646            url.clone()
647        } else {
648            let path = operation.path.trim_start_matches('/');
649            let mut url = self.shared.base_url.clone();
650            let prefix = self.shared.base_url.path().trim_end_matches('/');
651            let account = account_segment(&self.account_id)?;
652            url.set_path(&format!("{prefix}/{account}/{path}"));
653            url
654        };
655        if !operation.query.is_empty() {
656            url.query_pairs_mut().extend_pairs(&operation.query);
657        }
658        Ok(url)
659    }
660
661    async fn prepare(&self, operation: &Operation, url: &Url) -> Result<Request<Bytes>, Error> {
662        let mut request = Request::builder()
663            .method(operation.method.clone())
664            .uri(url.as_str())
665            .body(Bytes::new())
666            .map_err(|error| Error::usage(format!("request could not be built: {error}")))?;
667        let headers = request.headers_mut();
668        headers.insert(USER_AGENT, header_value(&self.shared.user_agent)?);
669        headers.insert(ACCEPT, HeaderValue::from_static("application/json"));
670        if let Some(body) = &operation.body {
671            headers.insert(CONTENT_TYPE, header_value(&body.content_type)?);
672            *request.body_mut() = body.bytes.clone();
673        }
674        self.shared.auth.authenticate(&mut request).await?;
675        Ok(request)
676    }
677
678    async fn finish(
679        &self,
680        operation: &Operation,
681        url: Url,
682        response: HttpResponse<Body>,
683        deadline: &Deadline,
684    ) -> Result<Response, Error> {
685        let status = response.status();
686        if !status.is_success() {
687            return Err(self.finish_failure(operation, response, deadline).await);
688        }
689        let headers = response.headers().clone();
690        let limit = self.shared.config.max_response_body_bytes;
691        let body = deadline
692            .bound(
693                response
694                    .into_body()
695                    .collect(limit, || Error::response_too_large(limit)),
696            )
697            .await?;
698        if operation.route.response == Representation::Json
699            && body.is_empty()
700            && status != StatusCode::NO_CONTENT
701        {
702            let mut error = Error::malformed_response("empty body");
703            if let Some(id) = headers.get("x-request-id").and_then(|v| v.to_str().ok()) {
704                error = error.with_request_id(id);
705            }
706            return Err(error);
707        }
708        Ok(Response {
709            status,
710            headers,
711            body,
712            url,
713        })
714    }
715
716    /// The error a non-2xx response maps to, its body read under the deadline: a body
717    /// that stalls past it is the deadline error, and one that fails to read is the
718    /// status alone.
719    async fn finish_failure(
720        &self,
721        _operation: &Operation,
722        response: HttpResponse<Body>,
723        deadline: &Deadline,
724    ) -> Error {
725        let status = response.status();
726        let headers = response.headers().clone();
727        let read = response
728            .into_body()
729            .collect(crate::error::MAX_ERROR_BODY_BYTES, || {
730                Error::response_too_large(crate::error::MAX_ERROR_BODY_BYTES)
731            });
732        match deadline.bound(read).await {
733            Ok(body) => Error::from_response(status, &headers, &body),
734            Err(error) if error.is_deadline_exceeded() => error,
735            Err(_) => Error::from_response(status, &headers, &[]),
736        }
737    }
738}
739
740#[cfg(feature = "reqwest")]
741fn shipped_http_client(timeout: Duration) -> Result<Arc<dyn HttpClient>, Error> {
742    Ok(Arc::new(crate::http::ReqwestClient::with_timeout(timeout)?))
743}
744
745#[cfg(not(feature = "reqwest"))]
746fn shipped_http_client(_timeout: Duration) -> Result<Arc<dyn HttpClient>, Error> {
747    Err(Error::usage(
748        "no HTTP client: supply one with ClientBuilder::http_client, or enable the reqwest feature",
749    ))
750}
751
752/// The account id as one path segment: percent-encoded, and never a segment that the URL
753/// parser would fold away (`.`, `..`, nothing at all), which would put the request outside
754/// the account's scope.
755fn account_segment(account_id: &str) -> Result<String, Error> {
756    let trimmed = account_id.trim_matches('.');
757    if account_id.is_empty() || trimmed.is_empty() {
758        return Err(Error::usage(format!(
759            "account id {account_id:?} is not a path segment"
760        )));
761    }
762    Ok(percent_encoding::utf8_percent_encode(account_id, ACCOUNT_SEGMENT).to_string())
763}
764
765const ACCOUNT_SEGMENT: &percent_encoding::AsciiSet = &percent_encoding::NON_ALPHANUMERIC
766    .remove(b'-')
767    .remove(b'_')
768    .remove(b'.')
769    .remove(b'~');
770
771fn parse_base_url(base_url: &str) -> Result<Url, Error> {
772    let mut url = Url::parse(base_url.trim_end_matches('/'))
773        .map_err(|error| Error::usage(format!("base URL {base_url}: {error}")))?;
774    if url.cannot_be_a_base() || url.host_str().is_none() {
775        return Err(Error::usage(format!("base URL {base_url} has no host")));
776    }
777    require_secure_endpoint(&url).map_err(|_| Error::usage("base URL must use HTTPS"))?;
778    url.set_query(None);
779    url.set_fragment(None);
780    Ok(url)
781}
782
783pub(crate) fn header_value(value: &str) -> Result<HeaderValue, Error> {
784    HeaderValue::from_str(value)
785        .map_err(|_| Error::usage(format!("{value:?} is not a valid header value")))
786}
787
788impl From<ErrorCode> for Error {
789    fn from(code: ErrorCode) -> Error {
790        Error::new(code, code.as_str())
791    }
792}