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    /// Resolve a Package URL on this already-known API base, and choose the
201    /// server and version to call next for each release, as
202    /// [`Client::discover`] does for a TEI.
203    ///
204    /// A PURL names no server, so there is no `.well-known` step: the base is
205    /// the caller's. The PURL is sent exactly as it was parsed
206    /// ([`Purl::as_str`](libtea_core::Purl::as_str)), never in canonical form,
207    /// since the server matches the identifiers it stores.
208    ///
209    /// # Errors
210    ///
211    /// Returns [`ClientError::Unresolved`] for a TEA 404 (not evidence that
212    /// no release exists), and an error when a release has no server with a
213    /// supported version.
214    pub async fn discover_purl(
215        &self,
216        purl: &libtea_core::Purl,
217    ) -> Result<Vec<crate::ResolvedRelease>, ClientError> {
218        let releases = self.discover_identifier(None, Some(purl.as_str())).await?;
219        crate::resolve_releases(releases, &self.client.inner.supported)
220    }
221
222    /// `GET /products`.
223    ///
224    /// # Errors
225    ///
226    /// Returns an error on transport failure or a non-success status.
227    pub async fn query_products(
228        &self,
229        query: &libtea_core::ListParams<libtea_core::enums::ProductSort>,
230    ) -> Result<Page<Product>, ClientError> {
231        self.page("products", query, |sort| sort.as_str()).await
232    }
233
234    /// `GET /product/{uuid}`.
235    pub async fn get_product(&self, id: ProductId) -> Result<Product, ClientError> {
236        self.get_json(&format!("product/{id}"), &[]).await
237    }
238
239    /// `GET /product/{uuid}/releases`.
240    pub async fn list_product_releases(
241        &self,
242        id: ProductId,
243        query: &libtea_core::ListParams<libtea_core::enums::ReleaseSort>,
244    ) -> Result<Page<ProductRelease>, ClientError> {
245        self.page(&format!("product/{id}/releases"), query, |sort| {
246            sort.as_str()
247        })
248        .await
249    }
250
251    /// `GET /product/{uuid}/cle`.
252    pub async fn get_product_cle(&self, id: ProductId) -> Result<CleFetch, ClientError> {
253        self.cle(&format!("product/{id}/cle")).await
254    }
255
256    /// `GET /productReleases`.
257    pub async fn query_product_releases(
258        &self,
259        query: &libtea_core::ListParams<libtea_core::enums::ReleaseSort>,
260    ) -> Result<Page<ProductRelease>, ClientError> {
261        self.page("productReleases", query, |sort| sort.as_str())
262            .await
263    }
264
265    /// `GET /productRelease/{uuid}`.
266    pub async fn get_product_release(
267        &self,
268        id: ProductReleaseId,
269    ) -> Result<ProductReleaseWithCollection, ClientError> {
270        let bytes = self.get_bytes(&format!("productRelease/{id}"), &[]).await?;
271        Ok(parse_product_release(&bytes)?)
272    }
273
274    /// `GET /productRelease/{uuid}/cle`.
275    pub async fn get_product_release_cle(
276        &self,
277        id: ProductReleaseId,
278    ) -> Result<CleFetch, ClientError> {
279        self.cle(&format!("productRelease/{id}/cle")).await
280    }
281
282    /// `GET /productRelease/{uuid}/collections`.
283    pub async fn list_product_release_collections(
284        &self,
285        id: ProductReleaseId,
286        query: &libtea_core::ListParams<libtea_core::enums::CollectionSort>,
287    ) -> Result<Page<Collection>, ClientError> {
288        let page: Page<Collection> = self
289            .page(&format!("productRelease/{id}/collections"), query, |sort| {
290                sort.as_str()
291            })
292            .await?;
293        for collection in &page.results {
294            collection.validate()?;
295        }
296        Ok(page)
297    }
298
299    /// `GET /productRelease/{uuid}/collection/latest`.
300    pub async fn get_latest_product_release_collection(
301        &self,
302        id: ProductReleaseId,
303    ) -> Result<Collection, ClientError> {
304        let bytes = self
305            .get_bytes(&format!("productRelease/{id}/collection/latest"), &[])
306            .await?;
307        Ok(parse_collection(&bytes)?)
308    }
309
310    /// `GET /productRelease/{uuid}/collection/{version}`.
311    pub async fn get_product_release_collection(
312        &self,
313        id: ProductReleaseId,
314        version: u64,
315    ) -> Result<Collection, ClientError> {
316        let bytes = self
317            .get_bytes(&format!("productRelease/{id}/collection/{version}"), &[])
318            .await?;
319        Ok(parse_collection(&bytes)?)
320    }
321
322    /// `GET /components`.
323    pub async fn query_components(
324        &self,
325        query: &libtea_core::ListParams<libtea_core::enums::ComponentSort>,
326    ) -> Result<Page<Component>, ClientError> {
327        self.page("components", query, |sort| sort.as_str()).await
328    }
329
330    /// `GET /component/{uuid}`.
331    pub async fn get_component(&self, id: ComponentId) -> Result<Component, ClientError> {
332        self.get_json(&format!("component/{id}"), &[]).await
333    }
334
335    /// `GET /component/{uuid}/releases`.
336    pub async fn list_component_releases(
337        &self,
338        id: ComponentId,
339        query: &libtea_core::ListParams<libtea_core::enums::ReleaseSort>,
340    ) -> Result<Page<ComponentRelease>, ClientError> {
341        self.page(&format!("component/{id}/releases"), query, |sort| {
342            sort.as_str()
343        })
344        .await
345    }
346
347    /// `GET /component/{uuid}/cle`.
348    pub async fn get_component_cle(&self, id: ComponentId) -> Result<CleFetch, ClientError> {
349        self.cle(&format!("component/{id}/cle")).await
350    }
351
352    /// `GET /componentReleases`.
353    pub async fn query_component_releases(
354        &self,
355        query: &libtea_core::ListParams<libtea_core::enums::ReleaseSort>,
356    ) -> Result<Page<ComponentRelease>, ClientError> {
357        self.page("componentReleases", query, |sort| sort.as_str())
358            .await
359    }
360
361    /// `GET /componentRelease/{uuid}`.
362    pub async fn get_component_release(
363        &self,
364        id: ComponentReleaseId,
365    ) -> Result<ComponentReleaseWithCollection, ClientError> {
366        let bytes = self
367            .get_bytes(&format!("componentRelease/{id}"), &[])
368            .await?;
369        Ok(parse_component_release(&bytes)?)
370    }
371
372    /// `GET /componentRelease/{uuid}/cle`.
373    pub async fn get_component_release_cle(
374        &self,
375        id: ComponentReleaseId,
376    ) -> Result<CleFetch, ClientError> {
377        self.cle(&format!("componentRelease/{id}/cle")).await
378    }
379
380    /// `GET /componentRelease/{uuid}/collections`.
381    pub async fn list_component_release_collections(
382        &self,
383        id: ComponentReleaseId,
384        query: &libtea_core::ListParams<libtea_core::enums::CollectionSort>,
385    ) -> Result<Page<Collection>, ClientError> {
386        let page: Page<Collection> = self
387            .page(
388                &format!("componentRelease/{id}/collections"),
389                query,
390                |sort| sort.as_str(),
391            )
392            .await?;
393        for collection in &page.results {
394            collection.validate()?;
395        }
396        Ok(page)
397    }
398
399    /// `GET /componentRelease/{uuid}/collection/latest`.
400    pub async fn get_latest_component_release_collection(
401        &self,
402        id: ComponentReleaseId,
403    ) -> Result<Collection, ClientError> {
404        let bytes = self
405            .get_bytes(&format!("componentRelease/{id}/collection/latest"), &[])
406            .await?;
407        Ok(parse_collection(&bytes)?)
408    }
409
410    /// `GET /componentRelease/{uuid}/collection/{version}`.
411    pub async fn get_component_release_collection(
412        &self,
413        id: ComponentReleaseId,
414        version: u64,
415    ) -> Result<Collection, ClientError> {
416        let bytes = self
417            .get_bytes(&format!("componentRelease/{id}/collection/{version}"), &[])
418            .await?;
419        Ok(parse_collection(&bytes)?)
420    }
421
422    /// `GET /artifact/{uuid}/latest`.
423    pub async fn get_latest_artifact(
424        &self,
425        id: libtea_core::ArtifactId,
426    ) -> Result<Artifact, ClientError> {
427        let bytes = self
428            .get_bytes(&format!("artifact/{id}/latest"), &[])
429            .await?;
430        Ok(parse_artifact(&bytes)?)
431    }
432
433    /// `GET /artifact/{uuid}/{version}`.
434    pub async fn get_artifact(
435        &self,
436        id: libtea_core::ArtifactId,
437        version: u64,
438    ) -> Result<Artifact, ClientError> {
439        let bytes = self
440            .get_bytes(&format!("artifact/{id}/{version}"), &[])
441            .await?;
442        Ok(parse_artifact(&bytes)?)
443    }
444
445    /// Download one format of an artifact revision.
446    ///
447    /// When the format has `url`, that external URL is fetched and the TEA
448    /// access token is not sent. Otherwise the versioned download endpoint is
449    /// used. Declared checksums are checked over the bytes left after HTTP
450    /// content coding is removed (integrity of decoded bytes, not authenticity).
451    pub async fn download_format(
452        &self,
453        artifact: &Artifact,
454        media_type: &str,
455        if_none_match: Option<&str>,
456    ) -> Result<ArtifactFetch, ClientError> {
457        let format = artifact.format(media_type).ok_or_else(|| {
458            ClientError::Model(libtea_core::ModelError::Invalid(format!(
459                "artifact has no format `{media_type}`"
460            )))
461        })?;
462        format.validate()?;
463        let checksums = format.checksums.clone().unwrap_or_default();
464        if let Some(external) = &format.url {
465            let url = Url::parse(external).map_err(|_| {
466                ClientError::Model(libtea_core::ModelError::Invalid(
467                    "external artifact URL".into(),
468                ))
469            })?;
470            return self
471                .download_url(url, None, if_none_match, &checksums, false)
472                .await;
473        }
474        self.download_api(
475            &format!("artifact/{}/{}/download", artifact.uuid, artifact.version),
476            Some(media_type),
477            if_none_match,
478            &checksums,
479        )
480        .await
481    }
482
483    /// `GET /artifact/{uuid}/latest/download`.
484    pub async fn download_latest_artifact(
485        &self,
486        id: libtea_core::ArtifactId,
487        media_type: Option<&str>,
488        checksums: &[Checksum],
489        if_none_match: Option<&str>,
490    ) -> Result<ArtifactFetch, ClientError> {
491        self.download_api(
492            &format!("artifact/{id}/latest/download"),
493            media_type,
494            if_none_match,
495            checksums,
496        )
497        .await
498    }
499
500    /// `GET /artifact/{uuid}/{version}/download`.
501    pub async fn download_artifact(
502        &self,
503        id: libtea_core::ArtifactId,
504        version: u64,
505        media_type: Option<&str>,
506        checksums: &[Checksum],
507        if_none_match: Option<&str>,
508    ) -> Result<ArtifactFetch, ClientError> {
509        self.download_api(
510            &format!("artifact/{id}/{version}/download"),
511            media_type,
512            if_none_match,
513            checksums,
514        )
515        .await
516    }
517
518    /// Download a detached signature for one content format.
519    ///
520    /// `media_type` selects the artifact format, not the signature's own media type.
521    /// An external `signatureUrl` is fetched without a TEA access token.
522    pub async fn download_signature_for_format(
523        &self,
524        artifact: &Artifact,
525        media_type: &str,
526        if_none_match: Option<&str>,
527    ) -> Result<SignatureFetch, ClientError> {
528        let format = artifact.format(media_type).ok_or_else(|| {
529            ClientError::Model(libtea_core::ModelError::Invalid(format!(
530                "artifact has no format `{media_type}`"
531            )))
532        })?;
533        if let Some(external) = &format.signature_url {
534            let url = Url::parse(external).map_err(|_| {
535                ClientError::Model(libtea_core::ModelError::Invalid(
536                    "external artifact URL".into(),
537                ))
538            })?;
539            return match self
540                .download_url(url, None, if_none_match, &[], false)
541                .await?
542            {
543                ArtifactFetch::Body(body) => Ok(SignatureFetch::Present(Box::new(body))),
544                ArtifactFetch::NotModified { etag, .. } => Ok(SignatureFetch::NotModified { etag }),
545            };
546        }
547        self.signature_api(
548            &format!(
549                "artifact/{}/{}/signature/download",
550                artifact.uuid, artifact.version
551            ),
552            Some(media_type),
553            if_none_match,
554        )
555        .await
556    }
557
558    /// `GET /artifact/{uuid}/{version}/signature/download`.
559    pub async fn download_signature(
560        &self,
561        id: libtea_core::ArtifactId,
562        version: u64,
563        media_type: Option<&str>,
564        if_none_match: Option<&str>,
565    ) -> Result<SignatureFetch, ClientError> {
566        self.signature_api(
567            &format!("artifact/{id}/{version}/signature/download"),
568            media_type,
569            if_none_match,
570        )
571        .await
572    }
573
574    /// `GET /artifact/{uuid}/latest/signature/download`.
575    pub async fn download_latest_signature(
576        &self,
577        id: libtea_core::ArtifactId,
578        media_type: Option<&str>,
579        if_none_match: Option<&str>,
580    ) -> Result<SignatureFetch, ClientError> {
581        self.signature_api(
582            &format!("artifact/{id}/latest/signature/download"),
583            media_type,
584            if_none_match,
585        )
586        .await
587    }
588
589    /// `HEAD` the versioned artifact download and return the response headers without a body.
590    pub async fn head_artifact(
591        &self,
592        id: libtea_core::ArtifactId,
593        version: u64,
594        media_type: Option<&str>,
595    ) -> Result<std::collections::HashMap<String, String>, ClientError> {
596        let mut query = Vec::new();
597        if let Some(media_type) = media_type {
598            query.push(("mediaType", media_type));
599        }
600        let url = operation_url(
601            &self.prefix,
602            &format!("artifact/{id}/{version}/download"),
603            &query,
604        )?;
605        let response = self
606            .client
607            .inner
608            .send(Call {
609                method: reqwest::Method::HEAD,
610                url,
611                api_prefix: Some(self.prefix.clone()),
612                artifact: true,
613                body: None,
614                content_type: None,
615                basic_auth: false,
616                if_none_match: None,
617                if_modified_since: None,
618                max_body: 0,
619            })
620            .await?;
621        if !response.status.is_success() && response.status.as_u16() != 304 {
622            return Err(map_api_error(&response));
623        }
624        let mut headers = std::collections::HashMap::new();
625        for (name, value) in response.headers.iter() {
626            if name == reqwest::header::AUTHORIZATION {
627                continue;
628            }
629            if let Ok(text) = value.to_str() {
630                headers.insert(name.to_string(), text.to_owned());
631            }
632        }
633        Ok(headers)
634    }
635
636    async fn page<T, S, F>(
637        &self,
638        path: &str,
639        query: &libtea_core::ListParams<S>,
640        sort_name: F,
641    ) -> Result<Page<T>, ClientError>
642    where
643        T: DeserializeOwned,
644        F: Fn(&S) -> &'static str,
645    {
646        query.validate()?;
647        let mut pairs: Vec<(String, String)> = Vec::new();
648        if let Some(size) = query.page_size {
649            pairs.push(("pageSize".into(), size.to_string()));
650        }
651        if let Some(token) = &query.page_token {
652            pairs.push(("pageToken".into(), token.clone()));
653        }
654        if let Some(field) = &query.sort_field {
655            pairs.push(("sortField".into(), sort_name(field).to_owned()));
656        }
657        if let Some(order) = query.sort_order {
658            pairs.push(("sortOrder".into(), order.as_str().to_owned()));
659        }
660        if let Some(id_type) = &query.id_type {
661            pairs.push(("idType".into(), id_type.as_str().to_owned()));
662        }
663        if let Some(id_value) = &query.id_value {
664            pairs.push(("idValue".into(), id_value.clone()));
665        }
666        let borrowed: Vec<(&str, &str)> = pairs
667            .iter()
668            .map(|(k, v)| (k.as_str(), v.as_str()))
669            .collect();
670        self.get_json(path, &borrowed).await
671    }
672
673    async fn cle(&self, path: &str) -> Result<CleFetch, ClientError> {
674        let response = self.get_raw(path, &[], false).await?;
675        if response.status.as_u16() == 404 {
676            if let Some(code) = libtea_core::tea_error_code(
677                header_str(&response.headers, CONTENT_TYPE_HEADER),
678                &response.body,
679            ) {
680                if code == "NOT_IMPLEMENTED" {
681                    let message = libtea_core::TeaErrorBody::parse(&response.body)
682                        .ok()
683                        .and_then(|body| body.message);
684                    return Ok(CleFetch::NotImplemented { message });
685                }
686            }
687            return Err(map_api_error(&response));
688        }
689        if !response.status.is_success() {
690            return Err(map_api_error(&response));
691        }
692        require_json(&response)?;
693        Ok(CleFetch::Events(serde_json::from_slice(&response.body)?))
694    }
695
696    async fn get_json<T: DeserializeOwned>(
697        &self,
698        path: &str,
699        query: &[(&str, &str)],
700    ) -> Result<T, ClientError> {
701        let bytes = self.get_bytes(path, query).await?;
702        Ok(serde_json::from_slice(&bytes)?)
703    }
704
705    async fn get_bytes(&self, path: &str, query: &[(&str, &str)]) -> Result<Vec<u8>, ClientError> {
706        let response = self.get_raw(path, query, false).await?;
707        if !response.status.is_success() {
708            return Err(map_api_error(&response));
709        }
710        require_json(&response)?;
711        Ok(response.body.to_vec())
712    }
713
714    async fn get_raw(
715        &self,
716        path: &str,
717        query: &[(&str, &str)],
718        artifact: bool,
719    ) -> Result<crate::transport::RawResponse, ClientError> {
720        let url = operation_url(&self.prefix, path, query)?;
721        self.client
722            .inner
723            .send(Call {
724                method: reqwest::Method::GET,
725                url,
726                api_prefix: Some(self.prefix.clone()),
727                artifact,
728                body: None,
729                content_type: None,
730                basic_auth: false,
731                if_none_match: None,
732                if_modified_since: None,
733                max_body: if artifact {
734                    self.client.inner.limits.max_artifact_bytes
735                } else {
736                    self.client.inner.limits.max_json_bytes
737                },
738            })
739            .await
740    }
741
742    async fn download_api(
743        &self,
744        path: &str,
745        media_type: Option<&str>,
746        if_none_match: Option<&str>,
747        checksums: &[Checksum],
748    ) -> Result<ArtifactFetch, ClientError> {
749        let mut query = Vec::new();
750        if let Some(media_type) = media_type {
751            query.push(("mediaType", media_type));
752        }
753        let url = operation_url(&self.prefix, path, &query)?;
754        self.download_url(
755            url,
756            Some(self.prefix.clone()),
757            if_none_match,
758            checksums,
759            true,
760        )
761        .await
762    }
763
764    async fn download_url(
765        &self,
766        url: Url,
767        api_prefix: Option<Url>,
768        if_none_match: Option<&str>,
769        checksums: &[Checksum],
770        under_api: bool,
771    ) -> Result<ArtifactFetch, ClientError> {
772        let response = self
773            .client
774            .inner
775            .send(Call {
776                method: reqwest::Method::GET,
777                url,
778                api_prefix: if under_api { api_prefix } else { None },
779                artifact: true,
780                body: None,
781                content_type: None,
782                basic_auth: false,
783                if_none_match: if_none_match.map(str::to_owned),
784                if_modified_since: None,
785                max_body: self.client.inner.limits.max_artifact_bytes,
786            })
787            .await?;
788        if response.status.as_u16() == 304 {
789            return Ok(ArtifactFetch::NotModified {
790                etag: header_string(&response, "etag"),
791                cache_control: header_string(&response, "cache-control"),
792                vary: header_string(&response, "vary"),
793            });
794        }
795        if !response.status.is_success() {
796            return Err(map_api_error(&response));
797        }
798        let encoding = header_string(&response, "content-encoding");
799        let decoded = if response.content_decoded {
800            response.body.to_vec()
801        } else {
802            libtea_core::checksum::decode_content_coding(
803                &response.body,
804                encoding.as_deref(),
805                self.client.inner.limits.max_artifact_bytes,
806            )?
807        };
808        let integrity = libtea_core::verify_checksums_with_policy(
809            &decoded,
810            checksums,
811            self.client.inner.checksum_policy,
812        );
813        if !matches!(
814            integrity.outcome,
815            IntegrityOutcome::Verified | IntegrityOutcome::NotDeclared
816        ) {
817            // Bytes that came from the cache and failed their checksums must
818            // not stay there to be served (or renewed by a 304) again.
819            response.evict_cached().await;
820            return Err(ClientError::Integrity {
821                outcome: integrity.outcome.clone(),
822                report: integrity,
823            });
824        }
825        // The body passed its checks; only now may the cache keep it.
826        response.commit_cache().await;
827        let etag = header_string(&response, "etag");
828        let strong_etag = etag
829            .as_ref()
830            .is_some_and(|value| !value.trim().starts_with("W/"));
831        Ok(ArtifactFetch::Body(DownloadedArtifact {
832            bytes: decoded,
833            content_type: header_string(&response, "content-type"),
834            content_encoding: encoding,
835            etag,
836            strong_etag,
837            cache_control: header_string(&response, "cache-control"),
838            content_location: header_string(&response, "content-location"),
839            vary: header_string(&response, "vary"),
840            repr_digest: header_string(&response, "repr-digest"),
841            final_url: response.final_url.to_string(),
842            integrity,
843        }))
844    }
845
846    async fn signature_api(
847        &self,
848        path: &str,
849        media_type: Option<&str>,
850        if_none_match: Option<&str>,
851    ) -> Result<SignatureFetch, ClientError> {
852        match self
853            .download_api(path, media_type, if_none_match, &[])
854            .await
855        {
856            Ok(ArtifactFetch::Body(body)) => Ok(SignatureFetch::Present(Box::new(body))),
857            Ok(ArtifactFetch::NotModified { etag, .. }) => Ok(SignatureFetch::NotModified { etag }),
858            Err(ClientError::Api {
859                status: 404,
860                tea_error: Some(code),
861                ..
862            }) if code == "SIGNATURE_NOT_FOUND" => Ok(SignatureFetch::NotPublished),
863            Err(other) => Err(other),
864        }
865    }
866}
867
868fn require_json(response: &crate::transport::RawResponse) -> Result<(), ClientError> {
869    if is_json_content_type(header_str(&response.headers, CONTENT_TYPE_HEADER)) {
870        Ok(())
871    } else {
872        Err(ClientError::Model(libtea_core::ModelError::Invalid(
873            "expected application/json".into(),
874        )))
875    }
876}
877
878fn header_string(response: &crate::transport::RawResponse, name: &str) -> Option<String> {
879    response
880        .headers
881        .get(name)
882        .and_then(|value| value.to_str().ok())
883        .map(str::to_owned)
884}