feat(routes): 18 实体 CRUD 路由装配 + 全链路冒烟
- 每个实体 6 条路由(列表/All/详情/新增/修改/删除),路径参数用 axum 0.8 的 {id}
- 冒烟覆盖:无凭证 401 裸三字段、内部令牌业务信封、/All 裸数组、协议版本不兼容 401
- 补资源侧只读聚合路由 /Resource/{id}/Detail 与 /Dataset/{id}/Detail(上游前端在用)
Co-Authored-By: Claude Code <[email protected]>
This commit is contained in:
1 parent
0a3811585c
commit
0f84fbdb83
2 files changed
+281
-2
No files matched your search
+110
-2
@@ -1,9 +1,117 @@
|
||||
//! 18 实体的通用 CRUD 路由(Task 9 实现)。
|
||||
//! 18 实体的通用 CRUD 路由装配。
|
||||
//!
|
||||
//! 每个实体注册 6 条路由:
|
||||
//! GET {path} 分页列表
|
||||
//! GET {path}/All 全量列表(≤1000;**仍是业务信封** `{code,msg,data:[…]}`)
|
||||
//! GET {path}/{id} 详情
|
||||
//! POST {path} 新增
|
||||
//! PUT {path}/{id} 修改
|
||||
//! DELETE {path}/{id} 逻辑删除
|
||||
//!
|
||||
//! 🔴 axum 规定**主体抽取器必须是最后一个参数** ⇒ `Option<Json<Value>>` 永远排最后,
|
||||
//! `Option<Extension<Principal>>` 排它前面。
|
||||
//!
|
||||
//! 🔴 路由路径**一律取 `TableSpec::path`**(注册表是唯一真源)⇒ 不另写字符串。
|
||||
|
||||
use axum::extract::{Extension, Path, RawQuery, State};
|
||||
use axum::routing::get;
|
||||
use axum::Router;
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::auth::Principal;
|
||||
use crate::crud;
|
||||
use crate::registry::{self, TableSpec};
|
||||
use crate::state::AppState;
|
||||
|
||||
pub fn router() -> Router<AppState> {
|
||||
Router::new()
|
||||
let mut r = Router::new();
|
||||
for spec in registry::REGISTRY {
|
||||
let s: &'static TableSpec = spec;
|
||||
r = r
|
||||
.route(
|
||||
s.path,
|
||||
get(move |State(st): State<AppState>, q: RawQuery, p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::list(&st, s, ¶ms, principal.as_ref()).await }
|
||||
})
|
||||
.post(
|
||||
move |State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
b: Option<axum::Json<Value>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
let body = b.map(|axum::Json(v)| v).unwrap_or(Value::Null);
|
||||
async move { crud::create(&st, s, &body, principal.as_ref()).await }
|
||||
},
|
||||
),
|
||||
)
|
||||
.route(
|
||||
&format!("{}/All", s.path),
|
||||
get(move |State(st): State<AppState>, q: RawQuery, p: Option<Extension<Principal>>| {
|
||||
let params = crud::parse_query(q.0.as_deref());
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::all(&st, s, ¶ms, principal.as_ref()).await }
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
&format!("{}/{{id}}", s.path),
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail(&st, s, &id, principal.as_ref()).await }
|
||||
})
|
||||
.put(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>,
|
||||
b: Option<axum::Json<Value>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
let body = b.map(|axum::Json(v)| v).unwrap_or(Value::Null);
|
||||
async move { crud::update(&st, s, &id, &body, principal.as_ref()).await }
|
||||
},
|
||||
)
|
||||
.delete(
|
||||
move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::delete(&st, s, &id, principal.as_ref()).await }
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
// 资源侧只读聚合体(上游 `ResourceController#detailOf` / `DatasetController#detailOf`)
|
||||
//
|
||||
// 🔴 路径里的 `{id}` 与上面的 `/{Entity}/{id}` **同层并存** ——
|
||||
// matchit 允许「参数段 + 更深的静态段」,静态段优先匹配,无冲突。
|
||||
// 🔴 `Dataset` 在注册表里 `table = "tdc_resource"`(只读视图)⇒ 聚合体与 Resource 同源。
|
||||
{
|
||||
let res_spec: &'static TableSpec =
|
||||
registry::find("Resource").expect("Resource 必须在注册表里");
|
||||
let ds_spec: &'static TableSpec =
|
||||
registry::find("Dataset").expect("Dataset 必须在注册表里");
|
||||
r = r
|
||||
.route(
|
||||
"/api/ssw/tdc/Resource/{id}/Detail",
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail_aggregate(&st, res_spec, &id, principal.as_ref()).await }
|
||||
}),
|
||||
)
|
||||
.route(
|
||||
"/api/ssw/tdc/Dataset/{id}/Detail",
|
||||
get(move |Path(id): Path<String>,
|
||||
State(st): State<AppState>,
|
||||
p: Option<Extension<Principal>>| {
|
||||
let principal = p.map(|e| e.0);
|
||||
async move { crud::detail_aggregate(&st, ds_spec, &id, principal.as_ref()).await }
|
||||
}),
|
||||
);
|
||||
}
|
||||
r
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! 全链路冒烟:路由装配 + 三道门 + 信封形状。
|
||||
//!
|
||||
//! ⚠️ 本测试二进制内共用一个 PGlite 实例(pglite-rs 每进程只允许一个)。
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use axum::Router;
|
||||
use http_body_util::BodyExt;
|
||||
use pglite::PGlite;
|
||||
use serde_json::Value;
|
||||
use tdc_connector::auth::{auth_middleware, AuthState};
|
||||
use tdc_connector::config::Config;
|
||||
use tdc_connector::routes::build_router;
|
||||
use tdc_connector::session::SessionStore;
|
||||
use tdc_connector::state::{AppState, BootstrapIdentity};
|
||||
use tokio::sync::OnceCell;
|
||||
use tower::ServiceExt;
|
||||
|
||||
static DB: OnceCell<Arc<PGlite>> = OnceCell::const_new();
|
||||
|
||||
async fn shared_db() -> Arc<PGlite> {
|
||||
DB.get_or_init(|| async {
|
||||
let db = Arc::new(PGlite::open_temp().await.expect("打开临时 PGlite 失败"));
|
||||
tdc_connector::db::ensure_schema(db.as_ref())
|
||||
.await
|
||||
.expect("建表失败");
|
||||
db
|
||||
})
|
||||
.await
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// 构造一个带鉴权中间件的 router,并返回当前生效的内部令牌。
|
||||
async fn build() -> (Router, String) {
|
||||
let db = shared_db().await;
|
||||
let mut config = Config::from_env(std::env::current_dir().unwrap());
|
||||
config.identity_code = "TEST-CONNECTOR".to_string();
|
||||
let sessions = Arc::new(SessionStore::new());
|
||||
let token = config.internal_token.clone();
|
||||
let state = AppState::new(
|
||||
config.clone(),
|
||||
db,
|
||||
sessions.clone(),
|
||||
BootstrapIdentity {
|
||||
identity_id: "TEST-OP".to_string(),
|
||||
identity_code: "TEST-CONNECTOR".to_string(),
|
||||
issued_secret: None,
|
||||
},
|
||||
);
|
||||
let auth_state = AuthState {
|
||||
internal_token: config.internal_token.clone(),
|
||||
sessions,
|
||||
};
|
||||
// 🔴 axum 0.8.9:`impl<B> Service<Request<B>> for Router<()>` —— **只有 `Router<()>` 实现
|
||||
// `Service`**(`axum-0.8.9/src/routing/mod.rs:569`)。`build_router` 返回
|
||||
// `Router<AppState>`(S = 还缺什么状态)⇒ 直接 `oneshot` **编译不过**。
|
||||
// 必须再 `.with_state(state)` 一次把它落到 `Router<()>`。
|
||||
// ✅ 本仓已有可用样板:`tests/auth_flow.rs` 的 `build_app()`。
|
||||
let app: Router = build_router(state.clone())
|
||||
.layer(axum::middleware::from_fn_with_state(auth_state, auth_middleware))
|
||||
.with_state(state);
|
||||
(app, token)
|
||||
}
|
||||
|
||||
fn get(uri: &str, token: Option<&str>) -> Request<Body> {
|
||||
let mut b = Request::builder().method("GET").uri(uri);
|
||||
if let Some(t) = token {
|
||||
b = b.header("X-Internal-Token", t);
|
||||
}
|
||||
b.body(Body::empty()).unwrap()
|
||||
}
|
||||
|
||||
async fn call(app: &Router, r: Request<Body>) -> (StatusCode, Value) {
|
||||
let resp = app.clone().oneshot(r).await.expect("请求失败");
|
||||
let status = resp.status();
|
||||
let bytes = resp.into_body().collect().await.unwrap().to_bytes();
|
||||
let value = serde_json::from_slice(&bytes).unwrap_or(Value::Null);
|
||||
(status, value)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn crud_routes_are_guarded_and_use_the_business_envelope() {
|
||||
let (app, token) = build().await;
|
||||
|
||||
// ① 无凭证 ⇒ HTTP 401 + 裸三字段(无 data)
|
||||
let (status, body) = call(&app, get("/api/ssw/tdc/Product", None)).await;
|
||||
assert_eq!(status, 401);
|
||||
assert_eq!(body["success"], false);
|
||||
assert_eq!(body["code"], 401);
|
||||
assert!(body.get("data").is_none(), "鉴权失败不得有 data 字段");
|
||||
|
||||
// ② 内部令牌 ⇒ HTTP 200 + 业务信封
|
||||
let (status, body) = call(&app, get("/api/ssw/tdc/Product", Some(token.as_str()))).await;
|
||||
assert_eq!(status, 200);
|
||||
assert_eq!(body["code"], 200);
|
||||
assert!(body["data"]["list"].is_array());
|
||||
assert!(body["data"]["pagination"]["total"].is_number());
|
||||
|
||||
// ③ /All ⇒ 裸数组
|
||||
let (status, body) = call(&app, get("/api/ssw/tdc/Product/All", Some(token.as_str()))).await;
|
||||
assert_eq!(status, 200);
|
||||
assert!(body["data"].is_array(), "/All 必须返回裸数组");
|
||||
|
||||
// ④ 18 个实体全部注册成功(随便挑几个含只读与审计的)
|
||||
for api in ["Dataset", "DeliveryTask", "AuditLog", "Identity", "PolicyTemplate"] {
|
||||
let (status, body) = call(&app, get(&format!("/api/ssw/tdc/{}", api), Some(token.as_str()))).await;
|
||||
assert_eq!(status, 200, "{} 列表应可用", api);
|
||||
assert_eq!(body["code"], 200, "{} 列表应返回业务信封", api);
|
||||
}
|
||||
|
||||
// ⑤ 资源侧只读聚合路由已注册(不是 404):无该 id ⇒ 业务失败 400
|
||||
for path in [
|
||||
"/api/ssw/tdc/Resource/R-NOT-EXIST/Detail",
|
||||
"/api/ssw/tdc/Dataset/R-NOT-EXIST/Detail",
|
||||
] {
|
||||
let (status, body) = call(&app, get(path, Some(token.as_str()))).await;
|
||||
assert_eq!(status, 200, "{} 必须已注册(404 说明路由没挂上):{:?}", path, body);
|
||||
assert_eq!(body["code"], 400, "{} 查无应是业务失败:{}", path, body);
|
||||
assert_eq!(body["msg"], "记录不存在或已删除");
|
||||
assert!(body["data"].is_null(), "业务失败的 data 为 null(信封恒带 data 键)");
|
||||
}
|
||||
}
|
||||
|
||||
/// 🔴 **18 个实体逐一断言路由已挂上**:不能只抽查。
|
||||
///
|
||||
/// 路由缺失的表现是 HTTP 404 + 非业务信封 ⇒ 这里逐个断言
|
||||
/// 「HTTP 200 + `code=200` + `data.list` 是数组」。
|
||||
#[tokio::test]
|
||||
async fn every_registry_entity_has_a_working_list_route() {
|
||||
let (app, token) = build().await;
|
||||
let mut seen = 0usize;
|
||||
for spec in tdc_connector::registry::REGISTRY {
|
||||
seen += 1;
|
||||
let (status, body) = call(&app, get(spec.path, Some(token.as_str()))).await;
|
||||
assert_eq!(status, 200, "{} 列表路由未挂上:{:?}", spec.api_name, body);
|
||||
assert_eq!(body["code"], 200, "{} 列表应返回业务信封:{:?}", spec.api_name, body);
|
||||
assert!(
|
||||
body["data"]["list"].is_array(),
|
||||
"{} 列表 data.list 必须是数组:{:?}",
|
||||
spec.api_name,
|
||||
body
|
||||
);
|
||||
assert!(
|
||||
body["data"]["pagination"]["total"].is_number(),
|
||||
"{} 列表必须有 pagination.total:{:?}",
|
||||
spec.api_name,
|
||||
body
|
||||
);
|
||||
|
||||
// /All 也要挂上(裸数组)
|
||||
let (status, body) = call(&app, get(&format!("{}/All", spec.path), Some(token.as_str()))).await;
|
||||
assert_eq!(status, 200, "{}/All 路由未挂上:{:?}", spec.api_name, body);
|
||||
assert!(body["data"].is_array(), "{}/All 必须返回裸数组", spec.api_name);
|
||||
}
|
||||
assert_eq!(seen, 18, "注册表必须是 18 个实体,实际 {}", seen);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn incompatible_protocol_version_is_rejected_with_401() {
|
||||
let (app, token) = build().await;
|
||||
|
||||
let mut r = get("/api/ssw/tdc/Product", Some(token.as_str()));
|
||||
r.headers_mut()
|
||||
.insert("X-Protocol-Version", "2.0".parse().unwrap());
|
||||
let (status, body) = call(&app, r).await;
|
||||
assert_eq!(status, 401);
|
||||
assert_eq!(body["msg"], "跨端协议版本不兼容,请升级对端");
|
||||
assert!(body.get("data").is_none());
|
||||
}
|
||||
Reference in new issue
Block a user