arc-graph-core 0.4.0

Framework-free knowledge-graph model for arc-graph: nodes, typed kinds, weighted edges, adjacency index, filter/search and JSON/CSV import.
Documentation
//! JSON / CSV 导入(方案 §4「JSON / CSV 导入」)。
//!
//! 容错纪律(方案 §7):坏输入返回 `Err` 或跳过坏行并记入
//! [`ImportReport::warnings`],**绝不 panic**;JSON 结构错误、版本不识别
//! 属于文档级错误,整体拒绝。CSV 缺失的端点节点自动补建并计数,
//! 便于直接吃真实世界的引用表。

use crate::ids::{EdgeId, KindId, NodeId};
use crate::model::{
    DEFAULT_EDGE_WEIGHT, DEFAULT_NODE_WEIGHT, GraphError, KnowledgeGraph, Node, sanitize_weight,
};
use serde_json::Value;
use std::fmt;

/// 导入统计。`warnings` 为逐条跳过 / 自动补建说明(英文短句,方便日志检索)。
#[derive(Clone, Debug, Default, PartialEq)]
pub struct ImportReport {
    pub nodes: usize,
    pub edges: usize,
    pub kinds: usize,
    /// CSV 端点缺失而自动补建的节点数。
    pub auto_created_nodes: usize,
    pub warnings: Vec<String>,
}

impl fmt::Display for ImportReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "{} kinds, {} nodes, {} edges, {} auto-created, {} warnings",
            self.kinds,
            self.nodes,
            self.edges,
            self.auto_created_nodes,
            self.warnings.len()
        )
    }
}

// ---------------------------------------------------------------------------
// JSON(宽松模式:跳过坏条目并记录,结构错误整体拒绝)
// ---------------------------------------------------------------------------

/// 从 JSON 导入并返回统计。条目级错误(缺 id、坏数值)跳过并记 warning;
/// JSON 解析失败或顶层不是对象返回 `GraphError::Format`。
pub fn import_json_lenient(json: &str) -> Result<(KnowledgeGraph, ImportReport), GraphError> {
    let value: Value = serde_json::from_str(json).map_err(|e| GraphError::Format(e.to_string()))?;
    let obj = match value.as_object() {
        Some(o) => o,
        None => return Err(GraphError::Format("expected a JSON object".into())),
    };
    if let Some(version) = obj.get("version") {
        match version.as_u64() {
            Some(v) if v == u64::from(crate::FORMAT_VERSION) => {}
            _ => {
                return Err(GraphError::Format(format!(
                    "unsupported version {}",
                    version
                )));
            }
        }
    }

    let mut g = KnowledgeGraph::new();
    if obj.get("directed").and_then(Value::as_bool) == Some(true) {
        g.directed = true;
    }
    let mut report = ImportReport::default();

    // 类型
    if let Some(kinds) = obj.get("kinds").and_then(Value::as_array) {
        for (i, k) in kinds.iter().enumerate() {
            let Some(name) = k.get("name").and_then(Value::as_str) else {
                report
                    .warnings
                    .push(format!("kinds[{i}]: missing name, skipped"));
                continue;
            };
            let id = k
                .get("id")
                .and_then(Value::as_u64)
                .map(|raw| {
                    let id = KindId(raw);
                    g.upsert_kind(id, name);
                    id
                })
                .unwrap_or_else(|| g.add_kind(name));
            report.kinds += 1;
            let _ = id;
        }
    }

    // 节点
    if let Some(nodes) = obj.get("nodes").and_then(Value::as_array) {
        for (i, n) in nodes.iter().enumerate() {
            let Some(raw_id) = n.get("id").and_then(Value::as_u64) else {
                report
                    .warnings
                    .push(format!("nodes[{i}]: missing id, skipped"));
                continue;
            };
            let label = n
                .get("label")
                .and_then(Value::as_str)
                .unwrap_or_default()
                .to_string();
            let kind = match n.get("kind").and_then(Value::as_u64) {
                Some(raw) => {
                    let k = KindId(raw);
                    if g.kind(k).is_none() {
                        report
                            .warnings
                            .push(format!("nodes[{i}]: unknown kind {}, cleared", k));
                        None
                    } else {
                        Some(k)
                    }
                }
                None => None,
            };
            let weight = n
                .get("weight")
                .and_then(Value::as_f64)
                .map(|w| w as f32)
                .unwrap_or(DEFAULT_NODE_WEIGHT);
            let pinned = n.get("pinned").and_then(Value::as_bool).unwrap_or(false);
            let node = Node {
                id: NodeId(raw_id),
                kind,
                label,
                weight: sanitize_weight(weight, DEFAULT_NODE_WEIGHT),
                pinned,
            };
            match g.insert_node(node) {
                Ok(()) => report.nodes += 1,
                Err(crate::model::GraphError::DuplicateId(_)) => report
                    .warnings
                    .push(format!("nodes[{i}]: duplicate id {raw_id}, skipped")),
                Err(e) => return Err(e),
            }
        }
    }

    // 边
    if let Some(edges) = obj.get("edges").and_then(Value::as_array) {
        for (i, e) in edges.iter().enumerate() {
            let (Some(src), Some(dst)) = (
                e.get("source").and_then(Value::as_u64),
                e.get("target").and_then(Value::as_u64),
            ) else {
                report
                    .warnings
                    .push(format!("edges[{i}]: missing endpoint, skipped"));
                continue;
            };
            let source = NodeId(src);
            let target = NodeId(dst);
            ensure_endpoint(&mut g, &mut report, source);
            ensure_endpoint(&mut g, &mut report, target);
            let weight = e
                .get("weight")
                .and_then(Value::as_f64)
                .map(|w| w as f32)
                .unwrap_or(DEFAULT_EDGE_WEIGHT);
            let label = e.get("label").and_then(Value::as_str).map(str::to_string);
            match g.add_edge(source, target, weight, label) {
                Ok(_) => report.edges += 1,
                Err(err) => report.warnings.push(format!("edges[{i}]: {err}, skipped")),
            }
        }
    }

    Ok((g, report))
}

