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

Generated by: LCOV version 2.1-beta