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)]
32#[non_exhaustive]
33pub struct HttpClientConfig {
34 /// 请求超时时间(秒),默认 30 秒
35 pub timeout_secs: u64,
36
37 /// 每个主机最大空闲连接数,默认 10
38 pub pool_max_idle_per_host: usize,
39
40 /// 连接池空闲超时时间(秒),默认 90 秒
41 pub pool_idle_timeout_secs: u64,
42
43 /// 自定义 User-Agent,默认为 None(使用 reqwest 默认值)
44 pub user_agent: Option<String>,
45
46 /// 是否接受无效的 TLS 证书,默认 false(生产环境不应设为 true)
47 pub accept_invalid_certs: bool,
48
49 /// 代理 URL,默认为 None(不使用代理)
50 pub proxy_url: Option<String>,
51
52 /// 熔断器策略,默认 None(不启用)。设为 `Some(..)` 后,对连续失败的目标
53 /// host 快速失败(返回 `BaseError::HttpCircuitBreakerOpen`),按 host 分键。
54 pub circuit_breaker: Option<crate::http::CircuitBreakerConfig>,
55}
56
57impl Default for HttpClientConfig {
58 fn default() -> Self {
59 Self {
60 timeout_secs: 30,
61 pool_max_idle_per_host: 10,
62 pool_idle_timeout_secs: 90,
63 user_agent: None,
64 accept_invalid_certs: false,
65 proxy_url: None,
66 circuit_breaker: None,
67 }
68 }
69}
70
71impl HttpClientConfig {
72 /// 验证 HTTP 客户端配置。
73 ///
74 /// 拒绝会导致请求立即失败或连接池配置退化的零值参数。
75 pub fn validate(&self) -> Result<(), BaseError> {
76 if self.timeout_secs == 0 {
77 return Err(BaseError::ParamInvalid(
78 "http.timeout_secs".to_string(),
79 "HTTP 请求超时时间必须大于 0 秒".to_string(),
80 ));
81 }
82 if self.pool_max_idle_per_host == 0 {
83 return Err(BaseError::ParamInvalid(
84 "http.pool_max_idle_per_host".to_string(),
85 "每个主机最大空闲连接数必须大于 0".to_string(),
86 ));
87 }
88 if self.pool_idle_timeout_secs == 0 {
89 return Err(BaseError::ParamInvalid(
90 "http.pool_idle_timeout_secs".to_string(),
91 "连接池空闲超时时间必须大于 0 秒".to_string(),
92 ));
93 }
94 if let Some(circuit_breaker) = &self.circuit_breaker {
95 circuit_breaker.validate()?;
96 }
97
98 Ok(())
99 }
100}
101
102#[cfg(test)]
103mod config_tests {
104 use super::*;
105
106 #[test]
107 fn test_http_client_config_validate_rejects_zero_values() {
108 let invalid_configs = [
109 HttpClientConfig {
110 timeout_secs: 0,
111 ..HttpClientConfig::default()
112 },
113 HttpClientConfig {
114 pool_max_idle_per_host: 0,
115 ..HttpClientConfig::default()
116 },
117 HttpClientConfig {
118 pool_idle_timeout_secs: 0,
119 ..HttpClientConfig::default()
120 },
121 ];
122
123 for config in invalid_configs {
124 let err = config.validate().expect_err("HTTP 客户端零值配置应被拒绝");
125
126 assert!(matches!(err, BaseError::ParamInvalid(_, _)));
127 }
128 }
129
130 #[test]
131 fn test_with_config_rejects_invalid_config_before_building_client() {
132 let config = HttpClientConfig {
133 timeout_secs: 0,
134 ..HttpClientConfig::default()
135 };
136
137 let err = HttpClient::with_config(config)
138 .expect_err("无效 HTTP 配置应在构建 reqwest client 前被拒绝");
139
140 assert!(matches!(err, BaseError::ParamInvalid(field, _) if field == "http.timeout_secs"));
141 }
142
143 #[test]
144 fn test_http_client_config_validate_rejects_invalid_circuit_breaker_config() {
145 let config = HttpClientConfig {
146 circuit_breaker: Some(crate::http::CircuitBreakerConfig {
147 failure_threshold: 0,
148 ..crate::http::CircuitBreakerConfig::default()
149 }),
150 ..HttpClientConfig::default()
151 };
152
153 let err = config
154 .validate()
155 .expect_err("HTTP 客户端应拒绝非法熔断器配置");
156
157 assert!(matches!(
158 err,
159 BaseError::ParamInvalid(field, _) if field == "http.circuit_breaker.failure_threshold"
160 ));
161 }
162}
163
164/// HTTP 客户端
165///
166/// 提供 HTTP 请求构建和发送能力。
167///
168/// 内部持有 `Arc<reqwest::Client>`,`clone()` 时复用同一连接池(即 `Arc::clone`),
169/// 不会创建新的底层连接池。
170///
171/// # 示例
172///
173/// ```rust,ignore
174/// use yang_base::http::HttpClient;
175///
176/// // 初始化全局客户端
177/// HttpClient::init_global(30)?;
178///
179/// // 使用全局客户端发起请求
180/// let response = HttpClient::global()?
181/// .get("https://api.example.com/users")
182/// .send()
183/// .await?;
184/// ```
185#[derive(Clone, Debug)]
186pub struct HttpClient {
187 /// reqwest 客户端(Arc 包装,clone 时复用同一连接池)
188 client: Client,
189
190 /// 默认超时时间
191 default_timeout: Duration,
192
193 /// 默认 Token(可选)
194 default_token: Arc<RwLock<Option<String>>>,
195
196 /// 熔断器(可选,默认 None)。clone 时共享同一份状态。
197 circuit_breaker: Option<crate::http::CircuitBreaker>,
198}
199
200impl HttpClient {
201 /// 使用结构化配置创建 HTTP 客户端
202 ///
203 /// # 参数
204 ///
205 /// - `cfg`: HTTP 客户端配置
206 ///
207 /// # 返回
208 ///
209 /// - `Ok(HttpClient)`: 客户端实例
210 /// - `Err(BaseError::HttpClientCreateFailed)`: 创建失败(如代理 URL 无效)
211 ///
212 /// # 示例
213 ///
214 /// ```rust,ignore
215 /// use yang_base::http::{HttpClient, HttpClientConfig};
216 ///
217 /// let config = HttpClientConfig {
218 /// timeout_secs: 60,
219 /// pool_max_idle_per_host: 20,
220 /// ..Default::default()
221 /// };
222 /// let client = HttpClient::with_config(config)?;
223 /// ```
224 pub fn with_config(cfg: HttpClientConfig) -> Result<Self, BaseError> {
225 cfg.validate()?;
226
227 // 构建 reqwest 客户端
228 let mut builder = Client::builder()
229 .timeout(Duration::from_secs(cfg.timeout_secs))
230 .pool_max_idle_per_host(cfg.pool_max_idle_per_host)
231 .pool_idle_timeout(Duration::from_secs(cfg.pool_idle_timeout_secs))
232 .danger_accept_invalid_certs(cfg.accept_invalid_certs);
233
234 // 设置自定义 User-Agent
235 if let Some(ua) = cfg.user_agent {
236 builder = builder.user_agent(ua);
237 }
238
239 // 设置代理
240 if let Some(proxy_url) = cfg.proxy_url {
241 let proxy =
242 reqwest::Proxy::all(&proxy_url).map_err(BaseError::HttpClientCreateFailed)?;
243 builder = builder.proxy(proxy);
244 }
245
246 let client = builder.build().map_err(BaseError::HttpClientCreateFailed)?;
247
248 let circuit_breaker = cfg
249 .circuit_breaker
250 .map(crate::http::CircuitBreaker::new)
251 .transpose()?;
252
253 Ok(Self {
254 client,
255 default_timeout: Duration::from_secs(cfg.timeout_secs),
256 default_token: Arc::new(RwLock::new(None)),
257 circuit_breaker,
258 })
259 }
260
261 /// 创建新的 HTTP 客户端
262 ///
263 /// 委托给 `with_config`,使用默认配置并仅覆盖超时时间。
264 ///
265 /// # 参数
266 ///
267 /// - `timeout_secs`: 默认超时时间(秒)
268 ///
269 /// # 返回
270 ///
271 /// - `Ok(HttpClient)`: 客户端实例
272 /// - `Err(BaseError)`: 创建失败
273 ///
274 /// # 示例
275 ///
276 /// ```rust,ignore
277 /// let client = HttpClient::new(30)?;
278 /// ```
279 pub fn new(timeout_secs: u64) -> Result<Self, BaseError> {
280 // 委托给 with_config,仅覆盖超时时间
281 Self::with_config(HttpClientConfig {
282 timeout_secs,
283 ..Default::default()
284 })
285 }
286
287 /// 使用完整配置初始化全局 HTTP 客户端
288 ///
289 /// 允许配置连接池大小、User-Agent、代理等高级选项。
290 /// 重复调用返回 `BaseError::HttpClientAlreadyInitialized`。
291 ///
292 /// # 参数
293 ///
294 /// - `config`: HTTP 客户端配置
295 ///
296 /// # 返回
297 ///
298 /// - `Ok(())`: 初始化成功
299 /// - `Err(BaseError::HttpClientAlreadyInitialized)`: 已初始化(重复调用)
300 /// - `Err(BaseError::HttpClientCreateFailed)`: 客户端创建失败
301 ///
302 /// # 示例
303 ///
304 /// ```rust,ignore
305 /// use yang_base::http::HttpClientConfig;
306 ///
307 /// let config = HttpClientConfig {
308 /// timeout_secs: 60,
309 /// pool_max_idle_per_host: 20,
310 /// user_agent: Some("MyApp/1.0".to_string()),
311 /// ..Default::default()
312 /// };
313 /// HttpClient::init_global_with_config(config)?;
314 /// ```
315 pub fn init_global_with_config(config: HttpClientConfig) -> Result<(), BaseError> {
316 let timeout = config.timeout_secs;
317 let client = Self::with_config(config)?;
318
319 GLOBAL_HTTP_CLIENT
320 .set(client)
321 .map_err(|_| BaseError::HttpClientAlreadyInitialized)?;
322
323 log::info!("全局 HTTP 客户端已初始化,超时时间: {} 秒", timeout);
324 Ok(())
325 }
326
327 /// 初始化全局 HTTP 客户端(仅超时时间)
328 ///
329 /// 使用默认配置,仅覆盖超时时间。如需完整配置(连接池、UA、代理等),
330 /// 请使用 [`init_global_with_config`](Self::init_global_with_config)。
331 ///
332 /// # 参数
333 ///
334 /// - `timeout_secs`: 默认超时时间(秒)
335 ///
336 /// # 返回
337 ///
338 /// - `Ok(())`: 初始化成功
339 /// - `Err(BaseError::HttpClientAlreadyInitialized)`: 已初始化(重复调用)
340 /// - `Err(BaseError::HttpClientCreateFailed)`: 客户端创建失败
341 ///
342 /// # 示例
343 ///
344 /// ```rust,ignore
345 /// HttpClient::init_global(30)?;
346 /// ```
347 pub fn init_global(timeout_secs: u64) -> Result<(), BaseError> {
348 Self::init_global_with_config(HttpClientConfig {
349 timeout_secs,
350 ..Default::default()
351 })
352 }
353
354 /// 获取全局 HTTP 客户端
355 ///
356 /// # 返回
357 ///
358 /// - `Ok(&HttpClient)`: 客户端实例
359 /// - `Err(BaseError::HttpClientNotInitialized)`: 客户端未初始化
360 ///
361 /// # 示例
362 ///
363 /// ```rust,ignore
364 /// let client = HttpClient::global()?;
365 /// ```
366 pub fn global() -> Result<&'static HttpClient, BaseError> {
367 // 未初始化返回结构化错误
368 GLOBAL_HTTP_CLIENT
369 .get()
370 .ok_or(BaseError::HttpClientNotInitialized)
371 }
372
373 /// 设置默认 Token
374 ///
375 /// # 参数
376 ///
377 /// - `token`: Token 字符串
378 ///
379 /// # 示例
380 ///
381 /// ```rust,ignore
382 /// let mut client = HttpClient::new(30)?;
383 /// client.set_default_token("your_token".to_string());
384 /// ```
385 pub fn set_default_token(&self, token: String) {
386 // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续写入
387 let mut default_token = self
388 .default_token
389 .write()
390 .unwrap_or_else(|p| p.into_inner());
391 *default_token = Some(token);
392 log::debug!("已设置默认 Token");
393 }
394
395 /// 获取默认 Token
396 fn get_default_token(&self) -> Option<String> {
397 // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续读取
398 let default_token = self.default_token.read().unwrap_or_else(|p| p.into_inner());
399 default_token.clone()
400 }
401
402 /// 创建请求构建器
403 ///
404 /// 注意:`self.client.clone()` 是 `Arc::clone`,复用同一底层连接池,
405 /// 不会创建新的 TCP 连接池,多个请求共享连接。
406 ///
407 /// # 参数
408 ///
409 /// - `method`: HTTP 方法
410 /// - `url`: 请求 URL
411 ///
412 /// # 返回
413 ///
414 /// - `RequestBuilder`: 请求构建器
415 ///
416 /// # 示例
417 ///
418 /// ```rust,ignore
419 /// use reqwest::Method;
420 ///
421 /// let response = client
422 /// .request(Method::GET, "https://api.example.com/users")
423 /// .send()
424 /// .await?;
425 /// ```
426 pub fn request(&self, method: Method, url: &str) -> RequestBuilder {
427 // self.client.clone() 是 Arc::clone,复用同一连接池
428 RequestBuilder::new(
429 self.client.clone(),
430 method,
431 url.to_string(),
432 self.default_timeout,
433 self.get_default_token(),
434 self.circuit_breaker.clone(),
435 )
436 }
437
438 /// GET 请求
439 ///
440 /// # 参数
441 ///
442 /// - `url`: 请求 URL
443 ///
444 /// # 返回
445 ///
446 /// - `RequestBuilder`: 请求构建器
447 ///
448 /// # 示例
449 ///
450 /// ```rust,ignore
451 /// let response = client
452 /// .get("https://api.example.com/users")
453 /// .send()
454 /// .await?;
455 /// ```
456 pub fn get(&self, url: &str) -> RequestBuilder {
457 self.request(Method::GET, url)
458 }
459
460 /// POST 请求
461 ///
462 /// # 参数
463 ///
464 /// - `url`: 请求 URL
465 ///
466 /// # 返回
467 ///
468 /// - `RequestBuilder`: 请求构建器
469 ///
470 /// # 示例
471 ///
472 /// ```rust,ignore
473 /// let response = client
474 /// .post("https://api.example.com/users")
475 /// .json(&user)?
476 /// .send()
477 /// .await?;
478 /// ```
479 pub fn post(&self, url: &str) -> RequestBuilder {
480 self.request(Method::POST, url)
481 }
482
483 /// PUT 请求
484 ///
485 /// # 参数
486 ///
487 /// - `url`: 请求 URL
488 ///
489 /// # 返回
490 ///
491 /// - `RequestBuilder`: 请求构建器
492 ///
493 /// # 示例
494 ///
495 /// ```rust,ignore
496 /// let response = client
497 /// .put("https://api.example.com/users/1")
498 /// .json(&user)?
499 /// .send()
500 /// .await?;
501 /// ```
502 pub fn put(&self, url: &str) -> RequestBuilder {
503 self.request(Method::PUT, url)
504 }
505
506 /// DELETE 请求
507 ///
508 /// # 参数
509 ///
510 /// - `url`: 请求 URL
511 ///
512 /// # 返回
513 ///
514 /// - `RequestBuilder`: 请求构建器
515 ///
516 /// # 示例
517 ///
518 /// ```rust,ignore
519 /// let response = client
520 /// .delete("https://api.example.com/users/1")
521 /// .send()
522 /// .await?;
523 /// ```
524 pub fn delete(&self, url: &str) -> RequestBuilder {
525 self.request(Method::DELETE, url)
526 }
527
528 /// PATCH 请求
529 ///
530 /// # 参数
531 ///
532 /// - `url`: 请求 URL
533 ///
534 /// # 返回
535 ///
536 /// - `RequestBuilder`: 请求构建器
537 ///
538 /// # 示例
539 ///
540 /// ```rust,ignore
541 /// let response = client
542 /// .patch("https://api.example.com/users/1")
543 /// .json(&updates)?
544 /// .send()
545 /// .await?;
546 /// ```
547 pub fn patch(&self, url: &str) -> RequestBuilder {
548 self.request(Method::PATCH, url)
549 }
550}