linera_views/views/mod.rs
1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{fmt::Debug, future::Future, io::Write};
5
6use linera_base::crypto::CryptoHash;
7pub use linera_views_derive::{
8 ClonableView, CryptoHashRootView, CryptoHashView, HashableView, RootView, View,
9};
10use serde::Serialize;
11
12use crate::{batch::Batch, common::HasherOutput, ViewError};
13
14#[cfg(test)]
15#[path = "unit_tests/views.rs"]
16mod tests;
17
18/// The `RegisterView` implements a register for a single value.
19pub mod register_view;
20
21/// The `LazyRegisterView` implements a register for a single value with lazy loading.
22pub mod lazy_register_view;
23
24/// The `LogView` implements a log list that can be pushed.
25pub mod log_view;
26
27/// The `BucketQueueView` implements a queue that can push on the back and delete on the front and group data in buckets.
28pub mod bucket_queue_view;
29
30/// The `QueueView` implements a queue that can push on the back and delete on the front.
31pub mod queue_view;
32
33/// The `MapView` implements a map with ordered keys.
34pub mod map_view;
35
36/// The `SetView` implements a set with ordered entries.
37pub mod set_view;
38
39/// The `CollectionView` implements a map structure whose keys are ordered and the values are views.
40pub mod collection_view;
41
42/// The `ReentrantCollectionView` implements a map structure whose keys are ordered and the values are views with concurrent access.
43pub mod reentrant_collection_view;
44
45/// The implementation of a key-value store view.
46pub mod key_value_store_view;
47
48/// Wrapping a view to memoize hashing.
49pub mod hashable_wrapper;
50
51/// Wrapping a view to compute hash based on the history of modifications to the view.
52pub mod historical_hash_wrapper;
53
54/// The minimum value for the view tags. Values in `0..MIN_VIEW_TAG` are used for other purposes.
55pub const MIN_VIEW_TAG: u8 = 1;
56
57/// A view gives exclusive access to read and write the data stored at an underlying
58/// address in storage.
59#[cfg_attr(not(web), trait_variant::make(Send + Sync))]
60pub trait View: Sized {
61 /// The number of keys used for the initialization
62 const NUM_INIT_KEYS: usize;
63
64 /// The type of context stored in this view
65 type Context: crate::context::Context;
66
67 /// Obtains a mutable reference to the internal context.
68 fn context(&self) -> &Self::Context;
69
70 /// Creates the keys needed for loading the view
71 fn pre_load(context: &Self::Context) -> Result<Vec<Vec<u8>>, ViewError>;
72
73 /// Loads a view from the values
74 fn post_load(context: Self::Context, values: &[Option<Vec<u8>>]) -> Result<Self, ViewError>;
75
76 /// Loads a view
77 fn load(context: Self::Context) -> impl Future<Output = Result<Self, ViewError>> {
78 async {
79 if Self::NUM_INIT_KEYS == 0 {
80 Self::post_load(context, &[])
81 } else {
82 use crate::{context::Context, store::ReadableKeyValueStore};
83 let keys = Self::pre_load(&context)?;
84 let values = context.store().read_multi_values_bytes(&keys).await?;
85 Self::post_load(context, &values)
86 }
87 }
88 }
89
90 /// Discards all pending changes. After that `flush` should have no effect to storage.
91 fn rollback(&mut self);
92
93 /// Returns [`true`] if flushing this view would result in changes to the persistent storage.
94 async fn has_pending_changes(&self) -> bool;
95
96 /// Clears the view. That can be seen as resetting to default. If the clear is followed
97 /// by a flush then all the relevant data is removed on the storage.
98 fn clear(&mut self);
99
100 /// Computes the batch of operations to persist changes to storage without modifying the view.
101 /// Crash-resistant storage implementations accumulate the desired changes in the `batch` variable.
102 /// The returned boolean indicates whether the operation removes the view or not.
103 fn pre_save(&self, batch: &mut Batch) -> Result<bool, ViewError>;
104
105 /// Updates the view state after the batch has been executed in the database.
106 /// This should be called after `pre_save` and after the batch has been successfully written to storage.
107 /// This leaves the view in a clean state with no pending changes.
108 ///
109 /// May panic if `pre_save` was not called right before on `self`.
110 fn post_save(&mut self);
111
112 /// Builds a trivial view that is already deleted
113 fn new(context: Self::Context) -> Result<Self, ViewError> {
114 let values = vec![None; Self::NUM_INIT_KEYS];
115 let mut view = Self::post_load(context, &values)?;
116 view.clear();
117 Ok(view)
118 }
119}
120
121/// A view which can have its context replaced.
122pub trait ReplaceContext<C: crate::context::Context>: View {
123 /// The type returned after replacing the context.
124 type Target: View<Context = C>;
125
126 /// Returns a view with a replaced context.
127 async fn with_context(&mut self, ctx: impl FnOnce(&Self::Context) -> C + Clone)
128 -> Self::Target;
129}
130
131/// A view that supports hashing its values.
132#[cfg_attr(not(web), trait_variant::make(Send))]
133pub trait HashableView: View {
134 /// How to compute hashes.
135 type Hasher: Hasher;
136
137 /// Computes the hash of the values.
138 ///
139 /// Implementations do not need to include a type tag. However, the usual precautions
140 /// to enforce collision resistance must be applied (e.g. including the length of a
141 /// collection of values).
142 async fn hash(&self) -> Result<<Self::Hasher as Hasher>::Output, ViewError>;
143
144 /// Same as `hash` but guaranteed to be wait-free.
145 async fn hash_mut(&mut self) -> Result<<Self::Hasher as Hasher>::Output, ViewError>;
146}
147
148/// The requirement for the hasher type in [`HashableView`].
149pub trait Hasher: Default + Write + Send + Sync + 'static {
150 /// The output type.
151 type Output: Debug + Clone + Eq + AsRef<[u8]> + 'static;
152
153 /// Finishes the hashing process and returns its output.
154 fn finalize(self) -> Self::Output;
155
156 /// Serializes a value with BCS and includes it in the hash.
157 fn update_with_bcs_bytes(&mut self, value: &impl Serialize) -> Result<(), ViewError> {
158 bcs::serialize_into(self, value)?;
159 Ok(())
160 }
161
162 /// Includes bytes in the hash.
163 fn update_with_bytes(&mut self, value: &[u8]) -> Result<(), ViewError> {
164 self.write_all(value)?;
165 Ok(())
166 }
167}
168
169impl Hasher for sha3::Sha3_256 {
170 type Output = HasherOutput;
171
172 fn finalize(self) -> Self::Output {
173 <sha3::Sha3_256 as sha3::Digest>::finalize(self)
174 }
175}
176
177/// A [`View`] whose staged modifications can be saved in storage.
178#[cfg_attr(not(web), trait_variant::make(Send))]
179pub trait RootView: View {
180 /// Saves the root view to the database context
181 async fn save(&mut self) -> Result<(), ViewError>;
182
183 /// Saves the root view to the database context and drops it without calling `post_save`.
184 async fn save_and_drop(self) -> Result<(), ViewError>;
185}
186
187/// A [`View`] that also supports crypto hash
188#[cfg_attr(not(web), trait_variant::make(Send))]
189pub trait CryptoHashView: HashableView {
190 /// Computing the hash and attributing the type to it. May require locking.
191 async fn crypto_hash(&self) -> Result<CryptoHash, ViewError>;
192
193 /// Same as `crypto_hash` but guaranteed to be wait-free.
194 async fn crypto_hash_mut(&mut self) -> Result<CryptoHash, ViewError>;
195}
196
197/// A [`RootView`] that also supports crypto hash
198#[cfg_attr(not(web), trait_variant::make(Send))]
199pub trait CryptoHashRootView: RootView + CryptoHashView {}
200
201/// A view that can be shared (unsafely) by cloning it.
202///
203/// Note: Calling `flush` on any of the shared views will break the other views. Therefore,
204/// cloning views is only safe if `flush` only ever happens after all the copies but one
205/// have been dropped.
206pub trait ClonableView: View {
207 /// Creates a clone of this view, sharing the underlying storage context but prone to
208 /// data races which can corrupt the view state.
209 fn clone_unchecked(&mut self) -> Result<Self, ViewError>;
210}