/// 边引用了未声明的节点时自动补建(label 为空,不固定)。
fn ensure_endpoint(g: &mut KnowledgeGraph, report: &mut ImportReport, id: NodeId) {
    if g.node(id).is_none() {
        let node = Node {
            id,
            kind: None,
            label: id.to_string(),
            weight: DEFAULT_NODE_WEIGHT,
            pinned: false,
        };
        if g.insert_node(node).is_ok() {
            report.nodes += 1;
            report.auto_created_nodes += 1;
            report
                .warnings
                .push(format!("auto-created missing endpoint {}", id));
        }
    }
}

// ---------------------------------------------------------------------------
// CSV(表头嗅探:含 source+target 是边表,否则按节点表处理)
// ---------------------------------------------------------------------------

/// 极简 RFC4180 解析:支持引号字段、字段内逗号 / 换行、CRLF。不依赖外部 crate。
fn parse_csv(input: &str) -> Vec<Vec<String>> {
    let mut rows: Vec<Vec<String>> = Vec::new();
    let mut row: Vec<String> = Vec::new();
    let mut field = String::new();
    let mut in_quotes = false;
    let mut chars = input.chars().peekable();
    while let Some(c) = chars.next() {
        if in_quotes {
            match c {
                '"' => {
                    if chars.peek() == Some(&'"') {
                        field.push('"');
                        chars.next();
                    } else {
                        in_quotes = false;
                    }
                }
                _ => field.push(c),
            }
            continue;
        }
        match c {
            '"' if field.is_empty() => in_quotes = true,
            ',' => {
                row.push(std::mem::take(&mut field));
            }
            '\r' => {}
            '\n' => {
                row.push(std::mem::take(&mut field));
                rows.push(std::mem::take(&mut row));
            }
            _ => field.push(c),
        }
    }
    if !field.is_empty() || !row.is_empty() {
        row.push(field);
        rows.push(row);
    }
    rows
}

fn header_index(header: &[String], name: &str) -> Option<usize> {
    header
        .iter()
        .position(|h| h.trim().eq_ignore_ascii_case(name))
}

