Line data Source code
1 : use pageserver_client::mgmt_api::{self, ResponseErrorMessageExt};
2 : use reqwest::{Method, Url};
3 : use serde::{de::DeserializeOwned, Serialize};
4 : use std::str::FromStr;
5 :
6 : pub struct Client {
7 : base_url: Url,
8 : jwt_token: Option<String>,
9 : client: reqwest::Client,
10 : }
11 :
12 : impl Client {
13 0 : pub fn new(base_url: Url, jwt_token: Option<String>) -> Self {
14 0 : Self {
15 0 : base_url,
16 0 : jwt_token,
17 0 : client: reqwest::ClientBuilder::new()
18 0 : .build()
19 0 : .expect("Failed to construct http client"),
20 0 : }
21 0 : }
22 :
23 : /// Simple HTTP request wrapper for calling into storage controller
24 0 : pub async fn dispatch<RQ, RS>(
25 0 : &self,
26 0 : method: Method,
27 0 : path: String,
28 0 : body: Option<RQ>,
29 0 : ) -> mgmt_api::Result<RS>
30 0 : where
31 0 : RQ: Serialize + Sized,
32 0 : RS: DeserializeOwned + Sized,
33 0 : {
34 0 : // The configured URL has the /upcall path prefix for pageservers to use: we will strip that out
35 0 : // for general purpose API access.
36 0 : let url = Url::from_str(&format!(
37 0 : "http://{}:{}/{path}",
38 0 : self.base_url.host_str().unwrap(),
39 0 : self.base_url.port().unwrap()
40 0 : ))
41 0 : .unwrap();
42 0 :
43 0 : let mut builder = self.client.request(method, url);
44 0 : if let Some(body) = body {
45 0 : builder = builder.json(&body)
46 0 : }
47 0 : if let Some(jwt_token) = &self.jwt_token {
48 0 : builder = builder.header(
49 0 : reqwest::header::AUTHORIZATION,
50 0 : format!("Bearer {jwt_token}"),
51 0 : );
52 0 : }
53 :
54 0 : let response = builder.send().await.map_err(mgmt_api::Error::ReceiveBody)?;
55 0 : let response = response.error_from_body().await?;
56 :
57 0 : response
58 0 : .json()
59 0 : .await
60 0 : .map_err(pageserver_client::mgmt_api::Error::ReceiveBody)
61 0 : }
62 : }
|