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
12/// 判断 HTTP 方法是否幂等(可默认安全重试)。
13///
14/// 依据 RFC 9110:GET/HEAD/OPTIONS/TRACE 为安全方法,PUT/DELETE 幂等;
15/// POST/PATCH 非幂等,重复发送可能造成重复写入(重复扣款、重复插入等)。
16///
17/// `reqwest::Method` 的 `PartialEq` 是手写实现,故这里用常量相等比较,
18/// 不使用 `matches!` 的结构性常量模式匹配。
19fn is_idempotent_method(method: &Method) -> bool {
20    *method == Method::GET
21        || *method == Method::HEAD
22        || *method == Method::OPTIONS
23        || *method == Method::TRACE
24        || *method == Method::PUT
25        || *method == Method::DELETE
26}
27
28fn redact_url_for_log(url: &str) -> String {
29    let Ok(mut parsed_url) = reqwest::Url::parse(url) else {
30        return "<invalid-url>".to_string();
31    };
32
33    parsed_url.set_query(None);
34    parsed_url.set_fragment(None);
35    if !parsed_url.username().is_empty() {
36        let _ = parsed_url.set_username("***");
37    }
38    if parsed_url.password().is_some() {
39        let _ = parsed_url.set_password(Some("***"));
40    }
41
42    parsed_url.to_string()
43}
44
45/// 请求级重试策略配置(L-4)。
46///
47/// 对临时性失败(连接错误、可重试的 5xx 等)按指数退避自动重试。
48/// 默认不重试——只有显式调用 [`RequestBuilder::retry`] 才启用。
49///
50/// 注意:当前仅实现「重试 + 指数退避 + 抖动」。熔断(circuit breaker)尚未实现,
51/// 如需熔断请在调用方或网关层处理。
52///
53/// 非幂等方法(POST/PATCH)默认不参与重试——即使启用了重试也只发送一次;
54/// 需要重试时须显式设置 [`RetryConfig::retry_non_idempotent`] 为 `true`,
55/// 由调用方自行承担重复写入(重复扣款/重复插入)的风险。
56///
57/// 重试等待受 [`RetryConfig::total_budget_ms`] 总预算钳制,避免长退避把单次
58/// `send()` 拖成不可控的长尾;另有 [`RetryConfig::jitter_percent`] 抖动去同步
59/// 并发重试。本配置只在调用方显式调用 [`RequestBuilder::retry`] 时生效,
60/// 应用层应另外配置 transport 的 `request_timeout`
61/// (`AxumTransportConfig::request_timeout`,默认 `None`)作为最终兜底。
62///
63/// # 示例
64///
65/// ```rust,ignore
66/// use yang_base::http::RetryConfig;
67///
68/// let cfg = RetryConfig {
69///     max_retries: 3,
70///     retry_on: vec![502, 503, 504],
71///     backoff_ms: 100, // 第 n 次重试前等待 backoff_ms * 2^(n-1) 毫秒
72///     retry_non_idempotent: false, // POST/PATCH 不重试
73///     total_budget_ms: 30_000,     // 单次 send() 内全部退避等待的总预算
74///     jitter_percent: 25,          // 退避抖动幅度 ±25%
75/// };
76/// ```
77#[derive(Debug, Clone)]
78pub struct RetryConfig {
79    /// 最大重试次数(不含首次请求)。0 等价于不重试。
80    pub max_retries: u32,
81    /// 命中这些 HTTP 状态码时重试(如 `[502, 503, 504]`)。
82    pub retry_on: Vec<u16>,
83    /// 初始退避毫秒数,按 `backoff_ms * 2^attempt` 指数增长。
84    pub backoff_ms: u64,
85    /// 是否允许非幂等方法(POST/PATCH)重试。默认 `false`。
86    ///
87    /// 默认关闭时,非幂等请求即使启用了重试也只发送一次,避免
88    /// 「服务端已处理但响应超时/连接中断」时重复扣款、重复插入。
89    /// 仅当调用方确认接口幂等(如带幂等键)时才可置为 `true`。
90    pub retry_non_idempotent: bool,
91    /// 单次 `send()` 内全部重试等待的总时间预算(毫秒)。
92    ///
93    /// 每次退避等待取 `min(抖动后退避, 剩余预算)`;预算耗尽后不再等待,
94    /// 直接返回最后一次请求的结果。必须大于 0(禁止「无预算」后门),
95    /// 上限 300_000 毫秒(`MAX_TOTAL_BUDGET_MS`)。
96    pub total_budget_ms: u64,
97    /// 单次退避的抖动幅度(百分比 `0..=100`)。0 表示不抖动。
98    ///
99    /// 抖动用于打散并发请求的同步重试(惊群):实际上限为初始退避的
100    /// ±`jitter_percent`%,取 `SystemTime` 纳秒 + 进程号 + 重试序号混合的
101    /// 非密码学熵源,不引入额外依赖。
102    pub jitter_percent: u8,
103}
104
105impl Default for RetryConfig {
106    fn default() -> Self {
107        Self {
108            max_retries: 3,
109            retry_on: vec![502, 503, 504],
110            backoff_ms: 100,
111            retry_non_idempotent: false,
112            total_budget_ms: 30_000,
113            jitter_percent: 25,
114        }
115    }
116}
117
118impl RetryConfig {
119    const MAX_RETRIES: u32 = 10;
120    const MAX_BACKOFF_MS: u64 = 60_000;
121    const MAX_TOTAL_BUDGET_MS: u64 = 300_000;
122
123    /// 验证请求级重试策略。
124    ///
125    /// `max_retries == 0` 表示显式禁用重试,此时 `retry_on` 与 `backoff_ms` 不参与发送。
126    pub fn validate(&self) -> Result<(), BaseError> {
127        if self.max_retries > Self::MAX_RETRIES {
128            return Err(BaseError::ParamInvalid(
129                "http.retry.max_retries".to_string(),
130                format!("最大重试次数不能超过 {}", Self::MAX_RETRIES),
131            ));
132        }
133
134        if self.max_retries == 0 {
135            return Ok(());
136        }
137
138        if self.retry_on.is_empty() {
139            return Err(BaseError::ParamInvalid(
140                "http.retry.retry_on".to_string(),
141                "启用重试时 retry_on 不能为空".to_string(),
142            ));
143        }
144
145        if let Some(status) = self
146            .retry_on
147            .iter()
148            .copied()
149            .find(|status| !(100..=599).contains(status))
150        {
151            return Err(BaseError::ParamInvalid(
152                "http.retry.retry_on".to_string(),
153                format!("非法 HTTP 状态码: {status}"),
154            ));
155        }
156
157        if self.backoff_ms == 0 {
158            return Err(BaseError::ParamInvalid(
159                "http.retry.backoff_ms".to_string(),
160                "启用重试时初始退避时间必须大于 0 毫秒".to_string(),
161            ));
162        }
163
164        if self.backoff_ms > Self::MAX_BACKOFF_MS {
165            return Err(BaseError::ParamInvalid(
166                "http.retry.backoff_ms".to_string(),
167                format!("初始退避时间不能超过 {} 毫秒", Self::MAX_BACKOFF_MS),
168            ));
169        }
170
171        if self.total_budget_ms == 0 || self.total_budget_ms > Self::MAX_TOTAL_BUDGET_MS {
172            return Err(BaseError::ParamInvalid(
173                "http.retry.total_budget_ms".to_string(),
174                format!("重试总预算必须在 1..={} 毫秒内", Self::MAX_TOTAL_BUDGET_MS),
175            ));
176        }
177
178        if self.jitter_percent > 100 {
179            return Err(BaseError::ParamInvalid(
180                "http.retry.jitter_percent".to_string(),
181                "退避抖动百分比不能超过 100".to_string(),
182            ));
183        }
184
185        Ok(())
186    }
187}
188
189/// 对退避时长施加 ±`jitter_percent`% 抖动,避免并发请求同步重试(惊群)。
190///
191/// 纯整数运算:`span = base_ms / 100 * jitter_percent`,返回值落在
192/// `[base_ms - span, base_ms + span]`。熵源仅用于打散去同步,非密码学用途,
193/// 故直接复用 `SystemTime` 纳秒 + 进程号 + 重试序号,不引入 `rand` 等依赖。
194fn jittered_backoff(base_ms: u64, jitter_percent: u8, attempt: u32) -> u64 {
195    let jp = u64::from(jitter_percent.min(100));
196    if base_ms == 0 || jp == 0 {
197        return base_ms;
198    }
199
200    let span = base_ms / 100 * jp;
201    if span == 0 {
202        return base_ms;
203    }
204
205    let entropy = std::time::SystemTime::now()
206        .duration_since(std::time::UNIX_EPOCH)
207        .map_or(0, |d| u64::from(d.subsec_nanos()))
208        ^ u64::from(std::process::id())
209        ^ u64::from(attempt);
210
211    base_ms
212        .saturating_sub(span)
213        .saturating_add(entropy % span.saturating_mul(2).saturating_add(1))
214}
215
216/// HTTP 请求构建器
217///
218/// 提供链式调用接口构建 HTTP 请求。
219///
220/// # Header 错误处理
221///
222/// `header`、`headers` 等方法在解析失败时不会立即返回错误,而是将错误信息
223/// 累积到内部 `header_errors` 列表中。调用 `send()` 时,若存在累积的 header
224/// 错误,则返回 `BaseError::ParamInvalid("header", ...)` 而不发送请求。
225///
226/// # 示例
227///
228/// ```rust,ignore
229/// // tools 为启动期经 ToolsBuilder::http(...) 冻结的应用资源;Action 内则用 ctx.http()?
230/// let response = tools.http()?
231///     .get("https://api.example.com/users")
232///     .header("X-Custom-Header", "value")
233///     .query("page", "1")
234///     .bearer_token("your_token")
235///     .timeout(60)
236///     .send()
237///     .await?;
238/// ```
239pub struct RequestBuilder {
240    /// reqwest 客户端(Arc 包装,clone 时复用同一连接池)
241    client: Client,
242
243    /// HTTP 方法
244    method: Method,
245
246    /// 请求 URL
247    url: String,
248
249    /// 请求头
250    headers: HeaderMap,
251
252    /// 累积的 header 解析错误列表
253    ///
254    /// `header`、`headers` 方法在解析失败时将错误描述追加到此列表,
255    /// `send()` 时若非空则返回 `BaseError::ParamInvalid`。
256    header_errors: Vec<String>,
257
258    /// 查询参数
259    query_params: Vec<(String, String)>,
260
261    /// 请求体
262    body: Option<Vec<u8>>,
263
264    /// 超时时间
265    timeout: Duration,
266
267    /// 出站响应体最大允许字节数(来自 HttpClientConfig)
268    max_response_bytes: usize,
269
270    /// Token(可选)
271    token: Option<String>,
272
273    /// 重试策略(可选,默认不重试)
274    retry: Option<RetryConfig>,
275
276    /// 熔断器(可选,默认 None)。来自创建该构建器的 HttpClient,共享状态。
277    circuit_breaker: Option<crate::http::CircuitBreaker>,
278}
279
280impl RequestBuilder {
281    /// 创建新的请求构建器
282    ///
283    /// # 参数
284    ///
285    /// - `client`: reqwest 客户端(Arc 包装,clone 时复用同一连接池)
286    /// - `method`: HTTP 方法
287    /// - `url`: 请求 URL
288    /// - `timeout`: 超时时间
289    /// - `max_response_bytes`: 出站响应体最大允许字节数
290    /// - `token`: 默认 Token
291    /// - `circuit_breaker`: 熔断器(可选,来自 HttpClient)
292    pub(crate) fn new(
293        client: Client,
294        method: Method,
295        url: String,
296        timeout: Duration,
297        max_response_bytes: usize,
298        token: Option<String>,
299        circuit_breaker: Option<crate::http::CircuitBreaker>,
300    ) -> Self {
301        Self {
302            client,
303            method,
304            url,
305            headers: HeaderMap::new(),
306            header_errors: Vec::new(),
307            query_params: Vec::new(),
308            body: None,
309            timeout,
310            max_response_bytes,
311            token,
312            retry: None,
313            circuit_breaker,
314        }
315    }
316
317    /// 设置请求头
318    ///
319    /// 若 header 名称或值解析失败,错误信息将被累积到内部错误列表,
320    /// 不会立即返回错误。调用 `send()` 时若存在累积错误则返回 `BaseError::ParamInvalid`。
321    ///
322    /// # 参数
323    ///
324    /// - `name`: 请求头名称
325    /// - `value`: 请求头值
326    ///
327    /// # 示例
328    ///
329    /// ```rust,ignore
330    /// let response = client
331    ///     .get("https://api.example.com/users")
332    ///     .header("X-Custom-Header", "value")
333    ///     .send()
334    ///     .await?;
335    /// ```
336    pub fn header(mut self, name: &str, value: &str) -> Self {
337        // 解析 header 名称
338        let header_name = match HeaderName::from_bytes(name.as_bytes()) {
339            Ok(n) => n,
340            Err(e) => {
341                // 累积错误,不立即返回
342                self.header_errors
343                    .push(format!("非法 header 名称 '{}': {}", name, e));
344                return self;
345            }
346        };
347
348        // 解析 header 值
349        let header_value = match HeaderValue::from_str(value) {
350            Ok(v) => v,
351            Err(e) => {
352                // 累积错误,不立即返回
353                self.header_errors
354                    .push(format!("非法 header 值 '{}': {}", value, e));
355                return self;
356            }
357        };
358
359        self.headers.insert(header_name, header_value);
360        self
361    }
362
363    /// 批量设置请求头
364    ///
365    /// 若任意 header 名称或值解析失败,错误信息将被累积到内部错误列表,
366    /// 不会立即返回错误。调用 `send()` 时若存在累积错误则返回 `BaseError::ParamInvalid`。
367    ///
368    /// # 参数
369    ///
370    /// - `headers`: 请求头列表
371    ///
372    /// # 示例
373    ///
374    /// ```rust,ignore
375    /// let response = client
376    ///     .get("https://api.example.com/users")
377    ///     .headers(vec![
378    ///         ("X-Custom-Header-1", "value1"),
379    ///         ("X-Custom-Header-2", "value2"),
380    ///     ])
381    ///     .send()
382    ///     .await?;
383    /// ```
384    pub fn headers(mut self, headers: Vec<(&str, &str)>) -> Self {
385        for (name, value) in headers {
386            // 解析 header 名称
387            let header_name = match HeaderName::from_bytes(name.as_bytes()) {
388                Ok(n) => n,
389                Err(e) => {
390                    // 累积错误,继续处理其余 header
391                    self.header_errors
392                        .push(format!("非法 header 名称 '{}': {}", name, e));
393                    continue;
394                }
395            };
396
397            // 解析 header 值
398            let header_value = match HeaderValue::from_str(value) {
399                Ok(v) => v,
400                Err(e) => {
401                    // 累积错误,继续处理其余 header
402                    self.header_errors
403                        .push(format!("非法 header 值 '{}': {}", value, e));
404                    continue;
405                }
406            };
407
408            self.headers.insert(header_name, header_value);
409        }
410        self
411    }
412
413    /// 设置 Content-Type
414    ///
415    /// # 参数
416    ///
417    /// - `content_type`: Content-Type 值
418    ///
419    /// # 示例
420    ///
421    /// ```rust,ignore
422    /// let response = client
423    ///     .post("https://api.example.com/users")
424    ///     .content_type("application/json")
425    ///     .send()
426    ///     .await?;
427    /// ```
428    pub fn content_type(self, content_type: &str) -> Self {
429        self.header("Content-Type", content_type)
430    }
431
432    /// 设置 Bearer Token
433    ///
434    /// # 参数
435    ///
436    /// - `token`: Token 字符串
437    ///
438    /// # 示例
439    ///
440    /// ```rust,ignore
441    /// let response = client
442    ///     .get("https://api.example.com/users")
443    ///     .bearer_token("your_token")
444    ///     .send()
445    ///     .await?;
446    /// ```
447    pub fn bearer_token(mut self, token: &str) -> Self {
448        self.token = Some(token.to_string());
449        self
450    }
451
452    /// 设置 User-Agent
453    ///
454    /// # 参数
455    ///
456    /// - `user_agent`: User-Agent 值
457    ///
458    /// # 示例
459    ///
460    /// ```rust,ignore
461    /// let response = client
462    ///     .get("https://api.example.com/users")
463    ///     .user_agent("MyApp/1.0")
464    ///     .send()
465    ///     .await?;
466    /// ```
467    pub fn user_agent(self, user_agent: &str) -> Self {
468        self.header("User-Agent", user_agent)
469    }
470
471    /// 添加查询参数
472    ///
473    /// # 参数
474    ///
475    /// - `key`: 参数名
476    /// - `value`: 参数值
477    ///
478    /// # 示例
479    ///
480    /// ```rust,ignore
481    /// let response = client
482    ///     .get("https://api.example.com/users")
483    ///     .query("page", "1")
484    ///     .query("limit", "10")
485    ///     .send()
486    ///     .await?;
487    /// ```
488    pub fn query(mut self, key: &str, value: &str) -> Self {
489        self.query_params.push((key.to_string(), value.to_string()));
490        self
491    }
492
493    /// 批量添加查询参数
494    ///
495    /// # 参数
496    ///
497    /// - `params`: 查询参数列表
498    ///
499    /// # 示例
500    ///
501    /// ```rust,ignore
502    /// let response = client
503    ///     .get("https://api.example.com/users")
504    ///     .queries(vec![("page", "1"), ("limit", "10")])
505    ///     .send()
506    ///     .await?;
507    /// ```
508    pub fn queries(mut self, params: Vec<(&str, &str)>) -> Self {
509        for (key, value) in params {
510            self.query_params.push((key.to_string(), value.to_string()));
511        }
512        self
513    }
514
515    /// 设置 JSON 请求体
516    ///
517    /// # 参数
518    ///
519    /// - `json`: 可序列化为 JSON 的数据
520    ///
521    /// # 返回
522    ///
523    /// - `Ok(Self)`: 设置成功
524    /// - `Err(BaseError)`: 序列化失败
525    ///
526    /// # 示例
527    ///
528    /// ```rust,ignore
529    /// #[derive(Serialize)]
530    /// struct User {
531    ///     name: String,
532    ///     email: String,
533    /// }
534    ///
535    /// let user = User {
536    ///     name: "Alice".to_string(),
537    ///     email: "alice@example.com".to_string(),
538    /// };
539    ///
540    /// let response = client
541    ///     .post("https://api.example.com/users")
542    ///     .json(&user)?
543    ///     .send()
544    ///     .await?;
545    /// ```
546    pub fn json<T: Serialize>(mut self, json: &T) -> Result<Self, BaseError> {
547        let json_bytes =
548            serde_json::to_vec(json).map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
549
550        self.body = Some(json_bytes);
551        self = self.content_type("application/json");
552
553        Ok(self)
554    }
555
556    /// 设置表单请求体
557    ///
558    /// 使用 `serde_urlencoded` 对表单数据进行 URL 编码,正确处理特殊字符、
559    /// 空格、UTF-8 字符等,并自动设置 `Content-Type: application/x-www-form-urlencoded`。
560    ///
561    /// # 参数
562    ///
563    /// - `form`: 表单数据(键值对列表)
564    ///
565    /// # 示例
566    ///
567    /// ```rust,ignore
568    /// let response = client
569    ///     .post("https://api.example.com/login")
570    ///     .form(vec![("username", "alice"), ("password", "secret")])
571    ///     .send()
572    ///     .await?;
573    /// ```
574    pub fn form(mut self, form: Vec<(&str, &str)>) -> Self {
575        // 使用 serde_urlencoded 进行标准 URL 编码,正确处理特殊字符
576        match serde_urlencoded::to_string(&form) {
577            Ok(encoded) => {
578                self.body = Some(encoded.into_bytes());
579                // 自动设置 Content-Type
580                self = self.content_type("application/x-www-form-urlencoded");
581            }
582            Err(e) => {
583                // 编码失败时累积错误
584                self.header_errors.push(format!("表单数据编码失败: {}", e));
585            }
586        }
587        self
588    }
589
590    /// 设置原始字节请求体
591    ///
592    /// # 参数
593    ///
594    /// - `body`: 字节数据
595    ///
596    /// # 示例
597    ///
598    /// ```rust,ignore
599    /// let response = client
600    ///     .post("https://api.example.com/upload")
601    ///     .body(vec![0x00, 0x01, 0x02])
602    ///     .send()
603    ///     .await?;
604    /// ```
605    pub fn body(mut self, body: Vec<u8>) -> Self {
606        self.body = Some(body);
607        self
608    }
609
610    /// 设置文本请求体
611    ///
612    /// # 参数
613    ///
614    /// - `text`: 文本数据
615    ///
616    /// # 示例
617    ///
618    /// ```rust,ignore
619    /// let response = client
620    ///     .post("https://api.example.com/notes")
621    ///     .text("Hello, World!")
622    ///     .send()
623    ///     .await?;
624    /// ```
625    pub fn text(mut self, text: &str) -> Self {
626        self.body = Some(text.as_bytes().to_vec());
627        self = self.content_type("text/plain");
628        self
629    }
630
631    /// 设置超时时间
632    ///
633    /// # 参数
634    ///
635    /// - `timeout_secs`: 超时时间(秒)
636    ///
637    /// # 示例
638    ///
639    /// ```rust,ignore
640    /// let response = client
641    ///     .get("https://api.example.com/users")
642    ///     .timeout(60)
643    ///     .send()
644    ///     .await?;
645    /// ```
646    pub fn timeout(mut self, timeout_secs: u64) -> Self {
647        self.timeout = Duration::from_secs(timeout_secs);
648        self
649    }
650
651    /// 设置出站响应体最大允许字节数。
652    ///
653    /// 与 `HttpClientConfig::max_response_bytes` 语义一致:读取响应体时超限
654    /// 返回 `BaseError::HttpResponseTooLarge`。设为 0 会在 `send()` 前被拒绝。
655    ///
656    /// # 参数
657    ///
658    /// - `bytes`: 响应体最大允许字节数(必须大于 0)
659    ///
660    /// # 示例
661    ///
662    /// ```rust,ignore
663    /// let response = client
664    ///     .get("https://api.example.com/users")
665    ///     .max_response_bytes(1024 * 1024)
666    ///     .send()
667    ///     .await?;
668    /// ```
669    pub fn max_response_bytes(mut self, bytes: usize) -> Self {
670        self.max_response_bytes = bytes;
671        self
672    }
673
674    /// 设置请求级重试策略(L-4)。
675    ///
676    /// 默认不重试。启用后,对连接错误与命中 `retry_on` 的状态码按指数退避重试。
677    ///
678    /// 非幂等方法(POST/PATCH)默认不参与重试,需
679    /// [`RetryConfig::retry_non_idempotent`] 置为 `true` 才显式承担重复写风险。
680    ///
681    /// # 参数
682    ///
683    /// - `config`: 重试策略
684    ///
685    /// # 示例
686    ///
687    /// ```rust,ignore
688    /// use yang_base::http::RetryConfig;
689    ///
690    /// let response = client
691    ///     .get("https://api.example.com/users")
692    ///     .retry(RetryConfig::default())
693    ///     .send()
694    ///     .await?;
695    /// ```
696    pub fn retry(mut self, config: RetryConfig) -> Self {
697        self.retry = Some(config);
698        self
699    }
700
701    /// 发送请求
702    ///
703    /// 在发送前检查累积的 header 错误。若存在任何 header 解析错误,
704    /// 则返回 `BaseError::ParamInvalid("header", ...)` 而不发送请求。
705    ///
706    /// # 返回
707    ///
708    /// - `Ok(Response)`: 响应对象
709    /// - `Err(BaseError::ParamInvalid)`: 存在非法 header
710    /// - `Err(BaseError::HttpRequestFailed)`: 请求发送失败
711    ///
712    /// # 示例
713    ///
714    /// ```rust,ignore
715    /// let response = client
716    ///     .get("https://api.example.com/users")
717    ///     .send()
718    ///     .await?;
719    /// ```
720    pub async fn send(self) -> Result<Response, BaseError> {
721        // 检查累积的 header 错误,若非空则提前返回错误
722        if !self.header_errors.is_empty() {
723            return Err(BaseError::ParamInvalid(
724                "header".to_string(),
725                self.header_errors.join("; "),
726            ));
727        }
728
729        if self
730            .query_params
731            .iter()
732            .any(|(key, _)| key.trim().is_empty())
733        {
734            return Err(BaseError::ParamInvalid(
735                "query".to_string(),
736                "query 参数名称不能为空".to_string(),
737            ));
738        }
739
740        let parsed_url = reqwest::Url::parse(&self.url).map_err(|err| {
741            BaseError::ParamInvalid("url".to_string(), format!("非法 HTTP URL: {}", err))
742        })?;
743        if !matches!(parsed_url.scheme(), "http" | "https") {
744            return Err(BaseError::ParamInvalid(
745                "url".to_string(),
746                "HTTP 客户端仅支持 http 和 https URL".to_string(),
747            ));
748        }
749
750        if let Some(token) = &self.token {
751            let auth_value = format!("Bearer {}", token);
752            if let Err(err) = HeaderValue::from_str(&auth_value) {
753                return Err(BaseError::ParamInvalid(
754                    "authorization".to_string(),
755                    format!("非法 bearer token,无法构造 Authorization 头: {}", err),
756                ));
757            }
758        }
759
760        if self.timeout.is_zero() {
761            return Err(BaseError::ParamInvalid(
762                "http.timeout_secs".to_string(),
763                "HTTP 请求超时时间必须大于 0 秒".to_string(),
764            ));
765        }
766
767        if self.max_response_bytes == 0 {
768            return Err(BaseError::ParamInvalid(
769                "http.max_response_bytes".to_string(),
770                "HTTP 响应体上限必须大于 0 字节".to_string(),
771            ));
772        }
773
774        if let Some(retry) = &self.retry {
775            retry.validate()?;
776        }
777
778        let retry = self.retry.clone();
779
780        // 解析目标 host 用于熔断分键;无熔断器或解析失败时为 None(按无熔断处理)。
781        let host = self
782            .circuit_breaker
783            .as_ref()
784            .and_then(|_| parsed_url.host_str().map(|h| h.to_string()));
785
786        // 无重试策略:单次发送(与原行为一致,仅多一层熔断准入)
787        let Some(retry) = retry else {
788            return self.send_guarded(host.as_deref()).await;
789        };
790
791        // 非幂等方法未显式 opt-in:退化为单次发送。
792        // 该闸门同时覆盖状态码重试分支与传输错误重试分支——POST/PATCH 一旦命中
793        // `retry_on` 或连接中断同样会重放已生效的写入,须一并拦截。
794        if !is_idempotent_method(&self.method) && !retry.retry_non_idempotent {
795            return self.send_guarded(host.as_deref()).await;
796        }
797
798        // 有重试策略:最多发送 1 + max_retries 次。
799        // `remaining_budget_ms` 是本轮 `send()` 内全部退避等待共享的总预算。
800        let mut attempt: u32 = 0;
801        let mut remaining_budget_ms = retry.total_budget_ms;
802        loop {
803            let result = self.send_guarded(host.as_deref()).await;
804
805            let should_retry = match &result {
806                // 命中可重试状态码
807                Ok(resp) => retry.retry_on.contains(&resp.status()),
808                // 连接/超时等传输错误也重试
809                Err(BaseError::HttpRequestFailed(_)) => true,
810                // 熔断打开(HttpCircuitBreakerOpen)等其它错误不重试
811                Err(_) => false,
812            };
813
814            if !should_retry || attempt >= retry.max_retries {
815                return result;
816            }
817
818            // 指数退避 backoff_ms * 2^attempt,叠加抖动,再受剩余预算钳制:
819            // 预算耗尽(钳制后为 0)时不再等待,直接返回最后一次结果,避免
820            // 「重试 + 长退避」把单次 send() 拖成长尾。
821            let base = retry.backoff_ms.saturating_mul(1u64 << attempt.min(20));
822            let sleep_ms =
823                jittered_backoff(base, retry.jitter_percent, attempt).min(remaining_budget_ms);
824            if sleep_ms == 0 {
825                return result;
826            }
827
828            tokio::time::sleep(Duration::from_millis(sleep_ms)).await;
829            remaining_budget_ms -= sleep_ms;
830            attempt += 1;
831        }
832    }
833
834    /// 在熔断器准入检查下发送一次请求,并按结果记录成功/失败。
835    ///
836    /// - 准入:若熔断器对该 host 处于 Open(且未冷却),直接返回
837    ///   `BaseError::HttpCircuitBreakerOpen`,不实际发请求。
838    /// - 记账:传输错误与 5xx 视为失败,2xx/3xx/4xx 视为成功。
839    ///
840    /// 当 `host` 为 `None`(无熔断器或 URL 解析不出 host)时,等价于直接 `send_once`。
841    async fn send_guarded(&self, host: Option<&str>) -> Result<Response, BaseError> {
842        let breaker = self.circuit_breaker.as_ref();
843
844        if let (Some(breaker), Some(host)) = (breaker, host) {
845            if !breaker.allow(host) {
846                return Err(BaseError::HttpCircuitBreakerOpen(host.to_string()));
847            }
848        }
849
850        let result = self.send_once().await;
851
852        if let (Some(breaker), Some(host)) = (breaker, host) {
853            match &result {
854                Ok(resp) if resp.status() >= 500 => breaker.on_failure(host),
855                Ok(_) => breaker.on_success(host),
856                Err(_) => breaker.on_failure(host),
857            }
858        }
859
860        result
861    }
862
863    /// 构建并发送一次请求(不含重试)。
864    ///
865    /// 因重试需要重复发送,这里借用 `&self` 并克隆可复用的请求部件
866    /// (headers / query / body 均可 clone;`client` 为 `Arc`,clone 复用连接池)。
867    async fn send_once(&self) -> Result<Response, BaseError> {
868        // 构建请求
869        // 注意:self.client.clone() 是 Arc::clone,复用同一底层连接池,不创建新的 TCP 连接池
870        let mut request = self
871            .client
872            .request(self.method.clone(), &self.url)
873            .timeout(self.timeout);
874
875        // 添加请求头
876        request = request.headers(self.headers.clone());
877
878        // 添加 Token
879        if let Some(token) = &self.token {
880            request = request.bearer_auth(token);
881        }
882
883        // 添加查询参数
884        if !self.query_params.is_empty() {
885            request = request.query(&self.query_params);
886        }
887
888        // 添加请求体
889        if let Some(body) = &self.body {
890            request = request.body(body.clone());
891        }
892
893        // 发送请求(NG-1:记录方法/URL/状态码/耗时,便于排查外部 API 慢响应与失败)。
894        // URL 日志脱敏:移除 query,并隐藏 userinfo,避免泄漏 token/password。
895        let start = std::time::Instant::now();
896        let result = request.send().await;
897        let elapsed_ms = start.elapsed().as_millis();
898        let log_url = redact_url_for_log(&self.url);
899        match &result {
900            Ok(resp) => {
901                tracing::debug!(
902                    target: "yang_base::http",
903                    method = %self.method,
904                    url = %log_url,
905                    status = resp.status().as_u16(),
906                    elapsed_ms = elapsed_ms as u64,
907                    "HTTP 出站请求完成"
908                );
909            }
910            Err(e) => {
911                tracing::warn!(
912                    target: "yang_base::http",
913                    method = %self.method,
914                    url = %log_url,
915                    elapsed_ms = elapsed_ms as u64,
916                    timeout = e.is_timeout(),
917                    connect = e.is_connect(),
918                    builder = e.is_builder(),
919                    request = e.is_request(),
920                    "HTTP 出站请求失败"
921                );
922            }
923        }
924        let response = result.map_err(BaseError::HttpRequestFailed)?;
925
926        Ok(Response::new(response, self.max_response_bytes))
927    }
928}
929
930#[cfg(test)]
931mod retry_config_tests {
932    use super::*;
933    use std::sync::atomic::Ordering;
934
935    #[tokio::test]
936    async fn failed_request_logs_do_not_expose_url_secrets() {
937        let _ = rustls::crypto::ring::default_provider().install_default();
938        use std::io::Write;
939        use std::sync::{Arc, Mutex};
940        use tracing::instrument::WithSubscriber;
941        struct Writer(Arc<Mutex<Vec<u8>>>);
942        impl Write for Writer {
943            fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
944                self.0.lock().expect("日志锁").write(bytes)
945            }
946            fn flush(&mut self) -> std::io::Result<()> {
947                Ok(())
948            }
949        }
950        let buf = Arc::new(Mutex::new(Vec::new()));
951        let writer_buf = buf.clone();
952        let subscriber = tracing_subscriber::fmt()
953            .with_ansi(false)
954            .with_max_level(tracing::Level::DEBUG)
955            .with_writer(move || Writer(writer_buf.clone()))
956            .finish();
957        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("本地端口");
958        let port = listener.local_addr().expect("地址").port();
959        drop(listener);
960        let result = RequestBuilder::new(
961            Client::builder().no_proxy().build().expect("客户端"), Method::GET,
962            format!("http://user-secret:password-secret@127.0.0.1:{port}/path?token=query-secret#fragment-secret"),
963            Duration::from_secs(2), 1024, None, None
964        ).query("extra", "builder-secret").send().with_subscriber(subscriber).await;
965        let Err(BaseError::HttpRequestFailed(error)) = result else {
966            panic!("应返回原始请求错误");
967        };
968        assert!(
969            error.is_connect() || error.is_builder() || error.is_request(),
970            "{error:?}"
971        );
972        // reqwest 的异步客户端只在超时等少数路径把 URL 挂到错误上;连接被拒绝
973        // 的错误不带 URL(Linux CI 即如此,Windows 回环多表现为超时),因此仅在
974        // URL 存在时校验 builder 注入的参数,避免测试结果依赖平台错误路径。
975        if let Some(url) = error.url() {
976            assert!(
977                url.query()
978                    .is_some_and(|query| query.contains("builder-secret")),
979                "{url}"
980            );
981        }
982        let logs = String::from_utf8(buf.lock().expect("日志锁").clone()).expect("日志 UTF8");
983        assert!(logs.contains("HTTP 出站请求失败"));
984        for secret in [
985            "user-secret",
986            "password-secret",
987            "query-secret",
988            "fragment-secret",
989            "builder-secret",
990        ] {
991            assert!(!logs.contains(secret), "不得记录 {secret}: {logs}");
992        }
993    }
994
995    #[test]
996    fn test_redact_url_for_log_removes_query_and_userinfo() {
997        let redacted = redact_url_for_log("https://user:secret@example.com/path?token=secret&x=1");
998
999        assert_eq!(redacted, "https://***:***@example.com/path");
1000        assert!(!redacted.contains("token"));
1001        assert!(!redacted.contains("secret"));
1002        assert!(!redacted.contains("user"));
1003    }
1004
1005    #[test]
1006    fn test_retry_config_validate_rejects_unsafe_values() {
1007        let invalid_configs = [
1008            RetryConfig {
1009                max_retries: 11,
1010                ..RetryConfig::default()
1011            },
1012            RetryConfig {
1013                max_retries: 1,
1014                retry_on: Vec::new(),
1015                ..RetryConfig::default()
1016            },
1017            RetryConfig {
1018                max_retries: 1,
1019                backoff_ms: 0,
1020                ..RetryConfig::default()
1021            },
1022            RetryConfig {
1023                max_retries: 1,
1024                backoff_ms: 60_001,
1025                ..RetryConfig::default()
1026            },
1027            RetryConfig {
1028                max_retries: 1,
1029                retry_on: vec![99],
1030                ..RetryConfig::default()
1031            },
1032            RetryConfig {
1033                max_retries: 1,
1034                retry_on: vec![600],
1035                ..RetryConfig::default()
1036            },
1037        ];
1038
1039        for config in invalid_configs {
1040            assert!(matches!(
1041                config.validate(),
1042                Err(BaseError::ParamInvalid(_, _))
1043            ));
1044        }
1045    }
1046
1047    #[test]
1048    fn test_retry_config_validate_rejects_bad_budget_and_jitter() {
1049        let cases = [
1050            // 总预算不能为 0(不留「无预算」后门)
1051            (
1052                "http.retry.total_budget_ms",
1053                RetryConfig {
1054                    max_retries: 1,
1055                    total_budget_ms: 0,
1056                    ..RetryConfig::default()
1057                },
1058            ),
1059            // 总预算不能超过上限
1060            (
1061                "http.retry.total_budget_ms",
1062                RetryConfig {
1063                    max_retries: 1,
1064                    total_budget_ms: RetryConfig::MAX_TOTAL_BUDGET_MS + 1,
1065                    ..RetryConfig::default()
1066                },
1067            ),
1068            // 抖动百分比不能超过 100
1069            (
1070                "http.retry.jitter_percent",
1071                RetryConfig {
1072                    max_retries: 1,
1073                    jitter_percent: 101,
1074                    ..RetryConfig::default()
1075                },
1076            ),
1077        ];
1078
1079        for (expected_field, config) in cases {
1080            let err = match config.validate() {
1081                Ok(()) => panic!("非法 {expected_field} 应被 validate() 拒绝"),
1082                Err(err) => err,
1083            };
1084            assert!(
1085                matches!(&err, BaseError::ParamInvalid(field, _) if field == expected_field),
1086                "期望 ParamInvalid({expected_field}),实际 {err:?}"
1087            );
1088        }
1089    }
1090
1091    #[test]
1092    fn test_retry_config_default_and_boundaries_are_valid() {
1093        assert!(
1094            RetryConfig::default().validate().is_ok(),
1095            "默认配置必须通过校验"
1096        );
1097
1098        // 边界:预算取上限、抖动取 100 均为合法值
1099        assert!(RetryConfig {
1100            max_retries: 1,
1101            total_budget_ms: RetryConfig::MAX_TOTAL_BUDGET_MS,
1102            jitter_percent: 100,
1103            ..RetryConfig::default()
1104        }
1105        .validate()
1106        .is_ok());
1107    }
1108
1109    #[test]
1110    fn test_jittered_backoff_identity_and_bounds() {
1111        // jitter_percent = 0:恒等返回 base
1112        for base in [0_u64, 1, 99, 100, 1_000, u64::MAX] {
1113            assert_eq!(
1114                jittered_backoff(base, 0, 0),
1115                base,
1116                "jitter_percent=0 时退避时长不应改变"
1117            );
1118        }
1119
1120        // base = 0:任何抖动都只能得到 0
1121        assert_eq!(jittered_backoff(0, 100, 3), 0);
1122
1123        // span 向下取整为 0(base < 100):不做抖动,避免下溢
1124        assert_eq!(jittered_backoff(50, 1, 0), 50);
1125
1126        // jitter_percent = 100:结果落在 [base - span, base + span]
1127        let base = 1_000_u64;
1128        let span = base / 100 * 100;
1129        for attempt in 0..64 {
1130            let got = jittered_backoff(base, 100, attempt);
1131            assert!(
1132                (base - span..=base + span).contains(&got),
1133                "第 {attempt} 次抖动的退避 {got} 应落在 [{}, {}]",
1134                base - span,
1135                base + span
1136            );
1137        }
1138    }
1139
1140    /// 起一个对每个请求都回 `503` 的本地监听器,用于验证重试次数与耗时。
1141    ///
1142    /// 返回 `(监听地址, 请求计数)`;监听线程随测试结束由进程回收。
1143    fn spawn_503_listener() -> (
1144        std::net::SocketAddr,
1145        std::sync::Arc<std::sync::atomic::AtomicUsize>,
1146    ) {
1147        use std::io::{Read, Write};
1148        use std::sync::atomic::{AtomicUsize, Ordering};
1149        use std::sync::Arc;
1150
1151        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("本地监听端口应可绑定");
1152        let addr = listener.local_addr().expect("应能取得监听地址");
1153        let counter = Arc::new(AtomicUsize::new(0));
1154        let counter_for_thread = Arc::clone(&counter);
1155
1156        std::thread::spawn(move || {
1157            for stream in listener.incoming() {
1158                let Ok(mut stream) = stream else { break };
1159                counter_for_thread.fetch_add(1, Ordering::SeqCst);
1160                // 读走请求再回 503,避免客户端写请求时收到 EPIPE
1161                let mut buf = [0u8; 1024];
1162                let _ = stream.read(&mut buf);
1163                let _ = stream.write_all(
1164                    b"HTTP/1.1 503 Service Unavailable\r\nContent-Length: 0\r\nConnection: close\r\n\r\n",
1165                );
1166                let _ = stream.flush();
1167            }
1168        });
1169
1170        (addr, counter)
1171    }
1172
1173    /// 预算钳制:总预算小于首轮退避时只睡剩余预算,随后立即返回最后一次结果。
1174    #[tokio::test]
1175    async fn test_send_clamps_backoff_wait_to_total_budget() {
1176        let (addr, counter) = spawn_503_listener();
1177        let client = crate::http::HttpClient::new(30).expect("HTTP client should be valid");
1178
1179        let started = std::time::Instant::now();
1180        let result = client
1181            .get(&format!("http://{addr}/always-503"))
1182            .retry(RetryConfig {
1183                max_retries: 3,
1184                retry_on: vec![503],
1185                backoff_ms: 1_000,
1186                jitter_percent: 0,
1187                total_budget_ms: 5,
1188                ..RetryConfig::default()
1189            })
1190            .send()
1191            .await;
1192        let elapsed = started.elapsed();
1193
1194        // 预算耗尽不等于丢结果:仍须把最后一次响应(503)返回给调用方
1195        let resp = match result {
1196            Ok(resp) => resp,
1197            Err(err) => panic!("预算耗尽后应返回最后一次响应而非错误: {err:?}"),
1198        };
1199        assert_eq!(resp.status(), 503);
1200
1201        // 未钳制时退避合计 1000 + 2000 + 4000 = 7000ms;钳制后只有 1 次 5ms 等待
1202        assert!(
1203            elapsed < Duration::from_millis(500),
1204            "退避等待应被总预算钳制(未钳制需约 7s),实际耗时 {elapsed:?}"
1205        );
1206
1207        // 等监听线程计数落定:预算耗尽后不应再发第 3 次请求
1208        tokio::time::sleep(Duration::from_millis(200)).await;
1209        assert_eq!(
1210            counter.load(Ordering::SeqCst),
1211            2,
1212            "预算耗尽后应停止重试(首次 + 1 次重试共 2 次请求)"
1213        );
1214    }
1215
1216    #[tokio::test]
1217    async fn test_send_rejects_invalid_retry_config_before_network() {
1218        let builder = RequestBuilder::new(
1219            Client::new(),
1220            Method::GET,
1221            "http://127.0.0.1:1".to_string(),
1222            Duration::from_secs(30),
1223            10 * 1024 * 1024,
1224            None,
1225            None,
1226        )
1227        .retry(RetryConfig {
1228            max_retries: 11,
1229            ..RetryConfig::default()
1230        });
1231
1232        let err = match builder.send().await {
1233            Ok(_) => panic!("无效 retry 配置应在网络请求前被拒绝"),
1234            Err(err) => err,
1235        };
1236
1237        assert!(
1238            matches!(err, BaseError::ParamInvalid(field, _) if field == "http.retry.max_retries")
1239        );
1240    }
1241
1242    #[tokio::test]
1243    async fn test_send_rejects_zero_request_timeout_before_network() {
1244        let builder = RequestBuilder::new(
1245            Client::new(),
1246            Method::GET,
1247            "http://127.0.0.1:1".to_string(),
1248            Duration::from_secs(30),
1249            10 * 1024 * 1024,
1250            None,
1251            None,
1252        )
1253        .timeout(0);
1254
1255        let err = match builder.send().await {
1256            Ok(_) => panic!("0 秒请求超时应在网络请求前被拒绝"),
1257            Err(err) => err,
1258        };
1259
1260        assert!(matches!(err, BaseError::ParamInvalid(field, _) if field == "http.timeout_secs"));
1261    }
1262
1263    #[tokio::test]
1264    async fn test_send_rejects_blank_query_key_before_network() {
1265        let client = crate::http::HttpClient::new(30).expect("HTTP client should be valid");
1266        let result = client
1267            .get("https://api.example.com/users")
1268            .query("   ", "value")
1269            .send()
1270            .await;
1271
1272        let err = match result {
1273            Err(err) => err,
1274            Ok(_) => panic!("空白 query key 应在发送前被拒绝"),
1275        };
1276
1277        assert!(matches!(
1278            err,
1279            crate::error::BaseError::ParamInvalid(field, _) if field == "query"
1280        ));
1281    }
1282
1283    #[tokio::test]
1284    async fn test_send_rejects_invalid_bearer_token_before_network() {
1285        let builder = RequestBuilder::new(
1286            Client::new(),
1287            Method::GET,
1288            "http://127.0.0.1:1".to_string(),
1289            Duration::from_secs(30),
1290            10 * 1024 * 1024,
1291            Some("bad\r\ntoken".to_string()),
1292            None,
1293        );
1294
1295        let err = match builder.send().await {
1296            Ok(_) => panic!("非法 bearer token 应在网络请求前被拒绝"),
1297            Err(err) => err,
1298        };
1299
1300        assert!(matches!(err, BaseError::ParamInvalid(field, _) if field == "authorization"));
1301    }
1302
1303    #[tokio::test]
1304    async fn test_send_rejects_invalid_url_before_network() {
1305        let invalid_urls = ["not a url", "ftp://example.com/file"];
1306
1307        for url in invalid_urls {
1308            let builder = RequestBuilder::new(
1309                Client::new(),
1310                Method::GET,
1311                url.to_string(),
1312                Duration::from_secs(30),
1313                10 * 1024 * 1024,
1314                None,
1315                None,
1316            );
1317
1318            let err = match builder.send().await {
1319                Ok(_) => panic!("非法 URL 应在网络请求前被拒绝"),
1320                Err(err) => err,
1321            };
1322
1323            assert!(matches!(err, BaseError::ParamInvalid(field, _) if field == "url"));
1324        }
1325    }
1326
1327    #[test]
1328    fn test_is_idempotent_method_classification() {
1329        // 安全/幂等方法:默认允许重试
1330        for method in [
1331            Method::GET,
1332            Method::HEAD,
1333            Method::OPTIONS,
1334            Method::TRACE,
1335            Method::PUT,
1336            Method::DELETE,
1337        ] {
1338            assert!(
1339                is_idempotent_method(&method),
1340                "{method} 应被判定为幂等/安全方法"
1341            );
1342        }
1343
1344        // 非幂等方法:默认不参与重试
1345        for method in [Method::POST, Method::PATCH] {
1346            assert!(
1347                !is_idempotent_method(&method),
1348                "{method} 不应被判定为幂等方法"
1349            );
1350        }
1351    }
1352
1353    /// 起一个只计数、读完即断开的本地监听器,用于统计实际发起的请求次数。
1354    ///
1355    /// 返回 `(监听地址, 连接计数)`;监听线程随测试结束由进程回收。
1356    fn spawn_closing_listener() -> (
1357        std::net::SocketAddr,
1358        std::sync::Arc<std::sync::atomic::AtomicUsize>,
1359    ) {
1360        use std::io::Read;
1361        use std::sync::atomic::{AtomicUsize, Ordering};
1362        use std::sync::Arc;
1363
1364        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("本地监听端口应可绑定");
1365        let addr = listener.local_addr().expect("应能取得监听地址");
1366        let counter = Arc::new(AtomicUsize::new(0));
1367        let counter_for_thread = Arc::clone(&counter);
1368
1369        std::thread::spawn(move || {
1370            for stream in listener.incoming() {
1371                let Ok(mut stream) = stream else { break };
1372                counter_for_thread.fetch_add(1, Ordering::SeqCst);
1373                // 读走请求后直接关闭连接,制造传输错误(而非可重试状态码)
1374                let mut buf = [0u8; 1024];
1375                let _ = stream.read(&mut buf);
1376            }
1377        });
1378
1379        (addr, counter)
1380    }
1381
1382    /// 非幂等的 POST 未 opt-in 时,即使启用了重试也只发送一次。
1383    /// 标记 ignore:发起真实连接,依赖网络栈行为,默认跳过。
1384    #[tokio::test]
1385    #[ignore = "依赖网络栈行为,发起真实连接;默认跳过"]
1386    async fn test_post_not_retried_without_opt_in() {
1387        let (addr, counter) = spawn_closing_listener();
1388        let client = crate::http::HttpClient::new(1).expect("HTTP client should be valid");
1389
1390        let result = client
1391            .post(&format!("http://{addr}/never"))
1392            .retry(RetryConfig {
1393                max_retries: 3,
1394                retry_on: vec![503],
1395                backoff_ms: 1,
1396                retry_non_idempotent: false,
1397                ..RetryConfig::default()
1398            })
1399            .send()
1400            .await;
1401
1402        assert!(result.is_err(), "监听器直接断开,应返回传输错误");
1403        // 给监听线程留出计数落定的时间
1404        tokio::time::sleep(Duration::from_millis(200)).await;
1405        assert_eq!(
1406            counter.load(Ordering::SeqCst),
1407            1,
1408            "非幂等 POST 未 opt-in 时只应发送一次"
1409        );
1410    }
1411
1412    /// 非幂等的 POST 显式 opt-in 后,重试仍然生效(耗尽 max_retries)。
1413    /// 标记 ignore:发起真实连接,依赖网络栈行为,默认跳过。
1414    #[tokio::test]
1415    #[ignore = "依赖网络栈行为,发起真实连接;默认跳过"]
1416    async fn test_post_retried_when_opted_in() {
1417        let (addr, counter) = spawn_closing_listener();
1418        let client = crate::http::HttpClient::new(1).expect("HTTP client should be valid");
1419
1420        let result = client
1421            .post(&format!("http://{addr}/never"))
1422            .retry(RetryConfig {
1423                max_retries: 3,
1424                retry_on: vec![503],
1425                backoff_ms: 1,
1426                retry_non_idempotent: true,
1427                ..RetryConfig::default()
1428            })
1429            .send()
1430            .await;
1431
1432        assert!(result.is_err(), "监听器直接断开,应返回传输错误");
1433        tokio::time::sleep(Duration::from_millis(200)).await;
1434        assert_eq!(
1435            counter.load(Ordering::SeqCst),
1436            4,
1437            "opt-in 后应发送 1 + max_retries 次"
1438        );
1439    }
1440}