Skip to main content

libtea_client/
service.rs

1//! Typed TEA consumer operations.
2
3use libtea_core::{
4    is_json_content_type, parse_artifact, parse_collection, parse_component_release,
5    parse_product_release, versioned_api_prefix, Artifact, Checksum, Cle, Collection, Component,
6    ComponentId, ComponentRelease, ComponentReleaseId, ComponentReleaseWithCollection,
7    DiscoveryInfo, IntegrityOutcome, Page, Product, ProductId, ProductRelease, ProductReleaseId,
8    ProductReleaseWithCollection,
9};
10use serde::de::DeserializeOwned;
11use url::Url;
12
13use crate::error::ClientError;
14use crate::transport::{header_str, map_api_error, operation_url, Call, CONTENT_TYPE_HEADER};
15use crate::Client;
16
17/// A versioned TEA API base.
18///
19/// Paths are OpenAPI paths appended to `{rootUrl}/v{advertised-version}/`.
20#[derive(Clone)]
21pub struct Service {
22    client: Client,
23    root: String,
24    version: String,
25    prefix: Url,
26}
27
28/// Bytes of an artifact or signature after HTTP content coding is removed.
29#[derive(Debug, Clone, PartialEq, Eq)]
30#[non_exhaustive]
31pub struct DownloadedArtifact {
32    /// Decoded bytes.
33    pub bytes: Vec<u8>,
34    /// Response `Content-Type`.
35    pub content_type: Option<String>,
36    /// HTTP content coding that was removed, when one was declared.
37    pub content_encoding: Option<String>,
38    /// `ETag` as received. This is not a checksum.
39    pub etag: Option<String>,
40    /// Whether the tag is strong. A weak tag is not byte-identity proof.
41    pub strong_etag: bool,
42    /// `Cache-Control` as received. This client does not store a cache.
43    pub cache_control: Option<String>,
44    /// `Content-Location` as received.
45    pub content_location: Option<String>,
46    /// `Vary` as received.
47    pub vary: Option<String>,
48    /// `Repr-Digest` as received. It covers the HTTP representation, not the artifact checksum.
49    pub repr_digest: Option<String>,
50    /// Final URL after redirects.
51    pub final_url: String,
52    /// Checksum report. [`IntegrityOutcome::Verified`] means every declared
53    /// checksum matched **decoded** artifact bytes — not publisher authenticity.
54    /// A match on weak algorithms only (SHA-1) is an error unless
55    /// [`crate::ClientBuilder::allow_weak_checksums`] is set.
56    pub integrity: libtea_core::IntegrityReport,
57}
58
59/// Artifact download result.
60#[derive(Debug, Clone, PartialEq, Eq)]
61#[non_exhaustive]
62pub enum ArtifactFetch {
63    /// A response body.
64    Body(DownloadedArtifact),
65    /// Conditional GET found the selected representation unchanged.
66    #[non_exhaustive]
67    NotModified {
68        /// Validator from the 304 response.
69        etag: Option<String>,
70        /// Cache policy.
71        cache_control: Option<String>,
72        /// Vary header.
73        vary: Option<String>,
74    },
75}
76
77/// CLE projection result. `NotImplemented` is not a missing parent object.
78#[derive(Debug, Clone, PartialEq, Eq)]
79#[non_exhaustive]
80pub enum CleFetch {
81    /// Lifecycle projection.
82    Events(Cle),
83    /// The server does not implement CLE for this object.
84    #[non_exhaustive]
85    NotImplemented {
86        /// Optional diagnostic.
87        message: Option<String>,
88    },
89}
90
91/// Detached signature fetch.
92#[derive(Debug, Clone, PartialEq, Eq)]
93#[non_exhaustive]
94pub enum SignatureFetch {
95    /// Signature bytes. TEA does not define a checksum for the signature itself.
96    Present(Box<DownloadedArtifact>),
97    /// The revision exists and this format has no published signature.
98    NotPublished,
99    /// Conditional GET matched.
100    #[non_exhaustive]
101    NotModified {
102        /// Validator.
103        etag: Option<String>,
104    },
105}
106
107impl Service {
108    pub(crate) fn client_ref(&self) -> &Client {
109        &self.client
110    }
111
112    pub(crate) fn prefix_ref(&self) -> &Url {
113        &self.prefix
114    }
115
116    pub(crate) fn from_parts(
117        client: Client,
118        root: Url,
119        version: String,
120    ) -> Result<Self, ClientError> {
121        let prefix = versioned_api_prefix(root.as_str().trim_end_matches('/'), &version)?;
122        let prefix = Url::parse(&prefix).map_err(|_| {
123            ClientError::Model(libtea_core::ModelError::Invalid(
124                "versioned API prefix is not a URL".into(),
125            ))
126        })?;
127        Ok(Self {
128            client,
129            root: root.as_str().trim_end_matches('/').to_owned(),
130            version,
131            prefix,
132        })
133    }
134
135    /// API root without the version segment.
136    #[must_use]
137    pub fn root(&self) -> &str {
138        &self.root
139    }
140
141    /// Advertised version string used in the path.
142    #[must_use]
143    pub fn api_version(&self) -> &str {
144        &self.version
145    }
146
147    /// Resolve a TEI or PURL on this already-known API base.
148    ///
149    /// Exactly one of the arguments must be set.
150    ///
151    /// # Errors
152    ///
153    /// Returns [`ClientError::Unresolved`] for a TEA 404, which does not mean failover.
154    pub async fn discover_identifier(
155        &self,
156        tei: Option<&str>,
157        purl: Option<&str>,
158    ) -> Result<Vec<DiscoveryInfo>, ClientError> {
159        match (tei, purl) {
160            (Some(_), Some(_)) | (None, None) => {
161                return Err(ClientError::Model(libtea_core::ModelError::Invalid(
162                    "exactly one of tei or purl is required".into(),
163                )));
164            }
165            _ => {}
166        }
167        let mut query = Vec::new();
168        if let Some(tei) = tei {
169            query.push(("tei", tei));
170        }
171        if let Some(purl) = purl {
172            query.push(("purl", purl));
173        }
174        let response = self.get_raw("discovery", &query, false).await?;
175        if response.status.as_u16() == 404 {
176            if let Some(error) = libtea_core::tea_error_code(
177                header_str(&response.headers, CONTENT_TYPE_HEADER),
178                &response.body,
179            ) {
180                let message = libtea_core::TeaErrorBody::parse(&response.body)
181                    .ok()
182                    .and_then(|body| body.message);
183                return Err(ClientError::Unresolved {
184                    error: libtea_core::escape_control_chars(&error),
185                    message: message.map(|text| libtea_core::escape_control_chars(&text)),
186                });
187            }
188        }
189        if !response.status.is_success() {
190            return Err(map_api_error(&response));
191        }
192        require_json(&response)?;
193        Ok(if self.client.inner.supported.is_lenient() {
194            DiscoveryInfo::parse_list_lenient(&response.body)?
195        } else {
196            DiscoveryInfo::parse_list(&response.body)?
197        })
198    }
199
200    /// `GET /products`.
201    ///
202    /// # Errors
203    ///
204    /// Returns an error on transport failure or a non-success status.
205    pub async fn query_products(
206        &self,
207        query: &libtea_core::ListParams<libtea_core::enums::ProductSort>,
208    ) -> Result<Page<Product>, ClientError> {
209        self.page("products", query, |sort| sort.as_str()).await
210    }
211
212    /// `GET /product/{uuid}`.
213    pub async fn get_product(&self, id: ProductId) -> Result<Product, ClientError> {
214        self.get_json(&format!("product/{id}"), &[]).await
215    }
216
217    /// `GET /product/{uuid}/releases`.
218    pub async fn list_product_releases(
219        &self,
220        id: ProductId,
221        query: &libtea_core::ListParams<libtea_core::enums::ReleaseSort>,
222    ) -> Result<Page<ProductRelease>, ClientError> {
223        self.page(&format!("product/{id}/releases"), query, |sort| {
224            sort.as_str()
225        })
226        .await
227    }
228
229    /// `GET /product/{uuid}/cle`.
230    pub async fn get_product_cle(&self, id: ProductId) -> Result<CleFetch, ClientError> {
231        self.cle(&format!("product/{id}/cle")).await
232    }
233
234    /// `GET /productReleases`.
235    pub async fn query_product_releases(
236        &self,
237        query: &libtea_core::ListParams<libtea_core::enums::ReleaseSort>,
238    ) -> Result<Page<ProductRelease>, ClientError> {
239        self.page("productReleases", query, |sort| sort.as_str())
240            .await
241    }
242
243    /// `GET /productRelease/{uuid}`.
244    pub async fn get_product_release(
245        &self,
246        id: ProductReleaseId,
247    ) -> Result<ProductReleaseWithCollection, ClientError> {
248        let bytes = self.get_bytes(&format!("productRelease/{id}"), &[]).await?;
249        Ok(parse_product_release(&bytes)?)
250    }
251
252    /// `GET /productRelease/{uuid}/cle`.
253    pub async fn get_product_release_cle(
254        &self,
255        id: ProductReleaseId,
256    ) -> Result<CleFetch, ClientError> {
257        self.cle(&format!("productRelease/{id}/cle")).await
258    }
259
260    /// `GET /productRelease/{uuid}/collections`.
261    pub async fn list_product_release_collections(
262        &self,
263        id: ProductReleaseId,
264        query: &libtea_core::ListParams<libtea_core::enums::CollectionSort>,
265    ) -> Result<Page<Collection>, ClientError> {
266        let page: Page<Collection> = self
267            .page(&format!("productRelease/{id}/collections"), query, |sort| {
268                sort.as_str()
269            })
270            .await?;
271        for collection in &page.results {
272            collection.validate()?;
273        }
274        Ok(page)
275    }
276
277    /// `GET /productRelease/{uuid}/collection/latest`.
278    pub async fn get_latest_product_release_collection(
279        &self,
280        id: ProductReleaseId,
281    ) -> Result<Collection, ClientError> {
282        let bytes = self
283            .get_bytes(&format!("productRelease/{id}/collection/latest"), &[])
284            .await?;
285        Ok(parse_collection(&bytes)?)
286    }
287
288    /// `GET /productRelease/{uuid}/collection/{version}`.
289    pub async fn get_product_release_collection(
290        &self,
291        id: ProductReleaseId,
292        version: u64,
293    ) -> Result<Collection, ClientError> {
294        let bytes = self
295            .get_bytes(&format!("productRelease/{id}/collection/{version}"), &[])
296            .await?;
297        Ok(parse_collection(&bytes)?)
298    }
299
300    /// `GET /components`.
301    pub async fn query_components(
302        &self,
303        query: &libtea_core::ListParams<libtea_core::enums::ComponentSort>,
304    ) -> Result<Page<Component>, ClientError> {
305        self.page("components", query, |sort| sort.as_str()).await
306    }
307
308    /// `GET /component/{uuid}`.
309    pub async fn get_component(&self, id: ComponentId) -> Result<Component, ClientError> {
310        self.get_json(&format!("component/{id}"), &[]).await
311    }
312
313    /// `GET /component/{uuid}/releases`.
314    pub async fn list_component_releases(
315        &self,
316        id: ComponentId,
317        query: &libtea_core::ListParams<libtea_core::enums::ReleaseSort>,
318    ) -> Result<Page<ComponentRelease>, ClientError> {
319        self.page(&format!("component/{id}/releases"), query, |sort| {
320            sort.as_str()
321        })
322        .await
323    }
324
325    /// `GET /component/{uuid}/cle`.
326    pub async fn get_component_cle(&self, id: ComponentId) -> Result<CleFetch, ClientError> {
327        self.cle(&format!("component/{id}/cle")).await
328    }
329
330    /// `GET /componentReleases`.
331    pub async fn query_component_releases(
332        &self,
333        query: &libtea_core::ListParams<libtea_core::enums::ReleaseSort>,
334    ) -> Result<Page<ComponentRelease>, ClientError> {
335        self.page("componentReleases", query, |sort| sort.as_str())
336            .await
337    }
338
339    /// `GET /componentRelease/{uuid}`.
340    pub async fn get_component_release(
341        &self,
342        id: ComponentReleaseId,
343    ) -> Result<ComponentReleaseWithCollection, ClientError> {
344        let bytes = self
345            .get_bytes(&format!("componentRelease/{id}"), &[])
346            .await?;
347        Ok(parse_component_release(&bytes)?)
348    }
349
350    /// `GET /componentRelease/{uuid}/cle`.
351    pub async fn get_component_release_cle(
352        &self,
353        id: ComponentReleaseId,
354    ) -> Result<CleFetch, ClientError> {
355        self.cle(&format!("componentRelease/{id}/cle")).await
356    }
357
358    /// `GET /componentRelease/{uuid}/collections`.
359    pub async fn list_component_release_collections(
360        &self,
361        id: ComponentReleaseId,
362        query: &libtea_core::ListParams<libtea_core::enums::CollectionSort>,
363    ) -> Result<Page<Collection>, ClientError> {
364        let page: Page<Collection> = self
365            .page(
366                &format!("componentRelease/{id}/collections"),
367                query,
368                |sort| sort.as_str(),
369            )
370            .await?;
371        for collection in &page.results {
372            collection.validate()?;
373        }
374        Ok(page)
375    }
376
377    /// `GET /componentRelease/{uuid}/collection/latest`.
378    pub async fn get_latest_component_release_collection(
379        &self,
380        id: ComponentReleaseId,
381    ) -> Result<Collection, ClientError> {
382        let bytes = self
383            .get_bytes(&format!("componentRelease/{id}/collection/latest"), &[])
384            .await?;
385        Ok(parse_collection(&bytes)?)
386    }
387
388    /// `GET /componentRelease/{uuid}/collection/{version}`.
389    pub async fn get_component_release_collection(
390        &self,
391        id: ComponentReleaseId,
392        version: u64,
393    ) -> Result<Collection, ClientError> {
394        let bytes = self
395            .get_bytes(&format!("componentRelease/{id}/collection/{version}"), &[])
396            .await?;
397        Ok(parse_collection(&bytes)?)
398    }
399
400    /// `GET /artifact/{uuid}/latest`.
401    pub async fn get_latest_artifact(
402        &self,
403        id: libtea_core::ArtifactId,
404    ) -> Result<Artifact, ClientError> {
405        let bytes = self
406            .get_bytes(&format!("artifact/{id}/latest"), &[])
407            .await?;
408        Ok(parse_artifact(&bytes)?)
409    }
410
411    /// `GET /artifact/{uuid}/{version}`.
412    pub async fn get_artifact(
413        &self,
414        id: libtea_core::ArtifactId,
415        version: u64,
416    ) -> Result<Artifact, ClientError> {
417        let bytes = self
418            .get_bytes(&format!("artifact/{id}/{version}"), &[])
419            .await?;
420        Ok(parse_artifact(&bytes)?)
421    }
422
423    /// Download one format of an artifact revision.
424    ///
425    /// When the format has `url`, that external URL is fetched and the TEA
426    /// access token is not sent. Otherwise the versioned download endpoint is
427    /// used. Declared checksums are checked over the bytes left after HTTP
428    /// content coding is removed (integrity of decoded bytes, not authenticity).
429    pub async fn download_format(
430        &self,
431        artifact: &Artifact,
432        media_type: &str,
433        if_none_match: Option<&str>,
434    ) -> Result<ArtifactFetch, ClientError> {
435        let format = artifact.format(media_type).ok_or_else(|| {
436            ClientError::Model(libtea_core::ModelError::Invalid(format!(
437                "artifact has no format `{media_type}`"
438            )))
439        })?;
440        format.validate()?;
441        let checksums = format.checksums.clone().unwrap_or_default();
442        if let Some(external) = &format.url {
443            let url = Url::parse(external).map_err(|_| {
444                ClientError::Model(libtea_core::ModelError::Invalid(
445                    "external artifact URL".into(),
446                ))
447            })?;
448            return self
449                .download_url(url, None, if_none_match, &checksums, false)
450                .await;
451        }
452        self.download_api(
453            &format!("artifact/{}/{}/download", artifact.uuid, artifact.version),
454            Some(media_type),
455            if_none_match,
456            &checksums,
457        )
458        .await
459    }
460
461    /// `GET /artifact/{uuid}/latest/download`.
462    pub async fn download_latest_artifact(
463        &self,
464        id: libtea_core::ArtifactId,
465        media_type: Option<&str>,
466        checksums: &[Checksum],
467        if_none_match: Option<&str>,
468    ) -> Result<ArtifactFetch, ClientError> {
469        self.download_api(
470            &format!("artifact/{id}/latest/download"),
471            media_type,
472            if_none_match,
473            checksums,
474        )
475        .await
476    }
477
478    /// `GET /artifact/{uuid}/{version}/download`.
479    pub async fn download_artifact(
480        &self,
481        id: libtea_core::ArtifactId,
482        version: u64,
483        media_type: Option<&str>,
484        checksums: &[Checksum],
485        if_none_match: Option<&str>,
486    ) -> Result<ArtifactFetch, ClientError> {
487        self.download_api(
488            &format!("artifact/{id}/{version}/download"),
489            media_type,
490            if_none_match,
491            checksums,
492        )
493        .await
494    }
495
496    /// Download a detached signature for one content format.
497    ///
498    /// `media_type` selects the artifact format, not the signature's own media type.
499    /// An external `signatureUrl` is fetched without a TEA access token.
500    pub async fn download_signature_for_format(
501        &self,
502        artifact: &Artifact,
503        media_type: &str,
504        if_none_match: Option<&str>,
505    ) -> Result<SignatureFetch, ClientError> {
506        let format = artifact.format(media_type).ok_or_else(|| {
507            ClientError::Model(libtea_core::ModelError::Invalid(format!(
508                "artifact has no format `{media_type}`"
509            )))
510        })?;
511        if let Some(external) = &format.signature_url {
512            let url = Url::parse(external).map_err(|_| {
513                ClientError::Model(libtea_core::ModelError::Invalid(
514                    "external artifact URL".into(),
515                ))
516            })?;
517            return match self
518                .download_url(url, None, if_none_match, &[], false)
519                .await?
520            {
521                ArtifactFetch::Body(body) => Ok(SignatureFetch::Present(Box::new(body))),
522                ArtifactFetch::NotModified { etag, .. } => Ok(SignatureFetch::NotModified { etag }),
523            };
524        }
525        self.signature_api(
526            &format!(
527                "artifact/{}/{}/signature/download",
528                artifact.uuid, artifact.version
529            ),
530            Some(media_type),
531            if_none_match,
532        )
533        .await
534    }
535
536    /// `GET /artifact/{uuid}/{version}/signature/download`.
537    pub async fn download_signature(
538        &self,
539        id: libtea_core::ArtifactId,
540        version: u64,
541        media_type: Option<&str>,
542        if_none_match: Option<&str>,
543    ) -> Result<SignatureFetch, ClientError> {
544        self.signature_api(
545            &format!("artifact/{id}/{version}/signature/download"),
546            media_type,
547            if_none_match,
548        )
549        .await
550    }
551
552    /// `GET /artifact/{uuid}/latest/signature/download`.
553    pub async fn download_latest_signature(
554        &self,
555        id: libtea_core::ArtifactId,
556        media_type: Option<&str>,
557        if_none_match: Option<&str>,
558    ) -> Result<SignatureFetch, ClientError> {
559        self.signature_api(
560            &format!("artifact/{id}/latest/signature/download"),
561            media_type,
562            if_none_match,
563        )
564        .await
565    }
566
567    /// `HEAD` the versioned artifact download and return the response headers without a body.
568    pub async fn head_artifact(
569        &self,
570        id: libtea_core::ArtifactId,
571        version: u64,
572        media_type: Option<&str>,
573    ) -> Result<std::collections::HashMap<String, String>, ClientError> {
574        let mut query = Vec::new();
575        if let Some(media_type) = media_type {
576            query.push(("mediaType", media_type));
577        }
578        let url = operation_url(
579            &self.prefix,
580            &format!("artifact/{id}/{version}/download"),
581            &query,
582        )?;
583        let response = self
584            .client
585            .inner
586            .send(Call {
587                method: reqwest::Method::HEAD,
588                url,
589                api_prefix: Some(self.prefix.clone()),
590                artifact: true,
591                body: None,
592                content_type: None,
593                basic_auth: false,
594                if_none_match: None,
595                if_modified_since: None,
596                max_body: 0,
597            })
598            .await?;
599        if !response.status.is_success() && response.status.as_u16() != 304 {
600            return Err(map_api_error(&response));
601        }
602        let mut headers = std::collections::HashMap::new();
603        for (name, value) in response.headers.iter() {
604            if name == reqwest::header::AUTHORIZATION {
605                continue;
606            }
607            if let Ok(text) = value.to_str() {
608                headers.insert(name.to_string(), text.to_owned());
609            }
610        }
611        Ok(headers)
612    }
613
614    async fn page<T, S, F>(
615        &self,
616        path: &str,
617        query: &libtea_core::ListParams<S>,
618        sort_name: F,
619    ) -> Result<Page<T>, ClientError>
620    where
621        T: DeserializeOwned,
622        F: Fn(&S) -> &'static str,
623    {
624        query.validate()?;
625        let mut pairs: Vec<(String, String)> = Vec::new();
626        if let Some(size) = query.page_size {
627            pairs.push(("pageSize".into(), size.to_string()));
628        }
629        if let Some(token) = &query.page_token {
630            pairs.push(("pageToken".into(), token.clone()));
631        }
632        if let Some(field) = &query.sort_field {
633            pairs.push(("sortField".into(), sort_name(field).to_owned()));
634        }
635        if let Some(order) = query.sort_order {
636            pairs.push(("sortOrder".into(), order.as_str().to_owned()));
637        }
638        if let Some(id_type) = &query.id_type {
639            pairs.push(("idType".into(), id_type.as_str().to_owned()));
640        }
641        if let Some(id_value) = &query.id_value {
642            pairs.push(("idValue".into(), id_value.clone()));
643        }
644        let borrowed: Vec<(&str, &str)> = pairs
645            .iter()
646            .map(|(k, v)| (k.as_str(), v.as_str()))
647            .collect();
648        self.get_json(path, &borrowed).await
649    }
650
651    async fn cle(&self, path: &str) -> Result<CleFetch, ClientError> {
652        let response = self.get_raw(path, &[], false).await?;
653        if response.status.as_u16() == 404 {
654            if let Some(code) = libtea_core::tea_error_code(
655                header_str(&response.headers, CONTENT_TYPE_HEADER),
656                &response.body,
657            ) {
658                if code == "NOT_IMPLEMENTED" {
659                    let message = libtea_core::TeaErrorBody::parse(&response.body)
660                        .ok()
661                        .and_then(|body| body.message);
662                    return Ok(CleFetch::NotImplemented { message });
663                }
664            }
665            return Err(map_api_error(&response));
666        }
667        if !response.status.is_success() {
668            return Err(map_api_error(&response));
669        }
670        require_json(&response)?;
671        Ok(CleFetch::Events(serde_json::from_slice(&response.body)?))
672    }
673
674    async fn get_json<T: DeserializeOwned>(
675        &self,
676        path: &str,
677        query: &[(&str, &str)],
678    ) -> Result<T, ClientError> {
679        let bytes = self.get_bytes(path, query).await?;
680        Ok(serde_json::from_slice(&bytes)?)
681    }
682
683    async fn get_bytes(&self, path: &str, query: &[(&str, &str)]) -> Result<Vec<u8>, ClientError> {
684        let response = self.get_raw(path, query, false).await?;
685        if !response.status.is_success() {
686            return Err(map_api_error(&response));
687        }
688        require_json(&response)?;
689        Ok(response.body.to_vec())
690    }
691
692    async fn get_raw(
693        &self,
694        path: &str,
695        query: &[(&str, &str)],
696        artifact: bool,
697    ) -> Result<crate::transport::RawResponse, ClientError> {
698        let url = operation_url(&self.prefix, path, query)?;
699        self.client
700            .inner
701            .send(Call {
702                method: reqwest::Method::GET,
703                url,
704                api_prefix: Some(self.prefix.clone()),
705                artifact,
706                body: None,
707                content_type: None,
708                basic_auth: false,
709                if_none_match: None,
710                if_modified_since: None,
711                max_body: if artifact {
712                    self.client.inner.limits.max_artifact_bytes
713                } else {
714                    self.client.inner.limits.max_json_bytes
715                },
716            })
717            .await
718    }
719
720    async fn download_api(
721        &self,
722        path: &str,
723        media_type: Option<&str>,
724        if_none_match: Option<&str>,
725        checksums: &[Checksum],
726    ) -> Result<ArtifactFetch, ClientError> {
727        let mut query = Vec::new();
728        if let Some(media_type) = media_type {
729            query.push(("mediaType", media_type));
730        }
731        let url = operation_url(&self.prefix, path, &query)?;
732        self.download_url(
733            url,
734            Some(self.prefix.clone()),
735            if_none_match,
736            checksums,
737            true,
738        )
739        .await
740    }
741
742    async fn download_url(
743        &self,
744        url: Url,
745        api_prefix: Option<Url>,
746        if_none_match: Option<&str>,
747        checksums: &[Checksum],
748        under_api: bool,
749    ) -> Result<ArtifactFetch, ClientError> {
750        let response = self
751            .client
752            .inner
753            .send(Call {
754                method: reqwest::Method::GET,
755                url,
756                api_prefix: if under_api { api_prefix } else { None },
757                artifact: true,
758                body: None,
759                content_type: None,
760                basic_auth: false,
761                if_none_match: if_none_match.map(str::to_owned),
762                if_modified_since: None,
763                max_body: self.client.inner.limits.max_artifact_bytes,
764            })
765            .await?;
766        if response.status.as_u16() == 304 {
767            return Ok(ArtifactFetch::NotModified {
768                etag: header_string(&response, "etag"),
769                cache_control: header_string(&response, "cache-control"),
770                vary: header_string(&response, "vary"),
771            });
772        }
773        if !response.status.is_success() {
774            return Err(map_api_error(&response));
775        }
776        let encoding = header_string(&response, "content-encoding");
777        let decoded = if response.content_decoded {
778            response.body.to_vec()
779        } else {
780            libtea_core::checksum::decode_content_coding(
781                &response.body,
782                encoding.as_deref(),
783                self.client.inner.limits.max_artifact_bytes,
784            )?
785        };
786        let integrity = libtea_core::verify_checksums_with_policy(
787            &decoded,
788            checksums,
789            self.client.inner.checksum_policy,
790        );
791        if !matches!(
792            integrity.outcome,
793            IntegrityOutcome::Verified | IntegrityOutcome::NotDeclared
794        ) {
795            // Bytes that came from the cache and failed their checksums must
796            // not stay there to be served (or renewed by a 304) again.
797            response.evict_cached().await;
798            return Err(ClientError::Integrity {
799                outcome: integrity.outcome.clone(),
800                report: integrity,
801            });
802        }
803        // The body passed its checks; only now may the cache keep it.
804        response.commit_cache().await;
805        let etag = header_string(&response, "etag");
806        let strong_etag = etag
807            .as_ref()
808            .is_some_and(|value| !value.trim().starts_with("W/"));
809        Ok(ArtifactFetch::Body(DownloadedArtifact {
810            bytes: decoded,
811            content_type: header_string(&response, "content-type"),
812            content_encoding: encoding,
813            etag,
814            strong_etag,
815            cache_control: header_string(&response, "cache-control"),
816            content_location: header_string(&response, "content-location"),
817            vary: header_string(&response, "vary"),
818            repr_digest: header_string(&response, "repr-digest"),
819            final_url: response.final_url.to_string(),
820            integrity,
821        }))
822    }
823
824    async fn signature_api(
825        &self,
826        path: &str,
827        media_type: Option<&str>,
828        if_none_match: Option<&str>,
829    ) -> Result<SignatureFetch, ClientError> {
830        match self
831            .download_api(path, media_type, if_none_match, &[])
832            .await
833        {
834            Ok(ArtifactFetch::Body(body)) => Ok(SignatureFetch::Present(Box::new(body))),
835            Ok(ArtifactFetch::NotModified { etag, .. }) => Ok(SignatureFetch::NotModified { etag }),
836            Err(ClientError::Api {
837                status: 404,
838                tea_error: Some(code),
839                ..
840            }) if code == "SIGNATURE_NOT_FOUND" => Ok(SignatureFetch::NotPublished),
841            Err(other) => Err(other),
842        }
843    }
844}
845
846fn require_json(response: &crate::transport::RawResponse) -> Result<(), ClientError> {
847    if is_json_content_type(header_str(&response.headers, CONTENT_TYPE_HEADER)) {
848        Ok(())
849    } else {
850        Err(ClientError::Model(libtea_core::ModelError::Invalid(
851            "expected application/json".into(),
852        )))
853    }
854}
855
856fn header_string(response: &crate::transport::RawResponse, name: &str) -> Option<String> {
857    response
858        .headers
859        .get(name)
860        .and_then(|value| value.to_str().ok())
861        .map(str::to_owned)
862}