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<TimelineStatus> {
85 0 : let uri = format!(
86 0 : "{}/v1/tenant/{}/timeline/{}",
87 0 : self.mgmt_api_endpoint, req.tenant_id, req.timeline_id
88 0 : );
89 0 : let resp = self.post(&uri, req).await?;
90 0 : resp.json().await.map_err(Error::ReceiveBody)
91 0 : }
92 :
93 0 : pub async fn pull_timeline(&self, req: &PullTimelineRequest) -> Result<PullTimelineResponse> {
94 0 : let uri = format!("{}/v1/pull_timeline", self.mgmt_api_endpoint);
95 0 : let resp = self.post(&uri, req).await?;
96 0 : resp.json().await.map_err(Error::ReceiveBody)
97 0 : }
98 :
99 0 : pub async fn exclude_timeline(
100 0 : &self,
101 0 : tenant_id: TenantId,
102 0 : timeline_id: TimelineId,
103 0 : req: &models::TimelineMembershipSwitchRequest,
104 0 : ) -> Result<models::TimelineDeleteResult> {
105 0 : let uri = format!(
106 0 : "{}/v1/tenant/{}/timeline/{}/exclude",
107 0 : self.mgmt_api_endpoint, tenant_id, timeline_id
108 0 : );
109 0 : let resp = self.put(&uri, req).await?;
110 0 : resp.json().await.map_err(Error::ReceiveBody)
111 0 : }
112 :
113 0 : pub async fn delete_timeline(
114 0 : &self,
115 0 : tenant_id: TenantId,
116 0 : timeline_id: TimelineId,
117 0 : ) -> Result<models::TimelineDeleteResult> {
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.request(Method::DELETE, &uri, ()).await?;
123 0 : resp.json().await.map_err(Error::ReceiveBody)
124 0 : }
125 :
126 0 : pub async fn bump_timeline_term(
127 0 : &self,
128 0 : tenant_id: TenantId,
129 0 : timeline_id: TimelineId,
130 0 : req: &models::TimelineTermBumpRequest,
131 0 : ) -> Result<models::TimelineTermBumpResponse> {
132 0 : let uri = format!(
133 0 : "{}/v1/tenant/{}/timeline/{}/term_bump",
134 0 : self.mgmt_api_endpoint, tenant_id, timeline_id
135 0 : );
136 0 : let resp = self.post(&uri, req).await?;
137 0 : resp.json().await.map_err(Error::ReceiveBody)
138 0 : }
139 :
140 0 : pub async fn timeline_status(
141 0 : &self,
142 0 : tenant_id: TenantId,
143 0 : timeline_id: TimelineId,
144 0 : ) -> Result<TimelineStatus> {
145 0 : let uri = format!(
146 0 : "{}/v1/tenant/{}/timeline/{}",
147 0 : self.mgmt_api_endpoint, tenant_id, timeline_id
148 0 : );
149 0 : let resp = self.get(&uri).await?;
150 0 : resp.json().await.map_err(Error::ReceiveBody)
151 0 : }
152 :
153 0 : pub async fn snapshot(
154 0 : &self,
155 0 : tenant_id: TenantId,
156 0 : timeline_id: TimelineId,
157 0 : stream_to: NodeId,
158 0 : ) -> Result<reqwest::Response> {
159 0 : let uri = format!(
160 0 : "{}/v1/tenant/{}/timeline/{}/snapshot/{}",
161 0 : self.mgmt_api_endpoint, tenant_id, timeline_id, stream_to.0
162 0 : );
163 0 : self.get(&uri).await
164 0 : }
165 :
166 0 : pub async fn utilization(&self) -> Result<SafekeeperUtilization> {
167 0 : let uri = format!("{}/v1/utilization", self.mgmt_api_endpoint);
168 0 : let resp = self.get(&uri).await?;
169 0 : resp.json().await.map_err(Error::ReceiveBody)
170 0 : }
171 :
172 0 : async fn post<B: serde::Serialize, U: IntoUrl>(
173 0 : &self,
174 0 : uri: U,
175 0 : body: B,
176 0 : ) -> Result<reqwest::Response> {
177 0 : self.request(Method::POST, uri, body).await
178 0 : }
179 :
180 0 : async fn put<B: serde::Serialize, U: IntoUrl>(
181 0 : &self,
182 0 : uri: U,
183 0 : body: B,
184 0 : ) -> Result<reqwest::Response> {
185 0 : self.request(Method::PUT, uri, body).await
186 0 : }
187 :
188 0 : async fn get<U: IntoUrl>(&self, uri: U) -> Result<reqwest::Response> {
189 0 : self.request(Method::GET, uri, ()).await
190 0 : }
191 :
192 : /// Send the request and check that the status code is good.
193 0 : async fn request<B: serde::Serialize, U: reqwest::IntoUrl>(
194 0 : &self,
195 0 : method: Method,
196 0 : uri: U,
197 0 : body: B,
198 0 : ) -> Result<reqwest::Response> {
199 0 : let res = self.request_noerror(method, uri, body).await?;
200 0 : let response = res.error_from_body().await?;
201 0 : Ok(response)
202 0 : }
203 :
204 : /// Just send the request.
205 0 : async fn request_noerror<B: serde::Serialize, U: reqwest::IntoUrl>(
206 0 : &self,
207 0 : method: Method,
208 0 : uri: U,
209 0 : body: B,
210 0 : ) -> Result<reqwest::Response> {
211 0 : let mut req = self.client.request(method, uri);
212 0 : if let Some(value) = &self.authorization_header {
213 0 : req = req.header(reqwest::header::AUTHORIZATION, value.get_contents())
214 0 : }
215 0 : req.json(&body).send().await.map_err(Error::ReceiveBody)
216 0 : }
217 : }
|