linera_views/views/
mod.rs

1// Copyright (c) Zefchain Labs, Inc.
2// SPDX-License-Identifier: Apache-2.0
3
4use std::{fmt::Debug, 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 `LogView` implements a log list that can be pushed.
22pub mod log_view;
23
24/// The `BucketQueueView` implements a queue that can push on the back and delete on the front and group data in buckets.
25pub mod bucket_queue_view;
26
27/// The `QueueView` implements a queue that can push on the back and delete on the front.
28pub mod queue_view;
29
30/// The `MapView` implements a map with ordered keys.
31pub mod map_view;
32
33/// The `SetView` implements a set with ordered entries.
34pub mod set_view;
35
36/// The `CollectionView` implements a map structure whose keys are ordered and the values are views.
37pub mod collection_view;
38
39/// The `ReentrantCollectionView` implements a map structure whose keys are ordered and the values are views with concurrent access.
40pub mod reentrant_collection_view;
41
42/// The implementation of a key-value store view.
43pub mod key_value_store_view;
44
45/// Wrapping a view to compute a hash.
46pub mod hashable_wrapper;
47
48/// The minimum value for the view tags. Values in `0..MIN_VIEW_TAG` are used for other purposes.
49pub const MIN_VIEW_TAG: u8 = 1;
50
51/// A view gives exclusive access to read and write the data stored at an underlying
52/// address in storage.
53#[cfg_attr(not(web), trait_variant::make(Send + Sync))]
54pub trait View: Sized {
55    /// The number of keys used for the initialization
56    const NUM_INIT_KEYS: usize;
57
58    /// The type of context stored in this view
59    type Context: crate::context::Context;
60
61    /// Obtains a mutable reference to the internal context.
62    fn context(&self) -> &Self::Context;
63
64    /// Creates the keys needed for loading the view
65    fn pre_load(context: &Self::Context) -> Result<Vec<Vec<u8>>, ViewError>;
66
67    /// Loads a view from the values
68    fn post_load(context: Self::Context, values: &[Option<Vec<u8>>]) -> Result<Self, ViewError>;
69
70    /// Loads a view
71    async fn load(context: Self::Context) -> Result<Self, ViewError>;
72
73    /// Discards all pending changes. After that `flush` should have no effect to storage.
74    fn rollback(&mut self);
75
76    /// Returns [`true`] if flushing this view would result in changes to the persistent storage.
77    async fn has_pending_changes(&self) -> bool;
78
79    /// Clears the view. That can be seen as resetting to default. If the clear is followed
80    /// by a flush then all the relevant data is removed on the storage.
81    fn clear(&mut self);
82
83    /// Persists changes to storage. This leaves the view still usable and is essentially neutral to the
84    /// program running. Crash-resistant storage implementations are expected to accumulate the desired
85    /// changes in the `batch` variable first. If the view is dropped without calling `flush`, staged
86    /// changes are simply lost.
87    /// The returned boolean indicates whether the operation removes the view or not.
88    fn flush(&mut self, batch: &mut Batch) -> Result<bool, ViewError>;
89
90    /// Builds a trivial view that is already deleted
91    fn new(context: Self::Context) -> Result<Self, ViewError> {
92        let values = vec![None; Self::NUM_INIT_KEYS];
93        let mut view = Self::post_load(context, &values)?;
94        view.clear();
95        Ok(view)
96    }
97}
98
99/// A view that supports hashing its values.
100#[cfg_attr(not(web), trait_variant::make(Send))]
101pub trait HashableView: View {
102    /// How to compute hashes.
103    type Hasher: Hasher;
104
105    /// Computes the hash of the values.
106    ///
107    /// Implementations do not need to include a type tag. However, the usual precautions
108    /// to enforce collision resistance must be applied (e.g. including the length of a
109    /// collection of values).
110    async fn hash_mut(&mut self) -> Result<<Self::Hasher as Hasher>::Output, ViewError>;
111
112    /// Computes the hash of the values.
113    ///
114    /// Implementations do not need to include a type tag. However, the usual precautions
115    /// to enforce collision resistance must be applied (e.g. including the length of a
116    /// collection of values).
117    async fn hash(&self) -> Result<<Self::Hasher as Hasher>::Output, ViewError>;
118}
119
120/// The requirement for the hasher type in [`HashableView`].
121pub trait Hasher: Default + Write + Send + Sync + 'static {
122    /// The output type.
123    type Output: Debug + Clone + Eq + AsRef<[u8]> + 'static;
124
125    /// Finishes the hashing process and returns its output.
126    fn finalize(self) -> Self::Output;
127
128    /// Serializes a value with BCS and includes it in the hash.
129    fn update_with_bcs_bytes(&mut self, value: &impl Serialize) -> Result<(), ViewError> {
130        bcs::serialize_into(self, value)?;
131        Ok(())
132    }
133
134    /// Includes bytes in the hash.
135    fn update_with_bytes(&mut self, value: &[u8]) -> Result<(), ViewError> {
136        self.write_all(value)?;
137        Ok(())
138    }
139}
140
141impl Hasher for sha3::Sha3_256 {
142    type Output = HasherOutput;
143
144    fn finalize(self) -> Self::Output {
145        <sha3::Sha3_256 as sha3::Digest>::finalize(self)
146    }
147}
148
149/// A [`View`] whose staged modifications can be saved in storage.
150#[cfg_attr(not(web), trait_variant::make(Send))]
151pub trait RootView: View {
152    /// Saves the root view to the database context
153    async fn save(&mut self) -> Result<(), ViewError>;
154}
155
156/// A [`View`] that also supports crypto hash
157#[cfg_attr(not(web), trait_variant::make(Send))]
158pub trait CryptoHashView: HashableView {
159    /// Computing the hash and attributing the type to it.
160    async fn crypto_hash(&self) -> Result<CryptoHash, ViewError>;
161
162    /// Computing the hash and attributing the type to it.
163    async fn crypto_hash_mut(&mut self) -> Result<CryptoHash, ViewError>;
164}
165
166/// A [`RootView`] that also supports crypto hash
167#[cfg_attr(not(web), trait_variant::make(Send))]
168pub trait CryptoHashRootView: RootView + CryptoHashView {}
169
170/// A [`ClonableView`] supports being shared (unsafely) by cloning it.
171///
172/// Sharing is unsafe because by having two view instances for the same data, they may have invalid
173/// state if both are used for writing.
174///
175/// Sharing the view is guaranteed to not cause data races if only one of the shared view instances
176/// is used for writing at any given point in time.
177pub trait ClonableView: View {
178    /// Creates a clone of this view, sharing the underlying storage context but prone to
179    /// data races which can corrupt the view state.
180    fn clone_unchecked(&mut self) -> Result<Self, ViewError>;
181}