Skip to main content

commonware_storage/archive/prunable/
storage.rs

1use super::{Config, Translator};
2use crate::{
3    archive::{Error, Identifier},
4    index::{unordered::Index, Unordered},
5    journal::segmented::oversized::{
6        Config as OversizedConfig, Oversized, Record as OversizedRecord,
7    },
8    rmap::RMap,
9};
10use commonware_codec::{CodecShared, FixedSize, Read, ReadExt, Write};
11use commonware_runtime::{
12    telemetry::metrics::{Counter, Gauge, GaugeExt, MetricsExt as _},
13    Buf, BufMut, BufferPooler, Metrics, Storage,
14};
15use commonware_utils::Array;
16use futures::{future::try_join_all, pin_mut, StreamExt};
17use std::collections::{btree_map, BTreeMap, BTreeSet};
18use tracing::debug;
19
20/// Index entry for the archive.
21#[derive(Debug, Clone, PartialEq)]
22struct Record<K: Array> {
23    /// The index for this entry.
24    index: u64,
25    /// The key for this entry.
26    key: K,
27    /// Byte offset in value journal (same section).
28    value_offset: u64,
29    /// Size of value data in the value journal.
30    value_size: u32,
31}
32
33impl<K: Array> Record<K> {
34    /// Create a new [Record].
35    const fn new(index: u64, key: K, value_offset: u64, value_size: u32) -> Self {
36        Self {
37            index,
38            key,
39            value_offset,
40            value_size,
41        }
42    }
43}
44
45impl<K: Array> Write for Record<K> {
46    fn write(&self, buf: &mut impl BufMut) {
47        self.index.write(buf);
48        self.key.write(buf);
49        self.value_offset.write(buf);
50        self.value_size.write(buf);
51    }
52}
53
54impl<K: Array> Read for Record<K> {
55    type Cfg = ();
56
57    fn read_cfg(buf: &mut impl Buf, _: &Self::Cfg) -> Result<Self, commonware_codec::Error> {
58        let index = u64::read(buf)?;
59        let key = K::read(buf)?;
60        let value_offset = u64::read(buf)?;
61        let value_size = u32::read(buf)?;
62        Ok(Self {
63            index,
64            key,
65            value_offset,
66            value_size,
67        })
68    }
69}
70
71impl<K: Array> FixedSize for Record<K> {
72    // index + key + value_offset + value_size
73    const SIZE: usize = u64::SIZE + K::SIZE + u64::SIZE + u32::SIZE;
74}
75
76impl<K: Array> OversizedRecord for Record<K> {
77    fn value_location(&self) -> (u64, u32) {
78        (self.value_offset, self.value_size)
79    }
80
81    fn with_location(mut self, offset: u64, size: u32) -> Self {
82        self.value_offset = offset;
83        self.value_size = size;
84        self
85    }
86}
87
88#[cfg(feature = "arbitrary")]
89impl<K: Array> arbitrary::Arbitrary<'_> for Record<K>
90where
91    K: for<'a> arbitrary::Arbitrary<'a>,
92{
93    fn arbitrary(u: &mut arbitrary::Unstructured<'_>) -> arbitrary::Result<Self> {
94        Ok(Self {
95            index: u64::arbitrary(u)?,
96            key: K::arbitrary(u)?,
97            value_offset: u64::arbitrary(u)?,
98            value_size: u32::arbitrary(u)?,
99        })
100    }
101}
102
103/// Implementation of `Archive` storage.
104pub struct Archive<T: Translator, E: BufferPooler + Storage + Metrics, K: Array, V: CodecShared> {
105    items_per_section: u64,
106
107    /// Combined index + value storage with crash recovery.
108    oversized: Oversized<E, Record<K>, V>,
109
110    pending: BTreeSet<u64>,
111
112    /// Oldest allowed section to read from. Updated when `prune` is called.
113    oldest_allowed: Option<u64>,
114
115    /// Maps translated key representation to its corresponding index.
116    keys: Index<T, u64>,
117
118    /// Maps index to its first position in the index journal.
119    indices: BTreeMap<u64, u64>,
120
121    /// Additional positions for indices that have more than one entry.
122    /// Only populated when used via [crate::archive::MultiArchive::put_multi].
123    extra_indices: BTreeMap<u64, Vec<u64>>,
124
125    /// Interval tracking for gap detection.
126    intervals: RMap,
127
128    // Metrics
129    items_tracked: Gauge,
130    indices_pruned: Counter,
131    unnecessary_reads: Counter,
132    gets: Counter,
133    has: Counter,
134    syncs: Counter,
135}
136
137impl<T: Translator, E: BufferPooler + Storage + Metrics, K: Array, V: CodecShared>
138    Archive<T, E, K, V>
139{
140    /// Calculate the section for a given index.
141    const fn section(&self, index: u64) -> u64 {
142        (index / self.items_per_section) * self.items_per_section
143    }
144
145    /// Iterate over all positions for a given index (first + extras).
146    fn iter_positions(&self, index: u64) -> impl Iterator<Item = u64> + '_ {
147        self.indices.get(&index).into_iter().copied().chain(
148            self.extra_indices
149                .get(&index)
150                .into_iter()
151                .flat_map(|v| v.iter().copied()),
152        )
153    }
154
155    /// Initialize a new `Archive` instance.
156    ///
157    /// The in-memory index for `Archive` is populated during this call
158    /// by replaying only the index journal (no values are read).
159    pub async fn init(context: E, cfg: Config<T, V::Cfg>) -> Result<Self, Error> {
160        // Initialize oversized journal
161        let oversized_cfg = OversizedConfig {
162            index_partition: cfg.key_partition,
163            value_partition: cfg.value_partition,
164            index_page_cache: cfg.key_page_cache,
165            index_write_buffer: cfg.key_write_buffer,
166            value_write_buffer: cfg.value_write_buffer,
167            compression: cfg.compression,
168            codec_config: cfg.codec_config,
169        };
170        let oversized: Oversized<E, Record<K>, V> =
171            Oversized::init(context.child("oversized"), oversized_cfg).await?;
172
173        // Initialize keys and replay index journal (no values read!)
174        let mut indices: BTreeMap<u64, u64> = BTreeMap::new();
175        let mut extra_indices: BTreeMap<u64, Vec<u64>> = BTreeMap::new();
176        let mut keys = Index::new(context.child("index"), cfg.translator.clone());
177        let mut intervals = RMap::new();
178        {
179            debug!("initializing archive from index journal");
180            let stream = oversized.replay(0, 0, cfg.replay_buffer).await?;
181            pin_mut!(stream);
182            while let Some(result) = stream.next().await {
183                let (_section, position, entry) = result?;
184
185                // Store index location (position in index journal)
186                match indices.entry(entry.index) {
187                    btree_map::Entry::Vacant(e) => {
188                        e.insert(position);
189                    }
190                    btree_map::Entry::Occupied(_) => {
191                        extra_indices.entry(entry.index).or_default().push(position);
192                    }
193                }
194
195                // Store index in keys
196                keys.insert(&entry.key, entry.index);
197
198                // Store index in intervals
199                intervals.insert(entry.index);
200            }
201            debug!("archive initialized");
202        }
203
204        // Initialize metrics
205        let items_tracked = context.gauge("items_tracked", "Number of items tracked");
206        let indices_pruned = context.counter("indices_pruned", "Number of indices pruned");
207        let unnecessary_reads = context.counter(
208            "unnecessary_reads",
209            "Number of unnecessary reads performed during key lookups",
210        );
211        let gets = context.counter("gets", "Number of gets performed");
212        let has = context.counter("has", "Number of has performed");
213        let syncs = context.counter("syncs", "Number of syncs called");
214        let _ = items_tracked.try_set(indices.len());
215
216        // Return populated archive
217        Ok(Self {
218            items_per_section: cfg.items_per_section.get(),
219            oversized,
220            pending: BTreeSet::new(),
221            oldest_allowed: None,
222            indices,
223            extra_indices,
224            intervals,
225            keys,
226            items_tracked,
227            indices_pruned,
228            unnecessary_reads,
229            gets,
230            has,
231            syncs,
232        })
233    }
234
235    async fn get_index(&self, index: u64) -> Result<Option<V>, Error> {
236        // Update metrics
237        self.gets.inc();
238
239        // Get first position at this index
240        let position = match self.indices.get(&index) {
241            Some(&position) => position,
242            None => return Ok(None),
243        };
244
245        // Fetch index entry to get value location
246        let section = self.section(index);
247        let entry = self.oversized.get(section, position).await?;
248        let (value_offset, value_size) = entry.value_location();
249
250        // Fetch value directly from blob storage (bypasses page cache)
251        let value = self
252            .oversized
253            .get_value(section, value_offset, value_size)
254            .await?;
255        Ok(Some(value))
256    }
257
258    async fn get_key(&self, key: &K) -> Result<Option<V>, Error> {
259        // Update metrics
260        self.gets.inc();
261
262        // Fetch index
263        let iter = self.keys.get(key);
264        let min_allowed = self.oldest_allowed.unwrap_or(0);
265        for index in iter {
266            // Continue if index is no longer allowed due to pruning.
267            if *index < min_allowed {
268                continue;
269            }
270
271            // Get all positions at this index
272            if !self.indices.contains_key(index) {
273                return Err(Error::RecordCorrupted);
274            }
275            let section = self.section(*index);
276
277            for position in self.iter_positions(*index) {
278                // Fetch index entry from index journal to verify key
279                let entry = self.oversized.get(section, position).await?;
280
281                // Verify key matches
282                if entry.key.as_ref() == key.as_ref() {
283                    // Fetch value directly from blob storage (bypasses page cache)
284                    let (value_offset, value_size) = entry.value_location();
285                    let value = self
286                        .oversized
287                        .get_value(section, value_offset, value_size)
288                        .await?;
289                    return Ok(Some(value));
290                }
291                self.unnecessary_reads.inc();
292            }
293        }
294
295        Ok(None)
296    }
297
298    fn has_index(&self, index: u64) -> bool {
299        // Check if index exists
300        self.indices.contains_key(&index)
301    }
302
303    async fn put_internal(
304        &mut self,
305        index: u64,
306        key: K,
307        data: V,
308        skip_if_index_exists: bool,
309    ) -> Result<(), Error> {
310        // Check last pruned
311        let oldest_allowed = self.oldest_allowed.unwrap_or(0);
312        if index < oldest_allowed {
313            return Err(Error::AlreadyPrunedTo(oldest_allowed));
314        }
315
316        // Check for existing index when enforcing single-item semantics.
317        if skip_if_index_exists && self.indices.contains_key(&index) {
318            return Ok(());
319        }
320
321        // Write value and index entry atomically (glob first, then index)
322        let section = self.section(index);
323        let entry = Record::new(index, key.clone(), 0, 0);
324        let (position, _, _) = self.oversized.append(section, entry, &data).await?;
325
326        // Store index location
327        match self.indices.entry(index) {
328            btree_map::Entry::Vacant(e) => {
329                e.insert(position);
330            }
331            btree_map::Entry::Occupied(_) => {
332                self.extra_indices.entry(index).or_default().push(position);
333            }
334        }
335
336        // Store interval
337        self.intervals.insert(index);
338
339        // Insert and prune any useless keys
340        self.keys
341            .insert_and_retain(&key, index, |v| *v >= oldest_allowed);
342
343        // Add section to pending
344        self.pending.insert(section);
345
346        // Update metrics
347        let _ = self.items_tracked.try_set(self.indices.len());
348        Ok(())
349    }
350
351    /// Prune `Archive` to the provided `min` (masked by the configured
352    /// section mask).
353    ///
354    /// If this is called with a min lower than the last pruned, nothing
355    /// will happen.
356    pub async fn prune(&mut self, min: u64) -> Result<(), Error> {
357        // Update `min` to reflect section mask
358        let min = self.section(min);
359
360        // Check if min is less than last pruned
361        if let Some(oldest_allowed) = self.oldest_allowed {
362            if min <= oldest_allowed {
363                // We don't return an error in this case because the caller
364                // shouldn't be burdened with converting `min` to some section.
365                return Ok(());
366            }
367        }
368        debug!(min, "pruning archive");
369
370        // Prune oversized journal (handles both index and values)
371        self.oversized.prune(min).await?;
372
373        // Remove pending writes (no need to call `sync` as we are pruning)
374        loop {
375            let next = match self.pending.iter().next() {
376                Some(section) if *section < min => *section,
377                _ => break,
378            };
379            self.pending.remove(&next);
380        }
381
382        // Remove all indices that are less than min
383        loop {
384            let next = match self.indices.first_key_value() {
385                Some((index, _)) if *index < min => *index,
386                _ => break,
387            };
388            self.indices.remove(&next).unwrap();
389            self.extra_indices.remove(&next);
390            self.indices_pruned.inc();
391        }
392
393        // Remove all keys from interval tree less than min
394        if min > 0 {
395            self.intervals.remove(0, min - 1);
396        }
397
398        // Update last pruned (to prevent reads from pruned sections)
399        self.oldest_allowed = Some(min);
400        let _ = self.items_tracked.try_set(self.indices.len());
401        Ok(())
402    }
403}
404
405impl<T: Translator, E: BufferPooler + Storage + Metrics, K: Array, V: CodecShared>
406    crate::archive::Archive for Archive<T, E, K, V>
407{
408    type Key = K;
409    type Value = V;
410
411    async fn put(&mut self, index: u64, key: K, data: V) -> Result<(), Error> {
412        self.put_internal(index, key, data, true).await
413    }
414
415    async fn get(&self, identifier: Identifier<'_, K>) -> Result<Option<V>, Error> {
416        match identifier {
417            Identifier::Index(index) => self.get_index(index).await,
418            Identifier::Key(key) => self.get_key(key).await,
419        }
420    }
421
422    async fn has(&self, identifier: Identifier<'_, K>) -> Result<bool, Error> {
423        self.has.inc();
424        match identifier {
425            Identifier::Index(index) => Ok(self.has_index(index)),
426            Identifier::Key(key) => self.get_key(key).await.map(|result| result.is_some()),
427        }
428    }
429
430    async fn sync(&mut self) -> Result<(), Error> {
431        // Collect pending sections and update metrics
432        let pending: Vec<u64> = self.pending.iter().copied().collect();
433        self.syncs.inc_by(pending.len() as u64);
434
435        // Sync oversized journal (handles both index and values)
436        let syncs: Vec<_> = pending.iter().map(|s| self.oversized.sync(*s)).collect();
437        try_join_all(syncs).await?;
438
439        self.pending.clear();
440        Ok(())
441    }
442
443    fn next_gap(&self, index: u64) -> (Option<u64>, Option<u64>) {
444        self.intervals.next_gap(index)
445    }
446
447    fn missing_items(&self, index: u64, max: usize) -> Vec<u64> {
448        self.intervals.missing_items(index, max)
449    }
450
451    fn ranges(&self) -> impl Iterator<Item = (u64, u64)> {
452        self.intervals.iter().map(|(&s, &e)| (s, e))
453    }
454
455    fn ranges_from(&self, from: u64) -> impl Iterator<Item = (u64, u64)> {
456        self.intervals.iter_from(from).map(|(&s, &e)| (s, e))
457    }
458
459    fn first_index(&self) -> Option<u64> {
460        self.intervals.first_index()
461    }
462
463    fn last_index(&self) -> Option<u64> {
464        self.intervals.last_index()
465    }
466
467    async fn destroy(self) -> Result<(), Error> {
468        Ok(self.oversized.destroy().await?)
469    }
470}
471
472impl<T: Translator, E: BufferPooler + Storage + Metrics, K: Array, V: CodecShared>
473    crate::archive::MultiArchive for Archive<T, E, K, V>
474{
475    async fn get_all(&self, index: u64) -> Result<Option<Vec<V>>, Error> {
476        // Update metrics
477        self.gets.inc();
478
479        // Check if the index exists.
480        if !self.indices.contains_key(&index) {
481            return Ok(None);
482        }
483
484        // Get all positions at this index
485        let section = self.section(index);
486        let extra_count = self.extra_indices.get(&index).map_or(0, Vec::len);
487
488        let mut values = Vec::with_capacity(1 + extra_count);
489        for position in self.iter_positions(index) {
490            // Fetch index entry from index journal to verify key
491            let entry = self.oversized.get(section, position).await?;
492
493            // Fetch value directly from blob storage (bypasses page cache)
494            let (value_offset, value_size) = entry.value_location();
495            let value = self
496                .oversized
497                .get_value(section, value_offset, value_size)
498                .await?;
499            values.push(value);
500        }
501        Ok(Some(values))
502    }
503
504    async fn put_multi(&mut self, index: u64, key: K, data: V) -> Result<(), Error> {
505        self.put_internal(index, key, data, false).await
506    }
507}
508
509#[cfg(all(test, feature = "arbitrary"))]
510mod conformance {
511    use super::*;
512    use commonware_codec::conformance::CodecConformance;
513    use commonware_utils::sequence::U64;
514
515    commonware_conformance::conformance_tests! {
516        CodecConformance<Record<U64>>
517    }
518}