Skip to main content

yang_base/http/
request.rs

1//! HTTP 请求构建器实现
2//!
3//! 提供链式调用接口构建 HTTP 请求。
4
5use crate::error::BaseError;
6use crate::http::response::Response;
7use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
8use reqwest::{Client, Method};
9use serde::Serialize;
10use std::time::Duration;
11
12fn redact_url_for_log(url: &str) -> String {
13    let Ok(mut parsed_url) = reqwest::Url::parse(url) else {
14        return "<invalid-url>".to_string();
15    };
16
17    parsed_url.set_query(None);
18    if !parsed_url.username().is_empty() {
19        let _ = parsed_url.set_username("***");
20    }
21    if parsed_url.password().is_some() {
22        let _ = parsed_url.set_password(Some("***"));
23    }
24
25    parsed_url.to_string()
26}
27
28/// 请求级重试策略配置(L-4)。
29///
30/// 对临时性失败(连接错误、可重试的 5xx 等)按指数退避自动重试。
31/// 默认不重试——只有显式调用 [`RequestBuilder::retry`] 才启用。
32///
33/// 注意:当前仅实现「重试 + 指数退避」。熔断(circuit breaker)尚未实现,
34/// 如需熔断请在调用方或网关层处理。
35///
36/// # 示例
37///
38/// ```rust,ignore
39/// use yang_base::http::RetryConfig;
40///
41/// let cfg = RetryConfig {
42///     max_retries: 3,
43///     retry_on: vec![502, 503, 504],
44///     backoff_ms: 100, // 第 n 次重试前等待 backoff_ms * 2^(n-1) 毫秒
45/// };
46/// ```
47#[derive(Debug, Clone)]
48pub struct RetryConfig {
49    /// 最大重试次数(不含首次请求)。0 等价于不重试。
50    pub max_retries: u32,
51    /// 命中这些 HTTP 状态码时重试(如 `[502, 503, 504]`)。
52    pub retry_on: Vec<u16>,
53    /// 初始退避毫秒数,按 `backoff_ms * 2^attempt` 指数增长。
54    pub backoff_ms: u64,
55}
56
57impl Default for RetryConfig {
58    fn default() -> Self {
59        Self {
60            max_retries: 3,
61            retry_on: vec![502, 503, 504],
62            backoff_ms: 100,
63        }
64    }
65}
66
67impl RetryConfig {
68    const MAX_RETRIES: u32 = 10;
69    const MAX_BACKOFF_MS: u64 = 60_000;
70
71    /// 验证请求级重试策略。
72    ///
73    /// `max_retries == 0` 表示显式禁用重试,此时 `retry_on` 与 `backoff_ms` 不参与发送。
74    pub fn validate(&self) -> Result<(), BaseError> {
75        if self.max_retries > Self::MAX_RETRIES {
76            return Err(BaseError::ParamInvalid(
77                "http.retry.max_retries".to_string(),
78                format!("最大重试次数不能超过 {}", Self::MAX_RETRIES),
79            ));
80        }
81
82        if self.max_retries == 0 {
83            return Ok(());
84        }
85
86        if self.retry_on.is_empty() {
87            return Err(BaseError::ParamInvalid(
88                "http.retry.retry_on".to_string(),
89                "启用重试时 retry_on 不能为空".to_string(),
90            ));
91        }
92
93        if let Some(status) = self
94            .retry_on
95            .iter()
96            .copied()
97            .find(|status| !(100..=599).contains(status))
98        {
99            return Err(BaseError::ParamInvalid(
100                "http.retry.retry_on".to_string(),
101                format!("非法 HTTP 状态码: {status}"),
102            ));
103        }
104
105        if self.backoff_ms == 0 {
106            return Err(BaseError::ParamInvalid(
107                "http.retry.backoff_ms".to_string(),
108                "启用重试时初始退避时间必须大于 0 毫秒".to_string(),
109            ));
110        }
111
112        if self.backoff_ms > Self::MAX_BACKOFF_MS {
113            return Err(BaseError::ParamInvalid(
114                "http.retry.backoff_ms".to_string(),
115                format!("初始退避时间不能超过 {} 毫秒", Self::MAX_BACKOFF_MS),
116            ));
117        }
118
119        Ok(())
120    }
121}
122
123/// HTTP 请求构建器
124///
125/// 提供链式调用接口构建 HTTP 请求。
126///
127/// # Header 错误处理
128///
129/// `header`、`headers` 等方法在解析失败时不会立即返回错误,而是将错误信息
130/// 累积到内部 `header_errors` 列表中。调用 `send()` 时,若存在累积的 header
131/// 错误,则返回 `BaseError::ParamInvalid("header", ...)` 而不发送请求。
132///
133/// # 示例
134///
135/// ```rust,ignore
136/// // tools 为启动期经 ToolsBuilder::http(...) 冻结的应用资源;Action 内则用 ctx.http()?
137/// let response = tools.http()?
138///     .get("https://api.example.com/users")
139///     .header("X-Custom-Header", "value")
140///     .query("page", "1")
141///     .bearer_token("your_token")
142///     .timeout(60)
143///     .send()
144///     .await?;
145/// ```
146pub struct RequestBuilder {
147    /// reqwest 客户端(Arc 包装,clone 时复用同一连接池)
148    client: Client,
149
150    /// HTTP 方法
151    method: Method,
152
153    /// 请求 URL
154    url: String,
155
156    /// 请求头
157    headers: HeaderMap,
158
159    /// 累积的 header 解析错误列表
160    ///
161    /// `header`、`headers` 方法在解析失败时将错误描述追加到此列表,
162    /// `send()` 时若非空则返回 `BaseError::ParamInvalid`。
163    header_errors: Vec<String>,
164
165    /// 查询参数
166    query_params: Vec<(String, String)>,
167
168    /// 请求体
169    body: Option<Vec<u8>>,
170
171    /// 超时时间
172    timeout: Duration,
173
174    /// Token(可选)
175    token: Option<String>,
176
177    /// 重试策略(可选,默认不重试)
178    retry: Option<RetryConfig>,
179
180    /// 熔断器(可选,默认 None)。来自创建该构建器的 HttpClient,共享状态。
181    circuit_breaker: Option<crate::http::CircuitBreaker>,
182}
183
184impl RequestBuilder {
185    /// 创建新的请求构建器
186    ///
187    /// # 参数
188    ///
189    /// - `client`: reqwest 客户端(Arc 包装,clone 时复用同一连接池)
190    /// - `method`: HTTP 方法
191    /// - `url`: 请求 URL
192    /// - `timeout`: 超时时间
193    /// - `token`: 默认 Token
194    /// - `circuit_breaker`: 熔断器(可选,来自 HttpClient)
195    pub(crate) fn new(
196        client: Client,
197        method: Method,
198        url: String,
199        timeout: Duration,
200        token: Option<String>,
201        circuit_breaker: Option<crate::http::CircuitBreaker>,
202    ) -> Self {
203        Self {
204            client,
205            method,
206            url,
207            headers: HeaderMap::new(),
208            header_errors: Vec::new(),
209            query_params: Vec::new(),
210            body: None,
211            timeout,
212            token,
213            retry: None,
214            circuit_breaker,
215        }
216    }
217
218    /// 设置请求头
219    ///
220    /// 若 header 名称或值解析失败,错误信息将被累积到内部错误列表,
221    /// 不会立即返回错误。调用 `send()` 时若存在累积错误则返回 `BaseError::ParamInvalid`。
222    ///
223    /// # 参数
224    ///
225    /// - `name`: 请求头名称
226    /// - `value`: 请求头值
227    ///
228    /// # 示例
229    ///
230    /// ```rust,ignore
231    /// let response = client
232    ///     .get("https://api.example.com/users")
233    ///     .header("X-Custom-Header", "value")
234    ///     .send()
235    ///     .await?;
236    /// ```
237    pub fn header(mut self, name: &str, value: &str) -> Self {
238        // 解析 header 名称
239        let header_name = match HeaderName::from_bytes(name.as_bytes()) {
240            Ok(n) => n,
241            Err(e) => {
242                // 累积错误,不立即返回
243                self.header_errors
244                    .push(format!("非法 header 名称 '{}': {}", name, e));
245                return self;
246            }
247        };
248
249        // 解析 header 值
250        let header_value = match HeaderValue::from_str(value) {
251            Ok(v) => v,
252            Err(e) => {
253                // 累积错误,不立即返回
254                self.header_errors
255                    .push(format!("非法 header 值 '{}': {}", value, e));
256                return self;
257            }
258        };
259
260        self.headers.insert(header_name, header_value);
261        self
262    }
263
264    /// 批量设置请求头
265    ///
266    /// 若任意 header 名称或值解析失败,错误信息将被累积到内部错误列表,
267    /// 不会立即返回错误。调用 `send()` 时若存在累积错误则返回 `BaseError::ParamInvalid`。
268    ///
269    /// # 参数
270    ///
271    /// - `headers`: 请求头列表
272    ///
273    /// # 示例
274    ///
275    /// ```rust,ignore
276    /// let response = client
277    ///     .get("https://api.example.com/users")
278    ///     .headers(vec![
279    ///         ("X-Custom-Header-1", "value1"),
280    ///         ("X-Custom-Header-2", "value2"),
281    ///     ])
282    ///     .send()
283    ///     .await?;
284    /// ```
285    pub fn headers(mut self, headers: Vec<(&str, &str)>) -> Self {
286        for (name, value) in headers {
287            // 解析 header 名称
288            let header_name = match HeaderName::from_bytes(name.as_bytes()) {
289                Ok(n) => n,
290                Err(e) => {
291                    // 累积错误,继续处理其余 header
292                    self.header_errors
293                        .push(format!("非法 header 名称 '{}': {}", name, e));
294                    continue;
295                }
296            };
297
298            // 解析 header 值
299            let header_value = match HeaderValue::from_str(value) {
300                Ok(v) => v,
301                Err(e) => {
302                    // 累积错误,继续处理其余 header
303                    self.header_errors
304                        .push(format!("非法 header 值 '{}': {}", value, e));
305                    continue;
306                }
307            };
308
309            self.headers.insert(header_name, header_value);
310        }
311        self
312    }
313
314    /// 设置 Content-Type
315    ///
316    /// # 参数
317    ///
318    /// - `content_type`: Content-Type 值
319    ///
320    /// # 示例
321    ///
322    /// ```rust,ignore
323    /// let response = client
324    ///     .post("https://api.example.com/users")
325    ///     .content_type("application/json")
326    ///     .send()
327    ///     .await?;
328    /// ```
329    pub fn content_type(self, content_type: &str) -> Self {
330        self.header("Content-Type", content_type)
331    }
332
333    /// 设置 Bearer Token
334    ///
335    /// # 参数
336    ///
337    /// - `token`: Token 字符串
338    ///
339    /// # 示例
340    ///
341    /// ```rust,ignore
342    /// let response = client
343    ///     .get("https://api.example.com/users")
344    ///     .bearer_token("your_token")
345    ///     .send()
346    ///     .await?;
347    /// ```
348    pub fn bearer_token(mut self, token: &str) -> Self {
349        self.token = Some(token.to_string());
350        self
351    }
352
353    /// 设置 User-Agent
354    ///
355    /// # 参数
356    ///
357    /// - `user_agent`: User-Agent 值
358    ///
359    /// # 示例
360    ///
361    /// ```rust,ignore
362    /// let response = client
363    ///     .get("https://api.example.com/users")
364    ///     .user_agent("MyApp/1.0")
365    ///     .send()
366    ///     .await?;
367    /// ```
368    pub fn user_agent(self, user_agent: &str) -> Self {
369        self.header("User-Agent", user_agent)
370    }
371
372    /// 添加查询参数
373    ///
374    /// # 参数
375    ///
376    /// - `key`: 参数名
377    /// - `value`: 参数值
378    ///
379    /// # 示例
380    ///
381    /// ```rust,ignore
382    /// let response = client
383    ///     .get("https://api.example.com/users")
384    ///     .query("page", "1")
385    ///     .query("limit", "10")
386    ///     .send()
387    ///     .await?;
388    /// ```
389    pub fn query(mut self, key: &str, value: &str) -> Self {
390        self.query_params.push((key.to_string(), value.to_string()));
391        self
392    }
393
394    /// 批量添加查询参数
395    ///
396    /// # 参数
397    ///
398    /// - `params`: 查询参数列表
399    ///
400    /// # 示例
401    ///
402    /// ```rust,ignore
403    /// let response = client
404    ///     .get("https://api.example.com/users")
405    ///     .queries(vec![("page", "1"), ("limit", "10")])
406    ///     .send()
407    ///     .await?;
408    /// ```
409    pub fn queries(mut self, params: Vec<(&str, &str)>) -> Self {
410        for (key, value) in params {
411            self.query_params.push((key.to_string(), value.to_string()));
412        }
413        self
414    }
415
416    /// 设置 JSON 请求体
417    ///
418    /// # 参数
419    ///
420    /// - `json`: 可序列化为 JSON 的数据
421    ///
422    /// # 返回
423    ///
424    /// - `Ok(Self)`: 设置成功
425    /// - `Err(BaseError)`: 序列化失败
426    ///
427    /// # 示例
428    ///
429    /// ```rust,ignore
430    /// #[derive(Serialize)]
431    /// struct User {
432    ///     name: String,
433    ///     email: String,
434    /// }
435    ///
436    /// let user = User {
437    ///     name: "Alice".to_string(),
438    ///     email: "alice@example.com".to_string(),
439    /// };
440    ///
441    /// let response = client
442    ///     .post("https://api.example.com/users")
443    ///     .json(&user)?
444    ///     .send()
445    ///     .await?;
446    /// ```
447    pub fn json<T: Serialize>(mut self, json: &T) -> Result<Self, BaseError> {
448        let json_bytes =
449            serde_json::to_vec(json).map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
450
451        self.body = Some(json_bytes);
452        self = self.content_type("application/json");
453
454        Ok(self)
455    }
456
457    /// 设置表单请求体
458    ///
459    /// 使用 `serde_urlencoded` 对表单数据进行 URL 编码,正确处理特殊字符、
460    /// 空格、UTF-8 字符等,并自动设置 `Content-Type: application/x-www-form-urlencoded`。
461    ///
462    /// # 参数
463    ///
464    /// - `form`: 表单数据(键值对列表)
465    ///
466    /// # 示例
467    ///
468    /// ```rust,ignore
469    /// let response = client
470    ///     .post("https://api.example.com/login")
471    ///     .form(vec![("username", "alice"), ("password", "secret")])
472    ///     .send()
473    ///     .await?;
474    /// ```
475    pub fn form(mut self, form: Vec<(&str, &str)>) -> Self {
476        // 使用 serde_urlencoded 进行标准 URL 编码,正确处理特殊字符
477        match serde_urlencoded::to_string(&form) {
478            Ok(encoded) => {
479                self.body = Some(encoded.into_bytes());
480                // 自动设置 Content-Type
481                self = self.content_type("application/x-www-form-urlencoded");
482            }
483            Err(e) => {
484                // 编码失败时累积错误
485                self.header_errors.push(format!("表单数据编码失败: {}", e));
486            }
487        }
488        self
489    }
490
491    /// 设置原始字节请求体
492    ///
493    /// # 参数
494    ///
495    /// - `body`: 字节数据
496    ///
497    /// # 示例
498    ///
499    /// ```rust,ignore
500    /// let response = client
501    ///     .post("https://api.example.com/upload")
502    ///     .body(vec![0x00, 0x01, 0x02])
503    ///     .send()
504    ///     .await?;
505    /// ```
506    pub fn body(mut self, body: Vec<u8>) -> Self {
507        self.body = Some(body);
508        self
509    }
510
511    /// 设置文本请求体
512    ///
513    /// # 参数
514    ///
515    /// - `text`: 文本数据
516    ///
517    /// # 示例
518    ///
519    /// ```rust,ignore
520    /// let response = client
521    ///     .post("https://api.example.com/notes")
522    ///     .text("Hello, World!")
523    ///     .send()
524    ///     .await?;
525    /// ```
526    pub fn text(mut self, text: &str) -> Self {
527        self.body = Some(text.as_bytes().to_vec());
528        self = self.content_type("text/plain");
529        self
530    }
531
532    /// 设置超时时间
533    ///
534    /// # 参数
535    ///
536    /// - `timeout_secs`: 超时时间(秒)
537    ///
538    /// # 示例
539    ///
540    /// ```rust,ignore
541    /// let response = client
542    ///     .get("https://api.example.com/users")
543    ///     .timeout(60)
544    ///     .send()
545    ///     .await?;
546    /// ```
547    pub fn timeout(mut self, timeout_secs: u64) -> Self {
548        self.timeout = Duration::from_secs(timeout_secs);
549        self
550    }
551
552    /// 设置请求级重试策略(L-4)。
553    ///
554    /// 默认不重试。启用后,对连接错误与命中 `retry_on` 的状态码按指数退避重试。
555    ///
556    /// # 参数
557    ///
558    /// - `config`: 重试策略
559    ///
560    /// # 示例
561    ///
562    /// ```rust,ignore
563    /// use yang_base::http::RetryConfig;
564    ///
565    /// let response = client
566    ///     .get("https://api.example.com/users")
567    ///     .retry(RetryConfig::default())
568    ///     .send()
569    ///     .await?;
570    /// ```
571    pub fn retry(mut self, config: RetryConfig) -> Self {
572        self.retry = Some(config);
573        self
574    }
575
576    /// 发送请求
577    ///
578    /// 在发送前检查累积的 header 错误。若存在任何 header 解析错误,
579    /// 则返回 `BaseError::ParamInvalid("header", ...)` 而不发送请求。
580    ///
581    /// # 返回
582    ///
583    /// - `Ok(Response)`: 响应对象
584    /// - `Err(BaseError::ParamInvalid)`: 存在非法 header
585    /// - `Err(BaseError::HttpRequestFailed)`: 请求发送失败
586    ///
587    /// # 示例
588    ///
589    /// ```rust,ignore
590    /// let response = client
591    ///     .get("https://api.example.com/users")
592    ///     .send()
593    ///     .await?;
594    /// ```
595    pub async fn send(self) -> Result<Response, BaseError> {
596        // 检查累积的 header 错误,若非空则提前返回错误
597        if !self.header_errors.is_empty() {
598            return Err(BaseError::ParamInvalid(
599                "header".to_string(),
600                self.header_errors.join("; "),
601            ));
602        }
603
604        if self
605            .query_params
606            .iter()
607            .any(|(key, _)| key.trim().is_empty())
608        {
609            return Err(BaseError::ParamInvalid(
610                "query".to_string(),
611                "query 参数名称不能为空".to_string(),
612            ));
613        }
614
615        let parsed_url = reqwest::Url::parse(&self.url).map_err(|err| {
616            BaseError::ParamInvalid("url".to_string(), format!("非法 HTTP URL: {}", err))
617        })?;
618        if !matches!(parsed_url.scheme(), "http" | "https") {
619            return Err(BaseError::ParamInvalid(
620                "url".to_string(),
621                "HTTP 客户端仅支持 http 和 https URL".to_string(),
622            ));
623        }
624
625        if let Some(token) = &self.token {
626            let auth_value = format!("Bearer {}", token);
627            if let Err(err) = HeaderValue::from_str(&auth_value) {
628                return Err(BaseError::ParamInvalid(
629                    "authorization".to_string(),
630                    format!("非法 bearer token,无法构造 Authorization 头: {}", err),
631                ));
632            }
633        }
634
635        if self.timeout.is_zero() {
636            return Err(BaseError::ParamInvalid(
637                "http.timeout_secs".to_string(),
638                "HTTP 请求超时时间必须大于 0 秒".to_string(),
639            ));
640        }
641
642        if let Some(retry) = &self.retry {
643            retry.validate()?;
644        }
645
646        let retry = self.retry.clone();
647
648        // 解析目标 host 用于熔断分键;无熔断器或解析失败时为 None(按无熔断处理)。
649        let host = self
650            .circuit_breaker
651            .as_ref()
652            .and_then(|_| parsed_url.host_str().map(|h| h.to_string()));
653
654        // 无重试策略:单次发送(与原行为一致,仅多一层熔断准入)
655        let Some(retry) = retry else {
656            return self.send_guarded(host.as_deref()).await;
657        };
658
659        // 有重试策略:最多发送 1 + max_retries 次
660        let mut attempt: u32 = 0;
661        loop {
662            let result = self.send_guarded(host.as_deref()).await;
663
664            let should_retry = match &result {
665                // 命中可重试状态码
666                Ok(resp) => retry.retry_on.contains(&resp.status()),
667                // 连接/超时等传输错误也重试
668                Err(BaseError::HttpRequestFailed(_)) => true,
669                // 熔断打开(HttpCircuitBreakerOpen)等其它错误不重试
670                Err(_) => false,
671            };
672
673            if !should_retry || attempt >= retry.max_retries {
674                return result;
675            }
676
677            // 指数退避:backoff_ms * 2^attempt
678            let backoff = retry.backoff_ms.saturating_mul(1u64 << attempt.min(20));
679            if backoff > 0 {
680                tokio::time::sleep(Duration::from_millis(backoff)).await;
681            }
682            attempt += 1;
683        }
684    }
685
686    /// 在熔断器准入检查下发送一次请求,并按结果记录成功/失败。
687    ///
688    /// - 准入:若熔断器对该 host 处于 Open(且未冷却),直接返回
689    ///   `BaseError::HttpCircuitBreakerOpen`,不实际发请求。
690    /// - 记账:传输错误与 5xx 视为失败,2xx/3xx/4xx 视为成功。
691    ///
692    /// 当 `host` 为 `None`(无熔断器或 URL 解析不出 host)时,等价于直接 `send_once`。
693    async fn send_guarded(&self, host: Option<&str>) -> Result<Response, BaseError> {
694        let breaker = self.circuit_breaker.as_ref();
695
696        if let (Some(breaker), Some(host)) = (breaker, host) {
697            if !breaker.allow(host) {
698                return Err(BaseError::HttpCircuitBreakerOpen(host.to_string()));
699            }
700        }
701
702        let result = self.send_once().await;
703
704        if let (Some(breaker), Some(host)) = (breaker, host) {
705            match &result {
706                Ok(resp) if resp.status() >= 500 => breaker.on_failure(host),
707                Ok(_) => breaker.on_success(host),
708                Err(_) => breaker.on_failure(host),
709            }
710        }
711
712        result
713    }
714
715    /// 构建并发送一次请求(不含重试)。
716    ///
717    /// 因重试需要重复发送,这里借用 `&self` 并克隆可复用的请求部件
718    /// (headers / query / body 均可 clone;`client` 为 `Arc`,clone 复用连接池)。
719    async fn send_once(&self) -> Result<Response, BaseError> {
720        // 构建请求
721        // 注意:self.client.clone() 是 Arc::clone,复用同一底层连接池,不创建新的 TCP 连接池
722        let mut request = self
723            .client
724            .request(self.method.clone(), &self.url)
725            .timeout(self.timeout);
726
727        // 添加请求头
728        request = request.headers(self.headers.clone());
729
730        // 添加 Token
731        if let Some(token) = &self.token {
732            request = request.bearer_auth(token);
733        }
734
735        // 添加查询参数
736        if !self.query_params.is_empty() {
737            request = request.query(&self.query_params);
738        }
739
740        // 添加请求体
741        if let Some(body) = &self.body {
742            request = request.body(body.clone());
743        }
744
745        // 发送请求(NG-1:记录方法/URL/状态码/耗时,便于排查外部 API 慢响应与失败)。
746        // URL 日志脱敏:移除 query,并隐藏 userinfo,避免泄漏 token/password。
747        let start = std::time::Instant::now();
748        let result = request.send().await;
749        let elapsed_ms = start.elapsed().as_millis();
750        let log_url = redact_url_for_log(&self.url);
751        match &result {
752            Ok(resp) => {
753                tracing::debug!(
754                    target: "yang_base::http",
755                    method = %self.method,
756                    url = %log_url,
757                    status = resp.status().as_u16(),
758                    elapsed_ms = elapsed_ms as u64,
759                    "HTTP 出站请求完成"
760                );
761            }
762            Err(e) => {
763                tracing::warn!(
764                    target: "yang_base::http",
765                    method = %self.method,
766                    url = %log_url,
767                    elapsed_ms = elapsed_ms as u64,
768                    error = %e,
769                    "HTTP 出站请求失败"
770                );
771            }
772        }
773        let response = result.map_err(BaseError::HttpRequestFailed)?;
774
775        Ok(Response::new(response))
776    }
777}
778
779#[cfg(test)]
780mod retry_config_tests {
781    use super::*;
782
783    #[test]
784    fn test_redact_url_for_log_removes_query_and_userinfo() {
785        let redacted = redact_url_for_log("https://user:secret@example.com/path?token=secret&x=1");
786
787        assert_eq!(redacted, "https://***:***@example.com/path");
788        assert!(!redacted.contains("token"));
789        assert!(!redacted.contains("secret"));
790        assert!(!redacted.contains("user"));
791    }
792
793    #[test]
794    fn test_retry_config_validate_rejects_unsafe_values() {
795        let invalid_configs = [
796            RetryConfig {
797                max_retries: 11,
798                ..RetryConfig::default()
799            },
800            RetryConfig {
801                max_retries: 1,
802                retry_on: Vec::new(),
803                ..RetryConfig::default()
804            },
805            RetryConfig {
806                max_retries: 1,
807                backoff_ms: 0,
808                ..RetryConfig::default()
809            },
810            RetryConfig {
811                max_retries: 1,
812                backoff_ms: 60_001,
813                ..RetryConfig::default()
814            },
815            RetryConfig {
816                max_retries: 1,
817                retry_on: vec![99],
818                ..RetryConfig::default()
819            },
820            RetryConfig {
821                max_retries: 1,
822                retry_on: vec![600],
823                ..RetryConfig::default()
824            },
825        ];
826
827        for config in invalid_configs {
828            assert!(matches!(
829                config.validate(),
830                Err(BaseError::ParamInvalid(_, _))
831            ));
832        }
833    }
834
835    #[tokio::test]
836    async fn test_send_rejects_invalid_retry_config_before_network() {
837        let builder = RequestBuilder::new(
838            Client::new(),
839            Method::GET,
840            "http://127.0.0.1:1".to_string(),
841            Duration::from_secs(30),
842            None,
843            None,
844        )
845        .retry(RetryConfig {
846            max_retries: 11,
847            ..RetryConfig::default()
848        });
849
850        let err = match builder.send().await {
851            Ok(_) => panic!("无效 retry 配置应在网络请求前被拒绝"),
852            Err(err) => err,
853        };
854
855        assert!(
856            matches!(err, BaseError::ParamInvalid(field, _) if field == "http.retry.max_retries")
857        );
858    }
859
860    #[tokio::test]
861    async fn test_send_rejects_zero_request_timeout_before_network() {
862        let builder = RequestBuilder::new(
863            Client::new(),
864            Method::GET,
865            "http://127.0.0.1:1".to_string(),
866            Duration::from_secs(30),
867            None,
868            None,
869        )
870        .timeout(0);
871
872        let err = match builder.send().await {
873            Ok(_) => panic!("0 秒请求超时应在网络请求前被拒绝"),
874            Err(err) => err,
875        };
876
877        assert!(matches!(err, BaseError::ParamInvalid(field, _) if field == "http.timeout_secs"));
878    }
879
880    #[tokio::test]
881    async fn test_send_rejects_blank_query_key_before_network() {
882        let client = crate::http::HttpClient::new(30).expect("HTTP client should be valid");
883        let result = client
884            .get("https://api.example.com/users")
885            .query("   ", "value")
886            .send()
887            .await;
888
889        let err = match result {
890            Err(err) => err,
891            Ok(_) => panic!("空白 query key 应在发送前被拒绝"),
892        };
893
894        assert!(matches!(
895            err,
896            crate::error::BaseError::ParamInvalid(field, _) if field == "query"
897        ));
898    }
899
900    #[tokio::test]
901    async fn test_send_rejects_invalid_bearer_token_before_network() {
902        let builder = RequestBuilder::new(
903            Client::new(),
904            Method::GET,
905            "http://127.0.0.1:1".to_string(),
906            Duration::from_secs(30),
907            Some("bad\r\ntoken".to_string()),
908            None,
909        );
910
911        let err = match builder.send().await {
912            Ok(_) => panic!("非法 bearer token 应在网络请求前被拒绝"),
913            Err(err) => err,
914        };
915
916        assert!(matches!(err, BaseError::ParamInvalid(field, _) if field == "authorization"));
917    }
918
919    #[tokio::test]
920    async fn test_send_rejects_invalid_url_before_network() {
921        let invalid_urls = ["not a url", "ftp://example.com/file"];
922
923        for url in invalid_urls {
924            let builder = RequestBuilder::new(
925                Client::new(),
926                Method::GET,
927                url.to_string(),
928                Duration::from_secs(30),
929                None,
930                None,
931            );
932
933            let err = match builder.send().await {
934                Ok(_) => panic!("非法 URL 应在网络请求前被拒绝"),
935                Err(err) => err,
936            };
937
938            assert!(matches!(err, BaseError::ParamInvalid(field, _) if field == "url"));
939        }
940    }
941}