vortex_session/lib.rs
1// SPDX-License-Identifier: Apache-2.0
2// SPDX-FileCopyrightText: Copyright the Vortex contributors
3
4mod arc_swap_map;
5pub mod registry;
6mod session;
7
8use std::any::Any;
9use std::fmt::Debug;
10use std::hash::Hasher;
11
12pub use arc_swap_map::ArcSwapMap;
13pub use session::SessionGuard;
14pub use session::VortexSession;
15pub use session::VortexSessionVar;
16
17#[derive(Debug, Clone, Copy, Default)]
18struct UnknownPluginPolicy {
19 allow_unknown: bool,
20}
21
22impl SessionVar for UnknownPluginPolicy {
23 fn as_any(&self) -> &dyn Any {
24 self
25 }
26
27 fn as_any_mut(&mut self) -> &mut dyn Any {
28 self
29 }
30}
31
32/// Trait for accessing the state of a Vortex session.
33pub trait SessionExt: Sized + private::Sealed {
34 /// Returns the [`VortexSession`].
35 fn session(&self) -> VortexSession;
36
37 /// Returns the session variable of type `V`, inserting a default one if it does not exist.
38 ///
39 /// This is [`get_or_insert_with`](Self::get_or_insert_with) with `V::default` as the
40 /// initializer.
41 fn get<V: VortexSessionVar + Default>(&self) -> SessionGuard<'_, V>;
42
43 /// Returns the session variable of type `V`, inserting the result of `init` if it does not
44 /// exist.
45 ///
46 /// Use this instead of [`get`](Self::get) when the first value of `V` depends on the session,
47 /// for example on another session variable. The value is constructed and inserted
48 /// copy-on-write: `init` runs without any lock held, so it may freely re-enter the session. A
49 /// concurrent insert of the same type is resolved by keeping the first value published, so
50 /// `init` may run even though its result is then dropped.
51 fn get_or_insert_with<V: VortexSessionVar>(
52 &self,
53 init: impl FnOnce() -> V,
54 ) -> SessionGuard<'_, V>;
55
56 /// Returns the session variable of type `V` if it exists.
57 fn get_opt<V: VortexSessionVar>(&self) -> Option<SessionGuard<'_, V>>;
58}
59
60mod private {
61 pub trait Sealed {}
62 impl Sealed for super::VortexSession {}
63}
64
65/// This trait defines variables that can be stored against a Vortex session.
66///
67/// Users should implement this trait for anything that you want to store on a `VortexSession`.
68pub trait SessionVar: Any + Send + Sync + Debug + 'static {
69 fn as_any(&self) -> &dyn Any;
70 fn as_any_mut(&mut self) -> &mut dyn Any;
71}
72
73/// With TypeIds as keys, there's no need to hash them. They are already hashes
74/// themselves, coming from the compiler. The IdHasher just holds the u64 of
75/// the TypeId, and then returns it, instead of doing any bit fiddling.
76#[derive(Default)]
77struct IdHasher(u64);
78
79impl Hasher for IdHasher {
80 #[inline]
81 fn finish(&self) -> u64 {
82 self.0
83 }
84
85 fn write(&mut self, _: &[u8]) {
86 unreachable!("TypeId calls write_u64");
87 }
88
89 #[inline]
90 fn write_u64(&mut self, id: u64) {
91 self.0 = id;
92 }
93}