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 // 安装 rustls 的进程级 CryptoProvider。
251 //
252 // 本 crate 走的是 reqwest 的 `rustls-tls-webpki-roots-no-provider`(原因见
253 // 工作区 `Cargo.toml` 里 reqwest 那段注释:带 provider 的变体会经
254 // `__rustls-ring` 的 `quinn?/ring` 把 quinn 及其 `rand 0.10` 链锁进
255 // `Cargo.lock`,而那条链需要 edition2024,直接击穿 MSRV 1.80)。
256 // `-no-provider` 不替我们选 provider,因此必须在这里显式安装:
257 // 不装的话**第一次 TLS 握手**才会失败("no process-level CryptoProvider
258 // available"),编译期与构造期都看不出来。
259 //
260 // provider 是进程级的,重复安装返回 `Err`,属预期,忽略即可。
261 let _ = rustls::crypto::ring::default_provider().install_default();
262
263 // 构建 reqwest 客户端
264 let mut builder = Client::builder()
265 .timeout(Duration::from_secs(cfg.timeout_secs))
266 .pool_max_idle_per_host(cfg.pool_max_idle_per_host)
267 .pool_idle_timeout(Duration::from_secs(cfg.pool_idle_timeout_secs))
268 .danger_accept_invalid_certs(cfg.accept_invalid_certs);
269
270 // 设置自定义 User-Agent
271 if let Some(ua) = cfg.user_agent {
272 builder = builder.user_agent(ua);
273 }
274
275 // 设置代理
276 if let Some(proxy_url) = cfg.proxy_url {
277 let proxy =
278 reqwest::Proxy::all(&proxy_url).map_err(BaseError::HttpClientCreateFailed)?;
279 builder = builder.proxy(proxy);
280 }
281
282 let client = builder.build().map_err(BaseError::HttpClientCreateFailed)?;
283
284 let circuit_breaker = cfg
285 .circuit_breaker
286 .map(crate::http::CircuitBreaker::new)
287 .transpose()?;
288
289 Ok(Self {
290 client,
291 default_timeout: Duration::from_secs(cfg.timeout_secs),
292 max_response_bytes: cfg.max_response_bytes,
293 default_token: Arc::new(RwLock::new(None)),
294 circuit_breaker,
295 })
296 }
297
298 /// 创建新的 HTTP 客户端
299 ///
300 /// 委托给 `with_config`,使用默认配置并仅覆盖超时时间。
301 ///
302 /// # 参数
303 ///
304 /// - `timeout_secs`: 默认超时时间(秒)
305 ///
306 /// # 返回
307 ///
308 /// - `Ok(HttpClient)`: 客户端实例
309 /// - `Err(BaseError)`: 创建失败
310 ///
311 /// # 示例
312 ///
313 /// ```rust,ignore
314 /// let client = HttpClient::new(30)?;
315 /// ```
316 pub fn new(timeout_secs: u64) -> Result<Self, BaseError> {
317 // 委托给 with_config,仅覆盖超时时间
318 Self::with_config(HttpClientConfig {
319 timeout_secs,
320 ..Default::default()
321 })
322 }
323
324 /// 设置默认 Token
325 ///
326 /// # 参数
327 ///
328 /// - `token`: Token 字符串
329 ///
330 /// # 示例
331 ///
332 /// ```rust,ignore
333 /// let mut client = HttpClient::new(30)?;
334 /// client.set_default_token("your_token".to_string());
335 /// ```
336 pub fn set_default_token(&self, token: String) {
337 // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续写入
338 let mut default_token = self
339 .default_token
340 .write()
341 .unwrap_or_else(|p| p.into_inner());
342 *default_token = Some(token);
343 log::debug!("已设置默认 Token");
344 }
345
346 /// 获取默认 Token
347 fn get_default_token(&self) -> Option<String> {
348 // 使用 unwrap_or_else 处理锁中毒:即使锁中毒也能恢复数据并继续读取
349 let default_token = self.default_token.read().unwrap_or_else(|p| p.into_inner());
350 default_token.clone()
351 }
352
353 /// 创建请求构建器
354 ///
355 /// 注意:`self.client.clone()` 是 `Arc::clone`,复用同一底层连接池,
356 /// 不会创建新的 TCP 连接池,多个请求共享连接。
357 ///
358 /// # 参数
359 ///
360 /// - `method`: HTTP 方法
361 /// - `url`: 请求 URL
362 ///
363 /// # 返回
364 ///
365 /// - `RequestBuilder`: 请求构建器
366 ///
367 /// # 示例
368 ///
369 /// ```rust,ignore
370 /// use reqwest::Method;
371 ///
372 /// let response = client
373 /// .request(Method::GET, "https://api.example.com/users")
374 /// .send()
375 /// .await?;
376 /// ```
377 pub fn request(&self, method: Method, url: &str) -> RequestBuilder {
378 // self.client.clone() 是 Arc::clone,复用同一连接池
379 RequestBuilder::new(
380 self.client.clone(),
381 method,
382 url.to_string(),
383 self.default_timeout,
384 self.max_response_bytes,
385 self.get_default_token(),
386 self.circuit_breaker.clone(),
387 )
388 }
389
390 /// GET 请求
391 ///
392 /// # 参数
393 ///
394 /// - `url`: 请求 URL
395 ///
396 /// # 返回
397 ///
398 /// - `RequestBuilder`: 请求构建器
399 ///
400 /// # 示例
401 ///
402 /// ```rust,ignore
403 /// let response = client
404 /// .get("https://api.example.com/users")
405 /// .send()
406 /// .await?;
407 /// ```
408 pub fn get(&self, url: &str) -> RequestBuilder {
409 self.request(Method::GET, url)
410 }
411
412 /// POST 请求
413 ///
414 /// # 参数
415 ///
416 /// - `url`: 请求 URL
417 ///
418 /// # 返回
419 ///
420 /// - `RequestBuilder`: 请求构建器
421 ///
422 /// # 示例
423 ///
424 /// ```rust,ignore
425 /// let response = client
426 /// .post("https://api.example.com/users")
427 /// .json(&user)?
428 /// .send()
429 /// .await?;
430 /// ```
431 pub fn post(&self, url: &str) -> RequestBuilder {
432 self.request(Method::POST, url)
433 }
434
435 /// PUT 请求
436 ///
437 /// # 参数
438 ///
439 /// - `url`: 请求 URL
440 ///
441 /// # 返回
442 ///
443 /// - `RequestBuilder`: 请求构建器
444 ///
445 /// # 示例
446 ///
447 /// ```rust,ignore
448 /// let response = client
449 /// .put("https://api.example.com/users/1")
450 /// .json(&user)?
451 /// .send()
452 /// .await?;
453 /// ```
454 pub fn put(&self, url: &str) -> RequestBuilder {
455 self.request(Method::PUT, url)
456 }
457
458 /// DELETE 请求
459 ///
460 /// # 参数
461 ///
462 /// - `url`: 请求 URL
463 ///
464 /// # 返回
465 ///
466 /// - `RequestBuilder`: 请求构建器
467 ///
468 /// # 示例
469 ///
470 /// ```rust,ignore
471 /// let response = client
472 /// .delete("https://api.example.com/users/1")
473 /// .send()
474 /// .await?;
475 /// ```
476 pub fn delete(&self, url: &str) -> RequestBuilder {
477 self.request(Method::DELETE, url)
478 }
479
480 /// PATCH 请求
481 ///
482 /// # 参数
483 ///
484 /// - `url`: 请求 URL
485 ///
486 /// # 返回
487 ///
488 /// - `RequestBuilder`: 请求构建器
489 ///
490 /// # 示例
491 ///
492 /// ```rust,ignore
493 /// let response = client
494 /// .patch("https://api.example.com/users/1")
495 /// .json(&updates)?
496 /// .send()
497 /// .await?;
498 /// ```
499 pub fn patch(&self, url: &str) -> RequestBuilder {
500 self.request(Method::PATCH, url)
501 }
502}