Skip to main content

link_cli/engine/
reclaiming.rs

1//! Explicit epoch-fenced reclamation for separately owned immutable namespaces.
2use super::{
3    cluster::{validate_keys, AtomicJournalStore, JournalVersion},
4    error,
5    maintenance::{JournalMaintenanceStore, JournalNamespaceEntry, JournalScanOptions},
6    object_cache::ObjectCache,
7    partitioned::JournalChunkOptions,
8};
9use crate::LinkError;
10use std::collections::BTreeMap;
11mod codec;
12mod collector;
13mod objects;
14
15#[derive(Clone, Copy, Debug)]
16pub struct ReclamationOptions {
17    pub max_keys: usize,
18    pub max_bytes: usize,
19    pub page_keys: usize,
20    /// Zero retains no cache. Payload accounting matches PartitionedJournalStore.
21    pub cache_bytes: usize,
22}
23impl Default for ReclamationOptions {
24    fn default() -> Self {
25        Self {
26            max_keys: 4096,
27            max_bytes: 8_388_608,
28            page_keys: 128,
29            cache_bytes: 0,
30        }
31    }
32}
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct ReclamationResult {
35    pub epoch: u64,
36    pub examined: usize,
37    pub deleted: usize,
38}
39/// Owns the supplied provider values. Use dedicated new namespaces; blob1
40/// catalogs are incompatible. No collection or background task runs automatically.
41pub struct ReclaimingPartitionedJournalStore<C, D> {
42    catalog: C,
43    partitions: BTreeMap<String, D>,
44    route: Box<dyn Fn(&str) -> String + Send + Sync>,
45    options: ReclamationOptions,
46    cache: Option<ObjectCache>,
47    chunks: Option<JournalChunkOptions>,
48}
49struct Snapshot {
50    values: Vec<JournalVersion>,
51    pointers: Vec<Option<codec::Pointer>>,
52    root: JournalVersion,
53    epoch: u64,
54}
55enum Group {
56    Complete(Vec<JournalVersion>),
57    Missing(usize),
58}
59impl<C: JournalMaintenanceStore, D: JournalMaintenanceStore>
60    ReclaimingPartitionedJournalStore<C, D>
61{
62    pub fn open(
63        catalog: C,
64        partitions: BTreeMap<String, D>,
65        route: impl Fn(&str) -> String + Send + Sync + 'static,
66        options: ReclamationOptions,
67    ) -> Result<Self, LinkError> {
68        Self::open_configured(catalog, partitions, route, options, None)
69    }
70    /// Select bounded chunks for new writes. Existing blob2 and chunks2 roots
71    /// remain readable. Every staged chunk uses the captured catalog epoch.
72    pub fn open_chunked(
73        catalog: C,
74        partitions: BTreeMap<String, D>,
75        route: impl Fn(&str) -> String + Send + Sync + 'static,
76        options: ReclamationOptions,
77        chunks: JournalChunkOptions,
78    ) -> Result<Self, LinkError> {
79        Self::open_configured(
80            catalog,
81            partitions,
82            route,
83            options,
84            Some(chunks.validate()?),
85        )
86    }
87    fn open_configured(
88        mut catalog: C,
89        mut partitions: BTreeMap<String, D>,
90        route: impl Fn(&str) -> String + Send + Sync + 'static,
91        options: ReclamationOptions,
92        chunks: Option<JournalChunkOptions>,
93    ) -> Result<Self, LinkError> {
94        if options.max_keys == 0
95            || options.max_bytes == 0
96            || !(1..=256).contains(&options.page_keys)
97        {
98            return Err(error("invalid reclamation limits"));
99        }
100        if partitions.is_empty() {
101            return Err(error("provide named maintenance-capable data stores"));
102        }
103        for key in partitions.keys() {
104            validate_keys(std::slice::from_ref(key))?;
105        }
106        let mut entries = codec::scan(&mut catalog, options, false)?;
107        if entries.is_empty() {
108            for provider in partitions.values_mut() {
109                if !codec::scan(provider, options, true)?.is_empty() {
110                    return Err(error("initial reclamation namespaces must be empty"));
111                }
112            }
113            // Exactly one initialization attempt; an unknown result propagates.
114            catalog.compare_exchange(
115                &[codec::EPOCH_KEY.into()],
116                &[JournalVersion::default()],
117                &[Some(vec!["gc1".into(), "0".into()])],
118            )?;
119            entries = codec::scan(&mut catalog, options, false)?;
120        }
121        codec::catalog(&entries, &partitions)?;
122        Ok(Self {
123            catalog,
124            partitions,
125            route: Box::new(route),
126            options,
127            cache: (options.cache_bytes > 0).then(|| ObjectCache::new(options.cache_bytes)),
128            chunks,
129        })
130    }
131    fn snapshot(&mut self, keys: &[String]) -> Result<Snapshot, LinkError> {
132        let mut selected = keys.to_vec();
133        selected.push(codec::EPOCH_KEY.into());
134        let mut values = codec::read(&mut self.catalog, &selected)?;
135        let root = values.pop().expect("validated snapshot length");
136        let epoch = codec::epoch(&root)?;
137        let pointers = values
138            .iter()
139            .map(|value| codec::pointer(value, epoch, &self.partitions))
140            .collect::<Result<_, _>>()?;
141        Ok(Snapshot {
142            values,
143            pointers,
144            root,
145            epoch,
146        })
147    }
148    fn group(&mut self, snapshot: &Snapshot) -> Result<Group, LinkError> {
149        let mut result = Vec::new();
150        for (index, (item, pointer)) in snapshot.values.iter().zip(&snapshot.pointers).enumerate() {
151            let Some(pointer) = pointer else {
152                result.push(JournalVersion::default());
153                continue;
154            };
155            let mut entries = Vec::new();
156            for reference in &pointer.references {
157                let Some(records) = self.read_object(&pointer.partition, reference)? else {
158                    return Ok(Group::Missing(index));
159                };
160                entries.extend(records);
161            }
162            result.push(JournalVersion {
163                generation: item.generation,
164                entries,
165            });
166        }
167        Ok(Group::Complete(result))
168    }
169}
170impl<C: JournalMaintenanceStore, D: JournalMaintenanceStore> AtomicJournalStore
171    for ReclaimingPartitionedJournalStore<C, D>
172{
173    fn supports_durable_flush(&self) -> bool {
174        self.catalog.supports_durable_flush()
175            && self
176                .partitions
177                .values()
178                .all(AtomicJournalStore::supports_durable_flush)
179    }
180    fn read(&mut self, keys: &[String]) -> Result<Vec<JournalVersion>, LinkError> {
181        codec::keys(keys)?;
182        let first = self.snapshot(keys)?;
183        let missing = match self.group(&first)? {
184            Group::Complete(result) => return Ok(result),
185            Group::Missing(index) => index,
186        };
187        let fresh = self.snapshot(keys)?;
188        if first.values[missing].generation == fresh.values[missing].generation
189            || first.values[missing].entries == fresh.values[missing].entries
190        {
191            return Err(error("missing or modified referenced reclamation object"));
192        }
193        // Discard the entire first group, even already owned/cache-hit entries.
194        match self.group(&fresh)? {
195            Group::Complete(result) => Ok(result),
196            Group::Missing(_) => Err(error("reclamation object retired during bounded retry")),
197        }
198    }
199    fn compare_exchange(
200        &mut self,
201        keys: &[String],
202        expected: &[JournalVersion],
203        updates: &[Option<Vec<String>>],
204    ) -> Result<bool, LinkError> {
205        codec::keys(keys)?;
206        if expected.len() != keys.len() || updates.len() != keys.len() {
207            return Err(error("expected generations and updates must match shards"));
208        }
209        let guards: Vec<_> = expected
210            .iter()
211            .map(|item| JournalVersion {
212                generation: item.generation,
213                entries: vec![],
214            })
215            .collect();
216        let staged = keys
217            .iter()
218            .zip(updates)
219            .map(|(key, update)| {
220                update
221                    .as_ref()
222                    .map(|data| {
223                        let partition = (self.route)(key);
224                        if !self.partitions.contains_key(&partition) {
225                            return Err(error("route must select a configured partition"));
226                        }
227                        let chunks = match self.chunks {
228                            Some(options) => options
229                                .split(data)?
230                                .into_iter()
231                                .map(<[String]>::to_vec)
232                                .collect(),
233                            None => vec![data.clone()],
234                        };
235                        Ok((partition, data.len(), chunks))
236                    })
237                    .transpose()
238            })
239            .collect::<Result<Vec<_>, _>>()?;
240        let current = self.snapshot(keys)?;
241        if current
242            .values
243            .iter()
244            .zip(&guards)
245            .any(|(a, b)| a.generation != b.generation)
246        {
247            return Ok(false);
248        }
249        let mut pointers = Vec::new();
250        for item in staged {
251            let Some((partition, total, chunks)) = item else {
252                pointers.push(None);
253                continue;
254            };
255            let mut pointer = if self.chunks.is_some() {
256                vec![
257                    "chunks2".into(),
258                    partition.clone(),
259                    total.to_string(),
260                    chunks.len().to_string(),
261                ]
262            } else {
263                vec!["blob2".into(), partition.clone()]
264            };
265            for records in chunks {
266                let (key, generation) = self.stage_object(&partition, current.epoch, &records)?;
267                pointer.extend([key, generation.to_string()]);
268                if self.chunks.is_some() {
269                    pointer.push(records.len().to_string());
270                }
271            }
272            pointers.push(Some(pointer));
273        }
274        let mut selected = keys.to_vec();
275        selected.push(codec::EPOCH_KEY.into());
276        let mut guards = guards;
277        guards.push(current.root);
278        pointers.push(None);
279        self.catalog.compare_exchange(&selected, &guards, &pointers)
280    }
281}