Skip to main content

link_cli/engine/
partitioned.rs

1//! Immutable journal objects on independent data stores; only small pointers
2//! participate in the catalog's atomic transaction. Never mutate/delete objects.
3use super::{
4    cluster::{validate_keys, AtomicJournalStore, JournalVersion},
5    error,
6};
7use crate::LinkError;
8use std::collections::BTreeMap;
9#[path = "partitioned/chunks.rs"]
10pub(crate) mod chunks;
11pub use chunks::JournalChunkOptions;
12
13pub struct PartitionedJournalStore<C, D> {
14    catalog: C,
15    partitions: BTreeMap<String, D>,
16    route: Box<dyn Fn(&str) -> String + Send + Sync>,
17    cache: Option<super::object_cache::ObjectCache>,
18    chunks: Option<JournalChunkOptions>,
19}
20impl<C: AtomicJournalStore, D: AtomicJournalStore> PartitionedJournalStore<C, D> {
21    pub fn new(
22        catalog: C,
23        partitions: BTreeMap<String, D>,
24        route: impl Fn(&str) -> String + Send + Sync + 'static,
25    ) -> Result<Self, LinkError> {
26        if partitions.is_empty() {
27            return Err(error("provide named atomic data stores"));
28        }
29        for key in partitions.keys() {
30            validate_keys(std::slice::from_ref(key))?;
31        }
32        Ok(Self {
33            catalog,
34            partitions,
35            route: Box::new(route),
36            cache: None,
37            chunks: None,
38        })
39    }
40
41    /// Cache verified immutable objects within a UTF-8 payload budget. Zero
42    /// disables caching. Catalog reads and publication checks always stay fresh.
43    /// Budget counts one byte per object/record plus record UTF-8 byte lengths;
44    /// keys, containers, and caller-owned returned copies are additional memory.
45    pub fn with_object_cache(mut self, bytes: usize) -> Self {
46        self.cache = (bytes > 0).then(|| super::object_cache::ObjectCache::new(bytes));
47        self
48    }
49    /// Select bounded immutable chunks for new writes. Upgraded readers accept
50    /// both layouts. Staging still reads and compares every selected object.
51    pub fn with_chunks(mut self, options: JournalChunkOptions) -> Result<Self, LinkError> {
52        self.chunks = Some(options.validate()?);
53        Ok(self)
54    }
55    fn read_object(
56        &mut self,
57        partition: &str,
58        reference: &chunks::Reference,
59    ) -> Result<Vec<String>, LinkError> {
60        if let Some(entries) = self
61            .cache
62            .as_mut()
63            .and_then(|cache| cache.get(partition, &reference.key, reference.generation))
64        {
65            chunks::validate(&entries, reference.records)?;
66            return Ok(entries);
67        }
68        let store = self
69            .partitions
70            .get_mut(partition)
71            .expect("validated partition");
72        let object = read_one(store, &reference.key)?;
73        if object.generation != reference.generation || address(&object.entries) != reference.key {
74            return Err(error("missing or modified immutable object"));
75        }
76        chunks::validate(&object.entries, reference.records)?;
77        if let Some(cache) = &mut self.cache {
78            cache.remember(
79                partition,
80                &reference.key,
81                reference.generation,
82                &object.entries,
83            );
84        }
85        Ok(object.entries)
86    }
87}
88// FNV is an index, not authentication. Full contents are compared on creation;
89// a collision fails safely rather than overwriting or reusing different data.
90fn address(records: &[String]) -> String {
91    let mut hash = 0xcbf29ce484222325u64;
92    let mut add = |bytes: &[u8]| {
93        for byte in bytes {
94            hash = (hash ^ u64::from(*byte)).wrapping_mul(0x100000001b3);
95        }
96    };
97    add(b"blob1|");
98    for record in records {
99        add(format!("{}:", record.len()).as_bytes());
100        add(record.as_bytes());
101    }
102    format!("blob1-{hash:016x}")
103}
104fn read_one<S: AtomicJournalStore>(store: &mut S, key: &str) -> Result<JournalVersion, LinkError> {
105    let mut values = store.read(&[key.into()])?;
106    if values.len() != 1 {
107        return Err(error("invalid immutable object snapshot"));
108    }
109    let value = values.remove(0);
110    if value.generation == 0 && !value.entries.is_empty() {
111        return Err(error("invalid absent immutable object"));
112    }
113    Ok(value)
114}
115impl<C: AtomicJournalStore, D: AtomicJournalStore> AtomicJournalStore
116    for PartitionedJournalStore<C, D>
117{
118    fn supports_durable_flush(&self) -> bool {
119        self.catalog.supports_durable_flush()
120            && self
121                .partitions
122                .values()
123                .all(AtomicJournalStore::supports_durable_flush)
124    }
125    fn read(&mut self, keys: &[String]) -> Result<Vec<JournalVersion>, LinkError> {
126        validate_keys(keys)?;
127        let pointers = self.catalog.read(keys)?;
128        if pointers.len() != keys.len() {
129            return Err(error("incomplete catalog snapshot"));
130        }
131        // Validate every selected pointer before the first data-store access.
132        let mut selected = Vec::new();
133        for value in pointers {
134            if value.generation == 0 && value.entries.is_empty() {
135                selected.push((0, None));
136                continue;
137            }
138            if value.generation == 0 {
139                return Err(error("invalid catalog generation"));
140            }
141            let manifest = chunks::manifest(&value.entries)?;
142            if !self.partitions.contains_key(&manifest.partition) {
143                return Err(error("invalid catalog pointer partition"));
144            }
145            selected.push((value.generation, Some(manifest)));
146        }
147        selected
148            .into_iter()
149            .map(|(generation, manifest)| {
150                let mut entries = Vec::new();
151                if let Some(manifest) = manifest {
152                    for reference in manifest.references {
153                        entries.extend(self.read_object(&manifest.partition, &reference)?);
154                    }
155                }
156                Ok(JournalVersion {
157                    generation,
158                    entries,
159                })
160            })
161            .collect()
162    }
163    fn compare_exchange(
164        &mut self,
165        keys: &[String],
166        expected: &[JournalVersion],
167        updates: &[Option<Vec<String>>],
168    ) -> Result<bool, LinkError> {
169        validate_keys(keys)?;
170        if expected.len() != keys.len() || updates.len() != keys.len() {
171            return Err(error("expected generations and updates must match shards"));
172        }
173        // Route and validate every update before any external staging operation.
174        let routes: Vec<_> = keys
175            .iter()
176            .zip(updates)
177            .map(|(key, update)| {
178                update
179                    .as_ref()
180                    .map(|data| {
181                        let partition = (self.route)(key);
182                        if !self.partitions.contains_key(&partition) {
183                            return Err(error("route must select a configured partition"));
184                        }
185                        let chunks = match self.chunks {
186                            Some(options) => options.split(data)?,
187                            None => vec![data.as_slice()],
188                        };
189                        Ok((partition, chunks))
190                    })
191                    .transpose()
192            })
193            .collect::<Result<_, _>>()?;
194        let mut pointers = Vec::new();
195        for (update, route) in updates.iter().zip(routes) {
196            let Some(data) = update else {
197                pointers.push(None);
198                continue;
199            };
200            let (partition, objects) = route.expect("validated route for every update");
201            let mut manifest = if self.chunks.is_some() {
202                vec![
203                    "chunks1".into(),
204                    partition.clone(),
205                    data.len().to_string(),
206                    objects.len().to_string(),
207                ]
208            } else {
209                vec!["blob1".into(), partition.clone()]
210            };
211            let store = self
212                .partitions
213                .get_mut(&partition)
214                .expect("validated partition");
215            for data in objects {
216                let key = address(data);
217                let mut object = read_one(store, &key)?;
218                if object.generation == 0 {
219                    // A lost response leaves an orphan. Never replay a mutation.
220                    store.compare_exchange(
221                        std::slice::from_ref(&key),
222                        &[object],
223                        &[Some(data.to_vec())],
224                    )?;
225                    object = read_one(store, &key)?;
226                }
227                if object.generation == 0 || object.entries != data {
228                    return Err(error(
229                        "immutable object collision or inconsistent data store",
230                    ));
231                }
232                manifest.extend([key, object.generation.to_string()]);
233                if self.chunks.is_some() {
234                    manifest.push(data.len().to_string());
235                }
236            }
237            pointers.push(Some(manifest));
238        }
239        self.catalog.compare_exchange(keys, expected, &pointers)
240    }
241}