LCOV - code coverage report
Current view: top level - safekeeper/src/http - client.rs (source / functions) Coverage Total Hit
Test: f8d8f5b90fa487a9e82c42da223f012f5d4fece7.info Lines: 0.0 % 76 0
Test Date: 2024-09-19 20:36:02 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::{NodeId, 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 :         stream_to: NodeId,
     101            0 :     ) -> Result<reqwest::Response> {
     102            0 :         let uri = format!(
     103            0 :             "{}/v1/tenant/{}/timeline/{}/snapshot/{}",
     104            0 :             self.mgmt_api_endpoint, tenant_id, timeline_id, stream_to.0
     105            0 :         );
     106            0 :         self.get(&uri).await
     107            0 :     }
     108              : 
     109            0 :     async fn get<U: IntoUrl>(&self, uri: U) -> Result<reqwest::Response> {
     110            0 :         self.request(Method::GET, uri, ()).await
     111            0 :     }
     112              : 
     113              :     /// Send the request and check that the status code is good.
     114            0 :     async fn request<B: serde::Serialize, U: reqwest::IntoUrl>(
     115            0 :         &self,
     116            0 :         method: Method,
     117            0 :         uri: U,
     118            0 :         body: B,
     119            0 :     ) -> Result<reqwest::Response> {
     120            0 :         let res = self.request_noerror(method, uri, body).await?;
     121            0 :         let response = res.error_from_body().await?;
     122            0 :         Ok(response)
     123            0 :     }
     124              : 
     125              :     /// Just send the request.
     126            0 :     async fn request_noerror<B: serde::Serialize, U: reqwest::IntoUrl>(
     127            0 :         &self,
     128            0 :         method: Method,
     129            0 :         uri: U,
     130            0 :         body: B,
     131            0 :     ) -> Result<reqwest::Response> {
     132            0 :         let req = self.client.request(method, uri);
     133            0 :         let req = if let Some(value) = &self.authorization_header {
     134            0 :             req.header(reqwest::header::AUTHORIZATION, value.get_contents())
     135              :         } else {
     136            0 :             req
     137              :         };
     138            0 :         req.json(&body).send().await.map_err(Error::ReceiveBody)
     139            0 :     }
     140              : }
        

Generated by: LCOV version 2.1-beta