1use crate::error::BaseError;
6use schemars::JsonSchema;
7use serde::Serialize;
8use std::path::PathBuf;
9
10#[derive(Debug, Clone, Serialize, JsonSchema)]
42#[non_exhaustive]
43pub struct ApiResponse {
44 pub code: i32,
49
50 pub message: String,
54
55 #[serde(skip_serializing_if = "Option::is_none")]
59 pub data: Option<serde_json::Value>,
60
61 #[serde(skip)]
66 #[schemars(skip)]
67 pub attachment: Option<ResponseAttachment>,
68
69 #[serde(skip)]
71 #[schemars(skip)]
72 http_status: Option<u16>,
73
74 #[serde(skip)]
76 #[schemars(skip)]
77 headers: Vec<(String, String)>,
78}
79
80impl ApiResponse {
81 pub fn success<T: Serialize>(data: T, message: impl Into<String>) -> Result<Self, BaseError> {
118 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 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 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 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 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 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 pub fn response_headers(&self) -> &[(String, String)] {
293 &self.headers
294 }
295
296 pub fn from_error(error: &BaseError) -> Self {
323 Self::fail(error.code(), error.to_string())
324 }
325}
326
327impl Default for ApiResponse {
328 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#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
364#[serde(tag = "type", rename_all = "snake_case")]
365pub enum ResponseBody {
366 Download {
368 path: PathBuf,
370 filename: String,
372 },
373 Preview {
375 path: PathBuf,
377 },
378 Redirect {
380 url: String,
382 },
383}
384
385impl ResponseBody {
386 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 pub fn preview(path: impl Into<PathBuf>) -> Self {
396 Self::Preview { path: path.into() }
397 }
398
399 pub fn redirect(url: impl Into<String>) -> Self {
401 Self::Redirect { url: url.into() }
402 }
403}
404
405#[derive(Debug, Clone, PartialEq, Eq)]
410pub enum ResponseAttachment {
411 Download {
413 path: PathBuf,
415 filename: String,
417 },
418 Preview {
420 path: PathBuf,
422 },
423 Redirect {
425 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
440pub(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 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 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 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 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 assert!(result.is_err(), "序列化失败应该返回错误");
516 if let Err(BaseError::JsonSerializeFailed(_)) = result {
517 } 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 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 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 assert!(!json.contains("\"data\""));
596 }
597
598 #[test]
599 fn test_response_body_constructors() {
600 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 assert_eq!(
611 ResponseBody::preview("/tmp/a.png"),
612 ResponseBody::Preview {
613 path: std::path::PathBuf::from("/tmp/a.png"),
614 }
615 );
616 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 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 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 let _schema = schemars::schema_for!(ResponseBody);
663 }
664
665 #[test]
666 fn test_attachment_response_json_wire_format_unchanged() {
667 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 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 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 #[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}