1
#![cfg_attr(docsrs, feature(doc_auto_cfg, 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_duration_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
//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
45

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

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

            
60
#[cfg(feature = "state-dir")]
61
pub mod state_dir;
62

            
63
use serde::{de::DeserializeOwned, Deserialize, Serialize};
64
use std::sync::Arc;
65

            
66
/// Wrapper type for Results returned from this crate.
67
type Result<T> = std::result::Result<T, crate::Error>;
68

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

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

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

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

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

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

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

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

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

            
175
impl<T> From<T> for Futureproof<T> {
176
2
    fn from(inner: T) -> Self {
177
2
        Self::Understandable(inner)
178
2
    }
179
}