Skip to main content

calimero_storage/
error.rs

1//! Error types for the storage system.
2
3use std::io::Error as IoError;
4
5use eyre::Report;
6use serde::Serialize;
7use thiserror::Error as ThisError;
8
9use crate::address::Id;
10use crate::collections::crdt_meta::MergeError;
11use calimero_primitives::identity::PublicKey;
12
13/// Errors that can occur when working with the storage system.
14#[derive(Debug, ThisError)]
15#[non_exhaustive]
16pub enum StorageError {
17    /// The requested action is not allowed.
18    #[error("Action not allowed: {0}")]
19    ActionNotAllowed(String),
20
21    /// An attempt was made to create an orphan, i.e. an entity that has not
22    /// been registered as either a root or having a parent. This was probably
23    /// cause by calling `save()` without calling `add_child_to()` first.
24    #[error("Cannot create orphan with ID: {0}")]
25    CannotCreateOrphan(Id),
26
27    /// A merge operation failed.
28    ///
29    /// This typically indicates that no merge function is registered for the
30    /// root entity type. Use `#[app::state]` macro or call
31    /// `register_crdt_merge::<YourState>()` to register a merge function.
32    ///
33    /// The inner `MergeError` preserves the specific failure reason for
34    /// programmatic error handling.
35    #[error("Merge failed: {0}")]
36    MergeFailure(#[from] MergeError),
37
38    /// An error occurred during deserialization.
39    #[error("Deserialization error: {0}")]
40    DeserializationError(IoError),
41
42    /// An index entry was not found for the specified entity. This would
43    /// indicate a bug in the system.
44    #[error("Index not found for ID: {0}")]
45    IndexNotFound(Id),
46
47    /// Invalid or corrupt data encountered.
48    #[error("Invalid data: {0}")]
49    InvalidData(String),
50
51    /// The provided timestamp for an action is invalid (too far in the future).
52    #[error("Invalid timestamp {0} for an action, too far in the future (local time: {1}).")]
53    InvalidTimestamp(u64, u64),
54
55    /// The provided signature for an action is invalid.
56    #[error("Invalid signature for user-owned data")]
57    InvalidSignature,
58
59    /// A remote action was rejected due to an invalid (old or reused) nonce.
60    /// `PublicKey` is `Box`ed to reduce the enum's size.
61    #[error("Nonce replay detected for user {}: received nonce {}", 0.0, 0.1)]
62    NonceReplay(Box<(PublicKey, u64)>),
63
64    /// The requested record was not found, but in the context it was asked for,
65    /// it was expected to be found and so this represents an error or some kind
66    /// of inconsistency in the stored data.
67    #[error("Record not found with ID: {0}")]
68    NotFound(Id),
69
70    /// An error occurred during serialization.
71    #[error("Serialization error: {0}")]
72    SerializationError(IoError),
73
74    /// An error from the Store.
75    #[error("Store error: {0}")]
76    StoreError(#[from] Report),
77
78    /// An unexpected ID was encountered.
79    #[error("Unexpected ID: {0}")]
80    UnexpectedId(Id),
81}
82
83impl Serialize for StorageError {
84    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
85        match *self {
86            Self::ActionNotAllowed(ref err) => serializer.serialize_str(err),
87            Self::MergeFailure(ref err) => serializer.serialize_str(&err.to_string()),
88            Self::DeserializationError(ref err) | Self::SerializationError(ref err) => {
89                serializer.serialize_str(&err.to_string())
90            }
91            Self::CannotCreateOrphan(id)
92            | Self::IndexNotFound(id)
93            | Self::UnexpectedId(id)
94            | Self::NotFound(id) => serializer.serialize_str(&id.to_string()),
95            Self::InvalidTimestamp(timestamp, local_time) => serializer.serialize_str(&format!(
96                "Invalid timestamp {} for an action, too far in the future (local time: {}).",
97                timestamp, local_time
98            )),
99            Self::InvalidData(ref msg) => serializer.serialize_str(msg),
100            Self::InvalidSignature => serializer.serialize_str("Invalid signature"),
101            Self::NonceReplay(ref data) => {
102                let (pk, nonce) = &**data;
103                serializer.serialize_str(&format!("Nonce replay for {}: {}", pk, nonce))
104            }
105            Self::StoreError(ref err) => serializer.serialize_str(&err.to_string()),
106        }
107    }
108}