use serde::Serialize;
use std::collections::{HashMap, VecDeque};
use crate::frontier_graph::{Edge, EdgeKind, FrontierGraph};
pub const SUPPORT_KINDS: [EdgeKind; 5] = [
EdgeKind::Supports,
EdgeKind::DependsOn,
EdgeKind::DerivedFrom,
EdgeKind::Discharges,
EdgeKind::Improves,
];
#[derive(Debug, Clone, Serialize)]
pub struct PathStep {
pub from: String,
pub to: String,
pub kind: &'static str,
pub note: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct Path {
pub from: String,
pub to: String,
pub nodes: Vec<String>,
pub steps: Vec<PathStep>,
pub hops: usize,
}
impl Path {
#[must_use]
pub fn to_json(&self) -> serde_json::Value {
serde_json::json!({
"schema": "vela.golden_thread.v0.1",
"from": self.from,
"to": self.to,
"hops": self.hops,
"nodes": self.nodes,
"steps": self.steps,
"derived": true,
})
}
}
#[must_use]
pub fn shortest_path(
graph: &FrontierGraph,
from: &str,
to: &str,
kinds: &[EdgeKind],
) -> Option<Path> {
if !graph.contains(from) || !graph.contains(to) {
return None;
}
if from == to {
return Some(Path {
from: from.to_string(),
to: to.to_string(),
nodes: vec![from.to_string()],
steps: vec![],
hops: 0,
});
}
let mut adj: HashMap<&str, Vec<&Edge>> = HashMap::new();
for e in graph.all_edges() {
if kinds.contains(&e.kind) {
adj.entry(e.source.as_str()).or_default().push(e);
}
}
let mut prev: HashMap<&str, &Edge> = HashMap::new();
let mut queue: VecDeque<&str> = VecDeque::new();
let mut seen: HashMap<&str, ()> = HashMap::new();
queue.push_back(from);
seen.insert(from, ());
while let Some(node) = queue.pop_front() {
for &e in adj.get(node).into_iter().flatten() {
let next = e.target.as_str();
if seen.contains_key(next) {
continue;
}
seen.insert(next, ());
prev.insert(next, e);
if next == to {
return Some(reconstruct(from, to, &prev));
}
queue.push_back(next);
}
}
None
}
fn reconstruct(from: &str, to: &str, prev: &HashMap<&str, &Edge>) -> Path {
let mut steps_rev: Vec<PathStep> = Vec::new();
let mut nodes_rev: Vec<String> = vec![to.to_string()];
let mut cur = to;
while cur != from {
let e = prev[cur];
steps_rev.push(PathStep {
from: e.source.clone(),
to: e.target.clone(),
kind: e.kind.as_str(),
note: e.note.clone(),
});
nodes_rev.push(e.source.clone());
cur = e.source.as_str();
}
nodes_rev.reverse();
steps_rev.reverse();
Path {
from: from.to_string(),
to: to.to_string(),
hops: steps_rev.len(),
nodes: nodes_rev,
steps: steps_rev,
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::project::assemble;
use crate::project::reverse_dep_index_tests::{link_to, synth_finding};
fn link_typed(target: &str, link_type: &str) -> crate::bundle::Link {
let mut link = link_to(target);
link.link_type = link_type.into();
link
}
#[test]
fn finds_shortest_support_chain() {
let a = synth_finding(0, vec![]);
let b = synth_finding(1, vec![link_typed(&a.id, "depends")]);
let c = synth_finding(2, vec![link_typed(&b.id, "depends")]);
let (a_id, c_id) = (a.id.clone(), c.id.clone());
let mut project = assemble("pf", vec![], 0, 0, "test");
project.findings = vec![a, b, c];
let g = FrontierGraph::from_project(&project);
let p = shortest_path(&g, &c_id, &a_id, &SUPPORT_KINDS).expect("path exists");
assert_eq!(p.hops, 2);
assert_eq!(p.nodes.first().unwrap(), &c_id);
assert_eq!(p.nodes.last().unwrap(), &a_id);
assert_eq!(p.steps.len(), 2);
}
#[test]
fn no_path_when_unconnected_or_wrong_direction() {
let a = synth_finding(0, vec![]);
let b = synth_finding(1, vec![link_typed(&a.id, "depends")]);
let (a_id, b_id) = (a.id.clone(), b.id.clone());
let mut project = assemble("pf2", vec![], 0, 0, "test");
project.findings = vec![a, b];
let g = FrontierGraph::from_project(&project);
assert!(shortest_path(&g, &a_id, &b_id, &SUPPORT_KINDS).is_none());
assert!(shortest_path(&g, &a_id, "vf_absent", &SUPPORT_KINDS).is_none());
}
#[test]
fn same_node_is_zero_hops() {
let a = synth_finding(0, vec![]);
let a_id = a.id.clone();
let mut project = assemble("pf3", vec![], 0, 0, "test");
project.findings = vec![a];
let g = FrontierGraph::from_project(&project);
let p = shortest_path(&g, &a_id, &a_id, &SUPPORT_KINDS).unwrap();
assert_eq!(p.hops, 0);
assert_eq!(p.nodes, vec![a_id]);
}
#[test]
fn kind_filter_excludes_other_relations() {
let a = synth_finding(0, vec![]);
let b = synth_finding(1, vec![link_typed(&a.id, "depends")]);
let c = synth_finding(2, vec![link_typed(&b.id, "contradicts")]);
let (a_id, c_id) = (a.id.clone(), c.id.clone());
let mut project = assemble("pf4", vec![], 0, 0, "test");
project.findings = vec![a, b, c];
let g = FrontierGraph::from_project(&project);
assert!(shortest_path(&g, &c_id, &a_id, &SUPPORT_KINDS).is_none());
}
}