1use crate::error::BaseError;
6use schemars::JsonSchema;
7use serde::Serialize;
8use std::path::PathBuf;
9
10const RAW_ALLOWED_CONTENT_TYPE: &str = "application/json";
21
22fn 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#[derive(Debug, Clone, Serialize, JsonSchema)]
66#[non_exhaustive]
67pub struct ApiResponse {
68 pub code: i32,
73
74 pub message: String,
78
79 #[serde(skip_serializing_if = "Option::is_none")]
83 pub data: Option<serde_json::Value>,
84
85 #[serde(skip)]
90 #[schemars(skip)]
91 pub attachment: Option<ResponseAttachment>,
92
93 #[serde(skip)]
95 #[schemars(skip)]
96 http_status: Option<u16>,
97
98 #[serde(skip)]
100 #[schemars(skip)]
101 headers: Vec<(String, String)>,
102}
103
104impl ApiResponse {
105 pub fn success<T: Serialize>(data: T, message: impl Into<String>) -> Result<Self, BaseError> {
142 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 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 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 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 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 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 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 pub fn response_headers(&self) -> &[(String, String)] {
332 &self.headers
333 }
334
335 pub fn from_error(error: &BaseError) -> Self {
362 Self::fail(error.code(), error.to_string())
363 }
364}
365
366impl Default for ApiResponse {
367 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
408#[serde(tag = "type", rename_all = "snake_case")]
409#[non_exhaustive]
410pub enum ResponseBody {
411 Download {
413 path: PathBuf,
415 filename: String,
417 },
418 Preview {
420 path: PathBuf,
422 },
423 Redirect {
425 url: String,
427 },
428 Raw {
436 body: String,
438 content_type: String,
440 },
441}
442
443impl ResponseBody {
444 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 pub fn preview(path: impl Into<PathBuf>) -> Self {
454 Self::Preview { path: path.into() }
455 }
456
457 pub fn redirect(url: impl Into<String>) -> Self {
459 Self::Redirect { url: url.into() }
460 }
461
462 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#[derive(Debug, Clone, PartialEq, Eq)]
505#[non_exhaustive]
506pub enum ResponseAttachment {
507 Download {
509 path: PathBuf,
511 filename: String,
513 },
514 Preview {
516 path: PathBuf,
518 },
519 Redirect {
521 url: String,
523 },
524 Raw {
526 body: String,
528 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
544pub(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 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 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 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 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 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 assert!(result.is_err(), "序列化失败应该返回错误");
626 if let Err(BaseError::JsonSerializeFailed(_)) = result {
627 } 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 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 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 assert!(!json.contains("\"data\""));
706 }
707
708 #[test]
709 fn test_response_body_constructors() {
710 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 assert_eq!(
721 ResponseBody::preview("/tmp/a.png"),
722 ResponseBody::Preview {
723 path: std::path::PathBuf::from("/tmp/a.png"),
724 }
725 );
726 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 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 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 let _schema = schemars::schema_for!(ResponseBody);
773 }
774
775 #[test]
776 fn test_attachment_response_json_wire_format_unchanged() {
777 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 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 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 #[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 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 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 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 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 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 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 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 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}