tor_persist/
lib.rs

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#![allow(mismatched_lifetime_syntaxes)] // temporary workaround for arti#2060
45//! <!-- @@ end lint list maintained by maint/add_warning @@ -->
46
47// TODO #1645 (either remove this, or decide to have it everywhere)
48#![cfg_attr(not(all(feature = "experimental", feature = "full")), allow(unused))]
49
50mod err;
51#[cfg(not(target_arch = "wasm32"))]
52mod fs;
53mod fs_mistrust_error_ext;
54mod handle;
55pub mod hsnickname;
56mod load_store;
57pub mod slug;
58#[cfg(feature = "testing")]
59mod testing;
60
61#[cfg(feature = "state-dir")]
62pub mod state_dir;
63
64use serde::{de::DeserializeOwned, Deserialize, Serialize};
65use std::sync::Arc;
66
67/// Wrapper type for Results returned from this crate.
68type Result<T> = std::result::Result<T, crate::Error>;
69
70pub use err::{Error, ErrorSource};
71#[cfg(not(target_arch = "wasm32"))]
72pub use fs::FsStateMgr;
73pub use fs_mistrust_error_ext::FsMistrustErrorExt;
74pub use handle::{DynStorageHandle, StorageHandle};
75pub use serde_json::Value as JsonValue;
76#[cfg(feature = "testing")]
77pub use testing::TestingStateMgr;
78
79/// An object that can manage persistent state.
80///
81/// State is implemented as a simple key-value store, where the values
82/// are objects that can be serialized and deserialized.
83///
84/// # Warnings
85///
86/// Current implementations may place additional limits on the types
87/// of objects that can be stored.  This is not a great example of OO
88/// design: eventually we should probably clarify that more.
89pub trait StateMgr: Clone {
90    /// Try to load the object with key `key` from the store.
91    ///
92    /// Return None if no such object exists.
93    fn load<D>(&self, key: &str) -> Result<Option<D>>
94    where
95        D: DeserializeOwned;
96    /// Try to save `val` with key `key` in the store.
97    ///
98    /// Replaces any previous value associated with `key`.
99    fn store<S>(&self, key: &str, val: &S) -> Result<()>
100    where
101        S: Serialize;
102    /// Return true if this is a read-write state manager.
103    ///
104    /// If it returns false, then attempts to `store` will fail with
105    /// an error of kind [`BadApiUsage`](tor_error::ErrorKind::BadApiUsage)
106    fn can_store(&self) -> bool;
107
108    /// Try to become a read-write state manager if possible, without
109    /// blocking.
110    ///
111    /// This function will return an error only if something really
112    /// unexpected went wrong.  It may return `Ok(_)` even if we don't
113    /// acquire the lock: check the return value or call
114    /// `[StateMgr::can_store()`] to see if the lock is held.
115    fn try_lock(&self) -> Result<LockStatus>;
116
117    /// Release any locks held and become a read-only state manager
118    /// again. If no locks were held, do nothing.
119    fn unlock(&self) -> Result<()>;
120
121    /// Make a new [`StorageHandle`] to store values of particular type
122    /// at a particular key.
123    fn create_handle<T>(self, key: impl Into<String>) -> DynStorageHandle<T>
124    where
125        Self: Send + Sync + Sized + 'static,
126        T: Serialize + DeserializeOwned + 'static,
127    {
128        Arc::new(handle::StorageHandleImpl::new(self, key.into()))
129    }
130}
131
132/// A possible outcome from calling [`StateMgr::try_lock()`]
133#[allow(clippy::exhaustive_enums)]
134#[derive(Debug, Copy, Clone, Eq, PartialEq)]
135#[must_use]
136pub enum LockStatus {
137    /// We didn't have the lock and were unable to acquire it.
138    NoLock,
139    /// We already held the lock, and didn't have anything to do.
140    AlreadyHeld,
141    /// We successfully acquired the lock for the first time.
142    NewlyAcquired,
143}
144
145impl LockStatus {
146    /// Return true if this status indicates that we hold the lock.
147    pub fn held(&self) -> bool {
148        !matches!(self, LockStatus::NoLock)
149    }
150}
151
152/// A wrapper type for types whose representation may change in future versions of Arti.
153///
154/// This uses `#[serde(untagged)]` to attempt deserializing as a type `T` first, and falls back
155/// to a generic JSON value representation if that fails.
156#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
157#[serde(untagged)]
158#[allow(clippy::exhaustive_enums)]
159pub enum Futureproof<T> {
160    /// A successfully-deserialized `T`.
161    Understandable(T),
162    /// A generic JSON value, representing a failure to deserialize a `T`.
163    Unknown(JsonValue),
164}
165
166impl<T> Futureproof<T> {
167    /// Convert the `Futureproof` into an `Option<T>`, throwing away an `Unknown` value.
168    pub fn into_option(self) -> Option<T> {
169        match self {
170            Futureproof::Understandable(x) => Some(x),
171            Futureproof::Unknown(_) => None,
172        }
173    }
174}
175
176impl<T> From<T> for Futureproof<T> {
177    fn from(inner: T) -> Self {
178        Self::Understandable(inner)
179    }
180}