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