LCOV - code coverage report
Current view: top level - safekeeper/src/http - client.rs (source / functions) Coverage Total Hit
Test: bb45db3982713bfd5bec075773079136e362195e.info Lines: 0.0 % 76 0
Test Date: 2024-12-11 15:53:32 Functions: 0.0 % 16 0

            Line data    Source code
       1              : //! Safekeeper http client.
       2              : //!
       3              : //! Partially copied from pageserver client; some parts might be better to be
       4              : //! united.
       5              : //!
       6              : //! It would be also good to move it out to separate crate, but this needs
       7              : //! duplication of internal-but-reported structs like WalSenderState, ServerInfo
       8              : //! etc.
       9              : 
      10              : use reqwest::{IntoUrl, Method, StatusCode};
      11              : use std::error::Error as _;
      12              : use utils::{
      13              :     http::error::HttpErrorBody,
      14              :     id::{NodeId, TenantId, TimelineId},
      15              :     logging::SecretString,
      16              : };
      17              : 
      18              : use super::routes::TimelineStatus;
      19              : 
      20              : #[derive(Debug, Clone)]
      21              : pub struct Client {
      22              :     mgmt_api_endpoint: String,
      23              :     authorization_header: Option<SecretString>,
      24              :     client: reqwest::Client,
      25              : }
      26              : 
      27              : #[derive(thiserror::Error, Debug)]
      28              : pub enum Error {
      29              :     /// Failed to receive body (reqwest error).
      30            0 :     #[error("receive body: {0}{}", .0.source().map(|e| format!(": {e}")).unwrap_or_default())]
      31              :     ReceiveBody(reqwest::Error),
      32              : 
      33              :     /// Status is not ok, but failed to parse body as `HttpErrorBody`.
      34              :     #[error("receive error body: {0}")]
      35              :     ReceiveErrorBody(String),
      36              : 
      37              :     /// Status is not ok; parsed error in body as `HttpErrorBody`.
      38              :     #[error("safekeeper API: {1}")]
      39              :     ApiError(StatusCode, String),
      40              : }
      41              : 
      42              : pub type Result<T> = std::result::Result<T, Error>;
      43              : 
      44              : pub trait ResponseErrorMessageExt: Sized {
      45              :     fn error_from_body(self) -> impl std::future::Future<Output = Result<Self>> + Send;
      46              : }
      47              : 
      48              : /// If status is not ok, try to extract error message from the body.
      49              : impl ResponseErrorMessageExt for reqwest::Response {
      50            0 :     async fn error_from_body(self) -> Result<Self> {
      51            0 :         let status = self.status();
      52            0 :         if !(status.is_client_error() || status.is_server_error()) {
      53            0 :             return Ok(self);
      54            0 :         }
      55            0 : 
      56            0 :         let url = self.url().to_owned();
      57            0 :         Err(match self.json::<HttpErrorBody>().await {
      58            0 :             Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg),
      59              :             Err(_) => {
      60            0 :                 Error::ReceiveErrorBody(format!("http error ({}) at {}.", status.as_u16(), url))
      61              :             }
      62              :         })
      63            0 :     }
      64              : }
      65              : 
      66              : impl Client {
      67            0 :     pub fn new(mgmt_api_endpoint: String, jwt: Option<SecretString>) -> Self {
      68            0 :         Self::from_client(reqwest::Client::new(), mgmt_api_endpoint, jwt)
      69            0 :     }
      70              : 
      71            0 :     pub fn from_client(
      72            0 :         client: reqwest::Client,
      73            0 :         mgmt_api_endpoint: String,
      74            0 :         jwt: Option<SecretString>,
      75            0 :     ) -> Self {
      76            0 :         Self {
      77            0 :             mgmt_api_endpoint,
      78            0 :             authorization_header: jwt
      79            0 :                 .map(|jwt| SecretString::from(format!("Bearer {}", jwt.get_contents()))),
      80            0 :             client,
      81            0 :         }
      82            0 :     }
      83              : 
      84            0 :     pub async fn timeline_status(
      85            0 :         &self,
      86            0 :         tenant_id: TenantId,
      87            0 :         timeline_id: TimelineId,
      88            0 :     ) -> Result<TimelineStatus> {
      89            0 :         let uri = format!(
      90            0 :             "{}/v1/tenant/{}/timeline/{}",
      91            0 :             self.mgmt_api_endpoint, tenant_id, timeline_id
      92            0 :         );
      93            0 :         let resp = self.get(&uri).await?;
      94            0 :         resp.json().await.map_err(Error::ReceiveBody)
      95            0 :     }
      96              : 
      97            0 :     pub async fn snapshot(
      98            0 :         &self,
      99            0 :         tenant_id: TenantId,
     100            0 :         timeline_id: TimelineId,
     101            0 :         stream_to: NodeId,
     102            0 :     ) -> Result<reqwest::Response> {
     103            0 :         let uri = format!(
     104            0 :             "{}/v1/tenant/{}/timeline/{}/snapshot/{}",
     105            0 :             self.mgmt_api_endpoint, tenant_id, timeline_id, stream_to.0
     106            0 :         );
     107            0 :         self.get(&uri).await
     108            0 :     }
     109              : 
     110            0 :     async fn get<U: IntoUrl>(&self, uri: U) -> Result<reqwest::Response> {
     111            0 :         self.request(Method::GET, uri, ()).await
     112            0 :     }
     113              : 
     114              :     /// Send the request and check that the status code is good.
     115            0 :     async fn request<B: serde::Serialize, U: reqwest::IntoUrl>(
     116            0 :         &self,
     117            0 :         method: Method,
     118            0 :         uri: U,
     119            0 :         body: B,
     120            0 :     ) -> Result<reqwest::Response> {
     121            0 :         let res = self.request_noerror(method, uri, body).await?;
     122            0 :         let response = res.error_from_body().await?;
     123            0 :         Ok(response)
     124            0 :     }
     125              : 
     126              :     /// Just send the request.
     127            0 :     async fn request_noerror<B: serde::Serialize, U: reqwest::IntoUrl>(
     128            0 :         &self,
     129            0 :         method: Method,
     130            0 :         uri: U,
     131            0 :         body: B,
     132            0 :     ) -> Result<reqwest::Response> {
     133            0 :         let req = self.client.request(method, uri);
     134            0 :         let req = if let Some(value) = &self.authorization_header {
     135            0 :             req.header(reqwest::header::AUTHORIZATION, value.get_contents())
     136              :         } else {
     137            0 :             req
     138              :         };
     139            0 :         req.json(&body).send().await.map_err(Error::ReceiveBody)
     140            0 :     }
     141              : }
        

Generated by: LCOV version 2.1-beta