1use 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#[derive(Clone)]
37pub struct JournalingKeyValueDatabase<D> {
38 database: D,
39}
40
41#[derive(Clone)]
43pub struct JournalingKeyValueStore<S> {
44 store: S,
46 has_exclusive_access: bool,
48}
49
50#[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
61const JOURNAL_TAG: u8 = 0;
63sa::const_assert!(JOURNAL_TAG < MIN_VIEW_TAG);
66
67#[repr(u8)]
68enum KeyTag {
69 Journal = 1,
71 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#[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 const MAX_KEY_SIZE: usize = S::MAX_KEY_SIZE;
120
121 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 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 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 let mut batch = self
279 .store
280 .read_value::<S::Batch>(&block_key)
281 .await?
282 .ok_or(JournalConsistencyError::FailureToRetrieveJournalBlock)?;
283 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 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 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 pub fn new(store: S) -> Self {
406 Self {
407 store,
408 has_exclusive_access: false,
409 }
410 }
411}