use std::cell::RefCell;
use std::collections::HashSet;
use std::rc::Rc;
use relate_core::{Error, NodeId, Path, RelId, Result};
use relate_ir::{Direction, NodePattern, PathPattern, RelPattern};
use crate::graph::{HopBuf, PeerHop};
use crate::overlay::ExecGraph;
use crate::store::RelTypes;
pub(crate) mod class_walk;
pub(crate) mod layered;
pub(crate) mod multi_source;
mod pair;
mod reach;
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum CommonEndNodes {
Allowed,
Forbidden,
}
impl CommonEndNodes {
pub(crate) fn reject(self, start: NodeId, end: NodeId, min: u32) -> Result<()> {
match self {
CommonEndNodes::Allowed => Ok(()),
CommonEndNodes::Forbidden if start == end && min > 0 => {
Err(common_end_nodes_forbidden())
}
CommonEndNodes::Forbidden => Ok(()),
}
}
}
pub(crate) fn common_end_nodes_forbidden() -> Error {
Error::execution(
"ShortestPathCommonEndNodes: The shortest path algorithm does not work when the start and end nodes are the same.",
)
}
pub(crate) fn reject_static_common_end_nodes(path: &PathPattern) -> Result<()> {
let same = path.is_shortest_path_function
&& path
.boundary_nodes()
.is_some_and(|(start, end)| start.variable.is_some() && start.variable == end.variable);
if same {
Err(common_end_nodes_forbidden())
} else {
Ok(())
}
}
#[cfg(test)]
mod all_pair_tests;
#[cfg(test)]
mod hop_reader_tests;
#[cfg(test)]
pub(crate) mod test_support;
#[cfg(test)]
mod tests;
#[cfg(test)]
thread_local! {
static EXPANDS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
#[cfg(test)]
fn note_expands(n: usize) {
EXPANDS.with(|c| c.set(c.get() + n as u64));
}
#[cfg(not(test))]
fn note_expands(_: usize) {}
#[cfg(test)]
pub(crate) fn take_shortest_expands() -> u64 {
EXPANDS.with(|c| c.replace(0))
}
#[derive(Clone)]
pub(crate) struct Search<'a, 'g> {
pub graph: &'a ExecGraph<'g>,
pub types: RelTypes,
pub dir: Direction,
pub min: u32,
pub max: u32,
pub all: bool,
pub skip: Option<RelId>,
pub scratch: RefCell<HopBuf>,
pub interior: Option<Rc<dyn Fn(NodeId) -> Result<bool> + 'a>>,
}
impl Search<'_, '_> {
pub(super) fn filters_interior(&self) -> bool {
self.interior.is_some()
}
pub(super) fn admits_interior(&self, node: NodeId) -> Result<bool> {
match &self.interior {
None => Ok(true),
Some(pred) => pred(node),
}
}
#[inline]
pub(crate) fn node_degree(&self, node: NodeId) -> usize {
self.graph.base().typed_adj_len(node, self.dir, &self.types)
}
pub(crate) fn reversed(&self) -> Self {
Self {
dir: self.dir.flip(),
..self.clone()
}
}
fn each_hop(&self, node: NodeId, mut f: impl FnMut(NodeId, RelId) -> Result<()>) -> Result<()> {
self.each_hop_batch_along(self.dir, node, |hops| {
hops.iter().try_for_each(|hop| f(hop.peer, hop.rid))
})
}
fn each_hop_batch_along(
&self,
dir: Direction,
node: NodeId,
mut f: impl FnMut(&[PeerHop]) -> Result<()>,
) -> Result<()> {
self.graph.cancel_tick()?;
let mut buf = std::mem::take(&mut *self.scratch.borrow_mut());
let result = self
.graph
.try_for_each_hop_batch(node, dir, &self.types, &mut buf, |hops| {
note_expands(hops.len());
f(hops)
});
*self.scratch.borrow_mut() = buf;
result
}
pub(crate) fn hops(&self, node: NodeId) -> Result<Vec<(NodeId, RelId)>> {
self.hops_along(self.dir, node)
}
fn hops_along(&self, dir: Direction, node: NodeId) -> Result<Vec<(NodeId, RelId)>> {
let mut out = Vec::new();
self.each_hop_batch_along(dir, node, |hops| {
out.extend(hops.iter().map(|hop| (hop.peer, hop.rid)));
Ok(())
})?;
Ok(out)
}
}
pub(crate) fn followable(start: &NodePattern, rel: &RelPattern, end: &NodePattern) -> bool {
rel.types_are_complete_filter()
&& rel.properties.is_none()
&& start.has_static_labels()
&& end.has_static_labels()
}
fn unique_rels(trail: &[RelId]) -> bool {
let mut seen = HashSet::new();
trail.iter().all(|r| seen.insert(*r))
}
pub(crate) fn path_from_trail(graph: &ExecGraph<'_>, start: NodeId, trail: &[RelId]) -> Path {
let mut nodes = Vec::new();
let mut rels = Vec::new();
nodes.push(
graph
.node(start)
.expect("path_from_trail: start node of the search's own view"),
);
let mut cur = start;
for rid in trail {
let rel = graph
.rel(*rid)
.expect("path_from_trail: trail relationship of the search's own view");
debug_assert!(
rel.start == cur || rel.end == cur,
"path_from_trail: trail is contiguous"
);
let next = if rel.start == cur { rel.end } else { rel.start };
rels.push(rel);
nodes.push(
graph
.node(next)
.expect("path_from_trail: trail node of the search's own view"),
);
cur = next;
}
Path { nodes, rels }
}