LCOV - code coverage report
Current view: top level - safekeeper/src/http - client.rs (source / functions) Coverage Total Hit
Test: 960803fca14b2e843c565dddf575f7017d250bc3.info Lines: 0.0 % 75 0
Test Date: 2024-06-22 23:41:44 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 utils::{
      12              :     http::error::HttpErrorBody,
      13              :     id::{TenantId, TimelineId},
      14              :     logging::SecretString,
      15              : };
      16              : 
      17              : use super::routes::TimelineStatus;
      18              : 
      19              : #[derive(Debug, Clone)]
      20              : pub struct Client {
      21              :     mgmt_api_endpoint: String,
      22              :     authorization_header: Option<SecretString>,
      23              :     client: reqwest::Client,
      24              : }
      25              : 
      26            0 : #[derive(thiserror::Error, Debug)]
      27              : pub enum Error {
      28              :     /// Failed to receive body (reqwest error).
      29              :     #[error("receive body: {0}")]
      30              :     ReceiveBody(reqwest::Error),
      31              : 
      32              :     /// Status is not ok, but failed to parse body as `HttpErrorBody`.
      33              :     #[error("receive error body: {0}")]
      34              :     ReceiveErrorBody(String),
      35              : 
      36              :     /// Status is not ok; parsed error in body as `HttpErrorBody`.
      37              :     #[error("safekeeper API: {1}")]
      38              :     ApiError(StatusCode, String),
      39              : }
      40              : 
      41              : pub type Result<T> = std::result::Result<T, Error>;
      42              : 
      43              : pub trait ResponseErrorMessageExt: Sized {
      44              :     fn error_from_body(self) -> impl std::future::Future<Output = Result<Self>> + Send;
      45              : }
      46              : 
      47              : /// If status is not ok, try to extract error message from the body.
      48              : impl ResponseErrorMessageExt for reqwest::Response {
      49            0 :     async fn error_from_body(self) -> Result<Self> {
      50            0 :         let status = self.status();
      51            0 :         if !(status.is_client_error() || status.is_server_error()) {
      52            0 :             return Ok(self);
      53            0 :         }
      54            0 : 
      55            0 :         let url = self.url().to_owned();
      56            0 :         Err(match self.json::<HttpErrorBody>().await {
      57            0 :             Ok(HttpErrorBody { msg }) => Error::ApiError(status, msg),
      58              :             Err(_) => {
      59            0 :                 Error::ReceiveErrorBody(format!("http error ({}) at {}.", status.as_u16(), url))
      60              :             }
      61              :         })
      62            0 :     }
      63              : }
      64              : 
      65              : impl Client {
      66            0 :     pub fn new(mgmt_api_endpoint: String, jwt: Option<SecretString>) -> Self {
      67            0 :         Self::from_client(reqwest::Client::new(), mgmt_api_endpoint, jwt)
      68            0 :     }
      69              : 
      70            0 :     pub fn from_client(
      71            0 :         client: reqwest::Client,
      72            0 :         mgmt_api_endpoint: String,
      73            0 :         jwt: Option<SecretString>,
      74            0 :     ) -> Self {
      75            0 :         Self {
      76            0 :             mgmt_api_endpoint,
      77            0 :             authorization_header: jwt
      78            0 :                 .map(|jwt| SecretString::from(format!("Bearer {}", jwt.get_contents()))),
      79            0 :             client,
      80            0 :         }
      81            0 :     }
      82              : 
      83            0 :     pub async fn timeline_status(
      84            0 :         &self,
      85            0 :         tenant_id: TenantId,
      86            0 :         timeline_id: TimelineId,
      87            0 :     ) -> Result<TimelineStatus> {
      88            0 :         let uri = format!(
      89            0 :             "{}/v1/tenant/{}/timeline/{}",
      90            0 :             self.mgmt_api_endpoint, tenant_id, timeline_id
      91            0 :         );
      92            0 :         let resp = self.get(&uri).await?;
      93            0 :         resp.json().await.map_err(Error::ReceiveBody)
      94            0 :     }
      95              : 
      96            0 :     pub async fn snapshot(
      97            0 :         &self,
      98            0 :         tenant_id: TenantId,
      99            0 :         timeline_id: TimelineId,
     100            0 :     ) -> Result<reqwest::Response> {
     101            0 :         let uri = format!(
     102            0 :             "{}/v1/tenant/{}/timeline/{}/snapshot",
     103            0 :             self.mgmt_api_endpoint, tenant_id, timeline_id
     104            0 :         );
     105            0 :         self.get(&uri).await
     106            0 :     }
     107              : 
     108            0 :     async fn get<U: IntoUrl>(&self, uri: U) -> Result<reqwest::Response> {
     109            0 :         self.request(Method::GET, uri, ()).await
     110            0 :     }
     111              : 
     112              :     /// Send the request and check that the status code is good.
     113            0 :     async fn request<B: serde::Serialize, U: reqwest::IntoUrl>(
     114            0 :         &self,
     115            0 :         method: Method,
     116            0 :         uri: U,
     117            0 :         body: B,
     118            0 :     ) -> Result<reqwest::Response> {
     119            0 :         let res = self.request_noerror(method, uri, body).await?;
     120            0 :         let response = res.error_from_body().await?;
     121            0 :         Ok(response)
     122            0 :     }
     123              : 
     124              :     /// Just send the request.
     125            0 :     async fn request_noerror<B: serde::Serialize, U: reqwest::IntoUrl>(
     126            0 :         &self,
     127            0 :         method: Method,
     128            0 :         uri: U,
     129            0 :         body: B,
     130            0 :     ) -> Result<reqwest::Response> {
     131            0 :         let req = self.client.request(method, uri);
     132            0 :         let req = if let Some(value) = &self.authorization_header {
     133            0 :             req.header(reqwest::header::AUTHORIZATION, value.get_contents())
     134              :         } else {
     135            0 :             req
     136              :         };
     137            0 :         req.json(&body).send().await.map_err(Error::ReceiveBody)
     138            0 :     }
     139              : }
        

Generated by: LCOV version 2.1-beta