Files
tdc-rs/src/envelope.rs
T
adminandClaude Code 43fcefc6ab fix(contract): 补 ActionResult 的 IntoResponse;修配置变量名与雪花号回绕
- envelope: 补 impl IntoResponse(状态码恒 200,业务成败只由 body.code 表达)
- config: 认规格名 TDC_LOCAL_STANDALONE(TDC_STANDALONE 保留为别名);
  抽 env_or_default 统一处理空串/纯空白回落
- ids: 改毫秒+12位序列打包 + CAS 循环,序列用满时拒绝产出而非回绕出重复 id;
  修正纪元注释(1_600_000_000_000 = 2020-09-13)

Co-Authored-By: Claude Code <[email protected]>
2026-10-24 14:36:17 +08:00

183 lines
5.4 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 新版契约响应信封:HTTP 200 + `{code, msg, data}`。
//!
//! ⚠️ **鉴权失败不走本信封** —— 上游 `TdcAuthFilter` 回的是
//! `{"success":false,"code":401,"msg":"…"}`(**无 `data`、多 `success:false`**)。
//! 两套形状必须分开实现,见 `auth::reject`。
use axum::http::StatusCode;
use axum::response::{IntoResponse, Response};
use axum::Json;
use serde::Serialize;
use serde_json::Value;
pub const CODE_OK: i32 = 200;
pub const CODE_FAIL: i32 = 400;
pub const CODE_FORBIDDEN: i32 = 403;
pub const CODE_SERVER_ERROR: i32 = 500;
pub const CODE_SESSION_EXPIRED: i32 = 600;
#[derive(Debug, Clone, Serialize)]
pub struct ActionResult<T> {
pub code: i32,
pub msg: Option<String>,
pub data: Option<T>,
}
impl<T> ActionResult<T> {
pub fn ok(data: T) -> Self {
Self {
code: CODE_OK,
msg: None,
data: Some(data),
}
}
pub fn ok_msg(msg: impl Into<String>, data: T) -> Self {
Self {
code: CODE_OK,
msg: Some(msg.into()),
data: Some(data),
}
}
}
impl ActionResult<Value> {
/// 业务失败:**HTTP 仍为 200**,用 body 的 `code` 表达失败。
pub fn fail(msg: impl Into<String>) -> Self {
Self {
code: CODE_FAIL,
msg: Some(msg.into()),
data: None,
}
}
pub fn fail_code(code: i32, msg: impl Into<String>) -> Self {
Self {
code,
msg: Some(msg.into()),
data: None,
}
}
/// 分页列表:`{pagination:{currentPage,pageSize,total}, list:[…]}`。
pub fn page(list: Vec<Value>, pagination: Pagination) -> Self {
let data = serde_json::to_value(PageData { pagination, list })
.expect("PageData 一定可序列化");
Self {
code: CODE_OK,
msg: None,
data: Some(data),
}
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Pagination {
pub current_page: i64,
pub page_size: i64,
pub total: i64,
}
#[derive(Debug, Clone, Serialize)]
pub struct PageData {
pub pagination: Pagination,
pub list: Vec<Value>,
}
/// 业务信封 → HTTP 响应。
///
/// 🔴 **状态码恒为 200**,无论 `self.code` 是多少 —— 业务成败只由 body 的 `code` 表达
/// (全局约束:业务失败一律 HTTP 200 + `{code,msg,data}`)。
///
/// ⚠️ 本 impl 只服务**业务信封**。鉴权失败(401/403)是另一套形状
/// `{"success":false,"code":401,"msg":"…"}`(无 `data`),由鉴权层单独实现,
/// **不要**塞进本信封。
impl<T: Serialize> IntoResponse for ActionResult<T> {
fn into_response(self) -> Response {
(StatusCode::OK, Json(self)).into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn ok_has_null_msg_and_wrapped_data() {
let r = ActionResult::ok(json!({"a": 1}));
assert_eq!(
serde_json::to_value(&r).unwrap(),
json!({"code": 200, "msg": null, "data": {"a": 1}})
);
}
#[test]
fn write_ops_carry_the_chinese_message() {
let r = ActionResult::ok_msg("新增成功", "12345");
assert_eq!(
serde_json::to_value(&r).unwrap(),
json!({"code": 200, "msg": "新增成功", "data": "12345"})
);
}
#[test]
fn business_failure_is_still_http_200_with_code_400() {
let r = ActionResult::fail("记录不存在或已删除");
assert_eq!(
serde_json::to_value(&r).unwrap(),
json!({"code": 400, "msg": "记录不存在或已删除", "data": null})
);
}
#[test]
fn page_shape_matches_jnpf_pagelistvo() {
let r = ActionResult::page(
vec![json!({"id": "1"})],
Pagination {
current_page: 2,
page_size: 20,
total: 41,
},
);
assert_eq!(
serde_json::to_value(&r).unwrap(),
json!({
"code": 200,
"msg": null,
"data": {
"pagination": {"currentPage": 2, "pageSize": 20, "total": 41},
"list": [{"id": "1"}]
}
})
);
}
/// 🔴 业务失败也必须回 HTTP **200**;成败只由 body 的 `code` 表达。
#[tokio::test]
async fn into_response_keeps_http_200_for_business_failure() {
let resp = ActionResult::fail("记录不存在或已删除").into_response();
assert_eq!(resp.status(), StatusCode::OK, "业务失败不得走 4xx");
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.expect("读 body");
let v: Value = serde_json::from_slice(&body).expect("body 是 JSON");
assert_eq!(v["code"], 400);
assert_eq!(v["msg"], "记录不存在或已删除");
assert!(v["data"].is_null());
}
#[tokio::test]
async fn into_response_of_ok_is_http_200_with_wrapped_data() {
let resp = ActionResult::ok(json!({"a": 1})).into_response();
assert_eq!(resp.status(), StatusCode::OK);
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
.await
.expect("读 body");
let v: Value = serde_json::from_slice(&body).expect("body 是 JSON");
assert_eq!(v["code"], 200);
assert_eq!(v["data"], json!({"a": 1}));
}
}