Skip to main content

fasm_storage/
error.rs

1//! The retryability contract every storage error must answer.
2
3/// Error contract for storage failures that can be safely retried by discarding
4/// the current logical attempt and rerunning it from the start.
5///
6/// "Retryable" here is a statement about the *whole* logical operation, not
7/// about a single round-trip. A transactional backend that rejects a commit
8/// because of a read/write conflict is retryable: nothing was written, and
9/// rerunning the state transition from its beginning is sound. A serialization
10/// failure, a key-schema violation, or a prefix violation is not: the input is
11/// wrong and will be just as wrong the second time.
12///
13/// # The snapshot-before-erasure rule
14///
15/// Retryability lives on the *concrete* error value. Any wrapper that
16/// type-erases a storage error — boxing it as `dyn Error`, rendering it to a
17/// `String`, folding it into a variant that no longer names the backend type —
18/// **must** call [`is_retryable`] on the concrete error *before* erasing it and
19/// carry the resulting `bool` alongside the erased value:
20///
21/// ```
22/// use std::error::Error;
23///
24/// use fasm_storage::{Commit, RetryableStorageError};
25///
26/// enum ClientError {
27///     Storage {
28///         /// Snapshotted *before* the source was boxed.
29///         retryable: bool,
30///         source: Box<dyn Error + Send + Sync>,
31///     },
32/// }
33///
34/// impl ClientError {
35///     fn storage(err: impl Error + RetryableStorageError + Send + Sync + 'static) -> Self {
36///         Self::Storage { retryable: err.is_retryable(), source: Box::new(err) }
37///     }
38/// }
39///
40/// impl RetryableStorageError for ClientError {
41///     fn is_retryable(&self) -> bool {
42///         match self {
43///             Self::Storage { retryable, .. } => *retryable,
44///         }
45///     }
46/// }
47///
48/// async fn commit<C: Commit>(session: C) -> Result<(), ClientError> {
49///     session.commit().await.map_err(ClientError::storage)
50/// }
51/// ```
52///
53/// Once the type is gone the answer is unrecoverable, and the tempting default
54/// is exactly the wrong one in both directions: reporting `false` silently
55/// converts a transient commit conflict into a permanent failure, while
56/// reporting `true` retries operations that can never succeed.
57///
58/// [`is_retryable`]: RetryableStorageError::is_retryable
59pub trait RetryableStorageError {
60    /// Returns `true` when the caller may safely rerun the entire logical
61    /// operation from the beginning.
62    ///
63    /// Implementations must be conservative: return `false` whenever it is not
64    /// certain that the attempt left no partial effect behind.
65    fn is_retryable(&self) -> bool;
66}