1use std::collections::BTreeSet;
8
9use rkyv::{Archive, Deserialize, Serialize};
10
11use crate::types::{GraphScope, mint_local_statement_id};
12
13use super::edge_taxonomy::{
14 ArrangementSubKind, ContainmentSubKind, ImportedSubKind, NavigationTrigger, ProvenanceSubKind,
15 RelationDurability, SemanticSubKind,
16};
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
20pub struct Traversal {
21 pub timestamp_ms: u64,
22 pub trigger: NavigationTrigger,
23}
24
25impl Traversal {
26 pub fn now(trigger: NavigationTrigger) -> Self {
27 let timestamp_ms = crate::time::unix_epoch_millis();
28 Self {
29 timestamp_ms,
30 trigger,
31 }
32 }
33}
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Archive, Serialize, Deserialize)]
37pub struct EdgeMetrics {
38 pub total_navigations: u64,
39 pub forward_navigations: u64,
40 pub backward_navigations: u64,
41 pub last_navigated_at: Option<u64>,
42}
43
44impl EdgeMetrics {
45 fn new() -> Self {
46 Self {
47 total_navigations: 0,
48 forward_navigations: 0,
49 backward_navigations: 0,
50 last_navigated_at: None,
51 }
52 }
53
54 fn record(&mut self, traversal: Traversal) {
55 self.total_navigations = self.total_navigations.saturating_add(1);
56 if traversal.trigger.contributes_to_forward_count() {
57 self.forward_navigations = self.forward_navigations.saturating_add(1);
58 } else {
59 self.backward_navigations = self.backward_navigations.saturating_add(1);
60 }
61 self.last_navigated_at = Some(traversal.timestamp_ms);
62 }
63}
64
65impl Default for EdgeMetrics {
66 fn default() -> Self {
67 Self::new()
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize)]
72pub struct SemanticStatement {
73 pub statement_id: String,
74 pub predicate: String,
75 pub recognized_sub_kind: Option<SemanticSubKind>,
76 pub label: Option<String>,
77 pub graph_scope: GraphScope,
78 pub provenance_iri: Option<String>,
79 pub asserted_at_ms: Option<u64>,
80}
81
82impl SemanticStatement {
83 pub fn new(
84 predicate: String,
85 recognized_sub_kind: Option<SemanticSubKind>,
86 label: Option<String>,
87 graph_scope: GraphScope,
88 provenance_iri: Option<String>,
89 asserted_at_ms: Option<u64>,
90 ) -> Self {
91 Self {
92 statement_id: mint_local_statement_id(),
93 predicate,
94 recognized_sub_kind,
95 label,
96 graph_scope,
97 provenance_iri,
98 asserted_at_ms,
99 }
100 }
101}
102
103#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
104pub struct SemanticData {
105 pub sub_kinds: BTreeSet<SemanticSubKind>,
109 pub label: Option<String>,
111 pub predicate: Option<String>,
119 pub statements: Vec<SemanticStatement>,
121}
122
123#[derive(Debug, Clone, PartialEq, Eq, Default)]
129pub struct SemanticStatementSpec {
130 pub predicate: String,
131 pub recognized_sub_kind: Option<SemanticSubKind>,
132 pub label: Option<String>,
133 pub graph_scope: GraphScope,
134 pub provenance_iri: Option<String>,
135 pub asserted_at_ms: Option<u64>,
136}
137
138#[derive(Debug, Clone, PartialEq, Eq)]
140pub struct StatementAssert {
141 pub statement_id: String,
144 pub changed: bool,
147}
148
149impl SemanticData {
150 pub fn statements(&self) -> &[SemanticStatement] {
151 &self.statements
152 }
153
154 pub fn assert_statement(&mut self, spec: SemanticStatementSpec) -> StatementAssert {
160 if let Some(existing) = self.statements.iter_mut().find(|statement| {
161 statement.recognized_sub_kind == spec.recognized_sub_kind
162 && statement.predicate == spec.predicate
163 && statement.graph_scope == spec.graph_scope
164 }) {
165 let changed = existing.label != spec.label
166 || existing.provenance_iri != spec.provenance_iri
167 || existing.asserted_at_ms != spec.asserted_at_ms;
168 let statement_id = existing.statement_id.clone();
169 if changed {
170 existing.label = spec.label;
171 existing.provenance_iri = spec.provenance_iri;
172 existing.asserted_at_ms = spec.asserted_at_ms;
173 self.rebuild_compat();
174 }
175 return StatementAssert {
176 statement_id,
177 changed,
178 };
179 }
180 let statement = SemanticStatement::new(
181 spec.predicate,
182 spec.recognized_sub_kind,
183 spec.label,
184 spec.graph_scope,
185 spec.provenance_iri,
186 spec.asserted_at_ms,
187 );
188 let statement_id = statement.statement_id.clone();
189 self.statements.push(statement);
190 self.rebuild_compat();
191 StatementAssert {
192 statement_id,
193 changed: true,
194 }
195 }
196
197 pub fn retract_statement(&mut self, statement_id: &str) -> bool {
201 let before = self.statements.len();
202 self.statements
203 .retain(|statement| statement.statement_id != statement_id);
204 if self.statements.len() == before {
205 return false;
206 }
207 self.rebuild_compat();
208 true
209 }
210
211 pub fn insert_statement(
212 &mut self,
213 recognized_sub_kind: Option<SemanticSubKind>,
214 predicate: String,
215 label: Option<String>,
216 graph_scope: GraphScope,
217 provenance_iri: Option<String>,
218 asserted_at_ms: Option<u64>,
219 ) -> bool {
220 if let Some(existing) = self.statements.iter_mut().find(|statement| {
221 statement.recognized_sub_kind == recognized_sub_kind
222 && statement.predicate == predicate
223 && statement.graph_scope == graph_scope
224 }) {
225 if existing.label != label
226 || existing.provenance_iri != provenance_iri
227 || existing.asserted_at_ms != asserted_at_ms
228 {
229 existing.label = label;
230 existing.provenance_iri = provenance_iri;
231 existing.asserted_at_ms = asserted_at_ms;
232 self.rebuild_compat();
233 return true;
234 }
235 return false;
236 }
237
238 self.statements.push(SemanticStatement::new(
239 predicate,
240 recognized_sub_kind,
241 label,
242 graph_scope,
243 provenance_iri,
244 asserted_at_ms,
245 ));
246 self.rebuild_compat();
247 true
248 }
249
250 pub fn push_persisted_statement(&mut self, statement: SemanticStatement) -> bool {
251 if self
252 .statements
253 .iter()
254 .any(|existing| existing.statement_id == statement.statement_id)
255 {
256 return false;
257 }
258 self.statements.push(statement);
259 self.rebuild_compat();
260 true
261 }
262
263 pub fn remove_statements_with_sub_kind(&mut self, sub_kind: SemanticSubKind) -> bool {
264 let before = self.statements.len();
265 self.statements
266 .retain(|statement| statement.recognized_sub_kind != Some(sub_kind));
267 if self.statements.len() == before {
268 return false;
269 }
270 self.rebuild_compat();
271 true
272 }
273
274 pub fn set_statement_predicate(&mut self, predicate: Option<String>) {
275 match predicate {
276 Some(predicate) => {
277 if self.statements.is_empty() {
278 self.statements.push(SemanticStatement::new(
279 predicate,
280 None,
281 self.label.clone(),
282 GraphScope::Default,
283 None,
284 None,
285 ));
286 } else {
287 for statement in &mut self.statements {
288 statement.predicate = predicate.clone();
289 }
290 }
291 }
292 None => {
293 self.statements
294 .retain(|statement| statement.recognized_sub_kind.is_some());
295 for statement in &mut self.statements {
296 if let Some(sub_kind) = statement.recognized_sub_kind {
297 statement.predicate = predicate_iri(sub_kind).to_string();
298 }
299 }
300 }
301 }
302 self.rebuild_compat();
303 }
304
305 fn rebuild_compat(&mut self) {
306 self.sub_kinds = self
307 .statements
308 .iter()
309 .filter_map(|statement| statement.recognized_sub_kind)
310 .collect();
311
312 let mut labels = self
313 .statements
314 .iter()
315 .filter_map(|statement| statement.label.clone())
316 .collect::<Vec<_>>();
317 labels.sort();
318 labels.dedup();
319 self.label = match labels.len() {
320 0 => None,
321 1 => labels.into_iter().next(),
322 _ => self
323 .statements
324 .iter()
325 .rev()
326 .find_map(|statement| statement.label.clone()),
327 };
328
329 let mut predicates = self
330 .statements
331 .iter()
332 .map(|statement| statement.predicate.clone())
333 .collect::<Vec<_>>();
334 predicates.sort();
335 predicates.dedup();
336 self.predicate = if predicates.len() == 1 {
337 predicates.into_iter().next()
338 } else {
339 None
340 };
341 }
342}
343
344pub const REL_VOCAB: &str = "https://mere.computer/ns/rel#";
349
350pub fn predicate_iri(sub_kind: SemanticSubKind) -> &'static str {
353 match sub_kind {
354 SemanticSubKind::Hyperlink => "https://mere.computer/ns/rel#hyperlink",
355 SemanticSubKind::UserGrouped => "https://mere.computer/ns/rel#user-grouped",
356 SemanticSubKind::AgentDerived => "https://mere.computer/ns/rel#agent-derived",
357 SemanticSubKind::Cites => "https://mere.computer/ns/rel#cites",
358 SemanticSubKind::Quotes => "https://mere.computer/ns/rel#quotes",
359 SemanticSubKind::Summarizes => "https://mere.computer/ns/rel#summarizes",
360 SemanticSubKind::Elaborates => "https://mere.computer/ns/rel#elaborates",
361 SemanticSubKind::ExampleOf => "https://mere.computer/ns/rel#example-of",
362 SemanticSubKind::Supports => "https://mere.computer/ns/rel#supports",
363 SemanticSubKind::Contradicts => "https://mere.computer/ns/rel#contradicts",
364 SemanticSubKind::Questions => "https://mere.computer/ns/rel#questions",
365 SemanticSubKind::SameEntityAs => "https://mere.computer/ns/rel#same-entity-as",
366 SemanticSubKind::DuplicateOf => "https://mere.computer/ns/rel#duplicate-of",
367 SemanticSubKind::CanonicalMirrorOf => "https://mere.computer/ns/rel#canonical-mirror-of",
368 SemanticSubKind::DependsOn => "https://mere.computer/ns/rel#depends-on",
369 SemanticSubKind::Blocks => "https://mere.computer/ns/rel#blocks",
370 SemanticSubKind::NextStep => "https://mere.computer/ns/rel#next-step",
371 }
372}
373
374pub fn sub_kind_from_iri(iri: &str) -> Option<SemanticSubKind> {
378 use strum::IntoEnumIterator;
379 SemanticSubKind::iter().find(|&sub_kind| predicate_iri(sub_kind) == iri)
380}
381
382pub fn all_semantic_sub_kinds() -> impl Iterator<Item = SemanticSubKind> {
387 use strum::IntoEnumIterator;
388 SemanticSubKind::iter()
389}
390
391#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
392pub struct TraversalData {
393 pub traversals: Vec<Traversal>,
394 pub metrics: EdgeMetrics,
395}
396
397impl TraversalData {
398 pub(crate) fn push(&mut self, traversal: Traversal) {
399 self.metrics.record(traversal);
400 self.traversals.push(traversal);
401 }
402}
403
404#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
405pub struct ArrangementData {
406 pub sub_kinds: BTreeSet<ArrangementSubKind>,
407}
408
409#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
410pub struct ContainmentData {
411 pub sub_kinds: BTreeSet<ContainmentSubKind>,
412}
413
414#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
415pub struct ImportedData {
416 pub sub_kinds: BTreeSet<ImportedSubKind>,
417}
418
419#[derive(Debug, Clone, PartialEq, Eq, Archive, Serialize, Deserialize, Default)]
420pub struct ProvenanceData {
421 pub sub_kinds: BTreeSet<ProvenanceSubKind>,
422}
423
424impl ContainmentData {
425 pub(crate) fn insert(&mut self, sub_kind: ContainmentSubKind) -> bool {
426 self.sub_kinds.insert(sub_kind)
427 }
428
429 pub(crate) fn remove(&mut self, sub_kind: ContainmentSubKind) -> bool {
430 self.sub_kinds.remove(&sub_kind)
431 }
432
433 pub(crate) fn contains(&self, sub_kind: ContainmentSubKind) -> bool {
434 self.sub_kinds.contains(&sub_kind)
435 }
436
437 pub(crate) fn is_empty(&self) -> bool {
438 self.sub_kinds.is_empty()
439 }
440}
441
442impl ArrangementData {
443 pub(crate) fn insert(&mut self, sub_kind: ArrangementSubKind) -> bool {
444 self.sub_kinds.insert(sub_kind)
445 }
446
447 pub(crate) fn remove(&mut self, sub_kind: ArrangementSubKind) -> bool {
448 self.sub_kinds.remove(&sub_kind)
449 }
450
451 pub(crate) fn contains(&self, sub_kind: ArrangementSubKind) -> bool {
452 self.sub_kinds.contains(&sub_kind)
453 }
454
455 pub(crate) fn is_empty(&self) -> bool {
456 self.sub_kinds.is_empty()
457 }
458
459 pub(crate) fn has_durable_relation(&self) -> bool {
460 self.sub_kinds
461 .iter()
462 .copied()
463 .any(|sub_kind| sub_kind.durability() == RelationDurability::Durable)
464 }
465
466 pub(crate) fn has_session_relation(&self) -> bool {
467 self.sub_kinds
468 .iter()
469 .copied()
470 .any(|sub_kind| sub_kind.durability() == RelationDurability::Session)
471 }
472}