fuel_core_storage/
lib.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
//! The crate `fuel-core-storage` contains storage types, primitives, tables used by `fuel-core`.
//! This crate doesn't contain the actual implementation of the storage. It works around the
//! `Database` and is used by services to provide a default implementation. Primitives
//! defined here are used by services but are flexible enough to customize the
//! logic when the `Database` is known.

#![cfg_attr(not(feature = "std"), no_std)]
#![deny(clippy::arithmetic_side_effects)]
#![deny(clippy::cast_possible_truncation)]
#![deny(unused_crate_dependencies)]
#![deny(missing_docs)]
#![deny(warnings)]

#[cfg(feature = "alloc")]
extern crate alloc;

use anyhow::anyhow;
use core::array::TryFromSliceError;
use fuel_core_types::services::executor::Error as ExecutorError;

#[cfg(feature = "alloc")]
use alloc::{
    boxed::Box,
    string::ToString,
};

pub use fuel_vm_private::{
    fuel_storage::*,
    storage::{
        predicate::PredicateStorageRequirements,
        ContractsAssetsStorage,
        InterpreterStorage,
    },
};

pub mod blueprint;
pub mod codec;
pub mod column;
pub mod iter;
pub mod kv_store;
pub mod structured_storage;
pub mod tables;
#[cfg(feature = "test-helpers")]
pub mod test_helpers;
pub mod transactional;
pub mod vm_storage;

use fuel_core_types::fuel_merkle::binary::MerkleTreeError;
pub use fuel_vm_private::storage::{
    ContractsAssetKey,
    ContractsStateData,
    ContractsStateKey,
};
#[doc(hidden)]
pub use paste;
#[cfg(feature = "test-helpers")]
#[doc(hidden)]
pub use rand;

/// The storage result alias.
pub type Result<T> = core::result::Result<T, Error>;

#[derive(Debug, derive_more::Display, derive_more::From)]
#[non_exhaustive]
/// Error occurring during interaction with storage
pub enum Error {
    /// Error occurred during serialization or deserialization of the entity.
    #[display(fmt = "error performing serialization or deserialization `{_0}`")]
    Codec(anyhow::Error),
    /// Error occurred during interaction with database.
    #[display(fmt = "error occurred in the underlying datastore `{_0:?}`")]
    DatabaseError(Box<dyn core::fmt::Debug + Send + Sync>),
    /// This error should be created with `not_found` macro.
    #[display(fmt = "resource was not found in table `{_0}` at the: {_1}")]
    NotFound(&'static str, &'static str),
    // TODO: Do we need this type at all?
    /// Unknown or not expected(by architecture) error.
    #[from]
    Other(anyhow::Error),
}

#[cfg(feature = "test-helpers")]
impl PartialEq for Error {
    fn eq(&self, other: &Self) -> bool {
        self.to_string().eq(&other.to_string())
    }
}

impl From<Error> for anyhow::Error {
    fn from(error: Error) -> Self {
        anyhow::Error::msg(error)
    }
}

impl From<TryFromSliceError> for Error {
    fn from(e: TryFromSliceError) -> Self {
        Self::Other(anyhow::anyhow!(e))
    }
}

impl From<Error> for ExecutorError {
    fn from(e: Error) -> Self {
        ExecutorError::StorageError(e.to_string())
    }
}

impl From<Error> for fuel_vm_private::prelude::InterpreterError<Error> {
    fn from(e: Error) -> Self {
        fuel_vm_private::prelude::InterpreterError::Storage(e)
    }
}

impl From<Error> for fuel_vm_private::prelude::RuntimeError<Error> {
    fn from(e: Error) -> Self {
        fuel_vm_private::prelude::RuntimeError::Storage(e)
    }
}

impl From<MerkleTreeError<Error>> for Error {
    fn from(e: MerkleTreeError<Error>) -> Self {
        match e {
            MerkleTreeError::StorageError(s) => s,
            e => Error::Other(anyhow!(e)),
        }
    }
}

/// The helper trait to work with storage errors.
pub trait IsNotFound {
    /// Return `true` if the error is [`Error::NotFound`].
    fn is_not_found(&self) -> bool;
}

impl IsNotFound for Error {
    fn is_not_found(&self) -> bool {
        matches!(self, Error::NotFound(_, _))
    }
}

impl<T> IsNotFound for Result<T> {
    fn is_not_found(&self) -> bool {
        match self {
            Err(err) => err.is_not_found(),
            _ => false,
        }
    }
}

/// The traits allow work with the storage in batches.
/// Some implementations can perform batch operations faster than one by one.
#[impl_tools::autoimpl(for<T: trait> &mut T)]
pub trait StorageBatchMutate<Type: Mappable>: StorageMutate<Type> {
    /// Initialize the storage with batch insertion. This method is more performant than
    /// [`Self::insert_batch`] in some cases.
    ///
    /// # Errors
    ///
    /// Returns an error if the storage is already initialized.
    fn init_storage<'a, Iter>(&mut self, set: Iter) -> Result<()>
    where
        Iter: 'a + Iterator<Item = (&'a Type::Key, &'a Type::Value)>,
        Type::Key: 'a,
        Type::Value: 'a;

    /// Inserts the key-value pair into the storage in batch.
    fn insert_batch<'a, Iter>(&mut self, set: Iter) -> Result<()>
    where
        Iter: 'a + Iterator<Item = (&'a Type::Key, &'a Type::Value)>,
        Type::Key: 'a,
        Type::Value: 'a;

    /// Removes the key-value pairs from the storage in batch.
    fn remove_batch<'a, Iter>(&mut self, set: Iter) -> Result<()>
    where
        Iter: 'a + Iterator<Item = &'a Type::Key>,
        Type::Key: 'a;
}

/// Creates `StorageError::NotFound` error with file and line information inside.
///
/// # Examples
///
/// ```
/// use fuel_core_storage::not_found;
/// use fuel_core_storage::tables::Messages;
///
/// let string_type = not_found!("BlockId");
/// let mappable_type = not_found!(Messages);
/// let mappable_path = not_found!(fuel_core_storage::tables::Messages);
/// ```
#[macro_export]
macro_rules! not_found {
    ($name: literal) => {
        $crate::Error::NotFound($name, concat!(file!(), ":", line!()))
    };
    ($ty: path) => {
        $crate::Error::NotFound(
            ::core::any::type_name::<$ty>(),
            concat!(file!(), ":", line!()),
        )
    };
}

#[cfg(test)]
mod test {
    use crate::tables::Coins;

    #[test]
    fn not_found_output() {
        #[rustfmt::skip]
        assert_eq!(
            format!("{}", not_found!("BlockId")),
            format!("resource was not found in table `BlockId` at the: {}:{}", file!(), line!() - 1)
        );
        #[rustfmt::skip]
        assert_eq!(
            format!("{}", not_found!(Coins)),
            format!("resource was not found in table `fuel_core_storage::tables::Coins` at the: {}:{}", file!(), line!() - 1)
        );
    }
}