use std::collections::HashMap;
use relate_core::{NodeId, RelId};
use super::adjacency::adj_build;
#[cfg(test)]
use super::build_counter::BuildCounter;
use super::shard::shard_rows;
use super::{live_version, Graph};
pub(in crate::graph) struct RelRow {
pub(in crate::graph) id: RelId,
pub(in crate::graph) start: NodeId,
pub(in crate::graph) type_id: u32,
pub(in crate::graph) end: NodeId,
pub(in crate::graph) ts: Option<i64>,
}
#[derive(Default)]
pub(in crate::graph) struct LabelCache(HashMap<NodeId, Vec<u32>>);
pub(in crate::graph) fn fill_labels<'m>(
map: &'m mut HashMap<NodeId, Vec<u32>>,
graph: &Graph,
node: NodeId,
) -> &'m mut Vec<u32> {
map.entry(node)
.or_insert_with(|| graph.live_label_ids(node))
}
impl LabelCache {
pub(in crate::graph) fn ensure(&mut self, graph: &Graph, node: NodeId) {
fill_labels(&mut self.0, graph, node);
}
pub(in crate::graph) fn get(&self, node: NodeId) -> &[u32] {
self.0
.get(&node)
.expect("the fold cached every endpoint's labels")
.as_slice()
}
}
#[cfg(test)]
thread_local! {
static ADJ_BUILDS: BuildCounter = const { BuildCounter::new() };
}
#[cfg(test)]
pub(super) fn take_adj_builds() -> u64 {
ADJ_BUILDS.with(BuildCounter::take)
}
impl Graph {
pub(super) fn rebuild_adj(&self) {
#[cfg(test)]
ADJ_BUILDS.with(BuildCounter::bump);
let rows = self.materialize_rel_rows();
let labels = self.endpoint_labels(&rows);
let start_shards = shard_rows(&rows, |row| row.start);
adj_build(self, &rows, &start_shards);
self.rebuild_degree_stats(&rows, &labels, &start_shards);
self.rebuild_count_stats(&rows, &labels, &start_shards);
self.recompute_used();
}
fn materialize_rel_rows(&self) -> Vec<RelRow> {
let mut rows: Vec<RelRow> = Vec::new();
self.rels.for_each(|id, vers| {
let Some(ver) = live_version(vers) else {
return;
};
let live = &ver.live;
let ts = live.payload.ts(&self.interner);
rows.push(RelRow {
id,
start: live.start,
type_id: live.type_id,
end: live.end,
ts,
});
});
rows
}
fn endpoint_labels(&self, rows: &[RelRow]) -> LabelCache {
let mut labels = LabelCache::default();
for row in rows {
labels.ensure(self, row.start);
labels.ensure(self, row.end);
}
labels
}
}