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,
36 pub rotate_owed: bool,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct LedgerEntry {
47 pub key: String,
49 pub digest: String,
52 pub version: u64,
54 pub deleted: bool,
56 pub changed_at: u64,
58}
59
60#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub struct Pruned {
63 pub highest: Option<u64>,
65 pub over_keep: bool,
68}
69
70pub trait LedgerTx {
73 fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError>;
75 fn put_record(
77 &mut self,
78 collection: &str,
79 record: &CollectionRecord,
80 ) -> Result<(), ReplicaError>;
81 fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError>;
83 fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError>;
85 fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError>;
87 fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError>;
89 fn changes_after(
92 &mut self,
93 collection: &str,
94 version: u64,
95 limit: usize,
96 ) -> Result<Vec<LedgerEntry>, ReplicaError>;
97 fn live_after(
100 &mut self,
101 collection: &str,
102 after: Option<&str>,
103 limit: usize,
104 ) -> Result<Vec<LedgerEntry>, ReplicaError>;
105 fn prune_tombstones(
109 &mut self,
110 collection: &str,
111 changed_before: u64,
112 keep: u64,
113 ) -> Result<Pruned, ReplicaError>;
114}
115
116pub trait LedgerStore {
121 fn ensure(&self, prefix: &str) -> Result<(), ReplicaError>;
123
124 fn write(
128 &self,
129 prefix: &str,
130 work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
131 ) -> Result<(), ReplicaError>;
132
133 fn read_record(
138 &self,
139 prefix: &str,
140 collection: &str,
141 ) -> Result<Option<CollectionRecord>, ReplicaError> {
142 let mut out = None;
143 self.write(prefix, &mut |tx| {
144 out = tx.record(collection)?;
145 Ok(())
146 })?;
147 Ok(out)
148 }
149}
150
151#[derive(Debug, Clone, Default)]
153struct MemoryCollection {
154 record: Option<CollectionRecord>,
155 entries: BTreeMap<String, LedgerEntry>,
156}
157
158type MemoryTables = BTreeMap<(String, String), MemoryCollection>;
159
160#[derive(Debug, Default)]
162pub struct MemoryLedger {
163 tables: Mutex<MemoryTables>,
164}
165
166impl MemoryLedger {
167 pub fn new() -> Self {
169 Self::default()
170 }
171}
172
173impl Clone for MemoryLedger {
174 fn clone(&self) -> Self {
175 let tables = self
178 .tables
179 .lock()
180 .unwrap_or_else(PoisonError::into_inner)
181 .clone();
182 Self {
183 tables: Mutex::new(tables),
184 }
185 }
186}
187
188impl LedgerStore for MemoryLedger {
189 fn ensure(&self, _prefix: &str) -> Result<(), ReplicaError> {
190 Ok(())
191 }
192
193 fn write(
194 &self,
195 prefix: &str,
196 work: &mut dyn FnMut(&mut dyn LedgerTx) -> Result<(), ReplicaError>,
197 ) -> Result<(), ReplicaError> {
198 let mut guard = self.tables.lock().unwrap_or_else(PoisonError::into_inner);
199 let mut copy = guard.clone();
200 let mut tx = MemoryTx {
201 prefix,
202 tables: &mut copy,
203 };
204 work(&mut tx)?;
205 *guard = copy;
206 Ok(())
207 }
208
209 fn read_record(
210 &self,
211 prefix: &str,
212 collection: &str,
213 ) -> Result<Option<CollectionRecord>, ReplicaError> {
214 let guard = self.tables.lock().unwrap_or_else(PoisonError::into_inner);
216 Ok(guard
217 .get(&(prefix.to_string(), collection.to_string()))
218 .and_then(|c| c.record.clone()))
219 }
220}
221
222struct MemoryTx<'a> {
223 prefix: &'a str,
224 tables: &'a mut MemoryTables,
225}
226
227impl MemoryTx<'_> {
228 fn get(&self, collection: &str) -> Option<&MemoryCollection> {
229 self.tables
230 .get(&(self.prefix.to_string(), collection.to_string()))
231 }
232
233 fn get_mut(&mut self, collection: &str) -> &mut MemoryCollection {
234 self.tables
235 .entry((self.prefix.to_string(), collection.to_string()))
236 .or_default()
237 }
238}
239
240impl LedgerTx for MemoryTx<'_> {
241 fn record(&mut self, collection: &str) -> Result<Option<CollectionRecord>, ReplicaError> {
242 Ok(self.get(collection).and_then(|c| c.record.clone()))
243 }
244
245 fn put_record(
246 &mut self,
247 collection: &str,
248 record: &CollectionRecord,
249 ) -> Result<(), ReplicaError> {
250 self.get_mut(collection).record = Some(record.clone());
251 Ok(())
252 }
253
254 fn entry(&mut self, collection: &str, key: &str) -> Result<Option<LedgerEntry>, ReplicaError> {
255 Ok(self
256 .get(collection)
257 .and_then(|c| c.entries.get(key).cloned()))
258 }
259
260 fn entries(&mut self, collection: &str) -> Result<Vec<LedgerEntry>, ReplicaError> {
261 Ok(self
262 .get(collection)
263 .map(|c| c.entries.values().cloned().collect())
264 .unwrap_or_default())
265 }
266
267 fn put_entry(&mut self, collection: &str, entry: &LedgerEntry) -> Result<(), ReplicaError> {
268 self.get_mut(collection)
269 .entries
270 .insert(entry.key.clone(), entry.clone());
271 Ok(())
272 }
273
274 fn delete_entry(&mut self, collection: &str, key: &str) -> Result<(), ReplicaError> {
275 self.get_mut(collection).entries.remove(key);
276 Ok(())
277 }
278
279 fn changes_after(
280 &mut self,
281 collection: &str,
282 version: u64,
283 limit: usize,
284 ) -> Result<Vec<LedgerEntry>, ReplicaError> {
285 let mut changed: Vec<LedgerEntry> = self
286 .get(collection)
287 .map(|c| {
288 c.entries
289 .values()
290 .filter(|e| e.version > version)
291 .cloned()
292 .collect()
293 })
294 .unwrap_or_default();
295 changed.sort_by_key(|e| e.version);
296 changed.truncate(limit);
297 Ok(changed)
298 }
299
300 fn live_after(
301 &mut self,
302 collection: &str,
303 after: Option<&str>,
304 limit: usize,
305 ) -> Result<Vec<LedgerEntry>, ReplicaError> {
306 Ok(self
307 .get(collection)
308 .map(|c| {
309 c.entries
310 .values()
311 .filter(|e| !e.deleted && after.map_or(true, |a| e.key.as_str() > a))
312 .take(limit)
313 .cloned()
314 .collect()
315 })
316 .unwrap_or_default())
317 }
318
319 fn prune_tombstones(
320 &mut self,
321 collection: &str,
322 changed_before: u64,
323 keep: u64,
324 ) -> Result<Pruned, ReplicaError> {
325 let entries = &mut self.get_mut(collection).entries;
326 let mut tombstones: Vec<(u64, u64, String)> = entries
327 .values()
328 .filter(|e| e.deleted)
329 .map(|e| (e.version, e.changed_at, e.key.clone()))
330 .collect();
331 tombstones.sort();
332 let excess = (tombstones.len() as u64).saturating_sub(keep);
333 let mut highest = None;
334 let mut remaining = 0;
335 for (index, (version, changed_at, key)) in tombstones.into_iter().enumerate() {
336 if (index as u64) < excess || changed_at < changed_before {
337 entries.remove(&key);
338 highest = highest.max(Some(version));
339 } else {
340 remaining += 1;
341 }
342 }
343 Ok(Pruned {
344 highest,
345 over_keep: remaining > keep,
346 })
347 }
348}