1
1
//! `tor-persist`: Persistent data storage for use with Tor.
2
//!
3
//! This crate is part of
4
//! [Arti](https://gitlab.torproject.org/tpo/core/arti/), a project to
5
//! implement [Tor](https://www.torproject.org/) in Rust.
6
//!
7
//! For now, users should construct storage objects directly with (for
8
//! example) [`FsStateMgr::from_path()`], but use them primarily via the
9
//! interfaces of the [`StateMgr`] trait.
10

            
11
#![deny(missing_docs)]
12
#![warn(noop_method_call)]
13
#![deny(unreachable_pub)]
14
#![warn(clippy::all)]
15
#![deny(clippy::await_holding_lock)]
16
#![deny(clippy::cargo_common_metadata)]
17
#![deny(clippy::cast_lossless)]
18
#![deny(clippy::checked_conversions)]
19
#![warn(clippy::cognitive_complexity)]
20
#![deny(clippy::debug_assert_with_mut_call)]
21
#![deny(clippy::exhaustive_enums)]
22
#![deny(clippy::exhaustive_structs)]
23
#![deny(clippy::expl_impl_clone_on_copy)]
24
#![deny(clippy::fallible_impl_from)]
25
#![deny(clippy::implicit_clone)]
26
#![deny(clippy::large_stack_arrays)]
27
#![warn(clippy::manual_ok_or)]
28
#![deny(clippy::missing_docs_in_private_items)]
29
#![deny(clippy::missing_panics_doc)]
30
#![warn(clippy::needless_borrow)]
31
#![warn(clippy::needless_pass_by_value)]
32
#![warn(clippy::option_option)]
33
#![warn(clippy::rc_buffer)]
34
#![deny(clippy::ref_option_ref)]
35
#![warn(clippy::semicolon_if_nothing_returned)]
36
#![warn(clippy::trait_duplication_in_bounds)]
37
#![deny(clippy::unnecessary_wraps)]
38
#![warn(clippy::unseparated_literal_suffix)]
39
#![deny(clippy::unwrap_used)]
40

            
41
#[cfg(not(target_arch = "wasm32"))]
42
mod fs;
43
mod handle;
44
#[cfg(feature = "testing")]
45
mod testing;
46

            
47
use serde::{de::DeserializeOwned, Deserialize, Serialize};
48
use std::sync::Arc;
49

            
50
/// Wrapper type for Results returned from this crate.
51
type Result<T> = std::result::Result<T, crate::Error>;
52

            
53
#[cfg(not(target_arch = "wasm32"))]
54
pub use fs::FsStateMgr;
55
pub use handle::{DynStorageHandle, StorageHandle};
56
pub use serde_json::Value as JsonValue;
57
#[cfg(feature = "testing")]
58
pub use testing::TestingStateMgr;
59

            
60
use tor_error::ErrorKind;
61

            
62
/// An object that can manage persistent state.
63
///
64
/// State is implemented as a simple key-value store, where the values
65
/// are objects that can be serialized and deserialized.
66
///
67
/// # Warnings
68
///
69
/// Current implementations may place additional limits on the types
70
/// of objects that can be stored.  This is not a great example of OO
71
/// design: eventually we should probably clarify that more.
72
pub trait StateMgr: Clone {
73
    /// Try to load the object with key `key` from the store.
74
    ///
75
    /// Return None if no such object exists.
76
    fn load<D>(&self, key: &str) -> Result<Option<D>>
77
    where
78
        D: DeserializeOwned;
79
    /// Try to save `val` with key `key` in the store.
80
    ///
81
    /// Replaces any previous value associated with `key`.
82
    fn store<S>(&self, key: &str, val: &S) -> Result<()>
83
    where
84
        S: Serialize;
85
    /// Return true if this is a read-write state manager.
86
    ///
87
    /// If it returns false, then attempts to `store` will fail with
88
    /// [`Error::NoLock`]
89
    fn can_store(&self) -> bool;
90

            
91
    /// Try to become a read-write state manager if possible, without
92
    /// blocking.
93
    ///
94
    /// This function will return an error only if something really
95
    /// unexpected went wrong.  It may return `Ok(_)` even if we don't
96
    /// acquire the lock: check the return value or call
97
    /// `[StateMgr::can_store()`] to see if the lock is held.
98
    fn try_lock(&self) -> Result<LockStatus>;
99

            
100
    /// Release any locks held and become a read-only state manager
101
    /// again. If no locks were held, do nothing.
102
    fn unlock(&self) -> Result<()>;
103

            
104
    /// Make a new [`StorageHandle`] to store values of particular type
105
    /// at a particular key.
106
    fn create_handle<T>(self, key: impl Into<String>) -> DynStorageHandle<T>
107
    where
108
        Self: Send + Sync + Sized + 'static,
109
        T: Serialize + DeserializeOwned + 'static,
110
    {
111
        Arc::new(handle::StorageHandleImpl::new(self, key.into()))
112
    }
113
}
114

            
115
/// A possible outcome from calling [`StateMgr::try_lock()`]
116
#[allow(clippy::exhaustive_enums)]
117
7
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
118
pub enum LockStatus {
119
    /// We didn't have the lock and were unable to acquire it.
120
    NoLock,
121
    /// We already held the lock, and didn't have anything to do.
122
    AlreadyHeld,
123
    /// We successfully acquired the lock for the first time.
124
    NewlyAcquired,
125
}
126

            
127
impl LockStatus {
128
    /// Return true if this status indicates that we hold the lock.
129
241
    pub fn held(&self) -> bool {
130
241
        !matches!(self, LockStatus::NoLock)
131
241
    }
132
}
133

            
134
/// An error manipulating persistent state.
135
//
136
// Such errors are "global" in the sense that it doesn't relate to any guard or any circuit
137
// or anything, so callers may use `#[from]` when they include it in their own error.
138
#[derive(thiserror::Error, Debug, Clone)]
139
#[non_exhaustive]
140
pub enum Error {
141
    /// An IO error occurred.
142
    #[error("IO error")]
143
    IoError(#[source] Arc<std::io::Error>),
144

            
145
    /// Tried to save without holding an exclusive lock.
146
    //
147
    // TODO This error seems to actually be sometimes used to make store a no-op.
148
    //      We should consider whether this is best handled as an error, but for now
149
    //      this seems adequate.
150
    #[error("Storage not locked")]
151
    NoLock,
152

            
153
    /// Problem when serializing JSON data.
154
    #[error("JSON serialization error")]
155
    Serialize(#[source] Arc<serde_json::Error>),
156

            
157
    /// Problem when deserializing JSON data.
158
    #[error("JSON serialization error")]
159
    Deserialize(#[source] Arc<serde_json::Error>),
160
}
161

            
162
impl tor_error::HasKind for Error {
163
    #[rustfmt::skip] // the tabular layout of the `match` makes this a lot clearer
164
    fn kind(&self) -> ErrorKind {
165
        use Error as E;
166
        use tor_error::ErrorKind as K;
167
        match self {
168
            E::IoError(..)     => K::PersistentStateAccessFailed,
169
            E::NoLock          => K::BadApiUsage,
170
            E::Serialize(..)   => K::Internal,
171
            E::Deserialize(..) => K::PersistentStateCorrupted,
172
        }
173
    }
174
}
175

            
176
impl From<std::io::Error> for Error {
177
    fn from(e: std::io::Error) -> Error {
178
        Error::IoError(Arc::new(e))
179
    }
180
}
181

            
182
/// Error conversion for JSON errors; use only when loading
183
2
fn load_error(e: serde_json::Error) -> Error {
184
2
    Error::Deserialize(Arc::new(e))
185
2
}
186

            
187
/// Error conversion for JSON errors; use only when storing
188
fn store_error(e: serde_json::Error) -> Error {
189
    Error::Serialize(Arc::new(e))
190
}
191

            
192
/// A wrapper type for types whose representation may change in future versions of Arti.
193
///
194
/// This uses `#[serde(untagged)]` to attempt deserializing as a type `T` first, and falls back
195
/// to a generic JSON value representation if that fails.
196
6
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
197
#[serde(untagged)]
198
#[allow(clippy::exhaustive_enums)]
199
pub enum Futureproof<T> {
200
    /// A successfully-deserialized `T`.
201
    Understandable(T),
202
    /// A generic JSON value, representing a failure to deserialize a `T`.
203
    Unknown(JsonValue),
204
}
205

            
206
impl<T> Futureproof<T> {
207
    /// Convert the `Futureproof` into an `Option<T>`, throwing away an `Unknown` value.
208
5
    pub fn into_option(self) -> Option<T> {
209
5
        match self {
210
3
            Futureproof::Understandable(x) => Some(x),
211
2
            Futureproof::Unknown(_) => None,
212
        }
213
5
    }
214
}
215

            
216
impl<T> From<T> for Futureproof<T> {
217
1
    fn from(inner: T) -> Self {
218
1
        Self::Understandable(inner)
219
1
    }
220
}