Debian Codegraph @

helix-event/src/registry.rs

raw symbols SCIP
1 //! A global registry where events are registered and can be
2 //! subscribed to by registering hooks. The registry identifies event
3 //! types using their type name so multiple event with the same type name
4 //! may not be registered (will cause a panic to ensure soundness)
5
6 use std::any::TypeId;
7
8 use anyhow::{bail, Result};
9 use hashbrown::hash_map::Entry;
10 use hashbrown::HashMap;
11 use parking_lot::RwLock;
12
13 use crate::hook::ErasedHook;
14 use crate::runtime_local;
15
16 pub struct Registry {
17 events: HashMap<&'static str, TypeId, foldhash::fast::FixedState>,
18 handlers: HashMap<&'static str, Vec<ErasedHook>, foldhash::fast::FixedState>,
19 }
20
21 impl Registry {
22 pub fn register_event<E: Event + 'static>(&mut self) {
23 let ty = TypeId::of::<E>();
24 assert_eq!(ty, TypeId::of::<E::Static>());
25 match self.events.entry(E::ID) {
26 Entry::Occupied(entry) => {
27 if entry.get() == &ty {
28 // don't warn during tests to avoid log spam
29 #[cfg(not(feature = "integration_test"))]
30 panic!("Event {} was registered multiple times", E::ID);
31 } else {
32 panic!("Multiple events with ID {} were registered", E::ID);
33 }
34 }
35 Entry::Vacant(ent) => {
36 ent.insert(ty);
37 self.handlers.insert(E::ID, Vec::new());
38 }
39 }
40 }
41
42 /// # Safety
43 ///
44 /// `hook` must be totally generic over all lifetime parameters of `E`. For
45 /// example if `E` was a known type `Foo<'a, 'b> then the correct trait bound
46 /// would be `F: for<'a, 'b, 'c> Fn(&'a mut Foo<'b, 'c>)` but there is no way to
47 /// express that kind of constraint for a generic type with the rust type system
48 /// right now.
49 pub unsafe fn register_hook<E: Event>(
50 &mut self,
51 hook: impl Fn(&mut E) -> Result<()> + 'static + Send + Sync,
52 ) {
53 // ensure event type ids match so we can rely on them always matching
54 let id = E::ID;
55 let Some(&event_id) = self.events.get(id) else {
56 panic!("Tried to register handler for unknown event {id}");
57 };
58 assert!(
59 TypeId::of::<E::Static>() == event_id,
60 "Tried to register invalid hook for event {id}"
61 );
62 let hook = ErasedHook::new(hook);
63 self.handlers.get_mut(id).unwrap().push(hook);
64 }
65
66 pub fn register_dynamic_hook(
67 &mut self,
68 hook: impl Fn() -> Result<()> + 'static + Send + Sync,
69 id: &str,
70 ) -> Result<()> {
71 // ensure event type ids match so we can rely on them always matching
72 if self.events.get(id).is_none() {
73 bail!("Tried to register handler for unknown event {id}");
74 };
75 let hook = ErasedHook::new_dynamic(hook);
76 self.handlers.get_mut(id).unwrap().push(hook);
77 Ok(())
78 }
79
80 pub fn dispatch<E: Event>(&self, mut event: E) {
81 let Some(hooks) = self.handlers.get(E::ID) else {
82 log::error!("Dispatched unknown event {}", E::ID);
83 return;
84 };
85 let event_id = self.events[E::ID];
86
87 assert_eq!(
88 TypeId::of::<E::Static>(),
89 event_id,
90 "Tried to dispatch invalid event {}",
91 E::ID
92 );
93
94 for hook in hooks {
95 // safety: event type is the same
96 if let Err(err) = unsafe { hook.call(&mut event) } {
97 log::error!("{} hook failed: {err:#?}", E::ID);
98 crate::status::report_blocking(err);
99 }
100 }
101 }
102 }
103
104 runtime_local! {
105 static REGISTRY: RwLock<Registry> = RwLock::new(Registry {
106 // hardcoded random number is good enough here we don't care about DOS resistance
107 // and avoids the additional complexity of `Option<Registry>`
108 events: HashMap::with_hasher(foldhash::fast::FixedState::with_seed(72536814787)),
109 handlers: HashMap::with_hasher(foldhash::fast::FixedState::with_seed(72536814787)),
110 });
111 }
112
113 pub(crate) fn with<T>(f: impl FnOnce(&Registry) -> T) -> T {
114 f(&REGISTRY.read())
115 }
116
117 pub(crate) fn with_mut<T>(f: impl FnOnce(&mut Registry) -> T) -> T {
118 f(&mut REGISTRY.write())
119 }
120
121 /// # Safety
122 /// The number of specified lifetimes and the static type *must* be correct.
123 /// This is ensured automatically by the [`events`](crate::events)
124 /// macro.
125 pub unsafe trait Event: Sized {
126 /// Globally unique (case sensitive) string that identifies this type.
127 /// A good candidate is the events type name
128 const ID: &'static str;
129 const LIFETIMES: usize;
130 type Static: Event + 'static;
131 }