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/// API 响应
11///
12/// 统一的 API 响应格式,用于所有 Action 的返回值
13///
14/// # 字段
15///
16/// - `code`: 状态码(0 表示成功,非零表示失败)
17/// - `message`: 响应消息
18/// - `data`: 响应数据(可选)
19///
20/// 标注 `#[non_exhaustive]`:未来新增字段不构成破坏性变更。
21/// 请使用 [`ApiResponse::success`] / [`ApiResponse::fail`] / [`ApiResponse::from_error`] 等构造。
22///
23/// # 示例
24///
25/// ```rust,ignore
26/// use yang_base::action::ApiResponse;
27/// use serde_json::json;
28///
29/// // 创建成功响应
30/// let response = ApiResponse::success(
31///     json!({ "id": 123, "name": "Alice" }),
32///     "操作成功"
33/// );
34/// assert_eq!(response.code, 0);
35///
36/// // 创建失败响应
37/// let response = ApiResponse::fail(400001, "参数错误");
38/// assert_eq!(response.code, 400001);
39/// assert!(response.data.is_none());
40/// ```
41#[derive(Debug, Clone, Serialize, JsonSchema)]
42#[non_exhaustive]
43pub struct ApiResponse {
44    /// 状态码
45    ///
46    /// - 0: 成功
47    /// - 非零: 失败(具体错误码由业务定义)
48    pub code: i32,
49
50    /// 响应消息
51    ///
52    /// 描述操作结果的文本信息
53    pub message: String,
54
55    /// 响应数据
56    ///
57    /// 成功时包含业务数据,失败时通常为 None
58    #[serde(skip_serializing_if = "Option::is_none")]
59    pub data: Option<serde_json::Value>,
60
61    /// 非 JSON 附件(文件下载/预览/重定向),由传输层消费。
62    ///
63    /// 仅当 Action 以 [`ResponseBody`] 为输出时由派发边界填充;
64    /// `serde(skip)` 保证普通 Action 的 JSON 线格式不受影响。
65    #[serde(skip)]
66    #[schemars(skip)]
67    pub attachment: Option<ResponseAttachment>,
68
69    /// 由 Action 显式声明、传输层消费的 HTTP 状态码覆盖。
70    #[serde(skip)]
71    #[schemars(skip)]
72    http_status: Option<u16>,
73
74    /// 由 Action 显式声明、传输层消费的响应头。
75    #[serde(skip)]
76    #[schemars(skip)]
77    headers: Vec<(String, String)>,
78}
79
80impl ApiResponse {
81    /// 创建成功响应
82    ///
83    /// 状态码为 0,包含业务数据。序列化失败时返回 `BaseError::JsonSerializeFailed`。
84    ///
85    /// # 参数
86    ///
87    /// - `data`: 响应数据(任何可序列化的类型)
88    /// - `message`: 成功消息
89    ///
90    /// # 返回
91    ///
92    /// - `Ok(ApiResponse)`: 序列化成功时返回响应实例
93    /// - `Err(BaseError::JsonSerializeFailed)`: 序列化失败时返回错误
94    ///
95    /// # Errors
96    ///
97    /// - `BaseError::JsonSerializeFailed`: 当 `data` 无法被序列化为 JSON 时
98    ///
99    /// # 示例
100    ///
101    /// ```rust,ignore
102    /// use yang_base::action::ApiResponse;
103    /// use serde_json::json;
104    ///
105    /// // 返回单个对象
106    /// let response = ApiResponse::success(
107    ///     json!({ "id": 1, "name": "Alice" }),
108    ///     "获取成功"
109    /// )?;
110    ///
111    /// // 返回影响行数
112    /// let response = ApiResponse::success(
113    ///     json!({ "affected": 1 }),
114    ///     "更新成功"
115    /// )?;
116    /// ```
117    pub fn success<T: Serialize>(data: T, message: impl Into<String>) -> Result<Self, BaseError> {
118        // 序列化数据,失败时返回结构化错误而非静默吞错
119        let json_value = serde_json::to_value(data)
120            .map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
121        Ok(Self {
122            code: 0,
123            message: message.into(),
124            data: Some(json_value),
125            attachment: None,
126            http_status: None,
127            headers: Vec::new(),
128        })
129    }
130
131    /// 创建成功响应(接受已序列化的 JSON 值)
132    ///
133    /// 当数据已经是 `serde_json::Value` 类型时,使用此方法可避免额外的序列化开销,
134    /// 且不会失败,因此直接返回 `Self` 而非 `Result`。
135    ///
136    /// # 参数
137    ///
138    /// - `data`: 已序列化的 JSON 值
139    /// - `message`: 成功消息
140    ///
141    /// # 返回
142    ///
143    /// - ApiResponse 实例
144    ///
145    /// # 示例
146    ///
147    /// ```rust,ignore
148    /// use yang_base::action::ApiResponse;
149    /// use serde_json::json;
150    ///
151    /// // 直接使用 serde_json::Value
152    /// let data = json!({ "id": 1, "name": "Alice" });
153    /// let response = ApiResponse::success_value(data, "获取成功");
154    /// assert_eq!(response.code, 0);
155    /// ```
156    pub fn success_value(data: serde_json::Value, message: impl Into<String>) -> Self {
157        Self {
158            code: 0,
159            message: message.into(),
160            data: Some(data),
161            attachment: None,
162            http_status: None,
163            headers: Vec::new(),
164        }
165    }
166
167    /// 创建失败响应
168    ///
169    /// 状态码为非零错误码,不包含数据
170    ///
171    /// # 参数
172    ///
173    /// - `code`: 错误码(非零整数)
174    /// - `message`: 错误消息
175    ///
176    /// # 返回
177    ///
178    /// - ApiResponse 实例
179    ///
180    /// # 示例
181    ///
182    /// ```rust,ignore
183    /// use yang_base::action::ApiResponse;
184    ///
185    /// // 参数错误
186    /// let response = ApiResponse::fail(400001, "参数缺失: username");
187    ///
188    /// // 权限错误
189    /// let response = ApiResponse::fail(403001, "权限不足");
190    ///
191    /// // 业务错误
192    /// let response = ApiResponse::fail(500001, "用户名已存在");
193    /// ```
194    pub fn fail(code: i32, message: impl Into<String>) -> Self {
195        Self {
196            code,
197            message: message.into(),
198            data: None,
199            attachment: None,
200            http_status: None,
201            headers: Vec::new(),
202        }
203    }
204
205    /// 创建携带附件的成功响应
206    ///
207    /// 由派发边界在识别到 Action 返回 [`ResponseBody`] 时调用。`data` 为 None,
208    /// 附件信息仅对传输层可见(`serde(skip)`),JSON 线格式保持不变。
209    ///
210    /// # 参数
211    ///
212    /// - `attachment`: 传输层消费的附件描述
213    /// - `message`: 成功消息
214    ///
215    /// # 返回
216    ///
217    /// - ApiResponse 实例
218    pub fn attachment(attachment: ResponseAttachment, message: impl Into<String>) -> Self {
219        Self {
220            code: 0,
221            message: message.into(),
222            data: None,
223            attachment: Some(attachment),
224            http_status: None,
225            headers: Vec::new(),
226        }
227    }
228
229    /// 覆盖 Action 静态声明的成功 HTTP 状态码。
230    pub fn with_http_status(mut self, status: u16) -> Result<Self, BaseError> {
231        if !(100..=599).contains(&status) {
232            return Err(BaseError::ConfigError(format!(
233                "响应 HTTP 状态码无效: {status}"
234            )));
235        }
236        self.http_status = Some(status);
237        Ok(self)
238    }
239
240    /// 追加一个经过最小 RFC 语法校验的响应头。
241    ///
242    /// 使用列表而不是 Map,以保留多个 `Set-Cookie` 等同名响应头。
243    pub fn with_header(
244        mut self,
245        name: impl Into<String>,
246        value: impl Into<String>,
247    ) -> Result<Self, BaseError> {
248        let name = name.into();
249        let value = value.into();
250        let valid_name = !name.is_empty()
251            && name.bytes().all(|byte| {
252                byte.is_ascii_alphanumeric()
253                    || matches!(
254                        byte,
255                        b'!' | b'#'
256                            | b'$'
257                            | b'%'
258                            | b'&'
259                            | b'\''
260                            | b'*'
261                            | b'+'
262                            | b'-'
263                            | b'.'
264                            | b'^'
265                            | b'_'
266                            | b'`'
267                            | b'|'
268                            | b'~'
269                    )
270            });
271        let valid_value = value
272            .bytes()
273            .all(|byte| byte == b'\t' || (byte >= 0x20 && byte != 0x7f));
274        if !valid_name || !valid_value {
275            return Err(BaseError::ConfigError(
276                "响应头名称或值包含非法字符".to_string(),
277            ));
278        }
279        self.headers.push((name, value));
280        Ok(self)
281    }
282
283    #[cfg(any(feature = "transport-axum", test))]
284    pub(crate) const fn http_status(&self) -> Option<u16> {
285        self.http_status
286    }
287
288    /// 返回 Action 显式追加、由传输层消费的响应头。
289    ///
290    /// 响应头不参与 [`ApiResponse`] 的 JSON 序列化;此只读视图主要用于
291    /// 传输适配器、集成测试以及需要检查 Cookie/缓存契约的应用层边界。
292    pub fn response_headers(&self) -> &[(String, String)] {
293        &self.headers
294    }
295
296    /// 从 BaseError 创建失败响应
297    ///
298    /// 自动提取错误码和错误消息。接受引用以避免消费 `BaseError` 所有权,
299    /// 调用方可在构建响应的同时保留 error 用于日志记录等后续用途。
300    ///
301    /// # 参数
302    ///
303    /// - `error`: BaseError 引用
304    ///
305    /// # 返回
306    ///
307    /// - ApiResponse 实例
308    ///
309    /// # 示例
310    ///
311    /// ```rust,ignore
312    /// use yang_base::action::ApiResponse;
313    /// use yang_base::error::BaseError;
314    ///
315    /// let error = BaseError::FieldRequired("username".to_string());
316    /// let response = ApiResponse::from_error(&error);
317    ///
318    /// assert_ne!(response.code, 0);
319    /// assert!(response.message.contains("username"));
320    /// assert!(response.data.is_none());
321    /// ```
322    pub fn from_error(error: &BaseError) -> Self {
323        Self::fail(error.code(), error.to_string())
324    }
325}
326
327impl Default for ApiResponse {
328    /// 创建默认响应
329    ///
330    /// 默认为成功响应,消息为 "OK",无数据
331    fn default() -> Self {
332        Self {
333            code: 0,
334            message: "OK".to_string(),
335            data: None,
336            attachment: None,
337            http_status: None,
338            headers: Vec::new(),
339        }
340    }
341}
342
343/// Action 的特殊业务响应体:文件下载、文件预览、重定向。
344///
345/// Action 将本类型作为 `type Output` 返回时,派发边界
346/// ([`DynAction::dispatch`](crate::action::DynAction))会识别并把它转为
347/// [`ApiResponse::attachment`],普通输出的 JSON 线格式不受影响。
348///
349/// # 示例
350///
351/// ```rust,ignore
352/// use yang_base::action::ResponseBody;
353///
354/// async fn index(&self, ctx: ActionContext, input: Self::Input) -> Result<Self::Output, BaseError> {
355///     // 文件下载
356///     Ok(ResponseBody::download("/data/report.pdf", "report.pdf"))
357///     // 文件预览
358///     // Ok(ResponseBody::preview("/data/a.png"))
359///     // 重定向
360///     // Ok(ResponseBody::redirect("https://example.com/next"))
361/// }
362/// ```
363#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
364#[serde(tag = "type", rename_all = "snake_case")]
365pub enum ResponseBody {
366    /// 文件下载:传输层以 `Content-Disposition: attachment` 返回文件字节。
367    Download {
368        /// 服务器本地文件路径。
369        path: PathBuf,
370        /// 下载文件名(写入 Content-Disposition 的 filename 参数)。
371        filename: String,
372    },
373    /// 文件预览:传输层以 `Content-Disposition: inline` 返回文件字节。
374    Preview {
375        /// 服务器本地文件路径。
376        path: PathBuf,
377    },
378    /// 重定向:传输层返回 302 状态码与 `Location` 头。
379    Redirect {
380        /// 目标地址。
381        url: String,
382    },
383}
384
385impl ResponseBody {
386    /// 构造文件下载响应。
387    pub fn download(path: impl Into<PathBuf>, filename: impl Into<String>) -> Self {
388        Self::Download {
389            path: path.into(),
390            filename: filename.into(),
391        }
392    }
393
394    /// 构造文件预览响应。
395    pub fn preview(path: impl Into<PathBuf>) -> Self {
396        Self::Preview { path: path.into() }
397    }
398
399    /// 构造重定向响应。
400    pub fn redirect(url: impl Into<String>) -> Self {
401        Self::Redirect { url: url.into() }
402    }
403}
404
405/// 一次响应携带的非 JSON 附件描述,由传输层消费,不参与 JSON 序列化。
406///
407/// 与 [`ResponseBody`] 结构一一对应;拆开是为了让 Action 输出类型满足
408/// `Serialize + JsonSchema` 契约,而响应上的附件字段不受该契约约束。
409#[derive(Debug, Clone, PartialEq, Eq)]
410pub enum ResponseAttachment {
411    /// 文件下载(`Content-Disposition: attachment`)。
412    Download {
413        /// 服务器本地文件路径。
414        path: PathBuf,
415        /// 下载文件名。
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}
429
430impl From<ResponseBody> for ResponseAttachment {
431    fn from(body: ResponseBody) -> Self {
432        match body {
433            ResponseBody::Download { path, filename } => Self::Download { path, filename },
434            ResponseBody::Preview { path } => Self::Preview { path },
435            ResponseBody::Redirect { url } => Self::Redirect { url },
436        }
437    }
438}
439
440/// 派发边界的统一输出去向:[`ResponseBody`] 转为附件响应,其余照旧序列化进 `data`。
441///
442/// 通过 `&dyn Any` downcast 识别 `ResponseBody`,不引入新的 trait bound,
443/// 因此现有 Action 的输出契约与 `Result<ApiResponse, BaseError>` 派发签名保持不变。
444pub(crate) fn wrap_dispatch_output<T>(output: T, message: &str) -> Result<ApiResponse, BaseError>
445where
446    T: Serialize + 'static,
447{
448    let erased = &output as &dyn std::any::Any;
449    if let Some(response) = erased.downcast_ref::<ApiResponse>() {
450        return Ok(response.clone());
451    }
452    if let Some(body) = erased.downcast_ref::<ResponseBody>() {
453        return Ok(ApiResponse::attachment(body.clone().into(), message));
454    }
455    ApiResponse::success(output, message)
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461    use serde_json::json;
462
463    #[test]
464    fn test_success_response() {
465        // success 现在返回 Result,需要用 ? 或 unwrap
466        let response =
467            ApiResponse::success(json!({ "id": 123, "name": "Alice" }), "操作成功").unwrap();
468
469        assert_eq!(response.code, 0);
470        assert_eq!(response.message, "操作成功");
471        assert!(response.data.is_some());
472
473        let data = response.data.unwrap();
474        assert_eq!(data["id"], 123);
475        assert_eq!(data["name"], "Alice");
476    }
477
478    #[test]
479    fn test_success_response_with_null() {
480        // 使用 success_value 传入已有的 JSON 值(不会失败)
481        let response = ApiResponse::success_value(serde_json::Value::Null, "操作成功");
482
483        assert_eq!(response.code, 0);
484        assert_eq!(response.message, "操作成功");
485        assert!(response.data.is_some());
486        assert_eq!(response.data.unwrap(), serde_json::Value::Null);
487    }
488
489    #[test]
490    fn test_success_value_response() {
491        // 测试 success_value 便捷构造器
492        let data = json!({ "count": 42 });
493        let response = ApiResponse::success_value(data, "查询成功");
494
495        assert_eq!(response.code, 0);
496        assert_eq!(response.message, "查询成功");
497        assert!(response.data.is_some());
498        assert_eq!(response.data.unwrap()["count"], 42);
499    }
500
501    #[test]
502    fn test_success_serialize_error_propagation() {
503        // 构造一个序列化时主动返回错误的类型
504        struct AlwaysFailSerialize;
505
506        impl serde::Serialize for AlwaysFailSerialize {
507            fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
508                use serde::ser::Error;
509                Err(S::Error::custom("测试序列化失败"))
510            }
511        }
512
513        let result = ApiResponse::success(AlwaysFailSerialize, "测试");
514        // 序列化失败应该返回 JsonSerializeFailed 错误
515        assert!(result.is_err(), "序列化失败应该返回错误");
516        if let Err(BaseError::JsonSerializeFailed(_)) = result {
517            // 正确:返回了 JsonSerializeFailed
518        } else {
519            panic!("期望 JsonSerializeFailed 错误");
520        }
521    }
522
523    #[test]
524    fn test_fail_response() {
525        let response = ApiResponse::fail(400001, "参数错误");
526
527        assert_eq!(response.code, 400001);
528        assert_eq!(response.message, "参数错误");
529        assert!(response.data.is_none());
530    }
531
532    #[test]
533    fn test_from_error() {
534        let error = BaseError::FieldRequired("username".to_string());
535        let response = ApiResponse::from_error(&error);
536
537        assert_ne!(response.code, 0);
538        assert!(response.message.contains("username"));
539        assert!(response.data.is_none());
540        // error 仍可用(未被消费)
541        assert_eq!(error.code(), 600006);
542    }
543
544    #[test]
545    fn test_default_response() {
546        let response = ApiResponse::default();
547
548        assert_eq!(response.code, 0);
549        assert_eq!(response.message, "OK");
550        assert!(response.data.is_none());
551    }
552
553    #[test]
554    fn transport_metadata_is_validated_and_never_serialized() {
555        let response = ApiResponse::default()
556            .with_http_status(304)
557            .expect("304 应是合法 HTTP 状态码")
558            .with_header("set-cookie", "session=one; HttpOnly")
559            .expect("Set-Cookie 应是合法响应头")
560            .with_header("set-cookie", "session=two; HttpOnly")
561            .expect("重复 Set-Cookie 必须保留");
562        assert_eq!(response.http_status(), Some(304));
563        assert_eq!(response.response_headers().len(), 2);
564        let wire = serde_json::to_value(&response).expect("响应应可序列化");
565        assert!(wire.get("http_status").is_none());
566        assert!(wire.get("headers").is_none());
567        assert!(ApiResponse::default().with_http_status(99).is_err());
568        assert!(ApiResponse::default()
569            .with_header("bad header", "value")
570            .is_err());
571        assert!(ApiResponse::default()
572            .with_header("x-test", "line\r\nbreak")
573            .is_err());
574    }
575
576    #[test]
577    fn test_serialize_response() {
578        // success 现在返回 Result
579        let response = ApiResponse::success(json!({ "count": 10 }), "查询成功").unwrap();
580
581        let json = serde_json::to_string(&response).unwrap();
582        assert!(json.contains("\"code\":0"));
583        assert!(json.contains("\"message\":\"查询成功\""));
584        assert!(json.contains("\"data\""));
585    }
586
587    #[test]
588    fn test_serialize_fail_response() {
589        let response = ApiResponse::fail(500001, "服务器错误");
590
591        let json = serde_json::to_string(&response).unwrap();
592        assert!(json.contains("\"code\":500001"));
593        assert!(json.contains("\"message\":\"服务器错误\""));
594        // data 字段应该被跳过
595        assert!(!json.contains("\"data\""));
596    }
597
598    #[test]
599    fn test_response_body_constructors() {
600        // download 携带路径与下载文件名
601        let download = ResponseBody::download("/tmp/report.pdf", "report.pdf");
602        assert_eq!(
603            download,
604            ResponseBody::Download {
605                path: std::path::PathBuf::from("/tmp/report.pdf"),
606                filename: "report.pdf".to_string(),
607            }
608        );
609        // preview 仅携带路径
610        assert_eq!(
611            ResponseBody::preview("/tmp/a.png"),
612            ResponseBody::Preview {
613                path: std::path::PathBuf::from("/tmp/a.png"),
614            }
615        );
616        // redirect 仅携带目标地址
617        assert_eq!(
618            ResponseBody::redirect("https://example.com/next"),
619            ResponseBody::Redirect {
620                url: "https://example.com/next".to_string(),
621            }
622        );
623    }
624
625    #[test]
626    fn test_response_body_into_attachment() {
627        // ResponseBody 到传输层附件描述的一一映射
628        let attachment: ResponseAttachment = ResponseBody::download("/tmp/a.bin", "a.bin").into();
629        assert_eq!(
630            attachment,
631            ResponseAttachment::Download {
632                path: std::path::PathBuf::from("/tmp/a.bin"),
633                filename: "a.bin".to_string(),
634            }
635        );
636        let attachment: ResponseAttachment = ResponseBody::preview("/tmp/b.png").into();
637        assert_eq!(
638            attachment,
639            ResponseAttachment::Preview {
640                path: std::path::PathBuf::from("/tmp/b.png"),
641            }
642        );
643        let attachment: ResponseAttachment = ResponseBody::redirect("/home").into();
644        assert_eq!(
645            attachment,
646            ResponseAttachment::Redirect {
647                url: "/home".to_string(),
648            }
649        );
650    }
651
652    #[test]
653    fn test_response_body_implements_action_output_contract() {
654        // 作为 Action::Output 必须满足 Serialize + JsonSchema + 'static
655        fn assert_output_contract<T: Serialize + schemars::JsonSchema + 'static>() {}
656        assert_output_contract::<ResponseBody>();
657
658        let body = ResponseBody::redirect("/next");
659        let json = serde_json::to_string(&body).unwrap();
660        assert!(json.contains("/next"), "ResponseBody 应可序列化: {json}");
661        // schema 生成不应 panic(output_schema 由构建期消费)
662        let _schema = schemars::schema_for!(ResponseBody);
663    }
664
665    #[test]
666    fn test_attachment_response_json_wire_format_unchanged() {
667        // 附件响应序列化后不得出现 attachment 字段,保持 JSON 线格式不变
668        let response = ApiResponse::attachment(
669            ResponseAttachment::Redirect {
670                url: "/next".to_string(),
671            },
672            "成功",
673        );
674        assert_eq!(response.code, 0);
675        assert!(response.data.is_none());
676        let json = serde_json::to_string(&response).unwrap();
677        assert!(
678            !json.contains("attachment"),
679            "线格式不得包含附件信息: {json}"
680        );
681        assert!(json.contains("\"code\":0"));
682    }
683
684    #[test]
685    fn test_plain_response_has_no_attachment() {
686        // 普通成功/失败响应不带附件
687        let ok = ApiResponse::success(json!({"a": 1}), "ok").unwrap();
688        assert!(ok.attachment.is_none());
689        let fail = ApiResponse::fail(1, "bad");
690        assert!(fail.attachment.is_none());
691        let default = ApiResponse::default();
692        assert!(default.attachment.is_none());
693    }
694
695    #[test]
696    fn test_wrap_dispatch_output_recognizes_response_body() {
697        // ResponseBody 输出转为附件响应,不进 data
698        let response = wrap_dispatch_output(ResponseBody::redirect("/next"), "成功").unwrap();
699        assert_eq!(response.code, 0);
700        assert!(response.data.is_none());
701        assert_eq!(
702            response.attachment,
703            Some(ResponseAttachment::Redirect {
704                url: "/next".to_string(),
705            })
706        );
707    }
708
709    #[test]
710    fn test_wrap_dispatch_output_passes_through_plain_output() {
711        // 普通输出照旧序列化进 data,attachment 为 None
712        #[derive(Serialize)]
713        struct Plain {
714            value: i32,
715        }
716        let response = wrap_dispatch_output(Plain { value: 7 }, "成功").unwrap();
717        assert_eq!(response.code, 0);
718        assert_eq!(response.data.unwrap()["value"], 7);
719        assert!(response.attachment.is_none());
720    }
721}