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