linera_views/backends/
journaling.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Turns a `DirectKeyValueStore` into a `KeyValueStore` by adding journaling.
5//!
6//! Journaling aims to allow writing arbitrarily large batches of data in an atomic way.
7//! This is useful for database backends that limit the number of keys and/or the size of
8//! the data that can be written atomically (i.e. in the same database transaction).
9//!
10//! Journaling requires to set aside a range of keys to hold a possible "header" and an
11//! array of unwritten entries called "blocks".
12//!
13//! When a new batch to be written exceeds the capacity of the underlying storage, the
14//! "slow path" is taken: the batch of operations is first written into blocks, then the
15//! journal header is (atomically) updated to make the batch of updates persistent.
16//!
17//! Before any new read or write operation, if a journal is present, it must first be
18//! cleared. This is done by processing every block of the journal successively. Every
19//! time the data in a block are written, the journal header is updated in the same
20//! transaction to mark the block as processed.
21
22use serde::{Deserialize, Serialize};
23use static_assertions as sa;
24use thiserror::Error;
25
26use crate::{
27    batch::{Batch, BatchValueWriter, DeletePrefixExpander, SimplifiedBatch},
28    store::{
29        DirectKeyValueStore, KeyValueDatabase, ReadableKeyValueStore, WithError,
30        WritableKeyValueStore,
31    },
32    views::MIN_VIEW_TAG,
33};
34
35/// A journaling key-value database.
36#[derive(Clone)]
37pub struct JournalingKeyValueDatabase<D> {
38    database: D,
39}
40
41/// A journaling key-value store.
42#[derive(Clone)]
43pub struct JournalingKeyValueStore<S> {
44    /// The inner store.
45    store: S,
46    /// Whether we have exclusive R/W access to the keys under root key.
47    has_exclusive_access: bool,
48}
49
50/// Data type indicating that the database is not consistent
51#[derive(Error, Debug)]
52#[allow(missing_docs)]
53pub enum JournalConsistencyError {
54    #[error("The journal block could not be retrieved, it could be missing or corrupted.")]
55    FailureToRetrieveJournalBlock,
56
57    #[error("Refusing to use the journal without exclusive database access to the root object.")]
58    JournalRequiresExclusiveAccess,
59}
60
61/// The tag used for the journal stuff.
62const JOURNAL_TAG: u8 = 0;
63// To prevent collisions, the tag value 0 is reserved for journals.
64// The tags used by views must be greater or equal than `MIN_VIEW_TAG`.
65sa::const_assert!(JOURNAL_TAG < MIN_VIEW_TAG);
66
67#[repr(u8)]
68enum KeyTag {
69    /// Prefix for the storing of the header of the journal.
70    Journal = 1,
71    /// Prefix for the block entry.
72    Entry,
73}
74
75fn get_journaling_key(tag: u8, pos: u32) -> Result<Vec<u8>, bcs::Error> {
76    let mut key = vec![JOURNAL_TAG];
77    key.extend([tag]);
78    bcs::serialize_into(&mut key, &pos)?;
79    Ok(key)
80}
81
82/// The header that contains the current state of the journal.
83#[derive(Serialize, Deserialize, Debug, Default)]
84struct JournalHeader {
85    block_count: u32,
86}
87
88impl<S> DeletePrefixExpander for &JournalingKeyValueStore<S>
89where
90    S: DirectKeyValueStore,
91{
92    type Error = S::Error;
93
94    async fn expand_delete_prefix(&self, key_prefix: &[u8]) -> Result<Vec<Vec<u8>>, Self::Error> {
95        self.store.find_keys_by_prefix(key_prefix).await
96    }
97}
98
99impl<D> WithError for JournalingKeyValueDatabase<D>
100where
101    D: WithError,
102{
103    type Error = D::Error;
104}
105
106impl<S> WithError for JournalingKeyValueStore<S>
107where
108    S: WithError,
109{
110    type Error = S::Error;
111}
112
113impl<S> ReadableKeyValueStore for JournalingKeyValueStore<S>
114where
115    S: ReadableKeyValueStore,
116    S::Error: From<JournalConsistencyError>,
117{
118    /// The size constant do not change
119    const MAX_KEY_SIZE: usize = S::MAX_KEY_SIZE;
120
121    /// The read stuff does not change
122    fn max_stream_queries(&self) -> usize {
123        self.store.max_stream_queries()
124    }
125
126    async fn read_value_bytes(&self, key: &[u8]) -> Result<Option<Vec<u8>>, Self::Error> {
127        self.store.read_value_bytes(key).await
128    }
129
130    async fn contains_key(&self, key: &[u8]) -> Result<bool, Self::Error> {
131        self.store.contains_key(key).await
132    }
133
134    async fn contains_keys(&self, keys: Vec<Vec<u8>>) -> Result<Vec<bool>, Self::Error> {
135        self.store.contains_keys(keys).await
136    }
137
138    async fn read_multi_values_bytes(
139        &self,
140        keys: Vec<Vec<u8>>,
141    ) -> Result<Vec<Option<Vec<u8>>>, Self::Error> {
142        self.store.read_multi_values_bytes(keys).await
143    }
144
145    async fn find_keys_by_prefix(&self, key_prefix: &[u8]) -> Result<Vec<Vec<u8>>, Self::Error> {
146        self.store.find_keys_by_prefix(key_prefix).await
147    }
148
149    async fn find_key_values_by_prefix(
150        &self,
151        key_prefix: &[u8],
152    ) -> Result<Vec<(Vec<u8>, Vec<u8>)>, Self::Error> {
153        self.store.find_key_values_by_prefix(key_prefix).await
154    }
155}
156
157impl<D> KeyValueDatabase for JournalingKeyValueDatabase<D>
158where
159    D: KeyValueDatabase,
160{
161    type Config = D::Config;
162    type Store = JournalingKeyValueStore<D::Store>;
163
164    fn get_name() -> String {
165        format!("journaling {}", D::get_name())
166    }
167
168    async fn connect(config: &Self::Config, namespace: &str) -> Result<Self, Self::Error> {
169        let database = D::connect(config, namespace).await?;
170        Ok(Self { database })
171    }
172
173    fn open_shared(&self, root_key: &[u8]) -> Result<Self::Store, Self::Error> {
174        let store = self.database.open_shared(root_key)?;
175        Ok(JournalingKeyValueStore {
176            store,
177            has_exclusive_access: false,
178        })
179    }
180
181    fn open_exclusive(&self, root_key: &[u8]) -> Result<Self::Store, Self::Error> {
182        let store = self.database.open_exclusive(root_key)?;
183        Ok(JournalingKeyValueStore {
184            store,
185            has_exclusive_access: true,
186        })
187    }
188
189    async fn list_all(config: &Self::Config) -> Result<Vec<String>, Self::Error> {
190        D::list_all(config).await
191    }
192
193    async fn list_root_keys(
194        config: &Self::Config,
195        namespace: &str,
196    ) -> Result<Vec<Vec<u8>>, Self::Error> {
197        D::list_root_keys(config, namespace).await
198    }
199
200    async fn delete_all(config: &Self::Config) -> Result<(), Self::Error> {
201        D::delete_all(config).await
202    }
203
204    async fn exists(config: &Self::Config, namespace: &str) -> Result<bool, Self::Error> {
205        D::exists(config, namespace).await
206    }
207
208    async fn create(config: &Self::Config, namespace: &str) -> Result<(), Self::Error> {
209        D::create(config, namespace).await
210    }
211
212    async fn delete(config: &Self::Config, namespace: &str) -> Result<(), Self::Error> {
213        D::delete(config, namespace).await
214    }
215}
216
217impl<S> WritableKeyValueStore for JournalingKeyValueStore<S>
218where
219    S: DirectKeyValueStore,
220    S::Error: From<JournalConsistencyError>,
221{
222    /// The size constant do not change
223    const MAX_VALUE_SIZE: usize = S::MAX_VALUE_SIZE;
224
225    async fn write_batch(&self, batch: Batch) -> Result<(), Self::Error> {
226        let batch = S::Batch::from_batch(self, batch).await?;
227        if Self::is_fastpath_feasible(&batch) {
228            self.store.write_batch(batch).await
229        } else {
230            if !self.has_exclusive_access {
231                return Err(JournalConsistencyError::JournalRequiresExclusiveAccess.into());
232            }
233            let header = self.write_journal(batch).await?;
234            self.coherently_resolve_journal(header).await
235        }
236    }
237
238    async fn clear_journal(&self) -> Result<(), Self::Error> {
239        let key = get_journaling_key(KeyTag::Journal as u8, 0)?;
240        let value = self.read_value::<JournalHeader>(&key).await?;
241        if let Some(header) = value {
242            self.coherently_resolve_journal(header).await?;
243        }
244        Ok(())
245    }
246}
247
248impl<S> JournalingKeyValueStore<S>
249where
250    S: DirectKeyValueStore,
251    S::Error: From<JournalConsistencyError>,
252{
253    /// Resolves the pending operations that were previously stored in the database
254    /// journal.
255    ///
256    /// For each block processed, we atomically update the journal header as well. When
257    /// the last block is processed, this atomically clears the journal and make the store
258    /// finally available again (for the range of keys managed by the journal).
259    ///
260    /// This function respects the constraints of the underlying key-value store `K` if
261    /// the following conditions are met:
262    ///
263    /// (1) each block contains at most `S::MAX_BATCH_SIZE - 2` operations;
264    ///
265    /// (2) the total size of the all operations in a block doesn't exceed:
266    /// `S::MAX_BATCH_TOTAL_SIZE - sizeof(block_key) - sizeof(header_key) - sizeof(bcs_header)`
267    ///
268    /// (3) every operation in a block satisfies the constraints on individual database
269    /// operations represented by `S::MAX_KEY_SIZE` and `S::MAX_VALUE_SIZE`.
270    ///
271    /// (4) `block_key` and `header_key` don't exceed `S::MAX_KEY_SIZE` and `bcs_header`
272    /// doesn't exceed `S::MAX_VALUE_SIZE`.
273    async fn coherently_resolve_journal(&self, mut header: JournalHeader) -> Result<(), S::Error> {
274        let header_key = get_journaling_key(KeyTag::Journal as u8, 0)?;
275        while header.block_count > 0 {
276            let block_key = get_journaling_key(KeyTag::Entry as u8, header.block_count - 1)?;
277            // Read the batch of updates (aka. "block") previously saved in the journal.
278            let mut batch = self
279                .store
280                .read_value::<S::Batch>(&block_key)
281                .await?
282                .ok_or(JournalConsistencyError::FailureToRetrieveJournalBlock)?;
283            // Execute the block and delete it from the journal atomically.
284            batch.add_delete(block_key);
285            header.block_count -= 1;
286            if header.block_count > 0 {
287                let value = bcs::to_bytes(&header)?;
288                batch.add_insert(header_key.clone(), value);
289            } else {
290                batch.add_delete(header_key.clone());
291            }
292            self.store.write_batch(batch).await?;
293        }
294        Ok(())
295    }
296
297    /// Writes the content of `batch` to the journal as a succession of blocks that can be
298    /// interpreted later by `coherently_resolve_journal`.
299    ///
300    /// Starting with a batch of operations that is typically too large to be executed in
301    /// one go (see `is_fastpath_feasible()` below), the goal of this function is to split
302    /// the batch into smaller blocks so that `coherently_resolve_journal` respects the
303    /// constraints of the underlying key-value store (see analysis above).
304    ///
305    /// For efficiency reasons, we write as many blocks as possible in each "transaction"
306    /// batch, using one write-operation per block. Then we also update the journal header
307    /// with the final number of blocks.
308    ///
309    /// As a result, the constraints of the underlying database are respected if the
310    /// following conditions are met while a "transaction" batch is being built:
311    ///
312    /// (1) The number of blocks per transaction doesn't exceed `S::MAX_BATCH_SIZE`.
313    /// But it is perfectly possible to have `S::MAX_BATCH_SIZE = usize::MAX`.
314    ///
315    /// (2) The total size of BCS-serialized blocks together with their corresponding keys
316    /// does not exceed `S::MAX_BATCH_TOTAL_SIZE`.
317    ///
318    /// (3) The size of each BCS-serialized block doesn't exceed `S::MAX_VALUE_SIZE`.
319    ///
320    /// (4) When processing a journal block, we have to do two other operations.
321    ///   (a) removing the existing block. The cost is `key_len`.
322    ///   (b) updating or removing the journal. The cost is `key_len + header_value_len`
323    ///       or `key_len`. An upper bound is thus
324    ///       `journal_len_upper_bound = key_len + header_value_len`.
325    ///   Thus the following has to be taken as upper bound on the block size:
326    ///   `S::MAX_BATCH_TOTAL_SIZE - key_len - journal_len_upper_bound`.
327    ///
328    /// NOTE:
329    /// * Since a block must contain at least one operation and M bytes of the
330    ///   serialization overhead (typically M is 2 or 3 bytes of vector sizes), condition (3)
331    ///   requires that each operation in the original batch satisfies:
332    ///   `sizeof(key) + sizeof(value) + M <= S::MAX_VALUE_SIZE`
333    ///
334    /// * Similarly, a transaction must contain at least one block so it is desirable that
335    ///   the maximum size of a block insertion `1 + sizeof(block_key) + S::MAX_VALUE_SIZE`
336    ///   plus M bytes of overhead doesn't exceed the threshold of condition (2).
337    async fn write_journal(&self, batch: S::Batch) -> Result<JournalHeader, S::Error> {
338        let header_key = get_journaling_key(KeyTag::Journal as u8, 0)?;
339        let key_len = header_key.len();
340        let header_value_len = bcs::serialized_size(&JournalHeader::default())?;
341        let journal_len_upper_bound = key_len + header_value_len;
342        // Each block in a transaction comes with a key.
343        let max_transaction_size = S::MAX_BATCH_TOTAL_SIZE;
344        let max_block_size = std::cmp::min(
345            S::MAX_VALUE_SIZE,
346            S::MAX_BATCH_TOTAL_SIZE - key_len - journal_len_upper_bound,
347        );
348
349        let mut iter = batch.into_iter();
350        let mut block_batch = S::Batch::default();
351        let mut block_size = 0;
352        let mut block_count = 0;
353        let mut transaction_batch = S::Batch::default();
354        let mut transaction_size = 0;
355        while iter.write_next_value(&mut block_batch, &mut block_size)? {
356            let (block_flush, transaction_flush) = {
357                if iter.is_empty() || transaction_batch.len() == S::MAX_BATCH_SIZE - 1 {
358                    (true, true)
359                } else {
360                    let next_block_size = iter
361                        .next_batch_size(&block_batch, block_size)?
362                        .expect("iter is not empty");
363                    let next_transaction_size = transaction_size + next_block_size + key_len;
364                    let transaction_flush = next_transaction_size > max_transaction_size;
365                    let block_flush = transaction_flush
366                        || block_batch.len() == S::MAX_BATCH_SIZE - 2
367                        || next_block_size > max_block_size;
368                    (block_flush, transaction_flush)
369                }
370            };
371            if block_flush {
372                block_size += block_batch.overhead_size();
373                let value = bcs::to_bytes(&block_batch)?;
374                block_batch = S::Batch::default();
375                assert_eq!(value.len(), block_size);
376                let key = get_journaling_key(KeyTag::Entry as u8, block_count)?;
377                transaction_batch.add_insert(key, value);
378                block_count += 1;
379                transaction_size += block_size + key_len;
380                block_size = 0;
381            }
382            if transaction_flush {
383                let batch = std::mem::take(&mut transaction_batch);
384                self.store.write_batch(batch).await?;
385                transaction_size = 0;
386            }
387        }
388        let header = JournalHeader { block_count };
389        if block_count > 0 {
390            let value = bcs::to_bytes(&header)?;
391            let mut batch = S::Batch::default();
392            batch.add_insert(header_key, value);
393            self.store.write_batch(batch).await?;
394        }
395        Ok(header)
396    }
397
398    fn is_fastpath_feasible(batch: &S::Batch) -> bool {
399        batch.len() <= S::MAX_BATCH_SIZE && batch.num_bytes() <= S::MAX_BATCH_TOTAL_SIZE
400    }
401}
402
403impl<S> JournalingKeyValueStore<S> {
404    /// Creates a new journaling store.
405    pub fn new(store: S) -> Self {
406        Self {
407            store,
408            has_exclusive_access: false,
409        }
410    }
411}