Skip to main content

arc_graph_core/
import.rs

1//! JSON / CSV 导入(方案 §4「JSON / CSV 导入」)。
2//!
3//! 容错纪律(方案 §7):坏输入返回 `Err` 或跳过坏行并记入
4//! [`ImportReport::warnings`],**绝不 panic**;JSON 结构错误、版本不识别
5//! 属于文档级错误,整体拒绝。CSV 缺失的端点节点自动补建并计数,
6//! 便于直接吃真实世界的引用表。
7
8use crate::ids::{EdgeId, KindId, NodeId};
9use crate::model::{
10    DEFAULT_EDGE_WEIGHT, DEFAULT_NODE_WEIGHT, GraphError, KnowledgeGraph, Node, sanitize_weight,
11};
12use serde_json::Value;
13use std::fmt;
14
15/// 导入统计。`warnings` 为逐条跳过 / 自动补建说明(英文短句,方便日志检索)。
16#[derive(Clone, Debug, Default, PartialEq)]
17pub struct ImportReport {
18    pub nodes: usize,
19    pub edges: usize,
20    pub kinds: usize,
21    /// CSV 端点缺失而自动补建的节点数。
22    pub auto_created_nodes: usize,
23    pub warnings: Vec<String>,
24}
25
26impl fmt::Display for ImportReport {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(
29            f,
30            "{} kinds, {} nodes, {} edges, {} auto-created, {} warnings",
31            self.kinds,
32            self.nodes,
33            self.edges,
34            self.auto_created_nodes,
35            self.warnings.len()
36        )
37    }
38}
39
40// ---------------------------------------------------------------------------
41// JSON(宽松模式:跳过坏条目并记录,结构错误整体拒绝)
42// ---------------------------------------------------------------------------
43
44/// 从 JSON 导入并返回统计。条目级错误(缺 id、坏数值)跳过并记 warning;
45/// JSON 解析失败或顶层不是对象返回 `GraphError::Format`。
46pub fn import_json_lenient(json: &str) -> Result<(KnowledgeGraph, ImportReport), GraphError> {
47    let value: Value = serde_json::from_str(json).map_err(|e| GraphError::Format(e.to_string()))?;
48    let obj = match value.as_object() {
49        Some(o) => o,
50        None => return Err(GraphError::Format("expected a JSON object".into())),
51    };
52    if let Some(version) = obj.get("version") {
53        match version.as_u64() {
54            Some(v) if v == u64::from(crate::FORMAT_VERSION) => {}
55            _ => {
56                return Err(GraphError::Format(format!(
57                    "unsupported version {}",
58                    version
59                )));
60            }
61        }
62    }
63
64    let mut g = KnowledgeGraph::new();
65    if obj.get("directed").and_then(Value::as_bool) == Some(true) {
66        g.directed = true;
67    }
68    let mut report = ImportReport::default();
69
70    // 类型
71    if let Some(kinds) = obj.get("kinds").and_then(Value::as_array) {
72        for (i, k) in kinds.iter().enumerate() {
73            let Some(name) = k.get("name").and_then(Value::as_str) else {
74                report
75                    .warnings
76                    .push(format!("kinds[{i}]: missing name, skipped"));
77                continue;
78            };
79            let id = k
80                .get("id")
81                .and_then(Value::as_u64)
82                .map(|raw| {
83                    let id = KindId(raw);
84                    g.upsert_kind(id, name);
85                    id
86                })
87                .unwrap_or_else(|| g.add_kind(name));
88            report.kinds += 1;
89            let _ = id;
90        }
91    }
92
93    // 节点
94    if let Some(nodes) = obj.get("nodes").and_then(Value::as_array) {
95        for (i, n) in nodes.iter().enumerate() {
96            let Some(raw_id) = n.get("id").and_then(Value::as_u64) else {
97                report
98                    .warnings
99                    .push(format!("nodes[{i}]: missing id, skipped"));
100                continue;
101            };
102            let label = n
103                .get("label")
104                .and_then(Value::as_str)
105                .unwrap_or_default()
106                .to_string();
107            let kind = match n.get("kind").and_then(Value::as_u64) {
108                Some(raw) => {
109                    let k = KindId(raw);
110                    if g.kind(k).is_none() {
111                        report
112                            .warnings
113                            .push(format!("nodes[{i}]: unknown kind {}, cleared", k));
114                        None
115                    } else {
116                        Some(k)
117                    }
118                }
119                None => None,
120            };
121            let weight = n
122                .get("weight")
123                .and_then(Value::as_f64)
124                .map(|w| w as f32)
125                .unwrap_or(DEFAULT_NODE_WEIGHT);
126            let pinned = n.get("pinned").and_then(Value::as_bool).unwrap_or(false);
127            let node = Node {
128                id: NodeId(raw_id),
129                kind,
130                label,
131                weight: sanitize_weight(weight, DEFAULT_NODE_WEIGHT),
132                pinned,
133            };
134            match g.insert_node(node) {
135                Ok(()) => report.nodes += 1,
136                Err(crate::model::GraphError::DuplicateId(_)) => report
137                    .warnings
138                    .push(format!("nodes[{i}]: duplicate id {raw_id}, skipped")),
139                Err(e) => return Err(e),
140            }
141        }
142    }
143
144    // 边
145    if let Some(edges) = obj.get("edges").and_then(Value::as_array) {
146        for (i, e) in edges.iter().enumerate() {
147            let (Some(src), Some(dst)) = (
148                e.get("source").and_then(Value::as_u64),
149                e.get("target").and_then(Value::as_u64),
150            ) else {
151                report
152                    .warnings
153                    .push(format!("edges[{i}]: missing endpoint, skipped"));
154                continue;
155            };
156            let source = NodeId(src);
157            let target = NodeId(dst);
158            ensure_endpoint(&mut g, &mut report, source);
159            ensure_endpoint(&mut g, &mut report, target);
160            let weight = e
161                .get("weight")
162                .and_then(Value::as_f64)
163                .map(|w| w as f32)
164                .unwrap_or(DEFAULT_EDGE_WEIGHT);
165            let label = e.get("label").and_then(Value::as_str).map(str::to_string);
166            match g.add_edge(source, target, weight, label) {
167                Ok(_) => report.edges += 1,
168                Err(err) => report.warnings.push(format!("edges[{i}]: {err}, skipped")),
169            }
170        }
171    }
172
173    Ok((g, report))
174}
175
176/// 边引用了未声明的节点时自动补建(label 为空,不固定)。
177fn ensure_endpoint(g: &mut KnowledgeGraph, report: &mut ImportReport, id: NodeId) {
178    if g.node(id).is_none() {
179        let node = Node {
180            id,
181            kind: None,
182            label: id.to_string(),
183            weight: DEFAULT_NODE_WEIGHT,
184            pinned: false,
185        };
186        if g.insert_node(node).is_ok() {
187            report.nodes += 1;
188            report.auto_created_nodes += 1;
189            report
190                .warnings
191                .push(format!("auto-created missing endpoint {}", id));
192        }
193    }
194}
195
196// ---------------------------------------------------------------------------
197// CSV(表头嗅探:含 source+target 是边表,否则按节点表处理)
198// ---------------------------------------------------------------------------
199
200/// 极简 RFC4180 解析:支持引号字段、字段内逗号 / 换行、CRLF。不依赖外部 crate。
201fn parse_csv(input: &str) -> Vec<Vec<String>> {
202    let mut rows: Vec<Vec<String>> = Vec::new();
203    let mut row: Vec<String> = Vec::new();
204    let mut field = String::new();
205    let mut in_quotes = false;
206    let mut chars = input.chars().peekable();
207    while let Some(c) = chars.next() {
208        if in_quotes {
209            match c {
210                '"' => {
211                    if chars.peek() == Some(&'"') {
212                        field.push('"');
213                        chars.next();
214                    } else {
215                        in_quotes = false;
216                    }
217                }
218                _ => field.push(c),
219            }
220            continue;
221        }
222        match c {
223            '"' if field.is_empty() => in_quotes = true,
224            ',' => {
225                row.push(std::mem::take(&mut field));
226            }
227            '\r' => {}
228            '\n' => {
229                row.push(std::mem::take(&mut field));
230                rows.push(std::mem::take(&mut row));
231            }
232            _ => field.push(c),
233        }
234    }
235    if !field.is_empty() || !row.is_empty() {
236        row.push(field);
237        rows.push(row);
238    }
239    rows
240}
241
242fn header_index(header: &[String], name: &str) -> Option<usize> {
243    header
244        .iter()
245        .position(|h| h.trim().eq_ignore_ascii_case(name))
246}
247
248/// 导入节点 CSV。表头需含 `id` 列;可选 `label` / `kind`(按名称引用,自动注册)/
249/// `weight` / `pinned`。坏行跳过并计数。
250pub fn import_csv_nodes(g: &mut KnowledgeGraph, csv: &str) -> Result<ImportReport, GraphError> {
251    let rows = parse_csv(csv);
252    let header = rows
253        .first()
254        .ok_or_else(|| GraphError::Format("empty CSV".into()))?;
255    let col_id = header_index(header, "id")
256        .ok_or_else(|| GraphError::Format("nodes CSV requires an \"id\" column".into()))?;
257    let col_label = header_index(header, "label");
258    let col_kind = header_index(header, "kind");
259    let col_weight = header_index(header, "weight");
260    let col_pinned = header_index(header, "pinned");
261
262    let mut report = ImportReport::default();
263    for (line, row) in rows.iter().enumerate().skip(1) {
264        let Some(raw_id) = row.get(col_id).and_then(|s| s.trim().parse::<u64>().ok()) else {
265            report
266                .warnings
267                .push(format!("nodes CSV line {}: bad id, skipped", line + 1));
268            continue;
269        };
270        let kind = col_kind.and_then(|c| row.get(c)).map(|name| {
271            // 按名称找已注册类型;找不到就注册新的(保证幂等导入)。
272            let name = name.trim().to_string();
273            let found = g.kinds().find(|k| k.name == name).map(|k| k.id);
274            found.unwrap_or_else(|| g.add_kind(name))
275        });
276        let weight = col_weight
277            .and_then(|c| row.get(c))
278            .and_then(|s| s.trim().parse::<f32>().ok())
279            .unwrap_or(DEFAULT_NODE_WEIGHT);
280        let pinned = col_pinned
281            .and_then(|c| row.get(c))
282            .map(|s| matches!(s.trim(), "1" | "true" | "TRUE" | "yes" | "Yes"))
283            .unwrap_or(false);
284        let label = col_label
285            .and_then(|c| row.get(c))
286            .map(|s| s.trim().to_string())
287            .unwrap_or_else(|| format!("kn{raw_id}"));
288        let node = Node {
289            id: NodeId(raw_id),
290            kind,
291            label,
292            weight: sanitize_weight(weight, DEFAULT_NODE_WEIGHT),
293            pinned,
294        };
295        match g.insert_node(node) {
296            Ok(()) => report.nodes += 1,
297            Err(crate::model::GraphError::DuplicateId(_)) => report.warnings.push(format!(
298                "nodes CSV line {}: duplicate id {raw_id}, skipped",
299                line + 1
300            )),
301            Err(e) => return Err(e),
302        }
303    }
304    report.kinds = g.kinds().count();
305    Ok(report)
306}
307
308/// 导入边 CSV。表头需含 `source` 与 `target`;可选 `weight` / `label`。
309/// 端点缺失自动补建;坏行跳过并计数。
310pub fn import_csv_edges(g: &mut KnowledgeGraph, csv: &str) -> Result<ImportReport, GraphError> {
311    let rows = parse_csv(csv);
312    let header = rows
313        .first()
314        .ok_or_else(|| GraphError::Format("empty CSV".into()))?;
315    let col_src = header_index(header, "source")
316        .ok_or_else(|| GraphError::Format("edges CSV requires a \"source\" column".into()))?;
317    let col_dst = header_index(header, "target")
318        .ok_or_else(|| GraphError::Format("edges CSV requires a \"target\" column".into()))?;
319    let col_weight = header_index(header, "weight");
320    let col_label = header_index(header, "label");
321
322    let mut report = ImportReport::default();
323    for (line, row) in rows.iter().enumerate().skip(1) {
324        let Some(raw_src) = row.get(col_src).and_then(|s| s.trim().parse::<u64>().ok()) else {
325            report
326                .warnings
327                .push(format!("edges CSV line {}: bad source, skipped", line + 1));
328            continue;
329        };
330        let Some(raw_dst) = row.get(col_dst).and_then(|s| s.trim().parse::<u64>().ok()) else {
331            report
332                .warnings
333                .push(format!("edges CSV line {}: bad target, skipped", line + 1));
334            continue;
335        };
336        ensure_endpoint(g, &mut report, NodeId(raw_src));
337        ensure_endpoint(g, &mut report, NodeId(raw_dst));
338        let weight = col_weight
339            .and_then(|c| row.get(c))
340            .and_then(|s| s.trim().parse::<f32>().ok())
341            .unwrap_or(DEFAULT_EDGE_WEIGHT);
342        let label = col_label
343            .and_then(|c| row.get(c))
344            .map(|s| s.trim().to_string())
345            .filter(|s| !s.is_empty());
346        match g.add_edge(NodeId(raw_src), NodeId(raw_dst), weight, label) {
347            Ok(EdgeId(_)) => report.edges += 1,
348            Err(err) => report
349                .warnings
350                .push(format!("edges CSV line {}: {err}, skipped", line + 1)),
351        }
352    }
353    Ok(report)
354}
355
356/// 一次性导入:结构化 JSON 文档,或自动嗅探的两张 CSV(节点表 + 边表,可空)。
357pub fn import_auto(
358    json: Option<&str>,
359    nodes_csv: Option<&str>,
360    edges_csv: Option<&str>,
361) -> Result<(KnowledgeGraph, ImportReport), GraphError> {
362    if let Some(json) = json {
363        return import_json_lenient(json);
364    }
365    let mut g = KnowledgeGraph::new();
366    let mut report = ImportReport::default();
367    if let Some(csv) = nodes_csv {
368        report.merge(import_csv_nodes(&mut g, csv)?);
369    }
370    if let Some(csv) = edges_csv {
371        report.merge(import_csv_edges(&mut g, csv)?);
372    }
373    Ok((g, report))
374}
375
376impl ImportReport {
377    fn merge(&mut self, other: ImportReport) {
378        self.nodes += other.nodes;
379        self.edges += other.edges;
380        self.kinds = self.kinds.max(other.kinds);
381        self.auto_created_nodes += other.auto_created_nodes;
382        self.warnings.extend(other.warnings);
383    }
384}