weavatrix_memory/projection/memory/
mod.rs1mod apply;
2pub(crate) mod index;
3mod parts;
4mod retraction;
5pub(crate) mod state;
6
7use crate::{
8 domain::{MemoryFact, MemoryNode, MemoryView, MemoryViewRef},
9 error::{MemoryError, Result},
10 id::{EntityId, FactId},
11 time::Timestamp,
12};
13use serde::{Deserialize, Serialize};
14use state::{NodeHistory, NodeRevision, Supersession};
15use std::collections::HashSet;
16
17pub use state::MemoryProjection;
18
19#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
20pub struct ProjectionClock {
21 pub valid_at: Timestamp,
22 pub known_at: Timestamp,
23}
24
25impl ProjectionClock {
26 #[must_use]
27 pub const fn new(valid_at: Timestamp, known_at: Timestamp) -> Self {
28 Self { valid_at, known_at }
29 }
30}
31
32impl MemoryProjection {
33 #[must_use]
34 pub const fn last_global_position(&self) -> Option<u64> {
35 self.last_global_position
36 }
37
38 #[must_use]
39 pub fn superseded_by(&self, fact: &FactId) -> Option<&FactId> {
40 self.supersessions
41 .get(fact)
42 .map(|change| &change.replacement)
43 }
44
45 pub(crate) fn visible_node(&self, id: &EntityId, known_at: Timestamp) -> Option<&MemoryNode> {
46 self.node_lookup
47 .get(id)
48 .and_then(|index| visible_revision(&self.nodes[*index], known_at))
49 }
50
51 pub(crate) fn fact(&self, id: &FactId) -> Option<&MemoryFact> {
52 self.fact_lookup.get(id).map(|index| &self.facts[*index])
53 }
54
55 pub(crate) fn all_facts(&self) -> &[MemoryFact] {
56 &self.facts
57 }
58
59 pub(crate) fn incident_fact_ids(&self, id: &EntityId) -> impl Iterator<Item = &FactId> + '_ {
60 self.node_lookup
61 .get(id)
62 .into_iter()
63 .flat_map(|index| {
64 let stable = &self.incident_facts
65 [self.incident_offsets[*index]..self.incident_offsets[*index + 1]];
66 stable
67 .iter()
68 .chain(self.incident_delta.get(index).into_iter().flatten())
69 })
70 .map(|index| &self.facts[*index].id)
71 }
72
73 #[must_use]
74 pub fn view(&self, clock: ProjectionClock) -> MemoryView {
75 self.view_ref(clock).into_owned()
76 }
77
78 #[must_use]
83 pub fn view_ref(&self, clock: ProjectionClock) -> MemoryViewRef<'_> {
84 let nodes = self
85 .nodes
86 .iter()
87 .filter_map(|revisions| visible_revision(revisions, clock.known_at))
88 .collect::<Vec<_>>();
89 let visible_ids = (nodes.len() != self.nodes.len()).then(|| {
90 nodes
91 .iter()
92 .map(|node| node.id.clone())
93 .collect::<HashSet<_>>()
94 });
95 let facts = self
96 .facts
97 .iter()
98 .filter(|fact| {
99 visible_ids.as_ref().is_none_or(|visible| {
100 visible.contains(&fact.source) && visible.contains(&fact.target)
101 }) && self.fact_is_active(fact, clock)
102 })
103 .collect();
104 MemoryViewRef { nodes, facts }
105 }
106
107 pub(crate) fn fact_is_active(&self, fact: &MemoryFact, clock: ProjectionClock) -> bool {
108 if fact.recorded_at > clock.known_at || fact.valid_from > clock.valid_at {
109 return false;
110 }
111 if fact
112 .valid_until
113 .is_some_and(|until| clock.valid_at >= until)
114 {
115 return false;
116 }
117 if self.supersessions.get(&fact.id).is_some_and(|change| {
118 change.recorded_at <= clock.known_at && change.valid_from <= clock.valid_at
119 }) {
120 return false;
121 }
122 self.known_retraction(&fact.id, clock.known_at)
123 .is_none_or(|change| change.valid_until > clock.valid_at)
124 }
125
126 fn insert_node(&mut self, revision: NodeRevision) -> Result<()> {
127 revision.node.validate()?;
128 if let Some(index) = self.node_lookup.get(&revision.node.id).copied() {
129 self.nodes[index].later.push(revision);
130 } else {
131 let index = self.nodes.len();
132 self.node_lookup.insert(revision.node.id.clone(), index);
133 self.nodes.push(NodeHistory::new(revision));
134 let offset = *self.incident_offsets.last().unwrap_or(&0);
135 self.incident_offsets.push(offset);
136 }
137 Ok(())
138 }
139
140 fn insert_fact(&mut self, fact: MemoryFact) -> Result<()> {
141 fact.validate()?;
142 let source = self.require_entity(&fact.source)?;
143 let target = self.require_entity(&fact.target)?;
144 if self.fact_lookup.contains_key(&fact.id) {
145 return Err(MemoryError::ConflictingFact {
146 id: fact.id.to_string(),
147 });
148 }
149 if let Some(prior) = &fact.supersedes {
150 self.apply_supersession(prior, &fact)?;
151 }
152 let index = self.facts.len();
153 self.fact_lookup.insert(fact.id.clone(), index);
154 self.incident_delta.entry(source).or_default().push(index);
155 if target != source {
156 self.incident_delta.entry(target).or_default().push(index);
157 }
158 self.facts.push(fact);
159 Ok(())
160 }
161
162 fn apply_supersession(&mut self, prior: &FactId, fact: &MemoryFact) -> Result<()> {
163 if !self.fact_lookup.contains_key(prior) {
164 return Err(MemoryError::MissingFact {
165 id: prior.to_string(),
166 });
167 }
168 if self.supersessions.contains_key(prior) {
169 return Err(MemoryError::ConflictingFact {
170 id: prior.to_string(),
171 });
172 }
173 self.supersessions.insert(
174 prior.clone(),
175 Supersession {
176 replacement: fact.id.clone(),
177 valid_from: fact.valid_from,
178 recorded_at: fact.recorded_at,
179 },
180 );
181 Ok(())
182 }
183
184 fn require_entity(&self, id: &EntityId) -> Result<usize> {
185 self.node_lookup
186 .get(id)
187 .copied()
188 .ok_or_else(|| MemoryError::MissingEntity { id: id.to_string() })
189 }
190}
191
192fn visible_revision(history: &NodeHistory, known_at: Timestamp) -> Option<&MemoryNode> {
193 core::iter::once(&history.first)
194 .chain(&history.later)
195 .filter(|revision| revision.recorded_at <= known_at)
196 .max_by_key(|revision| (revision.recorded_at, revision.position))
197 .map(|revision| &revision.node)
198}