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 @@ -->
4546// TODO #1645 (either remove this, or decide to have it everywhere)
47#![cfg_attr(not(all(feature = "experimental", feature = "full")), allow(unused))]
4849mod err;
50#[cfg(not(target_arch = "wasm32"))]
51mod fs;
52mod fs_mistrust_error_ext;
53mod handle;
54pub mod hsnickname;
55mod load_store;
56pub mod slug;
57#[cfg(feature = "testing")]
58mod testing;
5960#[cfg(feature = "state-dir")]
61pub mod state_dir;
6263use serde::{de::DeserializeOwned, Deserialize, Serialize};
64use std::sync::Arc;
6566/// Wrapper type for Results returned from this crate.
67type Result<T> = std::result::Result<T, crate::Error>;
6869pub use err::{Error, ErrorSource};
70#[cfg(not(target_arch = "wasm32"))]
71pub use fs::FsStateMgr;
72pub use fs_mistrust_error_ext::FsMistrustErrorExt;
73pub use handle::{DynStorageHandle, StorageHandle};
74pub use serde_json::Value as JsonValue;
75#[cfg(feature = "testing")]
76pub use testing::TestingStateMgr;
7778/// 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.
88pub trait StateMgr: Clone {
89/// Try to load the object with key `key` from the store.
90 ///
91 /// Return None if no such object exists.
92fn load<D>(&self, key: &str) -> Result<Option<D>>
93where
94D: DeserializeOwned;
95/// Try to save `val` with key `key` in the store.
96 ///
97 /// Replaces any previous value associated with `key`.
98fn store<S>(&self, key: &str, val: &S) -> Result<()>
99where
100S: 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)
105fn can_store(&self) -> bool;
106107/// 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.
114fn try_lock(&self) -> Result<LockStatus>;
115116/// Release any locks held and become a read-only state manager
117 /// again. If no locks were held, do nothing.
118fn unlock(&self) -> Result<()>;
119120/// Make a new [`StorageHandle`] to store values of particular type
121 /// at a particular key.
122fn create_handle<T>(self, key: impl Into<String>) -> DynStorageHandle<T>
123where
124Self: Send + Sync + Sized + 'static,
125 T: Serialize + DeserializeOwned + 'static,
126 {
127 Arc::new(handle::StorageHandleImpl::new(self, key.into()))
128 }
129}
130131/// A possible outcome from calling [`StateMgr::try_lock()`]
132#[allow(clippy::exhaustive_enums)]
133#[derive(Debug, Copy, Clone, Eq, PartialEq)]
134#[must_use]
135pub enum LockStatus {
136/// We didn't have the lock and were unable to acquire it.
137NoLock,
138/// We already held the lock, and didn't have anything to do.
139AlreadyHeld,
140/// We successfully acquired the lock for the first time.
141NewlyAcquired,
142}
143144impl LockStatus {
145/// Return true if this status indicates that we hold the lock.
146pub fn held(&self) -> bool {
147 !matches!(self, LockStatus::NoLock)
148 }
149}
150151/// 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)]
158pub enum Futureproof<T> {
159/// A successfully-deserialized `T`.
160Understandable(T),
161/// A generic JSON value, representing a failure to deserialize a `T`.
162Unknown(JsonValue),
163}
164165impl<T> Futureproof<T> {
166/// Convert the `Futureproof` into an `Option<T>`, throwing away an `Unknown` value.
167pub fn into_option(self) -> Option<T> {
168match self {
169 Futureproof::Understandable(x) => Some(x),
170 Futureproof::Unknown(_) => None,
171 }
172 }
173}
174175impl<T> From<T> for Futureproof<T> {
176fn from(inner: T) -> Self {
177Self::Understandable(inner)
178 }
179}