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