resource_metadata.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. use serde_json::{json, Value};
  2. use std::collections::HashMap;
  3. use super::PlatformClient;
  4. use bos_core::BosError;
  5. /// `node/batch_get@v1` 单次 `node_ids` 上限(平台契约 `maxItems: 500`,越界=`11103` 整批失败)。
  6. const BATCH_GET_MAX_IDS: usize = 500;
  7. /// `node/get_subtree@v1` 的深度/规模护栏(平台契约参数,越界由平台截断并置 `truncated`)。
  8. const RM_SUBTREE_MAX_DEPTH: i64 = 20;
  9. const RM_SUBTREE_MAX_NODES: i64 = 2000;
  10. /// 拆开平台信封:`code != 10000` ⇒ **失败**。
  11. ///
  12. /// 网关对"业务失败"仍回 `HTTP 200`+信封(实测 `node/create` 权限不足=`code 11001`),
  13. /// 只判 `status.is_success()` 就 `json_ok` ⇒ 前端看到 `0/成功` 但树上什么都没发生(假成功)。
  14. /// 故信封码的判定**收在这一层**,消费方拿到的 `Ok(v)` 必然是真成功的 `data`。
  15. fn rm_data(resp: &Value, api: &str) -> Result<Value, BosError> {
  16. if resp.get("code").and_then(Value::as_i64) != Some(bos_core::error::CODE_OK) {
  17. let brief: String = resp
  18. .get("message")
  19. .or_else(|| resp.get("msg"))
  20. .and_then(Value::as_str)
  21. .unwrap_or("")
  22. .chars()
  23. .take(200)
  24. .collect();
  25. return Err(BosError::biz(
  26. bos_core::ErrorCode::Downstream,
  27. format!("RM {api} 返回非成功码: code={} message={brief}", resp.get("code").and_then(Value::as_i64).map(|c| c.to_string()).unwrap_or_default()),
  28. ));
  29. }
  30. Ok(resp.get("data").cloned().unwrap_or(Value::Null))
  31. }
  32. /// [`PlatformClient::node_get_subtree`] 的产物:把平台的**单根嵌套**载荷摊平成父子清单。
  33. #[derive(Debug, Default)]
  34. pub struct RmSubtree {
  35. /// 前序遍历的节点清单(`depth` 从 0=根算起)。
  36. pub nodes: Vec<RmNode>,
  37. /// 平台据以判权的调用方作用域(形如 `end_user:376985101906509824`),原样透传供排障。
  38. pub grant_scope: Option<String>,
  39. /// 平台按 `max_depth`/`max_nodes` **截断**过 ⇒ 本次载荷不是整棵树。
  40. pub truncated: bool,
  41. }
  42. /// 平台资源树的一个节点(`node/get_subtree@v1` 载荷键名=`id`/`name`/`parent_id`/`children`,
  43. /// ⛔ `node_id`/`node_name`——2026-11-11 实测:写口用 `name`,读口亦用 `name`)。
  44. #[derive(Debug, Clone)]
  45. pub struct RmNode {
  46. pub id: String,
  47. /// 节点中文名;平台未给 ⇒ `None`(⛔ 拿 id 冒充名字)。
  48. pub name: Option<String>,
  49. /// 父节点 id;根节点=`None`。
  50. pub parent_id: Option<String>,
  51. pub depth: usize,
  52. }
  53. /// [`PlatformClient::node_batch_get`] 的产物。
  54. #[derive(Debug, Default)]
  55. pub struct BatchNodeNames {
  56. /// 命中节点:`node_id → node_name`(平台已按语言解析好的中文名)。
  57. pub names: HashMap<String, String>,
  58. /// 平台**明确未给名**的 id。⚠️ 该集合同时含「节点不存在」与「越权」两类,平台侧⛔ 区分
  59. /// ⇒ 消费方⛔ 把它渲染成"节点不存在",只能呈现为"名称未下发"。
  60. pub missing: Vec<String>,
  61. /// 平台本次据以判权的**调用方作用域**(形如 `end_user:376985101906509824`),原样透传供排障。
  62. pub grant_scope: Option<String>,
  63. }
  64. /// **客体树写接口**(`rt.node.*`/`rt.resource.*`):一律走 [`PlatformClient::post_json_as_user`],
  65. /// 把**最终用户 JWT 原样转发**给平台。
  66. ///
  67. /// ✅ 2026-11-08 业主改判(`U-103`,替代承接=总则§8.1 `:12`/§8.2 调用方身份列/纪律清单 §8.4):
  68. /// * 最终用户令牌的作用域=**项目**,所以"这棵树属于哪个项目"由**令牌自身**判定 ⇒
  69. /// ⛔ 任何"归属自报"请求头、⛔ 业务自报项目/租户;
  70. /// * 链路=客户端 → 业务服务 → 平台,我方是**转发方**、⛔ **代持方**;
  71. /// * ⛔ 用服务账号令牌(`post_json`=服务身份+`X-Internal-Token`)发起树写——那是"服务自发起动作",
  72. /// 正是被撤销的旧口径(内部服务白名单已作废);
  73. /// * 取不到令牌 ⇒ 由调用方(`AuthContext::end_user_token`)**显式失败**,⛔ 静默降级成服务身份。
  74. ///
  75. /// ⚠️ 本文件⛔ 出现"令牌缺失时回落 `post_json`"的兜底分支——那会把"最终用户没登录"伪装成
  76. /// "平台拒了",是 `U-103` 要消灭的形态。若平台对最终用户令牌返 `11001`(第 0 期未把 `rt.*`
  77. /// 授到 `end_user` 档位),**如实把失败透给前端**并登记证据,⛔ 在我方侧绕过。
  78. ///
  79. /// 例外:[`PlatformClient::registered_resource_list_all`](列举)仍走服务身份——总则§8.4 纪律 2
  80. /// 把"枚举型读取"收窄在服务侧,不随本次反转扩大。
  81. ///
  82. /// ⚠️ **网关路径必须逐字照注册表写**(2026-11-10 取证,缺口清单 B-14):本服务在网关的登记前缀是
  83. /// `/api/system/seoh-resource-metadata/resource-tree/`(注册中心库
  84. /// `seoh_service_registry.service_registry.t_registry_service_route` 实测 21 条路由全部带
  85. /// `resource-tree/` 段,如 `POST /api/system/seoh-resource-metadata/resource-tree/node/create@v1`)。
  86. /// 本文件此前写成 `/api/system/seoh-resource-metadata/node/*`(**少一段 `resource-tree/`**),
  87. /// 网关按 `method+path` 精确匹配 ⇒ 一律 `HTTP 404 / code 50000 未找到匹配路由`——该 404 曾被误读成
  88. /// "平台没开这个口"(→ 缺口清单 A-1 误判)与"dev 网关路由表整体为空"(→ B-14 误判),实为我方路径漂移。
  89. /// 对照实验(同一网关、同一时刻):写对前缀 ⇒ `code 11000 未登录`(路由存在、已转发);写错 ⇒ `50000`。
  90. impl PlatformClient {
  91. /// 建节点。**返回=信封里的 `data`**(新节点 id 在 `data.id`,⛔ `data.node_id`——2026-11-11 实测)。
  92. pub async fn node_create(&self, data: Value, user_token: &str) -> Result<Value, BosError> {
  93. let resp = self
  94. .post_json_as_user(
  95. "/api/system/seoh-resource-metadata/resource-tree/node/create@v1",
  96. json!({ "data": data }),
  97. user_token,
  98. )
  99. .await?;
  100. rm_data(&resp, "node/create")
  101. }
  102. /// 改名(`node/update@v1`)。**返回=信封里的 `data`**(内层失败码在本层判掉)。
  103. pub async fn node_rename(&self, data: Value, user_token: &str) -> Result<Value, BosError> {
  104. let resp = self
  105. .post_json_as_user(
  106. "/api/system/seoh-resource-metadata/resource-tree/node/update@v1",
  107. json!({ "data": data }),
  108. user_token,
  109. )
  110. .await?;
  111. rm_data(&resp, "node/update")
  112. }
  113. /// 删节点(`node/delete@v1`,契约=`{hierarchy_key, node_id}`,⛔ `confirm_name`——那是业务侧
  114. /// 二次确认口径,平台不认,多传只会被 `422` 拒掉)。**返回=信封里的 `data`**。
  115. pub async fn node_delete(&self, data: Value, user_token: &str) -> Result<Value, BosError> {
  116. let resp = self
  117. .post_json_as_user(
  118. "/api/system/seoh-resource-metadata/resource-tree/node/delete@v1",
  119. json!({ "data": data }),
  120. user_token,
  121. )
  122. .await?;
  123. rm_data(&resp, "node/delete")
  124. }
  125. /// 取整棵(或某子树)**结构与名称**(`node/get_subtree@v1`)——区域树父子几何的唯一真源。
  126. ///
  127. /// 载荷=`data.root` 单根嵌套;本函数摊平成 [`RmSubtree::nodes`](前序、含 `depth`),
  128. /// 消费方⛔ 再自己解析嵌套。`root` 为 `null`(树空)⇒ `nodes` 为空,由调用方判"树空"还是"取数失败"。
  129. /// `truncated` 由平台下发 ⇒ 调用方⛔ 把半棵树当全量渲染(本模块失败关闭)。
  130. pub async fn node_get_subtree(&self, hierarchy_key: &str, user_token: &str) -> Result<RmSubtree, BosError> {
  131. let resp = self
  132. .post_json_as_user(
  133. "/api/system/seoh-resource-metadata/resource-tree/node/get_subtree@v1",
  134. json!({
  135. "data": {
  136. "hierarchy_key": hierarchy_key,
  137. "max_depth": RM_SUBTREE_MAX_DEPTH,
  138. "max_nodes": RM_SUBTREE_MAX_NODES
  139. }
  140. }),
  141. user_token,
  142. )
  143. .await?;
  144. let payload = rm_data(&resp, "node/get_subtree")?;
  145. let mut out = RmSubtree {
  146. grant_scope: payload
  147. .get("grant_scope")
  148. .and_then(Value::as_str)
  149. .map(|s| s.to_string()),
  150. truncated: payload.get("truncated").and_then(Value::as_bool).unwrap_or(false),
  151. nodes: Vec::new(),
  152. };
  153. walk_subtree(payload.get("root"), 0, None, &mut out.nodes);
  154. Ok(out)
  155. }
  156. /// 批量按 `node_id` 取节点**中文名**(`POST node/batch_get@v1`,转发最终用户 JWT)。
  157. ///
  158. /// 平台侧该口早已随子树能力交付(对外契约见 commit `e95f7fc`,2026-11-08 21:13),并经平台
  159. /// 评估件 §1.6 **书面确认**=长期契约、`end_user` 作用域可用、⛔ 需开通、⛔ 需白名单。
  160. /// ⚠️ 本口存在这一事实,直接推翻了 `handlers/region.rs` 里"平台 RM 只开了 create/rename/delete
  161. /// 三个写接口、⛔ 批量读名口"的旧注释(该注释是本轮误判的直接来源,已一并订正)。
  162. ///
  163. /// 契约口径(逐条对平台契约,⛔ 凭印象改):
  164. /// * 单次 `node_ids` 上限 500,越界=`11103` **整批失败** ⇒ 本函数按 500 分片后合并;
  165. /// * **部分命中是正常形态**:命中进 `nodes`、未命中进 `missing`,⛔ 整批失败;
  166. /// * `missing` 混合「不存在」与「越权」,平台⛔ 区分 ⇒ 见 [`BatchNodeNames::missing`] 纪律;
  167. /// * `fields` 显式点名,⛔ 依赖平台默认字段集(默认含 `attributes`,白付解析成本)。
  168. pub async fn node_batch_get(
  169. &self,
  170. hierarchy_key: &str,
  171. node_ids: &[String],
  172. user_token: &str,
  173. ) -> Result<BatchNodeNames, BosError> {
  174. let mut out = BatchNodeNames::default();
  175. for chunk in node_ids.chunks(BATCH_GET_MAX_IDS) {
  176. let resp = self
  177. .post_json_as_user(
  178. "/api/system/seoh-resource-metadata/resource-tree/node/batch_get@v1",
  179. json!({
  180. "data": {
  181. "hierarchy_key": hierarchy_key,
  182. "node_ids": chunk,
  183. "fields": ["node_id", "node_name", "node_type"],
  184. }
  185. }),
  186. user_token,
  187. )
  188. .await?;
  189. let payload = rm_data(&resp, "node/batch_get")?;
  190. merge_batch_get_page(&payload, &mut out);
  191. }
  192. Ok(out)
  193. }
  194. /// 登记资源(把业务客体挂到树节点下)。**返回=信封里的 `data`**。
  195. ///
  196. /// 内层失败码在本层判掉:网关对业务失败仍回 HTTP 200+信封(同 [`rm_data`]),
  197. /// 只看 HTTP 状态会得到"挂树成功、树上什么都没有"的假成功。
  198. ///
  199. /// ⚠️ 契约要点(`seoh-docs/docs/services/resource-metadata.md` §4.4.5):
  200. /// * 幂等键=**同树 `(id_namespace, resource_id)`**;重放时平台回既有行(附 `idempotent replay`),
  201. /// **父节点不一致即 `13042`**(防静默改挂)——客户建档据此把"重复建档"与"改挂"都读成幂等冲突;
  202. /// * `hierarchy_key`/`parent_node_id`/`id_namespace`/`resource_id`/`name`/`resource_type`/
  203. /// `ref_kind`/`ref_payload` 为必填(`id_namespace` 文档写"可省、由同步层推导",但**直连口必填**:
  204. /// 平台实参结构体无 `Option`,缺字段直接反序列化失败)。
  205. pub async fn registered_resource_create(&self, data: Value, user_token: &str) -> Result<Value, BosError> {
  206. let resp = self
  207. .post_json_as_user(
  208. "/api/system/seoh-resource-metadata/resource-tree/registered_resource/create@v1",
  209. json!({ "data": data }),
  210. user_token,
  211. )
  212. .await?;
  213. let code = resp
  214. .get("code")
  215. .and_then(Value::as_i64)
  216. .unwrap_or(bos_core::error::CODE_OK);
  217. if code != bos_core::error::CODE_OK {
  218. let brief: String = resp
  219. .get("message")
  220. .or_else(|| resp.get("msg"))
  221. .and_then(Value::as_str)
  222. .unwrap_or("")
  223. .chars()
  224. .take(200)
  225. .collect();
  226. tracing::warn!(platform_code = code, platform_message = %brief, "RM registered_resource/create 返回非成功码");
  227. // 13042=同树同 (id_namespace, resource_id) 重复或幂等重放时父节点不一致
  228. // (总则§9.3 映射口径:等价「客户已挂载」幂等冲突)。
  229. return Err(match code {
  230. 13042 => BosError::klt(
  231. bos_core::KltCode::C001,
  232. format!("资源树已存在同一客户主体号的挂载(平台码 13042:{brief})"),
  233. ),
  234. other => BosError::biz(
  235. bos_core::ErrorCode::Downstream,
  236. format!("RM registered_resource/create 返回非成功码: code={other} message={brief}"),
  237. ),
  238. });
  239. }
  240. Ok(resp.get("data").cloned().unwrap_or(Value::Null))
  241. }
  242. /// 摘掉已登记的业务客体(公开 `registered_resource/delete@v1`,平台 2026-11-23 答复接)。
  243. ///
  244. /// 与 create 同构:`post_json_as_user` 原样转发操作人 end_user JWT;⛔ `internal/sync`、
  245. /// ⛔ `node/delete`(结构节点口)。成功/幂等均 `code=10000`,`data.applied_detail`∈
  246. /// `{deleted,noop}`;越权与 noop **分码**(11001/13061 vs 10000)。
  247. ///
  248. /// 权限键=`resource_metadata.registered_resource.delete@v1`(与 create 分权)。
  249. pub async fn registered_resource_delete(
  250. &self,
  251. data: Value,
  252. user_token: &str,
  253. ) -> Result<Value, BosError> {
  254. let resp = self
  255. .post_json_as_user(
  256. "/api/system/seoh-resource-metadata/resource-tree/registered_resource/delete@v1",
  257. json!({ "data": data }),
  258. user_token,
  259. )
  260. .await?;
  261. let data = rm_data(&resp, "registered_resource/delete")?;
  262. let detail = data
  263. .get("applied_detail")
  264. .and_then(Value::as_str)
  265. .unwrap_or("");
  266. if detail != "deleted" && detail != "noop" {
  267. return Err(BosError::biz(
  268. bos_core::ErrorCode::Downstream,
  269. format!(
  270. "RM registered_resource/delete 未返回 deleted/noop:applied_detail={detail}"
  271. ),
  272. ));
  273. }
  274. Ok(data)
  275. }
  276. /// 移动已注册实例(挂到另一节点)。
  277. ///
  278. /// ⚠️ **该口在平台侧不存在**(2026-11-10 取证):网关路由表里 RM 只有
  279. /// `resource-tree/registered_resource/create@v1`/`get_list@v1`/`get_list_by_type@v1` 三条
  280. /// 注册实例路由,RM 契约亦无 `registered_resource/move`(节点移动口 `resource-tree/node/move@v1`
  281. /// 只作用于**节点**,不作用于注册实例)⇒ 本函数调用必得 `HTTP 404 / code 50000`。
  282. /// 路径⛔ 就地"改个名字"蒙过去——改走哪条口(`registered_resource/create` 幂等重挂?还是请平台
  283. /// 补 move)是**口径决策**,登记在缺口清单 B-14c,由业主裁定后再改,本处保持如实透传平台 404。
  284. pub async fn registered_resource_move(&self, data: Value, user_token: &str) -> Result<Value, BosError> {
  285. self.post_json_as_user(
  286. "/api/system/seoh-resource-metadata/registered_resource/move@v1",
  287. json!({ "data": data }),
  288. user_token,
  289. )
  290. .await
  291. }
  292. /// 注册实例清单枚举的**唯一通道**(总则§8.3;CI 结构断言 `A74`,来源=平台侧技术债审计 `P-16`)。
  293. ///
  294. /// ⚠️ 本口 `page_size` 缺省 200、合法区间 `1..=5000`、越界由平台**显式报错**(无静默截断);
  295. /// RM 的旧通用清单口缺省 20 且**无上界校验** ⇒ ⛔ 消费(`A74` ①),需要枚举注册实例只走本函数。
  296. /// ⚠️ 取数完成条件=`next_cursor` 为空串/`Null`(同 `U-05` 纪律);⛔ 以「本页条数 < page_size」判完成(`A74` ②)。
  297. pub async fn registered_resource_list_all(
  298. &self,
  299. hierarchy_key: &str,
  300. resource_type: &str,
  301. page_size: i64,
  302. ) -> Result<Vec<Value>, BosError> {
  303. self.registered_resource_list_all_inner(hierarchy_key, resource_type, page_size, None)
  304. .await
  305. }
  306. /// 与 [`Self::registered_resource_list_all`] 同口同分页纪律,但用**最终用户令牌**(`U-103`)。
  307. ///
  308. /// 用途:建档挂树前的孤儿号预检。服务身份在部分环境对 `get_list_by_type` 回 `11001`,
  309. /// 而操作员票与写树同档,可枚举本项目已挂客户。
  310. pub async fn registered_resource_list_all_as_user(
  311. &self,
  312. hierarchy_key: &str,
  313. resource_type: &str,
  314. page_size: i64,
  315. user_token: &str,
  316. ) -> Result<Vec<Value>, BosError> {
  317. self.registered_resource_list_all_inner(hierarchy_key, resource_type, page_size, Some(user_token))
  318. .await
  319. }
  320. async fn registered_resource_list_all_inner(
  321. &self,
  322. hierarchy_key: &str,
  323. resource_type: &str,
  324. page_size: i64,
  325. user_token: Option<&str>,
  326. ) -> Result<Vec<Value>, BosError> {
  327. let size = page_size.clamp(1, 5_000);
  328. let mut cursor = String::new();
  329. let mut all: Vec<Value> = Vec::new();
  330. let path = "/api/system/seoh-resource-metadata/resource-tree/registered_resource/get_list_by_type@v1";
  331. loop {
  332. let body = json!({
  333. "data": {
  334. "hierarchy_key": hierarchy_key,
  335. "resource_type": resource_type,
  336. },
  337. "cursor": cursor,
  338. "page_size": size,
  339. });
  340. let resp = match user_token {
  341. Some(tok) => self.post_json_as_user(path, body, tok).await?,
  342. None => self.post_json(path, body).await?,
  343. };
  344. if resp.get("code").and_then(Value::as_i64) != Some(bos_core::error::CODE_OK) {
  345. return Err(BosError::biz(
  346. bos_core::ErrorCode::Downstream,
  347. format!("RM 清单口返回非成功码: {resp}"),
  348. ));
  349. }
  350. let (items, next) = parse_list_page(&resp)?;
  351. all.extend(items);
  352. if next.is_empty() {
  353. return Ok(all);
  354. }
  355. if next == cursor {
  356. return Err(BosError::internal("RM 清单口游标未推进,已失败关闭(不得当作取数完成)"));
  357. }
  358. cursor = next;
  359. }
  360. }
  361. }
  362. /// 解析清单口的一页应答:返回(本页 `items`,下一页游标)。
  363. /// 游标为空串或 `Null` =**取数完成**(`A74` ②;同 `U-05` 纪律);游标字段类型异常一律失败关闭。
  364. /// 兼容两种载荷位置:`data.{items,next_cursor}` 与顶层 `{items,pagination.next_cursor}`。
  365. fn parse_list_page(resp: &Value) -> Result<(Vec<Value>, String), BosError> {
  366. let payload = resp.get("data").cloned().unwrap_or_else(|| resp.clone());
  367. let items = payload
  368. .get("items")
  369. .and_then(Value::as_array)
  370. .map(|a| a.clone())
  371. .unwrap_or_default();
  372. let raw = payload
  373. .get("next_cursor")
  374. .or_else(|| payload.get("pagination").and_then(|p| p.get("next_cursor")))
  375. .cloned()
  376. .unwrap_or(Value::Null);
  377. let next = match raw {
  378. Value::Null => String::new(),
  379. Value::String(s) => s,
  380. other => return Err(BosError::internal(format!("RM 清单口 next_cursor 类型异常: {other}"))),
  381. };
  382. Ok((items, next))
  383. }
  384. /// 取 id 类字段的字符串形态:平台雪花 id 在 JSON 里可能是字符串,也可能是数字
  385. /// ⇒ ⛔ `as_str()` 单一形态取值(数字形态会被静默吞成"无 id",整棵树变空)。
  386. fn id_str(v: Option<&Value>) -> Option<String> {
  387. match v? {
  388. Value::String(s) if !s.trim().is_empty() => Some(s.trim().to_string()),
  389. Value::Number(n) => Some(n.to_string()),
  390. _ => None,
  391. }
  392. }
  393. /// 深度优先摊平 `data.root` 嵌套(⛔ 依赖 `children` 的排序,父子关系只取 `parent_id`/递归位置)。
  394. fn walk_subtree(node: Option<&Value>, depth: usize, parent_id: Option<String>, out: &mut Vec<RmNode>) {
  395. let Some(n) = node.filter(|v| v.is_object()) else { return };
  396. let Some(id) = id_str(n.get("id")).or_else(|| id_str(n.get("node_id"))) else { return };
  397. // 子节点没带 `parent_id` 时(实测:嵌套里只有根节点带),用递归位置补齐。
  398. let pid = id_str(n.get("parent_id")).or_else(|| id_str(n.get("parent_node_id"))).or_else(|| parent_id.clone());
  399. let name = n
  400. .get("name")
  401. .or_else(|| n.get("node_name"))
  402. .and_then(Value::as_str)
  403. .map(|s| s.trim().to_string())
  404. .filter(|s| !s.is_empty());
  405. out.push(RmNode { id: id.clone(), name, parent_id: pid, depth });
  406. if let Some(children) = n.get("children").and_then(Value::as_array) {
  407. for c in children {
  408. walk_subtree(Some(c), depth + 1, Some(id.clone()), out);
  409. }
  410. }
  411. }
  412. /// 合并 `node/batch_get@v1` **一片**应答到 `out`(分片时逐片调用,故 `missing` 累加、`grant_scope` 只取首个)。
  413. ///
  414. /// 口径(对平台契约,⛔ 凭印象改):
  415. /// * **部分命中是正常形态** ⇒ 命中进 `names`、未命中进 `missing`,两者互不抵消;
  416. /// * `nodes[]` 里 `node_id`/`node_name` 之外的字段只在 `fields` 点名时出现 ⇒ 缺字段即跳过该条,
  417. /// ⛔ 用 `node_id` 顶替名字(那等于编名);
  418. /// * `grant_scope` 由平台按调用令牌作用域下发,本函数只透传、⛔ 据此放宽可见范围。
  419. fn merge_batch_get_page(payload: &Value, out: &mut BatchNodeNames) {
  420. if out.grant_scope.is_none() {
  421. out.grant_scope = payload
  422. .get("grant_scope")
  423. .and_then(Value::as_str)
  424. .map(|s| s.to_string());
  425. }
  426. if let Some(items) = payload.get("nodes").and_then(Value::as_array) {
  427. for it in items {
  428. if let (Some(id), Some(name)) = (
  429. it.get("node_id").and_then(Value::as_str),
  430. it.get("node_name").and_then(Value::as_str),
  431. ) {
  432. out.names.insert(id.to_string(), name.to_string());
  433. }
  434. }
  435. }
  436. if let Some(m) = payload.get("missing").and_then(Value::as_array) {
  437. out.missing.extend(
  438. m.iter()
  439. .filter_map(Value::as_str)
  440. .map(|s| s.to_string()),
  441. );
  442. }
  443. }
  444. #[cfg(test)]
  445. mod tests {
  446. use super::*;
  447. #[test]
  448. fn empty_cursor_means_done() {
  449. let resp = json!({ "code": 10000, "data": { "items": [{ "id": 1 }], "next_cursor": "" } });
  450. let (items, next) = parse_list_page(&resp).unwrap();
  451. assert_eq!(items.len(), 1);
  452. assert!(next.is_empty(), "空串游标=取数完成");
  453. }
  454. #[test]
  455. fn null_cursor_means_done() {
  456. let resp = json!({ "code": 10000, "data": { "items": [], "next_cursor": null } });
  457. let (_, next) = parse_list_page(&resp).unwrap();
  458. assert!(next.is_empty());
  459. }
  460. #[test]
  461. fn non_empty_cursor_continues_pagination() {
  462. let resp = json!({ "code": 10000, "items": [{ "id": 1 }], "pagination": { "next_cursor": "c2" } });
  463. let (items, next) = parse_list_page(&resp).unwrap();
  464. assert_eq!(items.len(), 1);
  465. assert_eq!(next, "c2");
  466. }
  467. /// `A74` ② 的反面:⛔ 以「本页条数 < page_size」判完成——应答不满页但游标非空时必须继续翻页。
  468. #[test]
  469. fn short_page_with_cursor_must_not_be_treated_as_done() {
  470. let resp = json!({ "code": 10000, "data": { "items": [{ "id": 1 }], "next_cursor": "c2" } });
  471. let (items, next) = parse_list_page(&resp).unwrap();
  472. assert!(items.len() < 200, "本页不满页");
  473. assert!(!next.is_empty(), "不满页不等于取数完成");
  474. }
  475. #[test]
  476. fn malformed_cursor_fails_closed() {
  477. let resp = json!({ "code": 10000, "data": { "items": [], "next_cursor": 3 } });
  478. assert!(parse_list_page(&resp).is_err());
  479. }
  480. /// 平台契约:`missing` 非空是**正常形态**(部分命中),⛔ 整批作废——已命中的名字必须保留。
  481. #[test]
  482. fn partial_hit_keeps_names_and_records_missing() {
  483. let page = json!({
  484. "grant_scope": "end_user:376985101906509824",
  485. "nodes": [{ "node_id": "1793943094956229", "node_name": "上海市" }],
  486. "missing": ["shp"]
  487. });
  488. let mut out = BatchNodeNames::default();
  489. merge_batch_get_page(&page, &mut out);
  490. assert_eq!(out.names.get("1793943094956229").map(String::as_str), Some("上海市"));
  491. assert_eq!(out.missing, vec!["shp".to_string()]);
  492. assert_eq!(out.grant_scope.as_deref(), Some("end_user:376985101906509824"));
  493. }
  494. /// ⛔ 编名:条目缺 `node_name`(未按 `fields` 下发/平台未给)时跳过该条,
  495. /// 既不入 `names`、也⛔ 拿 `node_id` 当名字顶上。
  496. #[test]
  497. fn node_without_name_is_not_treated_as_named() {
  498. let page = json!({ "nodes": [{ "node_id": "1793943094956229", "node_type": "region" }] });
  499. let mut out = BatchNodeNames::default();
  500. merge_batch_get_page(&page, &mut out);
  501. assert!(out.names.is_empty(), "缺 node_name ⇒ 名称未下发");
  502. assert!(out.missing.is_empty(), "出现在 nodes[] 里就不是 missing");
  503. assert!(out.grant_scope.is_none());
  504. }
  505. /// 分片合并:`missing` 逐片累加,`grant_scope` 以首片为准(同一次调用作用域不变)。
  506. #[test]
  507. fn chunks_accumulate_missing_and_keep_first_grant_scope() {
  508. let mut out = BatchNodeNames::default();
  509. merge_batch_get_page(
  510. &json!({ "grant_scope": "end_user:A", "nodes": [], "missing": ["a"] }),
  511. &mut out,
  512. );
  513. merge_batch_get_page(
  514. &json!({ "grant_scope": "end_user:B", "nodes": [{ "node_id": "2", "node_name": "乙区" }], "missing": ["b"] }),
  515. &mut out,
  516. );
  517. assert_eq!(out.missing, vec!["a".to_string(), "b".to_string()]);
  518. assert_eq!(out.grant_scope.as_deref(), Some("end_user:A"));
  519. assert_eq!(out.names.len(), 1);
  520. }
  521. }