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
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
48

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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