Debian Codegraph @

helix-event/src/runtime.rs

raw symbols SCIP
1 //! The event system makes use of global to decouple different systems.
2 //! However, this can cause problems for the integration test system because
3 //! it runs multiple helix applications in parallel. Making the globals
4 //! thread-local does not work because a applications can/does have multiple
5 //! runtime threads. Instead this crate implements a similar notion to a thread
6 //! local but instead of being local to a single thread, the statics are local to
7 //! a single tokio-runtime. The implementation requires locking so it's not exactly efficient.
8 //!
9 //! Therefore this function is only enabled during integration tests and behaves like
10 //! a normal static otherwise. I would prefer this module to be fully private and to only
11 //! export the macro but the macro still need to construct these internals so it's marked
12 //! `doc(hidden)` instead
13
14 use std::ops::Deref;
15
16 #[cfg(not(feature = "integration_test"))]
17 pub struct RuntimeLocal<T: 'static> {
18 /// inner API used in the macro, not part of public API
19 #[doc(hidden)]
20 pub __data: T,
21 }
22
23 #[cfg(not(feature = "integration_test"))]
24 impl<T> Deref for RuntimeLocal<T> {
25 type Target = T;
26
27 fn deref(&self) -> &Self::Target {
28 &self.__data
29 }
30 }
31
32 #[cfg(not(feature = "integration_test"))]
33 #[macro_export]
34 macro_rules! runtime_local {
35 ($($(#[$attr:meta])* $vis: vis static $name:ident: $ty: ty = $init: expr;)*) => {
36 $($(#[$attr])* $vis static $name: $crate::runtime::RuntimeLocal<$ty> = $crate::runtime::RuntimeLocal {
37 __data: $init
38 };)*
39 };
40 }
41
42 #[cfg(feature = "integration_test")]
43 pub struct RuntimeLocal<T: 'static> {
44 data: parking_lot::RwLock<
45 hashbrown::HashMap<tokio::runtime::Id, &'static T, foldhash::fast::FixedState>,
46 >,
47 init: fn() -> T,
48 }
49
50 #[cfg(feature = "integration_test")]
51 impl<T> RuntimeLocal<T> {
52 /// inner API used in the macro, not part of public API
53 #[doc(hidden)]
54 pub const fn __new(init: fn() -> T) -> Self {
55 Self {
56 data: parking_lot::RwLock::new(hashbrown::HashMap::with_hasher(
57 foldhash::fast::FixedState::with_seed(12345678910),
58 )),
59 init,
60 }
61 }
62 }
63
64 #[cfg(feature = "integration_test")]
65 impl<T> Deref for RuntimeLocal<T> {
66 type Target = T;
67 fn deref(&self) -> &T {
68 let id = tokio::runtime::Handle::current().id();
69 let guard = self.data.read();
70 match guard.get(&id) {
71 Some(res) => res,
72 None => {
73 drop(guard);
74 let data = Box::leak(Box::new((self.init)()));
75 let mut guard = self.data.write();
76 guard.insert(id, data);
77 data
78 }
79 }
80 }
81 }
82
83 #[cfg(feature = "integration_test")]
84 #[macro_export]
85 macro_rules! runtime_local {
86 ($($(#[$attr:meta])* $vis: vis static $name:ident: $ty: ty = $init: expr;)*) => {
87 $($(#[$attr])* $vis static $name: $crate::runtime::RuntimeLocal<$ty> = $crate::runtime::RuntimeLocal::__new(|| $init);)*
88 };
89 }