yang_base/http/client.rs
1//! HTTP 客户端核心实现
2//!
3//! 提供全局 HTTP 客户端和请求构建能力。
4
5use crate::error::BaseError;
6use crate::http::request::RequestBuilder;
7use reqwest::{Client, Method};
8use std::sync::{Arc, OnceLock, RwLock};
9use std::time::Duration;
10
11/// 全局 HTTP 客户端实例
12static GLOBAL_HTTP_CLIENT: OnceLock<HttpClient> = OnceLock::new();
13
14/// HTTP 客户端配置
15///
16/// 用于通过 `HttpClient::with_config` 创建自定义配置的客户端
17///
18/// # 示例
19///
20/// ```rust,ignore
21/// use yang_base::http::{HttpClient, HttpClientConfig};
22///
23/// let config = HttpClientConfig {
24/// timeout_secs: 60,
25/// pool_max_idle_per_host: 10,
26/// user_agent: Some("MyApp/1.0".to_string()),
27/// ..Default::default()
28/// };
29/// let client = HttpClient::with_config(config)?;
30/// ```
31#[derive(Debug, Clone)]
32pub struct HttpClientConfig {
33 /// 请求超时时间(秒),默认 30 秒
34 pub timeout_secs: u64,
35
36 /// 每个主机最大空闲连接数,默认 10
37 pub pool_max_idle_per_host: usize,
38
39 /// 连接池空闲超时时间(秒),默认 90 秒
40 pub pool_idle_timeout_secs: u64,
41
42 /// 自定义 User-Agent,默认为 None(使用 reqwest 默认值)
43 pub user_agent: Option<String>,
44
45 /// 是否接受无效的 TLS 证书,默认 false(生产环境不应设为 true)
46 pub accept_invalid_certs: bool,
47
48 /// 代理 URL,默认为 None(不使用代理)
49 pub proxy_url: Option<String>,
50}
51
52impl Default for HttpClientConfig {
53 fn default() -> Self {
54 Self {
55 timeout_secs: 30,
56 pool_max_idle_per_host: 10,
57 pool_idle_timeout_secs: 90,
58 user_agent: None,
59 accept_invalid_certs: false,
60 proxy_url: None,
61 }
62 }
63}
64
65/// HTTP 客户端
66///
67/// 提供 HTTP 请求构建和发送能力。
68///
69/// 内部持有 `Arc<reqwest::Client>`,`clone()` 时复用同一连接池(即 `Arc::clone`),
70/// 不会创建新的底层连接池。
71///
72/// # 示例
73///
74/// ```rust,ignore
75/// use yang_base::http::HttpClient;
76///
77/// // 初始化全局客户端
78/// HttpClient::init_global(30)?;
79///
80/// // 使用全局客户端发起请求
81/// let response = HttpClient::global()?
82/// .get("https://api.example.com/users")
83/// .send()
84/// .await?;
85/// ```
86#[derive(Clone, Debug)]
87pub struct HttpClient {
88 /// reqwest 客户端(Arc 包装,clone 时复用同一连接池)
89 client: Client,
90
91 /// 默认超时时间
92 default_timeout: Duration,
93
94 /// 默认 Token(可选)
95 default_token: Arc<RwLock<Option<String>>>,
96}
97
98impl HttpClient {
99 /// 使用结构化配置创建 HTTP 客户端
100 ///
101 /// # 参数
102 ///
103 /// - `cfg`: HTTP 客户端配置
104 ///
105 /// # 返回
106 ///
107 /// - `Ok(HttpClient)`: 客户端实例
108 /// - `Err(BaseError::HttpClientCreateFailed)`: 创建失败(如代理 URL 无效)
109 ///
110 /// # 示例
111 ///
112 /// ```rust,ignore
113 /// use yang_base::http::{HttpClient, HttpClientConfig};
114 ///
115 /// let config = HttpClientConfig {
116 /// timeout_secs: 60,
117 /// pool_max_idle_per_host: 20,
118 /// ..Default::default()
119 /// };
120 /// let client = HttpClient::with_config(config)?;
121 /// ```
122 pub fn with_config(cfg: HttpClientConfig) -> Result<Self, BaseError> {
123 // 构建 reqwest 客户端
124 let mut builder = Client::builder()
125 .timeout(Duration::from_secs(cfg.timeout_secs))
126 .pool_max_idle_per_host(cfg.pool_max_idle_per_host)
127 .pool_idle_timeout(Duration::from_secs(cfg.pool_idle_timeout_secs))
128 .danger_accept_invalid_certs(cfg.accept_invalid_certs);
129
130 // 设置自定义 User-Agent
131 if let Some(ua) = cfg.user_agent {
132 builder = builder.user_agent(ua);
133 }
134
135 // 设置代理
136 if let Some(proxy_url) = cfg.proxy_url {
137 let proxy = reqwest::Proxy::all(&proxy_url)
138 .map_err(BaseError::HttpClientCreateFailed)?;
139 builder = builder.proxy(proxy);
140 }
141
142 let client = builder
143 .build()
144 .map_err(BaseError::HttpClientCreateFailed)?;
145
146 Ok(Self {
147 client,
148 default_timeout: Duration::from_secs(cfg.timeout_secs),
149 default_token: Arc::new(RwLock::new(None)),
150 })
151 }
152
153 /// 创建新的 HTTP 客户端
154 ///
155 /// 委托给 `with_config`,使用默认配置并仅覆盖超时时间。
156 ///
157 /// # 参数
158 ///
159 /// - `timeout_secs`: 默认超时时间(秒)
160 ///
161 /// # 返回
162 ///
163 /// - `Ok(HttpClient)`: 客户端实例
164 /// - `Err(BaseError)`: 创建失败
165 ///
166 /// # 示例
167 ///
168 /// ```rust,ignore
169 /// let client = HttpClient::new(30)?;
170 /// ```
171 pub fn new(timeout_secs: u64) -> Result<Self, BaseError> {
172 // 委托给 with_config,仅覆盖超时时间
173 Self::with_config(HttpClientConfig {
174 timeout_secs,
175 ..Default::default()
176 })
177 }
178
179 /// 初始化全局 HTTP 客户端
180 ///
181 /// # 参数
182 ///
183 /// - `timeout_secs`: 默认超时时间(秒)
184 ///
185 /// # 返回
186 ///
187 /// - `Ok(())`: 初始化成功
188 /// - `Err(BaseError::HttpClientAlreadyInitialized)`: 已初始化(重复调用)
189 /// - `Err(BaseError::HttpClientCreateFailed)`: 客户端创建失败
190 ///
191 /// # 示例
192 ///
193 /// ```rust,ignore
194 /// HttpClient::init_global(30)?;
195 /// ```
196 pub fn init_global(timeout_secs: u64) -> Result<(), BaseError> {
197 let client = Self::new(timeout_secs)?;
198
199 // 重复初始化返回结构化错误
200 GLOBAL_HTTP_CLIENT
201 .set(client)
202 .map_err(|_| BaseError::HttpClientAlreadyInitialized)?;
203
204 log::info!("全局 HTTP 客户端已初始化,超时时间: {} 秒", timeout_secs);
205 Ok(())
206 }
207
208 /// 获取全局 HTTP 客户端
209 ///
210 /// # 返回
211 ///
212 /// - `Ok(&HttpClient)`: 客户端实例
213 /// - `Err(BaseError::HttpClientNotInitialized)`: 客户端未初始化
214 ///
215 /// # 示例
216 ///
217 /// ```rust,ignore
218 /// let client = HttpClient::global()?;
219 /// ```
220 pub fn global() -> Result<&'static HttpClient, BaseError> {
221 // 未初始化返回结构化错误
222 GLOBAL_HTTP_CLIENT
223 .get()
224 .ok_or(BaseError::HttpClientNotInitialized)
225 }
226
227 /// 设置默认 Token
228 ///
229 /// # 参数
230 ///
231 /// - `token`: Token 字符串
232 ///
233 /// # 示例
234 ///
235 /// ```rust,ignore
236 /// let mut client = HttpClient::new(30)?;
237 /// client.set_default_token("your_token".to_string());
238 /// ```
239 pub fn set_default_token(&self, token: String) {
240 // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续写入
241 let mut default_token = self
242 .default_token
243 .write()
244 .unwrap_or_else(|p| p.into_inner());
245 *default_token = Some(token);
246 log::debug!("已设置默认 Token");
247 }
248
249 /// 获取默认 Token
250 fn get_default_token(&self) -> Option<String> {
251 // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续读取
252 let default_token = self
253 .default_token
254 .read()
255 .unwrap_or_else(|p| p.into_inner());
256 default_token.clone()
257 }
258
259 /// 创建请求构建器
260 ///
261 /// 注意:`self.client.clone()` 是 `Arc::clone`,复用同一底层连接池,
262 /// 不会创建新的 TCP 连接池,多个请求共享连接。
263 ///
264 /// # 参数
265 ///
266 /// - `method`: HTTP 方法
267 /// - `url`: 请求 URL
268 ///
269 /// # 返回
270 ///
271 /// - `RequestBuilder`: 请求构建器
272 ///
273 /// # 示例
274 ///
275 /// ```rust,ignore
276 /// use reqwest::Method;
277 ///
278 /// let response = client
279 /// .request(Method::GET, "https://api.example.com/users")
280 /// .send()
281 /// .await?;
282 /// ```
283 pub fn request(&self, method: Method, url: &str) -> RequestBuilder {
284 // self.client.clone() 是 Arc::clone,复用同一连接池
285 RequestBuilder::new(
286 self.client.clone(),
287 method,
288 url.to_string(),
289 self.default_timeout,
290 self.get_default_token(),
291 )
292 }
293
294 /// GET 请求
295 ///
296 /// # 参数
297 ///
298 /// - `url`: 请求 URL
299 ///
300 /// # 返回
301 ///
302 /// - `RequestBuilder`: 请求构建器
303 ///
304 /// # 示例
305 ///
306 /// ```rust,ignore
307 /// let response = client
308 /// .get("https://api.example.com/users")
309 /// .send()
310 /// .await?;
311 /// ```
312 pub fn get(&self, url: &str) -> RequestBuilder {
313 self.request(Method::GET, url)
314 }
315
316 /// POST 请求
317 ///
318 /// # 参数
319 ///
320 /// - `url`: 请求 URL
321 ///
322 /// # 返回
323 ///
324 /// - `RequestBuilder`: 请求构建器
325 ///
326 /// # 示例
327 ///
328 /// ```rust,ignore
329 /// let response = client
330 /// .post("https://api.example.com/users")
331 /// .json(&user)?
332 /// .send()
333 /// .await?;
334 /// ```
335 pub fn post(&self, url: &str) -> RequestBuilder {
336 self.request(Method::POST, url)
337 }
338
339 /// PUT 请求
340 ///
341 /// # 参数
342 ///
343 /// - `url`: 请求 URL
344 ///
345 /// # 返回
346 ///
347 /// - `RequestBuilder`: 请求构建器
348 ///
349 /// # 示例
350 ///
351 /// ```rust,ignore
352 /// let response = client
353 /// .put("https://api.example.com/users/1")
354 /// .json(&user)?
355 /// .send()
356 /// .await?;
357 /// ```
358 pub fn put(&self, url: &str) -> RequestBuilder {
359 self.request(Method::PUT, url)
360 }
361
362 /// DELETE 请求
363 ///
364 /// # 参数
365 ///
366 /// - `url`: 请求 URL
367 ///
368 /// # 返回
369 ///
370 /// - `RequestBuilder`: 请求构建器
371 ///
372 /// # 示例
373 ///
374 /// ```rust,ignore
375 /// let response = client
376 /// .delete("https://api.example.com/users/1")
377 /// .send()
378 /// .await?;
379 /// ```
380 pub fn delete(&self, url: &str) -> RequestBuilder {
381 self.request(Method::DELETE, url)
382 }
383
384 /// PATCH 请求
385 ///
386 /// # 参数
387 ///
388 /// - `url`: 请求 URL
389 ///
390 /// # 返回
391 ///
392 /// - `RequestBuilder`: 请求构建器
393 ///
394 /// # 示例
395 ///
396 /// ```rust,ignore
397 /// let response = client
398 /// .patch("https://api.example.com/users/1")
399 /// .json(&updates)?
400 /// .send()
401 /// .await?;
402 /// ```
403 pub fn patch(&self, url: &str) -> RequestBuilder {
404 self.request(Method::PATCH, url)
405 }
406}