use hashbrown::{HashMap, HashSet};
use std::sync::atomic::AtomicU64;
use crate::document::hako_doc::HakoDoc;
use crate::document::value::Value;
pub const MAX_TRAVERSE_DEPTH: usize = 32;
pub const MAX_TRAVERSE_DEPTH_CAP: usize = 256;
#[derive(Debug)]
pub struct Backlink {
pub src_col: String,
pub src_id: String,
pub field: String,
pub ver: AtomicU64,
}
#[derive(Debug, Default)]
pub struct BacklinkIndex {
tracked: HashSet<String>,
edges: HashMap<String, HashMap<String, Vec<Backlink>>>,
}
impl BacklinkIndex {
pub fn track(&mut self, collection: &str) {
self.tracked.insert(collection.to_string());
}
pub fn is_tracked(&self, collection: &str) -> bool {
self.tracked.contains(collection)
}
pub fn is_empty(&self) -> bool {
self.tracked.is_empty()
}
pub fn tracked_cols(&self) -> Vec<String> {
let mut out: Vec<String> = self.tracked.iter().cloned().collect();
out.sort();
out
}
pub fn index_doc(&mut self, src_col: &str, src_id: &str, doc: &HakoDoc) {
if self.tracked.is_empty() {
return;
}
for (field, value) in doc.fields.iter() {
let (tgt, tid) = match value {
Value::Reference { collection: tgt, doc_id: tid } => (tgt, tid),
_ => continue,
};
if !self.tracked.contains(tgt.as_str()) {
continue;
}
let edges = self
.edges
.entry(tgt.clone())
.or_default()
.entry(tid.clone())
.or_default();
if !edges.iter().any(|e| {
e.src_col == src_col && e.src_id == src_id && e.field.as_str() == &**field
}) {
edges.push(Backlink {
src_col: src_col.to_string(),
src_id: src_id.to_string(),
field: field.to_string(),
ver: AtomicU64::new(u64::MAX),
});
}
}
}
pub fn remove_doc(&mut self, collection: &str, doc_id: &str, doc: &HakoDoc) {
if self.edges.is_empty() {
return;
}
for value in doc.fields.iter().map(|(_, v)| v) {
if let Value::Reference { collection: tgt, doc_id: tid } = value {
if let Some(map) = self.edges.get_mut(tgt) {
if let Some(edges) = map.get_mut(tid) {
edges.retain(|e| !(e.src_col == collection && e.src_id == doc_id));
}
if map.get(tid).is_some_and(|e| e.is_empty()) {
map.remove(tid);
}
}
if self.edges.get(tgt).is_some_and(|m| m.is_empty()) {
self.edges.remove(tgt);
}
}
}
if let Some(map) = self.edges.get_mut(collection) {
map.remove(doc_id);
}
if self
.edges
.get(collection)
.is_some_and(|m| m.is_empty())
{
self.edges.remove(collection);
}
}
pub fn inbound(&self, tgt_col: &str, tgt_id: &str) -> Option<&Vec<Backlink>> {
self.edges.get(tgt_col).and_then(|m| m.get(tgt_id))
}
pub fn untrack(&mut self, collection: &str) -> bool {
self.clear_collection(collection);
self.tracked.remove(collection)
}
pub fn clear_collection(&mut self, collection: &str) {
self.edges.remove(collection);
let mut empty_maps = Vec::new();
for (tgt, map) in self.edges.iter_mut() {
for edges in map.values_mut() {
edges.retain(|e| e.src_col != collection);
}
map.retain(|_, edges| !edges.is_empty());
if map.is_empty() {
empty_maps.push(tgt.clone());
}
}
for tgt in empty_maps {
self.edges.remove(&tgt);
}
}
#[cfg(test)]
pub fn edge_count(&self) -> usize {
self.edges.values().map(|m| m.values().map(Vec::len).sum::<usize>()).sum()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TraverseDir {
Outgoing,
Incoming,
Both,
}
impl TraverseDir {
pub fn from_u32(v: u32) -> crate::error::Result<Self> {
match v {
0 => Ok(TraverseDir::Outgoing),
1 => Ok(TraverseDir::Incoming),
2 => Ok(TraverseDir::Both),
_ => Err(crate::error::HakoError::Corrupt(format!(
"unknown traverse direction {v} (0=outgoing, 1=incoming, 2=both)"
))),
}
}
pub fn uses_outgoing(self) -> bool {
matches!(self, TraverseDir::Outgoing | TraverseDir::Both)
}
pub fn uses_incoming(self) -> bool {
matches!(self, TraverseDir::Incoming | TraverseDir::Both)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TraverseSpec {
pub direction: TraverseDir,
pub edge_field: Option<String>,
pub max_depth: usize,
pub limit: usize,
pub via_edge: Option<String>,
pub weight_field: Option<String>,
pub node_match: Option<(String, Value)>,
pub edge_type: Option<(String, Value)>,
pub edge_match: Option<(String, Value)>,
pub include_path: bool,
pub include_via: bool,
}
impl TraverseSpec {
pub fn validate(&self) -> crate::error::Result<()> {
if self.max_depth == 0 || self.max_depth > MAX_TRAVERSE_DEPTH_CAP {
return Err(crate::error::HakoError::Corrupt(format!(
"traverse depth {} out of range 1..={MAX_TRAVERSE_DEPTH_CAP} (guidance: {MAX_TRAVERSE_DEPTH})",
self.max_depth
)));
}
if self.limit == 0 {
return Err(crate::error::HakoError::Corrupt(
"traverse limit must be >= 1".to_string(),
));
}
Ok(())
}
}