use crate::error::BaseError;
use schemars::JsonSchema;
use serde::Serialize;
use std::path::PathBuf;
const RAW_ALLOWED_CONTENT_TYPE: &str = "application/json";
fn validate_raw_content_type(content_type: &str) -> Result<(), BaseError> {
if content_type != RAW_ALLOWED_CONTENT_TYPE {
return Err(BaseError::ConfigError(format!(
"Raw 响应 content-type 只允许 {RAW_ALLOWED_CONTENT_TYPE},收到 {content_type}"
)));
}
Ok(())
}
#[derive(Debug, Clone, Serialize, JsonSchema)]
#[non_exhaustive]
pub struct ApiResponse {
pub code: i32,
pub message: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
#[serde(skip)]
#[schemars(skip)]
pub attachment: Option<ResponseAttachment>,
#[serde(skip)]
#[schemars(skip)]
http_status: Option<u16>,
#[serde(skip)]
#[schemars(skip)]
headers: Vec<(String, String)>,
}
impl ApiResponse {
pub fn success<T: Serialize>(data: T, message: impl Into<String>) -> Result<Self, BaseError> {
let json_value = serde_json::to_value(data)
.map_err(|e| BaseError::JsonSerializeFailed(e.to_string()))?;
Ok(Self {
code: 0,
message: message.into(),
data: Some(json_value),
attachment: None,
http_status: None,
headers: Vec::new(),
})
}
pub fn success_value(data: serde_json::Value, message: impl Into<String>) -> Self {
Self {
code: 0,
message: message.into(),
data: Some(data),
attachment: None,
http_status: None,
headers: Vec::new(),
}
}
pub fn fail(code: i32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
data: None,
attachment: None,
http_status: None,
headers: Vec::new(),
}
}
pub fn fail_value(code: i32, data: serde_json::Value, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
data: Some(data),
attachment: None,
http_status: None,
headers: Vec::new(),
}
}
pub fn attachment(attachment: ResponseAttachment, message: impl Into<String>) -> Self {
Self {
code: 0,
message: message.into(),
data: None,
attachment: Some(attachment),
http_status: None,
headers: Vec::new(),
}
}
pub fn with_http_status(mut self, status: u16) -> Result<Self, BaseError> {
if !(100..=599).contains(&status) {
return Err(BaseError::ConfigError(format!(
"响应 HTTP 状态码无效: {status}"
)));
}
self.http_status = Some(status);
Ok(self)
}
pub fn with_header(
mut self,
name: impl Into<String>,
value: impl Into<String>,
) -> Result<Self, BaseError> {
let name = name.into();
let value = value.into();
let valid_name = !name.is_empty()
&& name.bytes().all(|byte| {
byte.is_ascii_alphanumeric()
|| matches!(
byte,
b'!' | b'#'
| b'$'
| b'%'
| b'&'
| b'\''
| b'*'
| b'+'
| b'-'
| b'.'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~'
)
});
let valid_value = value
.bytes()
.all(|byte| byte == b'\t' || (byte >= 0x20 && byte != 0x7f));
if !valid_name || !valid_value {
return Err(BaseError::ConfigError(
"响应头名称或值包含非法字符".to_string(),
));
}
self.headers.push((name, value));
Ok(self)
}
#[cfg(any(feature = "transport-axum", test))]
pub(crate) const fn http_status(&self) -> Option<u16> {
self.http_status
}
pub fn response_headers(&self) -> &[(String, String)] {
&self.headers
}
pub fn from_error(error: &BaseError) -> Self {
Self::fail(error.code(), error.to_string())
}
}
impl Default for ApiResponse {
fn default() -> Self {
Self {
code: 0,
message: "OK".to_string(),
data: None,
attachment: None,
http_status: None,
headers: Vec::new(),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, schemars::JsonSchema)]
#[serde(tag = "type", rename_all = "snake_case")]
#[non_exhaustive]
pub enum ResponseBody {
Download {
path: PathBuf,
filename: String,
},
Preview {
path: PathBuf,
},
Redirect {
url: String,
},
Raw {
body: String,
content_type: String,
},
}
impl ResponseBody {
pub fn download(path: impl Into<PathBuf>, filename: impl Into<String>) -> Self {
Self::Download {
path: path.into(),
filename: filename.into(),
}
}
pub fn preview(path: impl Into<PathBuf>) -> Self {
Self::Preview { path: path.into() }
}
pub fn redirect(url: impl Into<String>) -> Self {
Self::Redirect { url: url.into() }
}
pub fn raw(
body: impl Into<String>,
content_type: impl Into<String>,
) -> Result<Self, BaseError> {
let content_type = content_type.into();
validate_raw_content_type(&content_type)?;
Ok(Self::Raw {
body: body.into(),
content_type,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ResponseAttachment {
Download {
path: PathBuf,
filename: String,
},
Preview {
path: PathBuf,
},
Redirect {
url: String,
},
Raw {
body: String,
content_type: String,
},
}
impl From<ResponseBody> for ResponseAttachment {
fn from(body: ResponseBody) -> Self {
match body {
ResponseBody::Download { path, filename } => Self::Download { path, filename },
ResponseBody::Preview { path } => Self::Preview { path },
ResponseBody::Redirect { url } => Self::Redirect { url },
ResponseBody::Raw { body, content_type } => Self::Raw { body, content_type },
}
}
}
pub(crate) fn wrap_dispatch_output<T>(output: T, message: &str) -> Result<ApiResponse, BaseError>
where
T: Serialize + 'static,
{
let erased = &output as &dyn std::any::Any;
if let Some(response) = erased.downcast_ref::<ApiResponse>() {
return Ok(response.clone());
}
if let Some(body) = erased.downcast_ref::<ResponseBody>() {
if let ResponseBody::Raw { content_type, .. } = body {
validate_raw_content_type(content_type)?;
}
return Ok(ApiResponse::attachment(body.clone().into(), message));
}
ApiResponse::success(output, message)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn test_success_response() {
let response =
ApiResponse::success(json!({ "id": 123, "name": "Alice" }), "操作成功").unwrap();
assert_eq!(response.code, 0);
assert_eq!(response.message, "操作成功");
assert!(response.data.is_some());
let data = response.data.unwrap();
assert_eq!(data["id"], 123);
assert_eq!(data["name"], "Alice");
}
#[test]
fn test_success_response_with_null() {
let response = ApiResponse::success_value(serde_json::Value::Null, "操作成功");
assert_eq!(response.code, 0);
assert_eq!(response.message, "操作成功");
assert!(response.data.is_some());
assert_eq!(response.data.unwrap(), serde_json::Value::Null);
}
#[test]
fn test_success_value_response() {
let data = json!({ "count": 42 });
let response = ApiResponse::success_value(data, "查询成功");
assert_eq!(response.code, 0);
assert_eq!(response.message, "查询成功");
assert!(response.data.is_some());
assert_eq!(response.data.unwrap()["count"], 42);
}
#[test]
fn test_success_serialize_error_propagation() {
struct AlwaysFailSerialize;
impl serde::Serialize for AlwaysFailSerialize {
fn serialize<S: serde::Serializer>(&self, _serializer: S) -> Result<S::Ok, S::Error> {
use serde::ser::Error;
Err(S::Error::custom("测试序列化失败"))
}
}
let result = ApiResponse::success(AlwaysFailSerialize, "测试");
assert!(result.is_err(), "序列化失败应该返回错误");
if let Err(BaseError::JsonSerializeFailed(_)) = result {
} else {
panic!("期望 JsonSerializeFailed 错误");
}
}
#[test]
fn test_fail_response() {
let response = ApiResponse::fail(400001, "参数错误");
assert_eq!(response.code, 400001);
assert_eq!(response.message, "参数错误");
assert!(response.data.is_none());
}
#[test]
fn test_from_error() {
let error = BaseError::FieldRequired("username".to_string());
let response = ApiResponse::from_error(&error);
assert_ne!(response.code, 0);
assert!(response.message.contains("username"));
assert!(response.data.is_none());
assert_eq!(error.code(), 600006);
}
#[test]
fn test_default_response() {
let response = ApiResponse::default();
assert_eq!(response.code, 0);
assert_eq!(response.message, "OK");
assert!(response.data.is_none());
}
#[test]
fn transport_metadata_is_validated_and_never_serialized() {
let response = ApiResponse::default()
.with_http_status(304)
.expect("304 应是合法 HTTP 状态码")
.with_header("set-cookie", "session=one; HttpOnly")
.expect("Set-Cookie 应是合法响应头")
.with_header("set-cookie", "session=two; HttpOnly")
.expect("重复 Set-Cookie 必须保留");
assert_eq!(response.http_status(), Some(304));
assert_eq!(response.response_headers().len(), 2);
let wire = serde_json::to_value(&response).expect("响应应可序列化");
assert!(wire.get("http_status").is_none());
assert!(wire.get("headers").is_none());
assert!(ApiResponse::default().with_http_status(99).is_err());
assert!(ApiResponse::default()
.with_header("bad header", "value")
.is_err());
assert!(ApiResponse::default()
.with_header("x-test", "line\r\nbreak")
.is_err());
}
#[test]
fn test_serialize_response() {
let response = ApiResponse::success(json!({ "count": 10 }), "查询成功").unwrap();
let json = serde_json::to_string(&response).unwrap();
assert!(json.contains("\"code\":0"));
assert!(json.contains("\"message\":\"查询成功\""));
assert!(json.contains("\"data\""));
}
#[test]
fn test_serialize_fail_response() {
let response = ApiResponse::fail(500001, "服务器错误");
let json = serde_json::to_string(&response).unwrap();
assert!(json.contains("\"code\":500001"));
assert!(json.contains("\"message\":\"服务器错误\""));
assert!(!json.contains("\"data\""));
}
#[test]
fn test_response_body_constructors() {
let download = ResponseBody::download("/tmp/report.pdf", "report.pdf");
assert_eq!(
download,
ResponseBody::Download {
path: std::path::PathBuf::from("/tmp/report.pdf"),
filename: "report.pdf".to_string(),
}
);
assert_eq!(
ResponseBody::preview("/tmp/a.png"),
ResponseBody::Preview {
path: std::path::PathBuf::from("/tmp/a.png"),
}
);
assert_eq!(
ResponseBody::redirect("https://example.com/next"),
ResponseBody::Redirect {
url: "https://example.com/next".to_string(),
}
);
}
#[test]
fn test_response_body_into_attachment() {
let attachment: ResponseAttachment = ResponseBody::download("/tmp/a.bin", "a.bin").into();
assert_eq!(
attachment,
ResponseAttachment::Download {
path: std::path::PathBuf::from("/tmp/a.bin"),
filename: "a.bin".to_string(),
}
);
let attachment: ResponseAttachment = ResponseBody::preview("/tmp/b.png").into();
assert_eq!(
attachment,
ResponseAttachment::Preview {
path: std::path::PathBuf::from("/tmp/b.png"),
}
);
let attachment: ResponseAttachment = ResponseBody::redirect("/home").into();
assert_eq!(
attachment,
ResponseAttachment::Redirect {
url: "/home".to_string(),
}
);
}
#[test]
fn test_response_body_implements_action_output_contract() {
fn assert_output_contract<T: Serialize + schemars::JsonSchema + 'static>() {}
assert_output_contract::<ResponseBody>();
let body = ResponseBody::redirect("/next");
let json = serde_json::to_string(&body).unwrap();
assert!(json.contains("/next"), "ResponseBody 应可序列化: {json}");
let _schema = schemars::schema_for!(ResponseBody);
}
#[test]
fn test_attachment_response_json_wire_format_unchanged() {
let response = ApiResponse::attachment(
ResponseAttachment::Redirect {
url: "/next".to_string(),
},
"成功",
);
assert_eq!(response.code, 0);
assert!(response.data.is_none());
let json = serde_json::to_string(&response).unwrap();
assert!(
!json.contains("attachment"),
"线格式不得包含附件信息: {json}"
);
assert!(json.contains("\"code\":0"));
}
#[test]
fn test_plain_response_has_no_attachment() {
let ok = ApiResponse::success(json!({"a": 1}), "ok").unwrap();
assert!(ok.attachment.is_none());
let fail = ApiResponse::fail(1, "bad");
assert!(fail.attachment.is_none());
let default = ApiResponse::default();
assert!(default.attachment.is_none());
}
#[test]
fn test_wrap_dispatch_output_recognizes_response_body() {
let response = wrap_dispatch_output(ResponseBody::redirect("/next"), "成功").unwrap();
assert_eq!(response.code, 0);
assert!(response.data.is_none());
assert_eq!(
response.attachment,
Some(ResponseAttachment::Redirect {
url: "/next".to_string(),
})
);
}
#[test]
fn test_wrap_dispatch_output_passes_through_plain_output() {
#[derive(Serialize)]
struct Plain {
value: i32,
}
let response = wrap_dispatch_output(Plain { value: 7 }, "成功").unwrap();
assert_eq!(response.code, 0);
assert_eq!(response.data.unwrap()["value"], 7);
assert!(response.attachment.is_none());
}
#[test]
fn raw_response_body_rejects_non_json_content_type() {
let failed = ResponseBody::raw("<html></html>", "text/html")
.expect_err("非 application/json 必须被拒绝");
assert!(
failed.to_string().contains("application/json"),
"错误信息应说明允许的 content-type,实际: {failed}"
);
}
#[test]
fn directly_constructed_raw_is_revalidated_at_dispatch_boundary() {
let body = ResponseBody::Raw {
body: "<html><script>alert(1)</script></html>".to_string(),
content_type: "text/html".to_string(),
};
let err =
wrap_dispatch_output(body, "成功").expect_err("派发边界必须拒绝直接构造的非 JSON Raw");
assert!(
matches!(&err, BaseError::ConfigError(_)),
"应与 raw() 使用同一错误类型,实际: {err:?}"
);
assert!(
err.to_string().contains("application/json"),
"错误信息应说明允许的 content-type,实际: {err}"
);
}
#[test]
fn directly_constructed_json_raw_still_maps_to_attachment() {
let body = ResponseBody::Raw {
body: r#"{"code":0,"msg":"ok"}"#.to_string(),
content_type: "application/json".to_string(),
};
let response = wrap_dispatch_output(body, "成功").expect("合法 Raw 应通过派发边界");
assert_eq!(response.code, 0);
assert!(response.data.is_none(), "Raw 不得进入 data");
assert_eq!(
response.attachment,
Some(ResponseAttachment::Raw {
body: r#"{"code":0,"msg":"ok"}"#.to_string(),
content_type: "application/json".to_string(),
})
);
}
#[test]
fn dispatch_validation_uses_same_exact_match_as_constructor() {
assert!(ResponseBody::raw("{}", "application/json; charset=utf-8").is_err());
let body = ResponseBody::Raw {
body: "{}".to_string(),
content_type: "application/json; charset=utf-8".to_string(),
};
assert!(
wrap_dispatch_output(body, "成功").is_err(),
"派发边界的白名单必须与 raw() 的精确匹配语义一致"
);
}
#[test]
fn attachment_raw_content_type_is_not_tightened() {
let response = ApiResponse::attachment(
ResponseAttachment::Raw {
body: "a,b\r\n1,2".to_string(),
content_type: "text/csv; charset=utf-8".to_string(),
},
"成功",
);
assert_eq!(
response.attachment,
Some(ResponseAttachment::Raw {
body: "a,b\r\n1,2".to_string(),
content_type: "text/csv; charset=utf-8".to_string(),
})
);
let passed = wrap_dispatch_output(response, "成功").expect("ApiResponse 应原样透传");
assert_eq!(
passed.attachment,
Some(ResponseAttachment::Raw {
body: "a,b\r\n1,2".to_string(),
content_type: "text/csv; charset=utf-8".to_string(),
})
);
}
#[test]
fn raw_response_body_maps_to_raw_attachment_without_envelope() {
let body = ResponseBody::raw(r#"{"code":0,"msg":"ok"}"#, "application/json")
.expect("application/json 应被接受");
let response = wrap_dispatch_output(body, "成功").expect("收口应成功");
assert_eq!(response.code, 0);
assert!(response.data.is_none(), "Raw 不得进入 data");
assert_eq!(
response.attachment,
Some(ResponseAttachment::Raw {
body: r#"{"code":0,"msg":"ok"}"#.to_string(),
content_type: "application/json".to_string(),
})
);
}
#[test]
fn raw_response_body_survives_json_wire_format() {
let body = ResponseBody::raw("{}", "application/json").expect("应被接受");
let response = wrap_dispatch_output(body, "成功").expect("收口应成功");
let json = serde_json::to_string(&response).expect("应可序列化");
assert!(
!json.contains("attachment"),
"线格式不得含 attachment: {json}"
);
}
}