kernel/graph/
assertion_handles.rs1use super::GraphStratum;
13use crate::persistence::PersistedEdge;
14use std::collections::BTreeMap;
15use std::fmt;
16
17#[derive(Debug, Clone, PartialEq, Eq)]
19pub struct HandleRow {
20 pub stratum: GraphStratum,
21 pub from: String,
22 pub to: String,
23}
24
25impl HandleRow {
26 fn of(stratum: GraphStratum, row: &PersistedEdge) -> Self {
27 Self {
28 stratum,
29 from: row.from_node_id.clone(),
30 to: row.to_node_id.clone(),
31 }
32 }
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct AssertionHandleRepeat {
38 pub statement_id: String,
39 pub first: HandleRow,
40 pub again: HandleRow,
41}
42
43impl fmt::Display for AssertionHandleRepeat {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 let site = |row: &HandleRow| format!("{:?} pair {} -> {}", row.stratum, row.from, row.to);
46 write!(
47 f,
48 "assertion handle {:?} repeats: held on {} and again on {}; one handle means one row",
49 self.statement_id,
50 site(&self.first),
51 site(&self.again)
52 )
53 }
54}
55
56impl std::error::Error for AssertionHandleRepeat {}
57
58#[derive(Default)]
60pub struct AssertionHandles<'a> {
61 held: BTreeMap<&'a str, (GraphStratum, &'a PersistedEdge)>,
62 legacy: BTreeMap<&'a str, &'a PersistedEdge>,
63}
64
65impl<'a> AssertionHandles<'a> {
66 pub fn new() -> Self {
67 Self::default()
68 }
69
70 pub fn admit(
72 &mut self,
73 stratum: GraphStratum,
74 row: &'a PersistedEdge,
75 ) -> Result<(), AssertionHandleRepeat> {
76 for statement in row.retained_assertions() {
77 let id = statement.statement_id.as_str();
78 let first = self
79 .held
80 .get(id)
81 .copied()
82 .or_else(|| self.legacy.get(id).map(|row| (GraphStratum::Surface, *row)));
83 if let Some((first, first_row)) = first {
84 return Err(AssertionHandleRepeat {
85 statement_id: id.to_owned(),
86 first: HandleRow::of(first, first_row),
87 again: HandleRow::of(stratum, row),
88 });
89 }
90 self.held.insert(id, (stratum, row));
91 }
92 Ok(())
93 }
94
95 pub fn hold_legacy_surface(&mut self, row: &'a PersistedEdge) {
98 for statement in row.retained_assertions() {
99 self.legacy
100 .entry(statement.statement_id.as_str())
101 .or_insert(row);
102 }
103 }
104
105 pub fn holds(&self, handle: &str) -> bool {
106 self.held.contains_key(handle) || self.legacy.contains_key(handle)
107 }
108
109 pub fn rows(&self) -> impl Iterator<Item = (&'a str, &'a PersistedEdge)> + '_ {
111 self.held.iter().map(|(handle, (_, row))| (*handle, *row))
112 }
113}
114
115pub fn validate_assertion_handles<'a>(
117 rows: impl IntoIterator<Item = (GraphStratum, &'a PersistedEdge)>,
118) -> Result<(), AssertionHandleRepeat> {
119 let mut handles = AssertionHandles::new();
120 rows.into_iter()
121 .try_for_each(|(stratum, row)| handles.admit(stratum, row))
122}