From 69cb6b84c3f1ba5a83693e138fac512c5e665e80 Mon Sep 17 00:00:00 2001 From: admin Date: Sun, 15 Nov 2026 13:06:22 +0800 Subject: [PATCH] =?UTF-8?q?feat(g16):=20=E6=89=A7=E8=A1=8C=E5=AE=8C?= =?UTF-8?q?=E6=88=90=E5=90=8E=E8=87=AA=E6=8A=A5=20ExecFact=20+=20=E8=84=B1?= =?UTF-8?q?=E6=95=8F=20ExecLog=EF=BC=88=E5=BC=80=E5=85=B3=E9=BB=98?= =?UTF-8?q?=E8=AE=A4=E5=85=B3=E9=97=AD=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/tdc/client/tds.rs | 31 +++ src/tdc/engine/config.rs | 6 + src/tdc/engine/mod.rs | 76 +++++- src/tdc/engine/report.rs | 498 +++++++++++++++++++++++++++++++++++++++ src/tdc/engine/state.rs | 4 + 5 files changed, 610 insertions(+), 5 deletions(-) create mode 100644 src/tdc/engine/report.rs diff --git a/src/tdc/client/tds.rs b/src/tdc/client/tds.rs index 49a7192..cc4641d 100644 --- a/src/tdc/client/tds.rs +++ b/src/tdc/client/tds.rs @@ -337,6 +337,37 @@ impl TdsClient { unwrap_data(env, "批次下单失败") } + /// 连接器上报**本端执行事实**(G15 GAP②,2026-11-15)。 + /// + /// 平台端点 `POST /api/ssw/tds/DeliveryTask/Internal/ExecFact`(`requireInternalOnly`), + /// 裁决器 `DeliveryTaskAuthorityService.upsertExecFact` 做参与方校验 / 幂等 / + /// 终态单调 / 非空覆盖。🔴 这是**既有**端点,本轮只把它接进真机执行链路,不改平台契约。 + pub async fn report_exec_fact(&self, body: &Value) -> Result { + let env = self + .send( + Method::POST, + "/api/ssw/tds/DeliveryTask/Internal/ExecFact", + Some(body), + ) + .await?; + unwrap_data(env, "执行事实上报失败") + } + + /// 连接器上报**脱敏后的本端执行日志正文**(G6,2026-11-15 平台新增端点)。 + /// + /// 🔴 与 `report_exec_fact` 分开写:执行事实表只存观测元数据(实体既定的「写点唯一」), + /// 原文落独立表并由登录态只读端点按 OPERATOR / PARTY 判据放出,不放宽跨机构可见性。 + pub async fn report_exec_log(&self, body: &Value) -> Result { + let env = self + .send( + Method::POST, + "/api/ssw/tds/DeliveryTask/Internal/ExecLog", + Some(body), + ) + .await?; + unwrap_data(env, "执行日志上报失败") + } + // ---------------- 整包型(上游原样返回 `{code,msg,data}`) ---------------- /// 本方账单列表(上游 `listBillingForConnector`):`POST /api/ssw/tds/BillingLedger/Internal/List`。 diff --git a/src/tdc/engine/config.rs b/src/tdc/engine/config.rs index b96eec1..0f4629f 100644 --- a/src/tdc/engine/config.rs +++ b/src/tdc/engine/config.rs @@ -19,6 +19,8 @@ use std::path::{Path, PathBuf}; use serde_json::Value; +use super::report::ReportConfig; + pub const ENV_ARTIFACT_DIR: &str = "TDC_EXEC_ARTIFACT_DIR"; pub const ENV_CONTROL_PLANE_URL: &str = "TDC_EXEC_CONTROL_PLANE_URL"; pub const ENV_CONTROL_PLANE_TOKEN: &str = "TDC_EXEC_CONTROL_PLANE_TOKEN"; @@ -111,6 +113,9 @@ pub struct ExecConfig { /// `true` ⇒ 只落**执行计划**(含完整命令 / 控制面调用),不 spawn、不 POST /desired。 /// 状态标 `Planned`,绝不写成 `Succeeded`。 pub dry_run: bool, + /// 执行完成后的**连接器自报**配置(G15 GAP② + G6)。 + /// 🔴 默认关闭(fail-closed / 可秒回滚);由部署侧 `TDC_EXEC_AUTO_REPORT=1` 显式开启。 + pub report: ReportConfig, } impl ExecConfig { @@ -196,6 +201,7 @@ impl ExecConfig { .map(|_| text) }), dry_run: flag(ENV_DRY_RUN), + report: ReportConfig::from_raw(env), // state_dir 由 path() 提前算好(不能在 struct 字面量里引用自身) state_dir, } diff --git a/src/tdc/engine/mod.rs b/src/tdc/engine/mod.rs index 76143d3..bea826c 100644 --- a/src/tdc/engine/mod.rs +++ b/src/tdc/engine/mod.rs @@ -25,14 +25,17 @@ pub mod config; pub mod digest; pub mod process; +pub mod report; pub mod state; use std::collections::BTreeMap; use std::path::Path; +use std::time::Duration; use serde_json::{json, Value}; use crate::tdc::client::mpc_control_plane::{MpcControlPlaneClient, NOOP_MESSAGE}; +use crate::tdc::client::tds::TdsClient; pub use config::ExecConfig; pub use state::{ExecPhase, ExecRecord, ExecStore}; @@ -41,6 +44,7 @@ use digest::{base64_encode, dir_digest, short_key}; use process::{ ensure_single_instance, spawn_detached, write_secret_file, InstanceGuard, SpawnRequest, }; +use report::{auto_report, ReportInput}; /// 允许的算子白名单。**不在表内一律拒**(不回落 `psi`:静默换算子会让「审的 ≠ 跑的」)。 const MPC_OPERATORS: [&str; 3] = ["psi", "lr", "lr-vertical"]; @@ -133,6 +137,8 @@ pub struct ExecRuntime { pub config: ExecConfig, pub store: ExecStore, pub control_plane: MpcControlPlaneClient, + /// 出向 TDS internal 通道(自报执行事实 / 脱敏日志用,与入向闸门令牌方向相反)。 + pub tds: TdsClient, } impl ExecRuntime { @@ -144,10 +150,18 @@ impl ExecRuntime { config.control_plane_url.clone(), config.control_plane_token.clone(), ); + // 与 TdcState 里那份同源配置;这里读超时放宽到 30s(日志正文可能上百 KiB)。 + let tds = TdsClient::with_timeouts( + std::env::var("SSW_TDS_BASE_URL").ok(), + std::env::var("SSW_TDS_INTERNAL_TOKEN").unwrap_or_default(), + Duration::from_secs(5), + Duration::from_secs(30), + ); Self { config, store, control_plane, + tds, } } @@ -344,7 +358,9 @@ impl ExecRuntime { } // ---- ⑤ mpc 算子点火 ---- - match self.ensure_mpc(&et_tag, &self_site, &parties, &payload) { + // 🔴 用 exec_id 作 mpc 日志 tag ⇒ 每次执行独立文件,不会把上一轮日志 append 进 + // 本轮摘要(resultHash 必须与设备侧回收到的整文件逐字对应)。 + match self.ensure_mpc(&exec_id, &self_site, &parties, &payload) { Ok(detail) => self.ok_step(&exec_id, ExecPhase::Mpc, "MPC 点火", detail), Err(reason) => { self.fail(&exec_id, ExecPhase::Mpc, "MPC 点火", reason); @@ -367,9 +383,55 @@ impl ExecRuntime { "收口", "各阶段已受理并拉起;MPC 结果需查算子日志与载荷通路证据", ); + // ---- ⑦ 连接器自报(G15 GAP② + G6)---- + // 等本端 mpc 子进程真正退出、日志落定,再由连接器自己回传执行事实 + + // 脱敏日志正文。不再是验收脚本代报。结果写进 ExecRecord.report, + // `Exec/Status` 可查 ⇒ 验收能断言「是设备自报的」。 + let report = self.auto_report_phase(&exec_id, &payload, &self_site).await; + self.store.mutate(&exec_id, |r| r.report = Some(report)); } } + /// 组装自报输入并调用 [`report::auto_report`](失败也只落状态,不影响已 SUCCEEDED 的执行)。 + async fn auto_report_phase( + &self, + exec_id: &str, + payload: &Value, + self_site: &str, + ) -> report::ExecReport { + let local_task_id = self + .store + .get(exec_id) + .map(|r| r.task_id) + .unwrap_or_default(); + // 🔴 平台 Exec/Start 载荷不带 connectorId(只在平台回执里)⇒ 本端 id 从 + // partyMap[selfParty] 解析;解析不到 ⇒ 空串 ⇒ auto_report fail-closed 拒报。 + let connector_id = + report::self_connector_id(payload, self_site, &self.config.site_of_party); + let version_no = payload + .get("versionNo") + .and_then(Value::as_i64) + .unwrap_or(1); + // `podNode` 取本端 site 端点的 host,与设备侧日志回收脚本的机器口径一致。 + let pod_node = self + .config + .endpoint_of_site + .get(self_site) + .and_then(|ep| ep.rsplit_once(':').map(|(h, _)| h.to_string())) + .unwrap_or_else(|| self_site.to_string()); + let tag = format!("mpc-{}", exec_id); + let input = ReportInput { + exec_id: exec_id.to_string(), + local_task_id, + connector_id, + version_no, + pod_node, + mpc_log: self.config.state_dir.join(format!("{}.log", tag)), + mpc_pid: self.config.state_dir.join(format!("{}.pid", tag)), + }; + auto_report(&self.config.report, &self.tds, &input).await + } + // ================================================================ // 各阶段实现 // ================================================================ @@ -814,7 +876,7 @@ impl ExecRuntime { } } - fn ensure_mpc(&self, tag: &str, self_site: &str, parties: &[String], payload: &Value) -> Result { + fn ensure_mpc(&self, exec_id: &str, self_site: &str, parties: &[String], payload: &Value) -> Result { let c = &self.config; if c.endpoint_of_site.is_empty() { return Err( @@ -868,7 +930,8 @@ impl ExecRuntime { .map(|s| s.trim().to_string()) .unwrap_or_default() }); - let mpc_tag = format!("mpc-{}", tag.trim_start_matches("et-")); + // 每次执行独立日志文件(exec_id 是 16 位 hex 短哈希,路径安全)。 + let mpc_tag = format!("mpc-{}", exec_id); let req = SpawnRequest::new(&c.mpc_bin, plan.args.clone(), &c.state_dir, &mpc_tag) .with_env("MPC_PSK", &psk); let pid = spawn_detached(&req)?; @@ -935,6 +998,7 @@ mod tests { config: c, store: ExecStore::new(&dir), control_plane: MpcControlPlaneClient::new(None, String::new()), + tds: TdsClient::new(None, String::new()), } } @@ -970,8 +1034,10 @@ mod tests { )]), "peers", ); - let (_args, peers) = r.mpc_args(&["p1".into(), "p2".into()], "p1"); - assert_eq!(peers, "alice=10.12.0.1:9449,carol=10.12.0.2:9449"); + // 🔴 原测试调的 `mpc_args` 早已被 `mpc_plan` 取代(测试编译不过)⇒ 改用真实计划推导 + let params = MpcParams::parse(&json!({ "operator": "psi" }), "test").unwrap(); + let plan = r.mpc_plan(¶ms, &["p1".into(), "p2".into()], "p1"); + assert_eq!(plan.peers, "alice=10.12.0.1:9449,carol=10.12.0.2:9449"); } #[test] diff --git a/src/tdc/engine/report.rs b/src/tdc/engine/report.rs new file mode 100644 index 0000000..9ee6f79 --- /dev/null +++ b/src/tdc/engine/report.rs @@ -0,0 +1,498 @@ +//! 执行完成后由**连接器自报**(G15 GAP② + G6 脱敏原文落平台),2026-11-15。 +//! +//! ## 为什么必须有这一层 +//! +//! 平台早有 `POST /DeliveryTask/Internal/ExecFact`(裁决器含参与方校验 / 幂等 / +//! 终态单调 / 非空覆盖),但真机执行链路**从未调用它** —— 之前是验收脚本用三机日志 +//! 观测结果**代报**。那是「人替设备说话」,不是设备自证。本模块把回传接进 +//! [`super::ExecRuntime::run`] 的收口阶段:等本端 `mpc` 子进程真正退出、日志落定, +//! 再由连接器自己用既有的 internal 出向通道上报。 +//! +//! ## 两条回传、同一个真相源 +//! +//! | 回传 | 端点 | 载荷要点 | +//! |---|---|---| +//! | 执行事实 | `POST /Internal/ExecFact`(**既有**) | `resultHash` = 本端**完整**原始日志 SHA-256 | +//! | 执行日志 | `POST /Internal/ExecLog`(本轮平台新增) | `logText` = **脱敏 + 限量**后的日志正文;`logSha256` = 该正文 SHA-256;`originalSha256` = 完整日志 SHA-256 | +//! +//! 🔴 `resultHash` 用**未脱敏的完整日志**,这样平台既有的「resultHash 可回溯到设备日志」 +//! 断言继续成立;原文端点单独持有脱敏正文,两者通过 `originalSha256` 关联。 +//! +//! ## 跨机构共享边界(G6 的显式修订) +//! +//! 实体注释原定「平台只汇总执行元数据,不含执行日志原文与任何数据内容」。本轮按 +//! 规格 §7-G6 给出的路径「连接器新增脱敏 + 限量回传端点、平台落附件」收口, +//! 但**不放宽可见性**:原文落在独立的 `tds_delivery_task_exec_log` 表,只对本任务 +//! OPERATOR / PARTY 登录态可见,跨任务、非参与方、内部令牌一律取不到。 +//! +//! 脱敏规则:`mpc --report json` 的 `{"kind":"table","rows":[[id],…]}` 结果行含**交集数据**, +//! 只把 `rows` 的值换成条数占位,其余每一行逐字保留(阶段/耗时/错误都可看)。 +//! 限量:`TDC_EXEC_REPORT_MAX_BYTES`(默认 256 KiB),超限截尾并如实标 `truncated=true`。 +//! +//! ## fail-closed +//! +//! - `TDC_EXEC_AUTO_REPORT` 未显式开启 ⇒ **不自报**(`SKIPPED`),可秒回滚; +//! - 缺 `connectorId` / 缺平台级 taskId / 日志文件不存在 ⇒ `FAILED`,不发半截请求; +//! - 等子进程超时 ⇒ 仍回传已落定的日志,但 `phase=FAILED` 且 `logComplete=false`, +//! **不会**伪装成完整成功; +//! - 任一 POST 失败 ⇒ `FAILED` + 真因写进执行状态,不吞错。 +//! +//! 🔴 每次执行的 mpc 日志用**唯一文件名**(见 `ensure_mpc` 用 `exec_id` 作 tag) +//! ⇒ 不同任务的日志不会 append 混淆,`resultHash` 与设备侧回收到的整文件逐字对应。 + +use std::collections::BTreeMap; +use std::path::{Path, PathBuf}; +use std::time::Duration; + +use serde::{Deserialize, Serialize}; +use serde_json::{json, Value}; + +use crate::tdc::client::tds::TdsClient; + +use super::digest::sha256_hex; +use super::process::live_pid; + +pub const ENV_AUTO_REPORT: &str = "TDC_EXEC_AUTO_REPORT"; +pub const ENV_SELF_ROLE: &str = "TDC_EXEC_SELF_ROLE"; +pub const ENV_SELF_ORG_NAME: &str = "TDC_EXEC_SELF_ORG_NAME"; +pub const ENV_REPORT_WAIT_SECONDS: &str = "TDC_EXEC_REPORT_WAIT_SECONDS"; +pub const ENV_REPORT_MAX_BYTES: &str = "TDC_EXEC_REPORT_MAX_BYTES"; + +pub const DEFAULT_WAIT_SECONDS: u64 = 600; +pub const DEFAULT_MAX_BYTES: usize = 256 * 1024; + +/// 自报配置(全部来自部署侧 env,纯函数装配 ⇒ 可单测)。 +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReportConfig { + pub enabled: bool, + pub self_role: String, + pub self_org_name: String, + pub wait_seconds: u64, + pub max_log_bytes: usize, +} + +impl ReportConfig { + pub fn from_raw(env: &BTreeMap) -> Self { + let get = |k: &str| -> Option { + env.get(k) + .map(|v| v.trim().to_string()) + .filter(|v| !v.is_empty()) + }; + let flag = |k: &str| -> bool { + matches!(get(k).as_deref(), Some("1") | Some("true") | Some("TRUE") | Some("yes")) + }; + Self { + enabled: flag(ENV_AUTO_REPORT), + self_role: get(ENV_SELF_ROLE).unwrap_or_else(|| "PROVIDER".to_string()), + self_org_name: get(ENV_SELF_ORG_NAME).unwrap_or_default(), + wait_seconds: get(ENV_REPORT_WAIT_SECONDS) + .and_then(|v| v.parse::().ok()) + .filter(|n| *n > 0) + .unwrap_or(DEFAULT_WAIT_SECONDS), + max_log_bytes: get(ENV_REPORT_MAX_BYTES) + .and_then(|v| v.parse::().ok()) + .filter(|n| *n > 0) + .unwrap_or(DEFAULT_MAX_BYTES), + } + } +} + +/// 写进 `ExecRecord.report` 的自报结果(`Exec/Status` 可查,验收据此断言「是设备自己报的」)。 +#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)] +#[serde(rename_all = "camelCase")] +pub struct ExecReport { + /// `REPORTED` / `FAILED` / `SKIPPED` + pub phase: String, + /// 是否由连接器自动上报(区别于验收脚本代报) + pub auto: bool, + pub platform_task_id: String, + pub connector_id: String, + pub log_path: String, + /// 本端**完整**原始日志 SHA-256(= ExecFact.resultHash) + pub original_sha256: String, + /// 落平台的**脱敏正文** SHA-256 + pub log_sha256: String, + pub log_bytes: usize, + pub truncated: bool, + pub log_complete: bool, + pub redacted_result_lines: usize, + pub exec_fact_ok: bool, + pub exec_log_ok: bool, + pub detail: String, + pub at: String, +} + +/// 一次自报所需的全部输入(由 `run()` 从 payload / 配置 / 状态组装)。 +#[derive(Debug, Clone)] +pub struct ReportInput { + pub exec_id: String, + /// 平台逐方下发的本地任务号(`G15T…-LA`) + pub local_task_id: String, + /// 下发载荷里的 `connectorId`(本端身份,平台参与方行的外键) + pub connector_id: String, + /// 下发载荷里的 `versionNo` + pub version_no: i64, + /// 本端 site 的 host(写 `podNode`,与设备侧回收脚本口径一致) + pub pod_node: String, + pub mpc_log: PathBuf, + pub mpc_pid: PathBuf, +} + +/// `G15T094019-LA` → `G15T094019`。 +/// +/// 平台 `AlgorithmExecDispatchServiceImpl.dispatchOne` 用的是参与方行的 `f_local_task_id`, +/// 部署侧按「平台任务号 + `-L<方标识>`」拼。🔴 只剥**尾部**的 `-L` + 大写字母后缀; +/// 任务号本身含短横线时不能误伤(所以要求后缀全大写且以 L 开头)。 +pub fn platform_task_id(local: &str) -> String { + if let Some((head, suffix)) = local.rsplit_once('-') { + if !head.is_empty() + && suffix.len() >= 2 + && suffix.starts_with('L') + && suffix[1..].chars().all(|c| c.is_ascii_uppercase()) + { + return head.to_string(); + } + } + local.to_string() +} + +/// 从平台 `Exec/Start` 载荷解析**本端**参与方连接器 id。 +/// +/// 🔴 2026-11-15 真机实测踩坑:平台 `AlgorithmExecDispatchServiceImpl.dispatchOne` +/// 下发的 payload **不带 `connectorId`**(该字段只出现在平台自己的回执 `one` 里), +/// 直接从 `payload["connectorId"]` 取恒为空 ⇒ 三机自报全部 fail-closed 拒报。 +/// 权威映射是随载荷下发的 `partyMap`(`pN` → `f_connector_id`),`selfParty` 是本端 `pN`。 +/// +/// 优先级:显式 `connectorId`(未来平台若带上则优先)→ `partyMap[selfParty]` +/// → `partyMap[本端 site 在 TDC_EXEC_PARTY_SITE_MAP 里反查到的 party]`。 +/// **都取不到就返回空串**:调用方 `auto_report` 拒报,绝不猜、绝不冒充他方身份。 +pub fn self_connector_id( + payload: &Value, + self_site: &str, + site_of_party: &BTreeMap, +) -> String { + if let Some(s) = payload + .get("connectorId") + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + { + return s.to_string(); + } + let map = payload.get("partyMap").and_then(Value::as_object); + let local_party = site_of_party + .iter() + .find(|(_, site)| site.as_str() == self_site) + .map(|(party, _)| party.as_str()); + let candidates = [ + payload.get("selfParty").and_then(Value::as_str), + local_party, + ]; + for key in candidates.into_iter().flatten() { + if let Some(cid) = map + .and_then(|m| m.get(key)) + .and_then(Value::as_str) + .map(str::trim) + .filter(|s| !s.is_empty()) + { + return cid.to_string(); + } + } + String::new() +} + +/// 日志脱敏 + 限量(纯函数,可单测;平台侧不再做二次处理)。 +/// +/// 保持**逐行**结构:只有 `{"kind":"table", ... "rows":[...]}` 这类结果行被改写, +/// 其它行原样保留。输出末尾与输入一致(不擅自补/删换行)。 +pub fn redact_log(raw: &[u8], max_bytes: usize) -> (String, bool, usize, bool) { + let text = String::from_utf8_lossy(raw); + let trailing_newline = text.ends_with('\n'); + let mut lines: Vec = Vec::new(); + let mut redacted = 0usize; + for line in text.split('\n') { + let trimmed = line.trim(); + if trimmed.starts_with('{') && trimmed.contains("\"kind\"") && trimmed.contains("table") { + if let Ok(mut v) = serde_json::from_str::(trimmed) { + if let Some(rows) = v.get("rows").and_then(Value::as_array) { + let n = rows.len(); + v["rows"] = json!(format!("", n)); + lines.push(v.to_string()); + redacted += 1; + continue; + } + } + // 解析不出结果行 ⇒ 保守整行占位,绝不放过可能含数据的原始字节 + lines.push("".to_string()); + redacted += 1; + continue; + } + lines.push(line.to_string()); + } + let mut out = lines.join("\n"); + if trailing_newline { + out.push('\n'); + } + let mut truncated = false; + if out.len() > max_bytes { + // 按字节边界截(可能落在 UTF-8 中间)⇒ 回退到最后一个合法字符边界 + let mut end = max_bytes.min(out.len()); + while end > 0 && !out.is_char_boundary(end) { + end -= 1; + } + out.truncate(end); + out.push_str("\n\n"); + truncated = true; + } + (out, trailing_newline, redacted, truncated) +} + +/// 从 `/proc//stat` 文本判断进程是否已退出。 +/// 格式 `pid (comm) S ppid ...`;comm 可能含空格/括号 ⇒ 从**最后一个** `)` 后取状态。 +/// `Z`(僵尸)/ `X`(dead)/ 格式不可解析,一律视为已退出。 +fn stat_shows_exited(stat: &str) -> bool { + // and_then 把 Option> 摊平成 Option;解析不出状态 + // (没有 ')' / 空串)一律 fail-closed 视为「已退出」,避免永远等下去。 + match stat + .rsplit_once(')') + .and_then(|(_, rest)| rest.trim().chars().next()) + { + Some('Z') | Some('X') | None => true, + Some(_) => false, + } +} + +/// mpc 子进程是否已退出(⇒ 日志已写完,可以算摘要)。 +/// +/// 🔴 2026-11-15 真机实测踩坑:`process::live_pid` 走 `kill -0`,子进程退出后 +/// 父进程未 `wait` 会留下**僵尸**(`state=Z`),`kill -0` 仍返回成功 ⇒ +/// `wait_for_mpc` 一直等到 600s 超时,`report` 迟迟写不进 `Exec/Status`。 +/// 故自报侧额外读 `/proc//stat` 过滤僵尸;不动 ET/Ray 的单实例判据。 +fn mpc_exited(pid_path: &Path) -> bool { + let pid = match live_pid(pid_path) { + None => return true, // pid 文件不存在 / 进程真的没了 + Some(p) => p, + }; + match std::fs::read_to_string(format!("/proc/{pid}/stat")) { + Ok(s) => stat_shows_exited(&s), + Err(_) => true, // /proc 读不到 ⇒ 视为已退出 + } +} + +/// 等 `mpc` 子进程退出(日志写完)。返回 `true` = 已正常退出;`false` = 超时。 +async fn wait_for_mpc(pid_path: &Path, wait_seconds: u64) -> bool { + let deadline = wait_seconds; + let mut elapsed = 0u64; + loop { + if mpc_exited(pid_path) { + return true; + } + if elapsed >= deadline { + return false; + } + tokio::time::sleep(Duration::from_secs(2)).await; + elapsed += 2; + } +} + +/// 执行一次完整自报。**不抛异常**:所有失败都变成 `ExecReport { phase: FAILED, … }`。 +pub async fn auto_report( + cfg: &ReportConfig, + tds: &TdsClient, + input: &ReportInput, +) -> ExecReport { + let mut r = ExecReport { + phase: "FAILED".to_string(), + auto: true, + platform_task_id: platform_task_id(&input.local_task_id), + connector_id: input.connector_id.clone(), + log_path: input.mpc_log.display().to_string(), + original_sha256: String::new(), + log_sha256: String::new(), + log_bytes: 0, + truncated: false, + log_complete: false, + redacted_result_lines: 0, + exec_fact_ok: false, + exec_log_ok: false, + detail: String::new(), + at: chrono::Utc::now().to_rfc3339(), + }; + if !cfg.enabled { + r.phase = "SKIPPED".into(); + r.detail = format!("{} 未开启 ⇒ 连接器不自报(可由验收链路代报,fail-closed)", ENV_AUTO_REPORT); + return r; + } + if r.connector_id.is_empty() { + r.detail = "下发载荷缺 connectorId ⇒ 无法定位本端参与方行,拒绝盲报".into(); + return r; + } + if tds.is_noop() { + r.detail = "未配置 SSW_TDS_BASE_URL ⇒ 出向通道 NOOP,拒绝伪装已上报".into(); + return r; + } + + r.log_complete = wait_for_mpc(&input.mpc_pid, cfg.wait_seconds).await; + let raw = match std::fs::read(&input.mpc_log) { + Ok(b) => b, + Err(e) => { + r.detail = format!("读本端 mpc 日志失败 {}: {}", input.mpc_log.display(), e); + return r; + } + }; + if raw.is_empty() { + r.detail = "本端 mpc 日志为空 ⇒ 无执行事实可报(不编造)".into(); + return r; + } + r.original_sha256 = sha256_hex(&raw); + let (log_text, _trailing, redacted, truncated) = redact_log(&raw, cfg.max_log_bytes); + r.log_sha256 = sha256_hex(log_text.as_bytes()); + r.log_bytes = log_text.len(); + r.redacted_result_lines = redacted; + r.truncated = truncated; + + let pod_phase = if r.log_complete { "SUCCEEDED" } else { "FAILED" }; + let fact = json!({ + "tdsTaskId": r.platform_task_id, + "connectorId": r.connector_id, + "role": cfg.self_role, + "orgName": cfg.self_org_name, + "podName": format!("mpc-local-{}", input.pod_node), + "podPhase": pod_phase, + "podNode": input.pod_node, + "versionNo": input.version_no, + "resultHash": r.original_sha256, + }); + let log_body = json!({ + "tdsTaskId": r.platform_task_id, + "connectorId": r.connector_id, + "role": cfg.self_role, + "localTaskId": input.local_task_id, + "execId": input.exec_id, + "logText": log_text, + "logSha256": r.log_sha256, + "originalSha256": r.original_sha256, + "byteSize": r.log_bytes, + "truncated": r.truncated, + "logComplete": r.log_complete, + "redactedResultLines": r.redacted_result_lines, + }); + + let mut errs: Vec = Vec::new(); + match tds.report_exec_fact(&fact).await { + Ok(_) => r.exec_fact_ok = true, + Err(e) => errs.push(format!("ExecFact: {}", e)), + } + match tds.report_exec_log(&log_body).await { + Ok(_) => r.exec_log_ok = true, + Err(e) => errs.push(format!("ExecLog: {}", e)), + } + + if errs.is_empty() && r.log_complete { + r.phase = "REPORTED".into(); + r.detail = format!( + "连接器自报完成:ExecFact(resultHash={}…) + ExecLog({} 字节 / 脱敏 {} 行);mpc 子进程已正常退出", + &r.original_sha256[..12], r.log_bytes, r.redacted_result_lines + ); + } else { + r.phase = "FAILED".into(); + let mut why = errs.join(";"); + if !r.log_complete { + let extra = format!("等 mpc 退出超时({}s)⇒ 日志可能不完整,已如实标 FAILED", cfg.wait_seconds); + if why.is_empty() { why = extra; } else { why = format!("{};{}", extra, why); } + } + r.detail = why; + } + r.at = chrono::Utc::now().to_rfc3339(); + r +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn auto_report_is_opt_in() { + let c = ReportConfig::from_raw(&BTreeMap::new()); + assert!(!c.enabled, "默认必须关闭,保证可回滚"); + assert_eq!(c.wait_seconds, DEFAULT_WAIT_SECONDS); + assert_eq!(c.max_log_bytes, DEFAULT_MAX_BYTES); + } + + #[test] + fn platform_task_id_strips_only_the_party_suffix() { + assert_eq!(platform_task_id("G15T094019-LA"), "G15T094019"); + assert_eq!(platform_task_id("G15T094019-LB"), "G15T094019"); + assert_eq!(platform_task_id("G15T-2026-11-15-LC"), "G15T-2026-11-15"); + assert_eq!(platform_task_id("PLAIN-TASK"), "PLAIN-TASK"); + assert_eq!(platform_task_id("G15T094019"), "G15T094019"); + } + + #[test] + fn self_connector_id_resolves_from_party_map() { + let mut sites = BTreeMap::new(); + sites.insert("p1".to_string(), "alice".to_string()); + sites.insert("p2".to_string(), "bob".to_string()); + sites.insert("p3".to_string(), "carol".to_string()); + // 平台真实载荷形态:没有 connectorId,只有 selfParty + partyMap(pN → f_connector_id) + let payload = json!({ + "selfParty": "p2", + "partyMap": {"p1": "111", "p2": "222", "p3": "333"}, + "versionNo": 1 + }); + assert_eq!(self_connector_id(&payload, "bob", &sites), "222"); + // 显式 connectorId 优先(未来平台若补上该字段) + let explicit = json!({"connectorId": "999", "selfParty": "p2", "partyMap": {"p2": "222"}}); + assert_eq!(self_connector_id(&explicit, "bob", &sites), "999"); + // 缺 selfParty ⇒ 用本端 site 在 TDC_EXEC_PARTY_SITE_MAP 里反查 party + let no_self = json!({"partyMap": {"p3": "333"}}); + assert_eq!(self_connector_id(&no_self, "carol", &sites), "333"); + // 三者都取不到 ⇒ 空串(auto_report 拒报,不猜、不冒充他方) + assert_eq!(self_connector_id(&json!({}), "alice", &sites), ""); + let bad = json!({"selfParty": "p9", "partyMap": {"p1": "111"}}); + assert_eq!(self_connector_id(&bad, "bob", &sites), ""); + } + + #[test] + fn stat_shows_exited_detects_zombie_and_keeps_running_states() { + // 真机抓到的形态:mpc 已退出但父进程未 wait ⇒ 僵尸 + assert!(stat_shows_exited("2325319 (mpc) Z 2285226 1 0 0 0")); + assert!(stat_shows_exited("1 (a b) X 0 0")); + assert!(stat_shows_exited("")); + assert!(!stat_shows_exited("2325319 (mpc) S 2285226 1 0 0 0")); + assert!(!stat_shows_exited("2325319 (mpc) R 2285226")); + // comm 内含括号/空格也必须以最后一个 ')' 为准 + assert!(!stat_shows_exited("7 (odd) name) S 1 0")); + } + + #[test] + fn redaction_keeps_process_lines_and_hides_result_rows() { + let raw = b"[mpc] stage=psi start\n{\"kind\":\"table\",\"rows\":[[1],[2],[3]]}\n[mpc] done\n"; + let (text, trailing, n, truncated) = redact_log(raw, 1024); + assert!(trailing); + assert_eq!(n, 1); + assert!(!truncated); + assert!(text.contains("[mpc] stage=psi start")); + assert!(text.contains("[mpc] done")); + assert!(!text.contains("[[1],[2],[3]]")); + assert!(text.contains("")); + assert!(text.ends_with('\n'), "末尾换行必须保留,便于与设备日志比对"); + } + + #[test] + fn unparsable_result_line_is_redacted_wholesale() { + let raw = b"{\"kind\":\"table\",\"rows\":BROKEN\n"; + let (text, _, n, _) = redact_log(raw, 1024); + assert_eq!(n, 1); + assert!(text.contains("")); + assert!(!text.contains("BROKEN")); + } + + #[test] + fn oversize_log_is_truncated_and_flagged() { + let raw = b"x".repeat(2048); + let (text, _, _, truncated) = redact_log(&raw, 256); + assert!(truncated); + assert!(text.contains(", /// 执行计划(dry-run 也会落,命令已脱敏)。 pub plan: Option, + /// 执行完成后连接器**自报**的结果(G15 GAP② + G6);旧状态文件无此键 ⇒ 默认 `None`。 + #[serde(default)] + pub report: Option, pub created_at: String, pub updated_at: String, } @@ -97,6 +100,7 @@ impl ExecRecord { message: "已受理,等待后台执行".to_string(), steps: Vec::new(), plan: None, + report: None, created_at: now.clone(), updated_at: now, }