1use std::collections::BTreeMap;
16use std::sync::{Mutex, PoisonError};
17
18use crate::ReplicaError;
19
20#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct CollectionRecord {
23 pub epoch: String,
25 pub version: u64,
27 pub floor: u64,
30 pub dirty: bool,
32 pub rotated_at: u64,
34 pub reconciled_at: u64,
39 pub rotate_owed: bool,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
49pub struct LedgerEntry {
50 pub key: String,
52 pub digest: String,
55 pub version: u64,
57 pub deleted: bool,
59 pub changed_at: u64,
61}
62
63#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
65pub struct Pruned {
66 pub highest: Option<u64>,
68 pub over_keep: bool,
71}
72
73pub trait LedgerTx {
76 fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError>;
78 fn put_record(
80 &mut self,
81 collection: &str,
82 record: &CollectionRecord,
83 ) -> Result<(), ReplicaError>;
84 fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError>;
86 fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError>;
88 fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError>;
90 fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError>;
92 fn changes_after(
95 &mut self,
96 collection: &str,
97 version: u64,
98 limit: usize,
99 ) -> Result<Vec<LedgerEntry>, ReplicaError>;
100 fn live_after(
103 &mut self,
104 collection: &str,
105 after: Option<&str>,
106 limit: usize,
107 ) -> Result<Vec<LedgerEntry>, ReplicaError>;
108 fn prune_tombstones(
112 &mut self,
113 collection: &str,
114 changed_before: u64,
115 keep: u64,
116 ) -> Result<Pruned, ReplicaError>;
117}
118
119pub trait LedgerStore {
124 fn ensure(&self, prefix: &str) -> Result<(), ReplicaError>;
126
127 fn write(
131 &self,
132 prefix: &str,
133 work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
134 ) -> Result<(), ReplicaError>;
135
136 fn read_record(
141 &self,
142 prefix: &str,
143 collection: &str,
144 ) -> Result<Option<CollectionRecord>, ReplicaError> {
145 let mut out = None;
146 self.write(prefix, &mut |tx| {
147 out = tx.record(collection)?;
148 Ok(())
149 })?;
150 Ok(out)
151 }
152}
153
154#[derive(Debug, Clone, Default)]
156struct MemoryCollection {
157 record: Option<CollectionRecord>,
158 entries: BTreeMap<String, LedgerEntry>,
159}
160
161type MemoryTables = BTreeMap<(String, String), MemoryCollection>;
162
163#[derive(Debug, Default)]
165pub struct MemoryLedger {
166 tables: Mutex<MemoryTables>,
167}
168
169impl MemoryLedger {
170 pub fn new() -> Self {
172 Self::default()
173 }
174}
175
176impl Clone for MemoryLedger {
177 fn clone(&self) -> Self {
178 let tables = self
181 .tables
182 .lock()
183 .unwrap_or_else(PoisonError::into_inner)
184 .clone();
185 Self {
186 tables: Mutex::new(tables),
187 }
188 }
189}
190
191impl LedgerStore for MemoryLedger {
192 fn ensure(&self, _prefix: &str) -> Result<(), ReplicaError> {
193 Ok(())
194 }
195
196 fn write(
197 &self,
198 prefix: &str,
199 work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
200 ) -> Result<(), ReplicaError> {
201 let mut guard = self.tables.lock().unwrap_or_else(PoisonError::into_inner);
202 let mut copy = guard.clone();
203 let mut tx = MemoryTx {
204 prefix,
205 tables: &mut copy,
206 };
207 work(&mut tx)?;
208 *guard = copy;
209 Ok(())
210 }
211
212 fn read_record(
213 &self,
214 prefix: &str,
215 collection: &str,
216 ) -> Result<Option<CollectionRecord>, ReplicaError> {
217 let guard = self.tables.lock().unwrap_or_else(PoisonError::into_inner);
219 Ok(guard
220 .get(&(prefix.to_string(), collection.to_string()))
221 .and_then(|c| c.record.clone()))
222 }
223}
224
225struct MemoryTx<'a> {
226 prefix: &'a str,
227 tables: &'a mut MemoryTables,
228}
229
230impl MemoryTx<'_> {
231 fn get(&self, collection: &str) -> Option<&MemoryCollection> {
232 self.tables
233 .get(&(self.prefix.to_string(), collection.to_string()))
234 }
235
236 fn get_mut(&mut self, collection: &str) -> &mut MemoryCollection {
237 self.tables
238 .entry((self.prefix.to_string(), collection.to_string()))
239 .or_default()
240 }
241}
242
243impl LedgerTx for MemoryTx<'_> {
244 fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError> {
245 Ok(self.get(collection).and_then(|c| c.record.clone()))
246 }
247
248 fn put_record(
249 &mut self,
250 collection: &str,
251 record: &CollectionRecord,
252 ) -> Result<(), ReplicaError> {
253 self.get_mut(collection).record = Some(record.clone());
254 Ok(())
255 }
256
257 fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError> {
258 Ok(self
259 .get(collection)
260 .and_then(|c| c.entries.get(key).cloned()))
261 }
262
263 fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError> {
264 Ok(self
265 .get(collection)
266 .map(|c| c.entries.values().cloned().collect())
267 .unwrap_or_default())
268 }
269
270 fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError> {
271 self.get_mut(collection)
272 .entries
273 .insert(entry.key.clone(), entry.clone());
274 Ok(())
275 }
276
277 fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError> {
278 self.get_mut(collection).entries.remove(key);
279 Ok(())
280 }
281
282 fn changes_after(
283 &mut self,
284 collection: &str,
285 version: u64,
286 limit: usize,
287 ) -> Result<Vec<LedgerEntry>, ReplicaError> {
288 let mut changed: Vec<LedgerEntry> = self
289 .get(collection)
290 .map(|c| {
291 c.entries
292 .values()
293 .filter(|e| e.version > version)
294 .cloned()
295 .collect()
296 })
297 .unwrap_or_default();
298 changed.sort_by_key(|e| e.version);
299 changed.truncate(limit);
300 Ok(changed)
301 }
302
303 fn live_after(
304 &mut self,
305 collection: &str,
306 after: Option<&str>,
307 limit: usize,
308 ) -> Result<Vec<LedgerEntry>, ReplicaError> {
309 Ok(self
310 .get(collection)
311 .map(|c| {
312 c.entries
313 .values()
314 .filter(|e| !e.deleted && after.map_or(true, |a| e.key.as_str() > a))
315 .take(limit)
316 .cloned()
317 .collect()
318 })
319 .unwrap_or_default())
320 }
321
322 fn prune_tombstones(
323 &mut self,
324 collection: &str,
325 changed_before: u64,
326 keep: u64,
327 ) -> Result<Pruned, ReplicaError> {
328 let entries = &mut self.get_mut(collection).entries;
329 let mut tombstones: Vec<(u64, u64, String)> = entries
330 .values()
331 .filter(|e| e.deleted)
332 .map(|e| (e.version, e.changed_at, e.key.clone()))
333 .collect();
334 tombstones.sort();
335 let excess = (tombstones.len() as u64).saturating_sub(keep);
336 let mut highest = None;
337 let mut remaining = 0;
338 for (index, (version, changed_at, key)) in tombstones.into_iter().enumerate() {
339 if (index as u64) < excess || changed_at < changed_before {
340 entries.remove(&key);
341 highest = highest.max(Some(version));
342 } else {
343 remaining += 1;
344 }
345 }
346 Ok(Pruned {
347 highest,
348 over_keep: remaining > keep,
349 })
350 }
351}