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
#![warn(clippy::cognitive_complexity)]
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
#![deny(clippy::print_stderr)]
28
#![deny(clippy::print_stdout)]
29
#![warn(clippy::rc_buffer)]
30
#![deny(clippy::ref_option_ref)]
31
#![warn(clippy::semicolon_if_nothing_returned)]
32
#![warn(clippy::trait_duplication_in_bounds)]
33
#![deny(clippy::unchecked_time_subtraction)]
34
#![deny(clippy::unnecessary_wraps)]
35
#![warn(clippy::unseparated_literal_suffix)]
36
#![deny(clippy::unwrap_used)]
37
#![deny(clippy::mod_module_files)]
38
#![allow(clippy::let_unit_value)] // This can reasonably be done for explicitness
39
#![allow(clippy::uninlined_format_args)]
40
#![allow(clippy::significant_drop_in_scrutinee)] // arti/-/merge_requests/588/#note_2812945
41
#![allow(clippy::result_large_err)] // temporary workaround for arti#587
42
#![allow(clippy::needless_raw_string_hashes)] // complained-about code is fine, often best
43
#![allow(clippy::needless_lifetimes)] // See arti#1765
44
#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45
#![allow(clippy::collapsible_if)] // See arti#2342
46
#![deny(clippy::unused_async)]
47
#![deny(clippy::string_slice)] // See arti#2571
48
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
49

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

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

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

            
67
use serde::{Deserialize, Serialize, de::DeserializeOwned};
68
use std::sync::Arc;
69

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

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

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

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

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

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

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

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

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

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

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