Skip to main content

yang_base/action/
response.rs

1//! Action 响应结构
2//!
3//! 提供统一的 API 响应格式,包含状态码、消息和数据。
4
5use crate::error::BaseError;
6use schemars::JsonSchema;
7use serde::Serialize;
8use std::path::PathBuf;
9
10/// [`ResponseBody::Raw`] 唯一允许的响应内容类型。
11///
12/// 该逃生口存在的理由是「外部系统的响应契约与框架 JSON 包络不兼容」,不是通用响应通道;
13/// [`ResponseBody::raw`] 构造器与派发边界 [`wrap_dispatch_output`] 都按本白名单校验,
14/// 防止该变体被用来返回 `text/html`,从而绕过前端 JSON 契约的保护。
15///
16/// 注意该保证只覆盖 [`ResponseBody::Raw`]:下游直接构造的
17/// [`ResponseAttachment::Raw`](如在用的 receivables-system `text/csv` 模板下载)与
18/// 按扩展名可能返回 `text/html`/`image/svg+xml` 的 [`ResponseBody::Preview`] 是另外的
19/// 非 JSON 通道,不在本白名单范围内。
20const RAW_ALLOWED_CONTENT_TYPE: &str = "application/json";
21
22/// 校验 Raw 响应内容类型。
23///
24/// 构造器与派发边界共用,确保「直接构造变体」不能绕过 [`ResponseBody::raw`] 的白名单。
25fn validate_raw_content_type(content_type: &str) -> Result<(), BaseError> {
26    if content_type != RAW_ALLOWED_CONTENT_TYPE {
27        return Err(BaseError::ConfigError(format!(
28            "Raw 响应 content-type 只允许 {RAW_ALLOWED_CONTENT_TYPE},收到 {content_type}"
29        )));
30    }
31    Ok(())
32}
33
34/// API 响应
35///
36/// 统一的 API 响应格式,用于所有 Action 的返回值
37///
38/// # 字段
39///
40/// - `code`: 状态码(0 表示成功,非零表示失败)
41/// - `message`: 响应消息
42/// - `data`: 响应数据(可选)
43///
44/// 标注 `#[non_exhaustive]`:未来新增字段不构成破坏性变更。
45/// 请使用 [`ApiResponse::success`] / [`ApiResponse::fail`] / [`ApiResponse::from_error`] 等构造。
46///
47/// # 示例
48///
49/// ```rust,ignore
50/// use yang_base::action::ApiResponse;
51/// use serde_json::json;
52///
53/// // 创建成功响应
54/// let response = ApiResponse::success(
55///     json!({ "id": 123, "name": "Alice" }),
56///     "操作成功"
57/// );
58/// assert_eq!(response.code, 0);
59///
60/// // 创建失败响应
61/// let response = ApiResponse::fail(400001, "参数错误");
62/// assert_eq!(response.code, 400001);
63/// assert!(response.data.is_none());
64/// ```
65#[derive(Debug, Clone, Serialize, JsonSchema)]
66#[non_exhaustive]
67pub struct ApiResponse {
68    /// 状态码
69    ///
70    /// - 0: 成功
71    /// - 非零: 失败(具体错误码由业务定义)
72    pub code: i32,
73
74    /// 响应消息
75    ///
76    /// 描述操作结果的文本信息
77    pub message: String,
78
79    /// 响应数据
80    ///
81    /// 成功时包含业务数据,失败时通常为 None
82    #[serde(skip_serializing_if = "Option::is_none")]
83    pub data: Option<serde_json::Value>,
84
85    /// 非 JSON 附件(文件下载/预览/重定向),由传输层消费。
86    ///
87    /// 仅当 Action 以 [`ResponseBody`] 为输出时由派发边界填充;
88    /// `serde(skip)` 保证普通 Action 的 JSON 线格式不受影响。
89    #[serde(skip)]
90    #[schemars(skip)]
91    pub attachment: Option<ResponseAttachment>,
92
93    /// 由 Action 显式声明、传输层消费的 HTTP 状态码覆盖。
94    #[serde(skip)]
95    #[schemars(skip)]
96    http_status: Option<u16>,
97
98    /// 由 Action 显式声明、传输层消费的响应头。
99    #[serde(skip)]
100    #[schemars(skip)]
101    headers: Vec<(String, String)>,
102}
103
104impl ApiResponse {
105    /// 创建成功响应
106    ///
107    /// 状态码为 0,包含业务数据。序列化失败时返回 `BaseError::JsonSerializeFailed`。
108    ///
109    /// # 参数
110    ///
111    /// - `data`: 响应数据(任何可序列化的类型)
112    /// - `message`: 成功消息
113    ///
114    /// # 返回
115    ///
116    /// - `Ok(ApiResponse)`: 序列化成功时返回响应实例
117    /// - `Err(BaseError::JsonSerializeFailed)`: 序列化失败时返回错误
118    ///
119    /// # Errors
120    ///
121    /// - `BaseError::JsonSerializeFailed`: 当 `data` 无法被序列化为 JSON 时
122    ///
123    /// # 示例
124    ///
125    /// ```rust,ignore
126    /// use yang_base::action::ApiResponse;
127    /// use serde_json::json;
128    ///
129    /// // 返回单个对象
130    /// let response = ApiResponse::success(
131    ///     json!({ "id": 1, "name": "Alice" }),
132    ///     "获取成功"
133    /// )?;
134    ///
135    /// // 返回影响行数
136    /// let response = ApiResponse::success(
137    ///     json!({ "affected": 1 }),
138    ///     "更新成功"
139    /// )?;
140    /// ```
141    pub fn success<T: Serialize>(data: T, message: impl Into<String>) -> Result<Self, BaseError> {
142        // 序列化数据,失败时返回结构化错误而非静默吞错
143        let json_value = serde_json::to_value(data)
144            .map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
145        Ok(Self {
146            code: 0,
147            message: message.into(),
148            data: Some(json_value),
149            attachment: None,
150            http_status: None,
151            headers: Vec::new(),
152        })
153    }
154
155    /// 创建成功响应(接受已序列化的 JSON 值)
156    ///
157    /// 当数据已经是 `serde_json::Value` 类型时,使用此方法可避免额外的序列化开销,
158    /// 且不会失败,因此直接返回 `Self` 而非 `Result`。
159    ///
160    /// # 参数
161    ///
162    /// - `data`: 已序列化的 JSON 值
163    /// - `message`: 成功消息
164    ///
165    /// # 返回
166    ///
167    /// - ApiResponse 实例
168    ///
169    /// # 示例
170    ///
171    /// ```rust,ignore
172    /// use yang_base::action::ApiResponse;
173    /// use serde_json::json;
174    ///
175    /// // 直接使用 serde_json::Value
176    /// let data = json!({ "id": 1, "name": "Alice" });
177    /// let response = ApiResponse::success_value(data, "获取成功");
178    /// assert_eq!(response.code, 0);
179    /// ```
180    pub fn success_value(data: serde_json::Value, message: impl Into<String>) -> Self {
181        Self {
182            code: 0,
183            message: message.into(),
184            data: Some(data),
185            attachment: None,
186            http_status: None,
187            headers: Vec::new(),
188        }
189    }
190
191    /// 创建失败响应
192    ///
193    /// 状态码为非零错误码,不包含数据
194    ///
195    /// # 参数
196    ///
197    /// - `code`: 错误码(非零整数)
198    /// - `message`: 错误消息
199    ///
200    /// # 返回
201    ///
202    /// - ApiResponse 实例
203    ///
204    /// # 示例
205    ///
206    /// ```rust,ignore
207    /// use yang_base::action::ApiResponse;
208    ///
209    /// // 参数错误
210    /// let response = ApiResponse::fail(400001, "参数缺失: username");
211    ///
212    /// // 权限错误
213    /// let response = ApiResponse::fail(403001, "权限不足");
214    ///
215    /// // 业务错误
216    /// let response = ApiResponse::fail(500001, "用户名已存在");
217    /// ```
218    pub fn fail(code: i32, message: impl Into<String>) -> Self {
219        Self {
220            code,
221            message: message.into(),
222            data: None,
223            attachment: None,
224            http_status: None,
225            headers: Vec::new(),
226        }
227    }
228
229    /// 创建携带诊断数据的失败响应。
230    ///
231    /// 与 [`ApiResponse::fail`](`data` 恒为空)相对,保留 `data` 载荷,
232    /// 供就绪探针等需要自描述失败原因的端点使用。
233    pub fn fail_value(code: i32, data: serde_json::Value, message: impl Into<String>) -> Self {
234        Self {
235            code,
236            message: message.into(),
237            data: Some(data),
238            attachment: None,
239            http_status: None,
240            headers: Vec::new(),
241        }
242    }
243
244    /// 创建携带附件的成功响应
245    ///
246    /// 由派发边界在识别到 Action 返回 [`ResponseBody`] 时调用。`data` 为 None,
247    /// 附件信息仅对传输层可见(`serde(skip)`),JSON 线格式保持不变。
248    ///
249    /// # 参数
250    ///
251    /// - `attachment`: 传输层消费的附件描述
252    /// - `message`: 成功消息
253    ///
254    /// # 返回
255    ///
256    /// - ApiResponse 实例
257    pub fn attachment(attachment: ResponseAttachment, message: impl Into<String>) -> Self {
258        Self {
259            code: 0,
260            message: message.into(),
261            data: None,
262            attachment: Some(attachment),
263            http_status: None,
264            headers: Vec::new(),
265        }
266    }
267
268    /// 覆盖 Action 静态声明的成功 HTTP 状态码。
269    pub fn with_http_status(mut self, status: u16) -> Result<Self, BaseError> {
270        if !(100..=599).contains(&status) {
271            return Err(BaseError::ConfigError(format!(
272                "响应 HTTP 状态码无效: {status}"
273            )));
274        }
275        self.http_status = Some(status);
276        Ok(self)
277    }
278
279    /// 追加一个经过最小 RFC 语法校验的响应头。
280    ///
281    /// 使用列表而不是 Map,以保留多个 `Set-Cookie` 等同名响应头。
282    pub fn with_header(
283        mut self,
284        name: impl Into<String>,
285        value: impl Into<String>,
286    ) -> Result<Self, BaseError> {
287        let name = name.into();
288        let value = value.into();
289        let valid_name = !name.is_empty()
290            && name.bytes().all(|byte| {
291                byte.is_ascii_alphanumeric()
292                    || matches!(
293                        byte,
294                        b'!' | b'#'
295                            | b'$'
296                            | b'%'
297                            | b'&'
298                            | b'\''
299                            | b'*'
300                            | b'+'
301                            | b'-'
302                            | b'.'
303                            | b'^'
304                            | b'_'
305                            | b'`'
306                            | b'|'
307                            | b'~'
308                    )
309            });
310        let valid_value = value
311            .bytes()
312            .all(|byte| byte == b'\t' || (byte >= 0x20 && byte != 0x7f));
313        if !valid_name || !valid_value {
314            return Err(BaseError::ConfigError(
315                "响应头名称或值包含非法字符".to_string(),
316            ));
317        }
318        self.headers.push((name, value));
319        Ok(self)
320    }
321
322    #[cfg(any(feature = "transport-axum", test))]
323    pub(crate) const fn http_status(&self) -> Option<u16> {
324        self.http_status
325    }
326
327    /// 返回 Action 显式追加、由传输层消费的响应头。
328    ///
329    /// 响应头不参与 [`ApiResponse`] 的 JSON 序列化;此只读视图主要用于
330    /// 传输适配器、集成测试以及需要检查 Cookie/缓存契约的应用层边界。
331    pub fn response_headers(&self) -> &[(String, String)] {
332        &self.headers
333    }
334
335    /// 从 BaseError 创建失败响应
336    ///
337    /// 自动提取错误码和错误消息。接受引用以避免消费 `BaseError` 所有权,
338    /// 调用方可在构建响应的同时保留 error 用于日志记录等后续用途。
339    ///
340    /// # 参数
341    ///
342    /// - `error`: BaseError 引用
343    ///
344    /// # 返回
345    ///
346    /// - ApiResponse 实例
347    ///
348    /// # 示例
349    ///
350    /// ```rust,ignore
351    /// use yang_base::action::ApiResponse;
352    /// use yang_base::error::BaseError;
353    ///
354    /// let error = BaseError::FieldRequired("username".to_string());
355    /// let response = ApiResponse::from_error(&error);
356    ///
357    /// assert_ne!(response.code, 0);
358    /// assert!(response.message.contains("username"));
359    /// assert!(response.data.is_none());
360    /// ```
361    pub fn from_error(error: &BaseError) -> Self {
362        Self::fail(error.code(), error.to_string())
363    }
364}
365
366impl Default for ApiResponse {
367    /// 创建默认响应
368    ///
369    /// 默认为成功响应,消息为 "OK",无数据
370    fn default() -> Self {
371        Self {
372            code: 0,
373            message: "OK".to_string(),
374            data: None,
375            attachment: None,
376            http_status: None,
377            headers: Vec::new(),
378        }
379    }
380}
381
382/// Action 的特殊业务响应体:文件下载、文件预览、重定向、原始响应体。
383///
384/// Action 将本类型作为 `type Output` 返回时,派发边界
385/// ([`DynAction::dispatch`](crate::action::DynAction))会识别并把它转为
386/// [`ApiResponse::attachment`],普通输出的 JSON 线格式不受影响。
387///
388/// 标注 `#[non_exhaustive]`:未来新增变体不再构成破坏性变更,下游穷尽 `match`
389/// 请保留通配臂。
390///
391/// # 示例
392///
393/// ```rust,ignore
394/// use yang_base::action::ResponseBody;
395///
396/// async fn index(&self, ctx: ActionContext, input: Self::Input) -> Result<Self::Output, BaseError> {
397///     // 文件下载
398///     Ok(ResponseBody::download("/data/report.pdf", "report.pdf"))
399///     // 文件预览
400///     // Ok(ResponseBody::preview("/data/a.png"))
401///     // 重定向
402///     // Ok(ResponseBody::redirect("https://example.com/next"))
403///     // 原始 JSON 响应体(不套 ApiResponse 包络)
404///     // ResponseBody::raw(r#"{"code":0,"msg":"ok"}"#, "application/json")
405/// }
406/// ```
407#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
408#[serde(tag = "type", rename_all = "snake_case")]
409#[non_exhaustive]
410pub enum ResponseBody {
411    /// 文件下载:传输层以 `Content-Disposition: attachment` 返回文件字节。
412    Download {
413        /// 服务器本地文件路径。
414        path: PathBuf,
415        /// 下载文件名(写入 Content-Disposition 的 filename 参数)。
416        filename: String,
417    },
418    /// 文件预览:传输层以 `Content-Disposition: inline` 返回文件字节。
419    Preview {
420        /// 服务器本地文件路径。
421        path: PathBuf,
422    },
423    /// 重定向:传输层返回 302 状态码与 `Location` 头。
424    Redirect {
425        /// 目标地址。
426        url: String,
427    },
428    /// 原始响应体:传输层直接以 `content_type` 返回 `body`,**不套 [`ApiResponse`] 包络**。
429    ///
430    /// 供外部系统要求固定响应形状(顶层键名、层级与框架包络不一致)时使用。
431    /// `content_type` 只允许 `application/json`;`body` 必须是该类型下的完整响应文本。
432    ///
433    /// 请优先用 [`ResponseBody::raw`] 构造,它会校验 `content_type`;派发边界
434    /// `wrap_dispatch_output` 会对直接构造的本变体再执行同一白名单校验。
435    Raw {
436        /// 完整响应体文本(UTF-8)。
437        body: String,
438        /// 响应 `Content-Type`;当前只允许 `application/json`。
439        content_type: String,
440    },
441}
442
443impl ResponseBody {
444    /// 构造文件下载响应。
445    pub fn download(path: impl Into<PathBuf>, filename: impl Into<String>) -> Self {
446        Self::Download {
447            path: path.into(),
448            filename: filename.into(),
449        }
450    }
451
452    /// 构造文件预览响应。
453    pub fn preview(path: impl Into<PathBuf>) -> Self {
454        Self::Preview { path: path.into() }
455    }
456
457    /// 构造重定向响应。
458    pub fn redirect(url: impl Into<String>) -> Self {
459        Self::Redirect { url: url.into() }
460    }
461
462    /// 构造原始响应体,传输层将原样返回 `body` 而不套 [`ApiResponse`] 包络。
463    ///
464    /// 这是给「外部系统契约与框架包络不兼容」用的逃生口,不是通用响应通道——
465    /// `content_type` 被限死为 `application/json`,防止它被用来返回 `text/html`。
466    /// 该白名单与派发边界 `wrap_dispatch_output` 的运行期再校验完全一致;
467    /// 直接构造 [`ResponseBody::Raw`] 的非法 `content_type` 会在派发时被拒绝。
468    ///
469    /// # 错误
470    ///
471    /// `content_type` 不是 `application/json` 时返回 [`BaseError::ConfigError`]。
472    ///
473    /// # 示例
474    ///
475    /// ```rust
476    /// use yang_base::action::ResponseBody;
477    ///
478    /// let body = ResponseBody::raw(r#"{"code":0}"#, "application/json")?;
479    /// assert!(matches!(body, ResponseBody::Raw { .. }));
480    ///
481    /// // 非 JSON 类型被拒绝
482    /// assert!(ResponseBody::raw("<html></html>", "text/html").is_err());
483    /// # Ok::<(), yang_base::BaseError>(())
484    /// ```
485    pub fn raw(
486        body: impl Into<String>,
487        content_type: impl Into<String>,
488    ) -> Result<Self, BaseError> {
489        let content_type = content_type.into();
490        validate_raw_content_type(&content_type)?;
491        Ok(Self::Raw {
492            body: body.into(),
493            content_type,
494        })
495    }
496}
497
498/// 一次响应携带的非 JSON 附件描述,由传输层消费,不参与 JSON 序列化。
499///
500/// 与 [`ResponseBody`] 结构一一对应;拆开是为了让 Action 输出类型满足
501/// `Serialize + JsonSchema` 契约,而响应上的附件字段不受该契约约束。
502///
503/// 标注 `#[non_exhaustive]`:未来新增变体不再构成破坏性变更。
504#[derive(Debug, Clone, PartialEq, Eq)]
505#[non_exhaustive]
506pub enum ResponseAttachment {
507    /// 文件下载(`Content-Disposition: attachment`)。
508    Download {
509        /// 服务器本地文件路径。
510        path: PathBuf,
511        /// 下载文件名。
512        filename: String,
513    },
514    /// 文件预览(`Content-Disposition: inline`)。
515    Preview {
516        /// 服务器本地文件路径。
517        path: PathBuf,
518    },
519    /// 重定向(302 + `Location`)。
520    Redirect {
521        /// 目标地址。
522        url: String,
523    },
524    /// 原始响应体:`Content-Type` 由变体自带,**不套 [`ApiResponse`] 包络**。
525    Raw {
526        /// 完整响应体文本。
527        body: String,
528        /// 响应 `Content-Type`。
529        content_type: String,
530    },
531}
532
533impl From<ResponseBody> for ResponseAttachment {
534    fn from(body: ResponseBody) -> Self {
535        match body {
536            ResponseBody::Download { path, filename } => Self::Download { path, filename },
537            ResponseBody::Preview { path } => Self::Preview { path },
538            ResponseBody::Redirect { url } => Self::Redirect { url },
539            ResponseBody::Raw { body, content_type } => Self::Raw { body, content_type },
540        }
541    }
542}
543
544/// 派发边界的统一输出去向:[`ResponseBody`] 转为附件响应,其余照旧序列化进 `data`。
545///
546/// 通过 `&dyn Any` downcast 识别 `ResponseBody`,不引入新的 trait bound,
547/// 因此现有 Action 的输出契约与 `Result<ApiResponse, BaseError>` 派发签名保持不变。
548pub(crate) fn wrap_dispatch_output<T>(output: T, message: &str) -> Result<ApiResponse, BaseError>
549where
550    T: Serialize + 'static,
551{
552    let erased = &output as &dyn std::any::Any;
553    if let Some(response) = erased.downcast_ref::<ApiResponse>() {
554        return Ok(response.clone());
555    }
556    if let Some(body) = erased.downcast_ref::<ResponseBody>() {
557        // 运行期再校验:`ResponseBody::Raw` 是对外可构造的变体,枚举上的
558        // `#[non_exhaustive]` 只限制下游穷尽 match,不能阻止直接构造变体绕过
559        // `raw()` 的白名单。此处复用同一校验函数,合法 `application/json` 零变化。
560        if let ResponseBody::Raw { content_type, .. } = body {
561            validate_raw_content_type(content_type)?;
562        }
563        return Ok(ApiResponse::attachment(body.clone().into(), message));
564    }
565    ApiResponse::success(output, message)
566}
567
568#[cfg(test)]
569mod tests {
570    use super::*;
571    use serde_json::json;
572
573    #[test]
574    fn test_success_response() {
575        // success 现在返回 Result,需要用 ? 或 unwrap
576        let response =
577            ApiResponse::success(json!({ "id": 123, "name": "Alice" }), "操作成功").unwrap();
578
579        assert_eq!(response.code, 0);
580        assert_eq!(response.message, "操作成功");
581        assert!(response.data.is_some());
582
583        let data = response.data.unwrap();
584        assert_eq!(data["id"], 123);
585        assert_eq!(data["name"], "Alice");
586    }
587
588    #[test]
589    fn test_success_response_with_null() {
590        // 使用 success_value 传入已有的 JSON 值(不会失败)
591        let response = ApiResponse::success_value(serde_json::Value::Null, "操作成功");
592
593        assert_eq!(response.code, 0);
594        assert_eq!(response.message, "操作成功");
595        assert!(response.data.is_some());
596        assert_eq!(response.data.unwrap(), serde_json::Value::Null);
597    }
598
599    #[test]
600    fn test_success_value_response() {
601        // 测试 success_value 便捷构造器
602        let data = json!({ "count": 42 });
603        let response = ApiResponse::success_value(data, "查询成功");
604
605        assert_eq!(response.code, 0);
606        assert_eq!(response.message, "查询成功");
607        assert!(response.data.is_some());
608        assert_eq!(response.data.unwrap()["count"], 42);
609    }
610
611    #[test]
612    fn test_success_serialize_error_propagation() {
613        // 构造一个序列化时主动返回错误的类型
614        struct AlwaysFailSerialize;
615
616        impl serde::Serialize for AlwaysFailSerialize {
617            fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
618                use serde::ser::Error;
619                Err(S::Error::custom("测试序列化失败"))
620            }
621        }
622
623        let result = ApiResponse::success(AlwaysFailSerialize, "测试");
624        // 序列化失败应该返回 JsonSerializeFailed 错误
625        assert!(result.is_err(), "序列化失败应该返回错误");
626        if let Err(BaseError::JsonSerializeFailed(_)) = result {
627            // 正确:返回了 JsonSerializeFailed
628        } else {
629            panic!("期望 JsonSerializeFailed 错误");
630        }
631    }
632
633    #[test]
634    fn test_fail_response() {
635        let response = ApiResponse::fail(400001, "参数错误");
636
637        assert_eq!(response.code, 400001);
638        assert_eq!(response.message, "参数错误");
639        assert!(response.data.is_none());
640    }
641
642    #[test]
643    fn test_from_error() {
644        let error = BaseError::FieldRequired("username".to_string());
645        let response = ApiResponse::from_error(&error);
646
647        assert_ne!(response.code, 0);
648        assert!(response.message.contains("username"));
649        assert!(response.data.is_none());
650        // error 仍可用(未被消费)
651        assert_eq!(error.code(), 600006);
652    }
653
654    #[test]
655    fn test_default_response() {
656        let response = ApiResponse::default();
657
658        assert_eq!(response.code, 0);
659        assert_eq!(response.message, "OK");
660        assert!(response.data.is_none());
661    }
662
663    #[test]
664    fn transport_metadata_is_validated_and_never_serialized() {
665        let response = ApiResponse::default()
666            .with_http_status(304)
667            .expect("304 应是合法 HTTP 状态码")
668            .with_header("set-cookie", "session=one; HttpOnly")
669            .expect("Set-Cookie 应是合法响应头")
670            .with_header("set-cookie", "session=two; HttpOnly")
671            .expect("重复 Set-Cookie 必须保留");
672        assert_eq!(response.http_status(), Some(304));
673        assert_eq!(response.response_headers().len(), 2);
674        let wire = serde_json::to_value(&response).expect("响应应可序列化");
675        assert!(wire.get("http_status").is_none());
676        assert!(wire.get("headers").is_none());
677        assert!(ApiResponse::default().with_http_status(99).is_err());
678        assert!(ApiResponse::default()
679            .with_header("bad header", "value")
680            .is_err());
681        assert!(ApiResponse::default()
682            .with_header("x-test", "line\r\nbreak")
683            .is_err());
684    }
685
686    #[test]
687    fn test_serialize_response() {
688        // success 现在返回 Result
689        let response = ApiResponse::success(json!({ "count": 10 }), "查询成功").unwrap();
690
691        let json = serde_json::to_string(&response).unwrap();
692        assert!(json.contains("\"code\":0"));
693        assert!(json.contains("\"message\":\"查询成功\""));
694        assert!(json.contains("\"data\""));
695    }
696
697    #[test]
698    fn test_serialize_fail_response() {
699        let response = ApiResponse::fail(500001, "服务器错误");
700
701        let json = serde_json::to_string(&response).unwrap();
702        assert!(json.contains("\"code\":500001"));
703        assert!(json.contains("\"message\":\"服务器错误\""));
704        // data 字段应该被跳过
705        assert!(!json.contains("\"data\""));
706    }
707
708    #[test]
709    fn test_response_body_constructors() {
710        // download 携带路径与下载文件名
711        let download = ResponseBody::download("/tmp/report.pdf", "report.pdf");
712        assert_eq!(
713            download,
714            ResponseBody::Download {
715                path: std::path::PathBuf::from("/tmp/report.pdf"),
716                filename: "report.pdf".to_string(),
717            }
718        );
719        // preview 仅携带路径
720        assert_eq!(
721            ResponseBody::preview("/tmp/a.png"),
722            ResponseBody::Preview {
723                path: std::path::PathBuf::from("/tmp/a.png"),
724            }
725        );
726        // redirect 仅携带目标地址
727        assert_eq!(
728            ResponseBody::redirect("https://example.com/next"),
729            ResponseBody::Redirect {
730                url: "https://example.com/next".to_string(),
731            }
732        );
733    }
734
735    #[test]
736    fn test_response_body_into_attachment() {
737        // ResponseBody 到传输层附件描述的一一映射
738        let attachment: ResponseAttachment = ResponseBody::download("/tmp/a.bin", "a.bin").into();
739        assert_eq!(
740            attachment,
741            ResponseAttachment::Download {
742                path: std::path::PathBuf::from("/tmp/a.bin"),
743                filename: "a.bin".to_string(),
744            }
745        );
746        let attachment: ResponseAttachment = ResponseBody::preview("/tmp/b.png").into();
747        assert_eq!(
748            attachment,
749            ResponseAttachment::Preview {
750                path: std::path::PathBuf::from("/tmp/b.png"),
751            }
752        );
753        let attachment: ResponseAttachment = ResponseBody::redirect("/home").into();
754        assert_eq!(
755            attachment,
756            ResponseAttachment::Redirect {
757                url: "/home".to_string(),
758            }
759        );
760    }
761
762    #[test]
763    fn test_response_body_implements_action_output_contract() {
764        // 作为 Action::Output 必须满足 Serialize + JsonSchema + 'static
765        fn assert_output_contract<T: Serialize + schemars::JsonSchema + 'static>() {}
766        assert_output_contract::<ResponseBody>();
767
768        let body = ResponseBody::redirect("/next");
769        let json = serde_json::to_string(&body).unwrap();
770        assert!(json.contains("/next"), "ResponseBody 应可序列化: {json}");
771        // schema 生成不应 panic(output_schema 由构建期消费)
772        let _schema = schemars::schema_for!(ResponseBody);
773    }
774
775    #[test]
776    fn test_attachment_response_json_wire_format_unchanged() {
777        // 附件响应序列化后不得出现 attachment 字段,保持 JSON 线格式不变
778        let response = ApiResponse::attachment(
779            ResponseAttachment::Redirect {
780                url: "/next".to_string(),
781            },
782            "成功",
783        );
784        assert_eq!(response.code, 0);
785        assert!(response.data.is_none());
786        let json = serde_json::to_string(&response).unwrap();
787        assert!(
788            !json.contains("attachment"),
789            "线格式不得包含附件信息: {json}"
790        );
791        assert!(json.contains("\"code\":0"));
792    }
793
794    #[test]
795    fn test_plain_response_has_no_attachment() {
796        // 普通成功/失败响应不带附件
797        let ok = ApiResponse::success(json!({"a": 1}), "ok").unwrap();
798        assert!(ok.attachment.is_none());
799        let fail = ApiResponse::fail(1, "bad");
800        assert!(fail.attachment.is_none());
801        let default = ApiResponse::default();
802        assert!(default.attachment.is_none());
803    }
804
805    #[test]
806    fn test_wrap_dispatch_output_recognizes_response_body() {
807        // ResponseBody 输出转为附件响应,不进 data
808        let response = wrap_dispatch_output(ResponseBody::redirect("/next"), "成功").unwrap();
809        assert_eq!(response.code, 0);
810        assert!(response.data.is_none());
811        assert_eq!(
812            response.attachment,
813            Some(ResponseAttachment::Redirect {
814                url: "/next".to_string(),
815            })
816        );
817    }
818
819    #[test]
820    fn test_wrap_dispatch_output_passes_through_plain_output() {
821        // 普通输出照旧序列化进 data,attachment 为 None
822        #[derive(Serialize)]
823        struct Plain {
824            value: i32,
825        }
826        let response = wrap_dispatch_output(Plain { value: 7 }, "成功").unwrap();
827        assert_eq!(response.code, 0);
828        assert_eq!(response.data.unwrap()["value"], 7);
829        assert!(response.attachment.is_none());
830    }
831
832    #[test]
833    fn raw_response_body_rejects_non_json_content_type() {
834        // Raw 只允许 application/json:这个逃生口不得被用来返回 text/html
835        let failed = ResponseBody::raw("<html></html>", "text/html")
836            .expect_err("非 application/json 必须被拒绝");
837        assert!(
838            failed.to_string().contains("application/json"),
839            "错误信息应说明允许的 content-type,实际: {failed}"
840        );
841    }
842
843    #[test]
844    fn directly_constructed_raw_is_revalidated_at_dispatch_boundary() {
845        // RED(修复前):枚举上的 #[non_exhaustive] 不阻止下游直接构造 Raw,
846        // text/html 会原样进入传输层,绕过 raw() 的 content-type 白名单。
847        let body = ResponseBody::Raw {
848            body: "<html><script>alert(1)</script></html>".to_string(),
849            content_type: "text/html".to_string(),
850        };
851
852        let err =
853            wrap_dispatch_output(body, "成功").expect_err("派发边界必须拒绝直接构造的非 JSON Raw");
854        assert!(
855            matches!(&err, BaseError::ConfigError(_)),
856            "应与 raw() 使用同一错误类型,实际: {err:?}"
857        );
858        assert!(
859            err.to_string().contains("application/json"),
860            "错误信息应说明允许的 content-type,实际: {err}"
861        );
862    }
863
864    #[test]
865    fn directly_constructed_json_raw_still_maps_to_attachment() {
866        // 合法直接构造(application/json)零变化:仍映射为 Raw 附件且不进入 data
867        let body = ResponseBody::Raw {
868            body: r#"{"code":0,"msg":"ok"}"#.to_string(),
869            content_type: "application/json".to_string(),
870        };
871
872        let response = wrap_dispatch_output(body, "成功").expect("合法 Raw 应通过派发边界");
873        assert_eq!(response.code, 0);
874        assert!(response.data.is_none(), "Raw 不得进入 data");
875        assert_eq!(
876            response.attachment,
877            Some(ResponseAttachment::Raw {
878                body: r#"{"code":0,"msg":"ok"}"#.to_string(),
879                content_type: "application/json".to_string(),
880            })
881        );
882    }
883
884    #[test]
885    fn dispatch_validation_uses_same_exact_match_as_constructor() {
886        // 与 raw() 完全一致:精确匹配 application/json;带参数的同类值同样被拒绝。
887        assert!(ResponseBody::raw("{}", "application/json; charset=utf-8").is_err());
888
889        let body = ResponseBody::Raw {
890            body: "{}".to_string(),
891            content_type: "application/json; charset=utf-8".to_string(),
892        };
893        assert!(
894            wrap_dispatch_output(body, "成功").is_err(),
895            "派发边界的白名单必须与 raw() 的精确匹配语义一致"
896        );
897    }
898
899    #[test]
900    fn attachment_raw_content_type_is_not_tightened() {
901        // 契约边界:校验只覆盖 ResponseBody::Raw,不得扩大到 ResponseAttachment::Raw /
902        // ApiResponse::attachment——receivables-system 的 text/csv 模板下载依赖此通道。
903        let response = ApiResponse::attachment(
904            ResponseAttachment::Raw {
905                body: "a,b\r\n1,2".to_string(),
906                content_type: "text/csv; charset=utf-8".to_string(),
907            },
908            "成功",
909        );
910        assert_eq!(
911            response.attachment,
912            Some(ResponseAttachment::Raw {
913                body: "a,b\r\n1,2".to_string(),
914                content_type: "text/csv; charset=utf-8".to_string(),
915            })
916        );
917
918        // 已携带非 JSON 附件的 ApiResponse 走 wrap_dispatch_output 的第一分支原样透传。
919        let passed = wrap_dispatch_output(response, "成功").expect("ApiResponse 应原样透传");
920        assert_eq!(
921            passed.attachment,
922            Some(ResponseAttachment::Raw {
923                body: "a,b\r\n1,2".to_string(),
924                content_type: "text/csv; charset=utf-8".to_string(),
925            })
926        );
927    }
928
929    #[test]
930    fn raw_response_body_maps_to_raw_attachment_without_envelope() {
931        // Raw 输出映射为 Raw 附件,且不进入 data
932        let body = ResponseBody::raw(r#"{"code":0,"msg":"ok"}"#, "application/json")
933            .expect("application/json 应被接受");
934        let response = wrap_dispatch_output(body, "成功").expect("收口应成功");
935        assert_eq!(response.code, 0);
936        assert!(response.data.is_none(), "Raw 不得进入 data");
937        assert_eq!(
938            response.attachment,
939            Some(ResponseAttachment::Raw {
940                body: r#"{"code":0,"msg":"ok"}"#.to_string(),
941                content_type: "application/json".to_string(),
942            })
943        );
944    }
945
946    #[test]
947    fn raw_response_body_survives_json_wire_format() {
948        // Raw 变体不得让 ApiResponse 的 JSON 线格式出现 attachment 字段
949        let body = ResponseBody::raw("{}", "application/json").expect("应被接受");
950        let response = wrap_dispatch_output(body, "成功").expect("收口应成功");
951        let json = serde_json::to_string(&response).expect("应可序列化");
952        assert!(
953            !json.contains("attachment"),
954            "线格式不得含 attachment: {json}"
955        );
956    }
957}