1use crate::Error;
4use reqwest::{Client, Method};
5use serde_json::Value;
6use std::time::Duration;
7
8pub struct HttpClient {
9 client: Client,
10 base_url: String,
11 service_key: String,
12 #[cfg_attr(not(test), allow(dead_code))]
13 timeout_ms: Option<u64>,
14}
15
16fn parse_timeout_ms(raw: Option<&str>) -> Option<u64> {
17 raw.and_then(|value| value.trim().parse::<u64>().ok())
18 .filter(|value| *value > 0)
19}
20
21impl HttpClient {
22 pub fn new(base_url: &str, service_key: &str) -> Result<Self, Error> {
23 let url = base_url.trim_end_matches('/').to_string();
24 let timeout_ms = parse_timeout_ms(std::env::var("EDGEBASE_HTTP_TIMEOUT_MS").ok().as_deref());
25 let mut builder = Client::builder();
26 if let Some(timeout_ms) = timeout_ms {
27 builder = builder.timeout(Duration::from_millis(timeout_ms));
28 }
29 Ok(Self {
30 client: builder.build()?,
31 base_url: url,
32 service_key: service_key.to_string(),
33 timeout_ms,
34 })
35 }
36
37 pub fn base_url(&self) -> &str {
38 &self.base_url
39 }
40
41 #[cfg_attr(not(test), allow(dead_code))]
42 pub(crate) fn timeout_ms(&self) -> Option<u64> {
43 self.timeout_ms
44 }
45
46 #[cfg_attr(not(test), allow(dead_code))]
47 pub(crate) fn parse_timeout_ms_for_tests(raw: Option<&str>) -> Option<u64> {
48 parse_timeout_ms(raw)
49 }
50
51 fn build_request(&self, method: Method, path: &str) -> reqwest::RequestBuilder {
52 let url = format!("{}{}", self.base_url, path);
53 let mut req = self.client.request(method, &url);
54 if let Ok(key) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.service_key.clone())) {
56 if !key.is_empty() {
57 req = req.header("X-EdgeBase-Service-Key", &key);
58 req = req.header("Authorization", format!("Bearer {}", key));
59 }
60 }
61 req
62 }
63
64 async fn send(&self, req: reqwest::RequestBuilder) -> Result<Value, Error> {
65 let resp = req.send().await?;
66 let status = resp.status();
67 let text = resp.text().await?;
68 if !status.is_success() {
69 let msg = serde_json::from_str::<Value>(&text)
70 .ok()
71 .and_then(|v| {
72 v.get("error")
73 .or_else(|| v.get("message"))
74 .and_then(|m| m.as_str())
75 .map(|s| s.to_string())
76 })
77 .unwrap_or_else(|| text.clone());
78 return Err(Error::Api {
79 status: status.as_u16(),
80 message: msg,
81 });
82 }
83 if text.is_empty() {
84 return Ok(Value::Null);
85 }
86 Ok(serde_json::from_str(&text)?)
87 }
88
89 pub async fn get(&self, path: &str) -> Result<Value, Error> {
90 let req = self.build_request(Method::GET, path);
91 self.send(req).await
92 }
93
94 pub async fn get_with_query(&self, path: &str, query: &std::collections::HashMap<String, String>) -> Result<Value, Error> {
95 let req = self.build_request(Method::GET, path).query(query);
96 self.send(req).await
97 }
98
99 pub async fn post(&self, path: &str, body: &Value) -> Result<Value, Error> {
100 let req = self.build_request(Method::POST, path).json(body);
101 self.send(req).await
102 }
103
104 pub async fn post_with_query(&self, path: &str, body: &Value, query: &std::collections::HashMap<String, String>) -> Result<Value, Error> {
105 let req = self.build_request(Method::POST, path).json(body).query(query);
106 self.send(req).await
107 }
108
109 pub async fn patch(&self, path: &str, body: &Value) -> Result<Value, Error> {
110 let req = self.build_request(Method::PATCH, path).json(body);
111 self.send(req).await
112 }
113
114 pub async fn delete(&self, path: &str) -> Result<Value, Error> {
115 let req = self.build_request(Method::DELETE, path);
116 self.send(req).await
117 }
118
119 pub async fn delete_with_body(&self, path: &str, body: &Value) -> Result<Value, Error> {
120 let req = self.build_request(Method::DELETE, path).json(body);
121 self.send(req).await
122 }
123
124 pub async fn head(&self, path: &str) -> Result<bool, Error> {
126 let req = self.build_request(Method::HEAD, path);
127 let resp = req.send().await?;
128 Ok(resp.status().is_success())
129 }
130
131 pub async fn put(&self, path: &str, body: &Value) -> Result<Value, Error> {
132 let req = self.build_request(Method::PUT, path).json(body);
133 self.send(req).await
134 }
135
136 pub async fn put_with_query(&self, path: &str, body: &Value, query: &std::collections::HashMap<String, String>) -> Result<Value, Error> {
137 let req = self.build_request(Method::PUT, path).json(body).query(query);
138 self.send(req).await
139 }
140
141 pub async fn upload_multipart(
143 &self, path: &str, key: &str, data: Vec<u8>, content_type: &str,
144 ) -> Result<Value, Error> {
145 use reqwest::multipart::{Form, Part};
146 let part = Part::bytes(data)
147 .file_name(key.to_string())
148 .mime_str(content_type)
149 .map_err(|e| Error::Url(e.to_string()))?;
150 let form = Form::new()
151 .part("file", part)
152 .text("key", key.to_string());
153 let url = format!("{}{}", self.base_url, path);
154 let mut req = self.client.post(&url).multipart(form);
155 if let Ok(key) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.service_key.clone())) {
157 if !key.is_empty() {
158 req = req.header("X-EdgeBase-Service-Key", &key);
159 req = req.header("Authorization", format!("Bearer {}", key));
160 }
161 }
162 self.send(req).await
163 }
164
165 pub async fn post_bytes(&self, path: &str, data: Vec<u8>, content_type: &str) -> Result<Value, Error> {
167 let req = self.build_request(Method::POST, path)
168 .header("Content-Type", content_type)
169 .body(data);
170 self.send(req).await
171 }
172
173 pub async fn download_raw(&self, path: &str) -> Result<Vec<u8>, Error> {
175 let req = self.build_request(Method::GET, path);
176 let resp = req.send().await?;
177 let status = resp.status();
178 if !status.is_success() {
179 let msg = resp.text().await.unwrap_or_default();
180 return Err(Error::Api { status: status.as_u16(), message: msg });
181 }
182 Ok(resp.bytes().await.map(|b| b.to_vec())?)
183 }
184}