use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LineageNode {
pub id: String,
#[serde(rename = "type")]
pub node_type: String,
pub label: String,
pub hash: String,
#[serde(default)]
pub metadata: HashMap<String, serde_json::Value>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LineageEdge {
pub source: String,
pub target: String,
pub relation: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct LineageDAG {
pub target_uri: String,
pub nodes: HashMap<String, LineageNode>,
pub edges: Vec<LineageEdge>,
}
#[derive(Debug, Default, Clone)]
pub struct LineageEngine {
nodes: HashMap<String, LineageNode>,
edges: Vec<LineageEdge>,
}
impl LineageEngine {
pub fn new() -> Self {
Self::default()
}
pub fn add_node(&mut self, node: LineageNode) {
self.nodes.insert(node.id.clone(), node);
}
pub fn add_edge(&mut self, source: &str, target: &str, relation: &str) {
self.edges.push(LineageEdge {
source: source.to_string(),
target: target.to_string(),
relation: relation.to_string(),
});
}
pub fn get_mcard_lineage(&self, target_uri: &str) -> LineageDAG {
let (visited_ids, reachable_edges) = crate::layer2::traversal::reachable_from_with_edges(
[target_uri.to_string()],
|curr| {
self.edges
.iter()
.filter(|edge| edge.target == *curr)
.map(|edge| (edge.source.clone(), edge.clone()))
.collect::<Vec<_>>()
},
);
let mut reachable_nodes = HashMap::new();
for id in visited_ids {
if let Some(node) = self.nodes.get(&id) {
reachable_nodes.insert(id, node.clone());
}
}
LineageDAG {
target_uri: target_uri.to_string(),
nodes: reachable_nodes,
edges: reachable_edges,
}
}
pub fn to_mermaid(&self, dag: &LineageDAG) -> String {
let mut lines = vec!["flowchart TD".to_string()];
for (id, node) in &dag.nodes {
let short_hash = if node.hash.len() > 8 {
&node.hash[..8]
} else {
&node.hash
};
lines.push(format!(" {}[\"{}\\n({}) \"]", id, node.label, short_hash));
}
for edge in &dag.edges {
lines.push(format!(" {} -->|{}| {}", edge.source, edge.relation, edge.target));
}
lines.join("\n")
}
pub fn to_dot(&self, dag: &LineageDAG) -> String {
let mut lines = vec!["digraph Lineage {".to_string(), " rankdir=LR;".to_string()];
for (id, node) in &dag.nodes {
let short_hash = if node.hash.len() > 8 {
&node.hash[..8]
} else {
&node.hash
};
lines.push(format!(" \"{}\" [label=\"{}\\n{}\"];", id, node.label, short_hash));
}
for edge in &dag.edges {
lines.push(format!(" \"{}\" -> \"{}\" [label=\"{}\"];", edge.source, edge.target, edge.relation));
}
lines.push("}".to_string());
lines.join("\n")
}
}