/// 导入节点 CSV。表头需含 `id` 列;可选 `label` / `kind`(按名称引用,自动注册)/
/// `weight` / `pinned`。坏行跳过并计数。
pub fn import_csv_nodes(g: &mut KnowledgeGraph, csv: &str) -> Result<ImportReport, GraphError> {
    let rows = parse_csv(csv);
    let header = rows
        .first()
        .ok_or_else(|| GraphError::Format("empty CSV".into()))?;
    let col_id = header_index(header, "id")
        .ok_or_else(|| GraphError::Format("nodes CSV requires an \"id\" column".into()))?;
    let col_label = header_index(header, "label");
    let col_kind = header_index(header, "kind");
    let col_weight = header_index(header, "weight");
    let col_pinned = header_index(header, "pinned");

    let mut report = ImportReport::default();
    for (line, row) in rows.iter().enumerate().skip(1) {
        let Some(raw_id) = row.get(col_id).and_then(|s| s.trim().parse::<u64>().ok()) else {
            report
                .warnings
                .push(format!("nodes CSV line {}: bad id, skipped", line + 1));
            continue;
        };
        let kind = col_kind.and_then(|c| row.get(c)).map(|name| {
            // 按名称找已注册类型;找不到就注册新的(保证幂等导入)。
            let name = name.trim().to_string();
            let found = g.kinds().find(|k| k.name == name).map(|k| k.id);
            found.unwrap_or_else(|| g.add_kind(name))
        });
        let weight = col_weight
            .and_then(|c| row.get(c))
            .and_then(|s| s.trim().parse::<f32>().ok())
            .unwrap_or(DEFAULT_NODE_WEIGHT);
        let pinned = col_pinned
            .and_then(|c| row.get(c))
            .map(|s| matches!(s.trim(), "1" | "true" | "TRUE" | "yes" | "Yes"))
            .unwrap_or(false);
        let label = col_label
            .and_then(|c| row.get(c))
            .map(|s| s.trim().to_string())
            .unwrap_or_else(|| format!("kn{raw_id}"));
        let node = Node {
            id: NodeId(raw_id),
            kind,
            label,
            weight: sanitize_weight(weight, DEFAULT_NODE_WEIGHT),
            pinned,
        };
        match g.insert_node(node) {
            Ok(()) => report.nodes += 1,
            Err(crate::model::GraphError::DuplicateId(_)) => report.warnings.push(format!(
                "nodes CSV line {}: duplicate id {raw_id}, skipped",
                line + 1
            )),
            Err(e) => return Err(e),
        }
    }
    report.kinds = g.kinds().count();
    Ok(report)
}

/// 导入边 CSV。表头需含 `source` 与 `target`;可选 `weight` / `label`。
/// 端点缺失自动补建;坏行跳过并计数。
pub fn import_csv_edges(g: &mut KnowledgeGraph, csv: &str) -> Result<ImportReport, GraphError> {
    let rows = parse_csv(csv);
    let header = rows
        .first()
        .ok_or_else(|| GraphError::Format("empty CSV".into()))?;
    let col_src = header_index(header, "source")
        .ok_or_else(|| GraphError::Format("edges CSV requires a \"source\" column".into()))?;
    let col_dst = header_index(header, "target")
        .ok_or_else(|| GraphError::Format("edges CSV requires a \"target\" column".into()))?;
    let col_weight = header_index(header, "weight");
    let col_label = header_index(header, "label");

    let mut report = ImportReport::default();
    for (line, row) in rows.iter().enumerate().skip(1) {
        let Some(raw_src) = row.get(col_src).and_then(|s| s.trim().parse::<u64>().ok()) else {
            report
                .warnings
                .push(format!("edges CSV line {}: bad source, skipped", line + 1));
            continue;
        };
        let Some(raw_dst) = row.get(col_dst).and_then(|s| s.trim().parse::<u64>().ok()) else {
            report
                .warnings
                .push(format!("edges CSV line {}: bad target, skipped", line + 1));
            continue;
        };
        ensure_endpoint(g, &mut report, NodeId(raw_src));
        ensure_endpoint(g, &mut report, NodeId(raw_dst));
        let weight = col_weight
            .and_then(|c| row.get(c))
            .and_then(|s| s.trim().parse::<f32>().ok())
            .unwrap_or(DEFAULT_EDGE_WEIGHT);
        let label = col_label
            .and_then(|c| row.get(c))
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty());
        match g.add_edge(NodeId(raw_src), NodeId(raw_dst), weight, label) {
            Ok(EdgeId(_)) => report.edges += 1,
            Err(err) => report
                .warnings
                .push(format!("edges CSV line {}: {err}, skipped", line + 1)),
        }
    }
    Ok(report)
}

/// 一次性导入:结构化 JSON 文档,或自动嗅探的两张 CSV(节点表 + 边表,可空)。
pub fn import_auto(
    json: Option<&str>,
    nodes_csv: Option<&str>,
    edges_csv: Option<&str>,
) -> Result<(KnowledgeGraph, ImportReport), GraphError> {
    if let Some(json) = json {
        return import_json_lenient(json);
    }
    let mut g = KnowledgeGraph::new();
    let mut report = ImportReport::default();
    if let Some(csv) = nodes_csv {
        report.merge(import_csv_nodes(&mut g, csv)?);
    }
    if let Some(csv) = edges_csv {
        report.merge(import_csv_edges(&mut g, csv)?);
    }
    Ok((g, report))
}

impl ImportReport {
    fn merge(&mut self, other: ImportReport) {
        self.nodes += other.nodes;
        self.edges += other.edges;
        self.kinds = self.kinds.max(other.kinds);
        self.auto_created_nodes += other.auto_created_nodes;
        self.warnings.extend(other.warnings);
    }
}