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