1
#![cfg_attr(docsrs, feature(doc_cfg))]
2
#![doc = include_str!("../README.md")]
3
// @@ begin lint list maintained by maint/add_warning @@
4
#![allow(renamed_and_removed_lints)] // @@REMOVE_WHEN(ci_arti_stable)
5
#![allow(unknown_lints)] // @@REMOVE_WHEN(ci_arti_nightly)
6
#![warn(missing_docs)]
7
#![warn(noop_method_call)]
8
#![warn(unreachable_pub)]
9
#![warn(clippy::all)]
10
#![deny(clippy::await_holding_lock)]
11
#![deny(clippy::cargo_common_metadata)]
12
#![deny(clippy::cast_lossless)]
13
#![deny(clippy::checked_conversions)]
14
#![allow(clippy::cognitive_complexity)] // See arti#2556
15
#![deny(clippy::debug_assert_with_mut_call)]
16
#![deny(clippy::exhaustive_enums)]
17
#![deny(clippy::exhaustive_structs)]
18
#![deny(clippy::expl_impl_clone_on_copy)]
19
#![deny(clippy::fallible_impl_from)]
20
#![deny(clippy::implicit_clone)]
21
#![deny(clippy::large_stack_arrays)]
22
#![warn(clippy::manual_ok_or)]
23
#![deny(clippy::missing_docs_in_private_items)]
24
#![warn(clippy::needless_borrow)]
25
#![warn(clippy::needless_pass_by_value)]
26
#![warn(clippy::option_option)]
27
#![warn(clippy::or_fun_call)]
28
#![deny(clippy::print_stderr)]
29
#![deny(clippy::print_stdout)]
30
#![warn(clippy::rc_buffer)]
31
#![deny(clippy::ref_option_ref)]
32
#![warn(clippy::semicolon_if_nothing_returned)]
33
#![warn(clippy::trait_duplication_in_bounds)]
34
#![deny(clippy::unchecked_time_subtraction)]
35
#![deny(clippy::unnecessary_wraps)]
36
#![warn(clippy::unseparated_literal_suffix)]
37
#![deny(clippy::unwrap_used)]
38
#![deny(clippy::mod_module_files)]
39
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
40
#![allow(clippy::uninlined_format_args)]
41
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
42
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
43
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
44
#![allow(clippy::needless_lifetimes)] // See arti#1765
45
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
46
#![allow(clippy::collapsible_if)] // See arti#2342
47
#![deny(clippy::unused_async)]
48
#![deny(clippy::string_slice)] // See arti#2571
49
#![allow(recursion_depth_exceeding_limit)] // arti#2715, rust/issues/159228
50
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
51

            
52
// TODO #1645 (either remove this, or decide to have it everywhere)
53
#![cfg_attr(not(all(feature = "experimental", feature = "full")), allow(unused))]
54

            
55
mod err;
56
#[cfg(not(target_arch = "wasm32"))]
57
mod fs;
58
mod fs_mistrust_error_ext;
59
mod handle;
60
pub mod hsnickname;
61
mod load_store;
62
pub mod slug;
63
#[cfg(feature = "testing")]
64
mod testing;
65

            
66
#[cfg(feature = "state-dir")]
67
pub mod state_dir;
68

            
69
use serde::{Deserialize, Serialize, de::DeserializeOwned};
70
use std::sync::Arc;
71

            
72
/// Wrapper type for Results returned from this crate.
73
type Result<T> = std::result::Result<T, crate::Error>;
74

            
75
pub use err::{Error, ErrorSource};
76
#[cfg(not(target_arch = "wasm32"))]
77
pub use fs::FsStateMgr;
78
pub use fs_mistrust_error_ext::FsMistrustErrorExt;
79
pub use handle::{DynStorageHandle, StorageHandle};
80
pub use serde_json::Value as JsonValue;
81
#[cfg(feature = "testing")]
82
pub use testing::TestingStateMgr;
83

            
84
/// An object that can manage persistent state.
85
///
86
/// State is implemented as a simple key-value store, where the values
87
/// are objects that can be serialized and deserialized.
88
///
89
/// # Warnings
90
///
91
/// Current implementations may place additional limits on the types
92
/// of objects that can be stored.  This is not a great example of OO
93
/// design: eventually we should probably clarify that more.
94
pub trait StateMgr: Clone {
95
    /// Try to load the object with key `key` from the store.
96
    ///
97
    /// Return None if no such object exists.
98
    fn load<D>(&self, key: &str) -> Result<Option<D>>
99
    where
100
        D: DeserializeOwned;
101
    /// Try to save `val` with key `key` in the store.
102
    ///
103
    /// Replaces any previous value associated with `key`.
104
    fn store<S>(&self, key: &str, val: &S) -> Result<()>
105
    where
106
        S: Serialize;
107
    /// Return true if this is a read-write state manager.
108
    ///
109
    /// If it returns false, then attempts to `store` will fail with
110
    /// an error of kind [`BadApiUsage`](tor_error::ErrorKind::BadApiUsage)
111
    fn can_store(&self) -> bool;
112

            
113
    /// Try to become a read-write state manager if possible, without
114
    /// blocking.
115
    ///
116
    /// This function will return an error only if something really
117
    /// unexpected went wrong.  It may return `Ok(_)` even if we don't
118
    /// acquire the lock: check the return value or call
119
    /// `[StateMgr::can_store()`] to see if the lock is held.
120
    fn try_lock(&self) -> Result<LockStatus>;
121

            
122
    /// Release any locks held and become a read-only state manager
123
    /// again. If no locks were held, do nothing.
124
    fn unlock(&self) -> Result<()>;
125

            
126
    /// Make a new [`StorageHandle`] to store values of particular type
127
    /// at a particular key.
128
    fn create_handle<T>(self, key: impl Into<String>) -> DynStorageHandle<T>
129
    where
130
        Self: Send + Sync + Sized + 'static,
131
        T: Serialize + DeserializeOwned + 'static,
132
    {
133
        Arc::new(handle::StorageHandleImpl::new(self, key.into()))
134
    }
135
}
136

            
137
/// A possible outcome from calling [`StateMgr::try_lock()`]
138
#[allow(clippy::exhaustive_enums)]
139
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
140
#[must_use]
141
pub enum LockStatus {
142
    /// We didn't have the lock and were unable to acquire it.
143
    NoLock,
144
    /// We already held the lock, and didn't have anything to do.
145
    AlreadyHeld,
146
    /// We successfully acquired the lock for the first time.
147
    NewlyAcquired,
148
}
149

            
150
impl LockStatus {
151
    /// Return true if this status indicates that we hold the lock.
152
3485
    pub fn held(&self) -> bool {
153
3485
        !matches!(self, LockStatus::NoLock)
154
3485
    }
155
}
156

            
157
/// A wrapper type for types whose representation may change in future versions of Arti.
158
///
159
/// This uses `#[serde(untagged)]` to attempt deserializing as a type `T` first, and falls back
160
/// to a generic JSON value representation if that fails.
161
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
162
#[serde(untagged)]
163
#[allow(clippy::exhaustive_enums)]
164
pub enum Futureproof<T> {
165
    /// A successfully-deserialized `T`.
166
    Understandable(T),
167
    /// A generic JSON value, representing a failure to deserialize a `T`.
168
    Unknown(JsonValue),
169
}
170

            
171
impl<T> Futureproof<T> {
172
    /// Convert the `Futureproof` into an `Option<T>`, throwing away an `Unknown` value.
173
4
    pub fn into_option(self) -> Option<T> {
174
4
        match self {
175
2
            Futureproof::Understandable(x) => Some(x),
176
2
            Futureproof::Unknown(_) => None,
177
        }
178
4
    }
179
}
180

            
181
impl<T> From<T> for Futureproof<T> {
182
    fn from(inner: T) -> Self {
183
        Self::Understandable(inner)
184
    }
185
}