Skip to main content

nsh_core/element/
engine_context.rs

1//! What a host gives one engine: typed values its UI sets' Rust code reads
2//! while that engine runs it ([`engine_context`]).
3//!
4//! Several engines run in one process (one per surface), and a module
5//! function is a free function: what it reaches of its host would be
6//! process-wide without this. The engine makes its context its thread's
7//! ([`EngineContext::enter`]) for its whole run, so module functions read
8//! it in the JS call, as ops and as `async` tasks (polled on that thread),
9//! and so do components. Work sent to other threads (`background`) does
10//! not see it: read it first and move the value there.
11
12use std::{
13    any::{Any, TypeId},
14    cell::RefCell,
15    fmt,
16    marker::PhantomData,
17    rc::Rc,
18    sync::Arc,
19};
20
21use rustc_hash::FxHashMap;
22
23type Values = FxHashMap<TypeId, Arc<dyn Any + Send + Sync>>;
24
25/// Typed values a host gives one engine (`EngineConfig::context`), at most
26/// one per type, which its Rust code reads with [`engine_context`].
27#[derive(Clone, Default)]
28#[non_exhaustive]
29pub struct EngineContext {
30    values: Arc<Values>,
31}
32
33impl EngineContext {
34    /// This context with `value` as its `T`, replacing one it had.
35    pub fn with<T: Send + Sync + 'static>(mut self, value: T) -> Self {
36        Arc::make_mut(&mut self.values).insert(TypeId::of::<T>(), Arc::new(value));
37        self
38    }
39
40    /// Its `T`, if it has one.
41    pub fn get<T: Send + Sync + 'static>(&self) -> Option<Arc<T>> {
42        self.values
43            .get(&TypeId::of::<T>())
44            .cloned()
45            .and_then(|value| value.downcast::<T>().ok())
46    }
47
48    /// Makes it the current thread's until the guard drops: what
49    /// [`engine_context`] reads there (the engine does this on its thread).
50    pub fn enter(&self) -> EngineContextGuard {
51        let previous = CURRENT.with(|current| current.replace(Some(self.clone())));
52        EngineContextGuard {
53            previous,
54            _thread: PhantomData,
55        }
56    }
57}
58
59impl fmt::Debug for EngineContext {
60    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61        f.debug_struct("EngineContext")
62            .field("values", &self.values.len())
63            .finish()
64    }
65}
66
67thread_local! {
68    /// The context of the engine on this thread.
69    static CURRENT: RefCell<Option<EngineContext>> = const { RefCell::new(None) };
70}
71
72/// Puts the thread's previous context back ([`EngineContext::enter`]).
73///
74/// It stays on the thread that entered. Its drop writes that thread's
75/// context, so the guard is not [`Send`].
76#[must_use = "the context is the thread's while the guard lives"]
77pub struct EngineContextGuard {
78    previous: Option<EngineContext>,
79    /// `Rc` is not `Send`: the guard cannot move to a thread whose
80    /// thread-local it must not write.
81    _thread: PhantomData<Rc<()>>,
82}
83
84// `Send` would make `EngineContextGuard::check` ambiguous (both impls
85// apply). A guard that moves to another thread would restore this
86// thread's previous context there.
87const _: fn() = || {
88    trait AmbiguousIfSend<A> {
89        fn check() {}
90    }
91    impl<T: ?Sized> AmbiguousIfSend<()> for T {}
92    impl<T: ?Sized + Send> AmbiguousIfSend<u8> for T {}
93    let _ = EngineContextGuard::check;
94};
95
96impl Drop for EngineContextGuard {
97    fn drop(&mut self) {
98        let previous = self.previous.take();
99        // Host values may read the context during cleanup; release the
100        // mutable borrow before dropping the context that owns them.
101        let outgoing = CURRENT.with(|current| current.replace(previous));
102        drop(outgoing);
103    }
104}
105
106/// The `T` the host gave the engine running this code
107/// ([`EngineContext::with`]); `None` without one, or off the engine's
108/// thread.
109pub fn engine_context<T: Send + Sync + 'static>() -> Option<Arc<T>> {
110    CURRENT.with(|current| current.borrow().as_ref()?.get::<T>())
111}
112
113#[cfg(test)]
114mod tests {
115    use super::*;
116
117    #[test]
118    fn a_thread_reads_the_context_it_entered_until_the_guard_drops() {
119        let outer = EngineContext::default().with(1_u32).with("outer");
120        let inner = EngineContext::default().with(2_u32);
121        assert_eq!(engine_context::<u32>(), None);
122        {
123            let _outer = outer.enter();
124            assert_eq!(engine_context::<u32>().as_deref(), Some(&1));
125            {
126                let _inner = inner.enter();
127                assert_eq!(engine_context::<u32>().as_deref(), Some(&2));
128                assert_eq!(engine_context::<&str>(), None);
129            }
130            assert_eq!(engine_context::<&str>().as_deref(), Some(&"outer"));
131        }
132        assert_eq!(engine_context::<u32>(), None);
133    }
134
135    #[test]
136    fn releasing_context_values_allows_them_to_read_the_restored_context() {
137        use std::sync::atomic::{AtomicBool, Ordering};
138
139        struct HostState(Arc<AtomicBool>);
140        impl Drop for HostState {
141            fn drop(&mut self) {
142                assert_eq!(engine_context::<u32>().as_deref(), Some(&7));
143                self.0.store(true, Ordering::SeqCst);
144            }
145        }
146
147        let _outer = EngineContext::default().with(7_u32).enter();
148        let released = Arc::new(AtomicBool::new(false));
149        // Only the thread-local owns this context when its guard exits,
150        // as after LocalEngine releases its driver during shutdown.
151        let inner = EngineContext::default()
152            .with(HostState(released.clone()))
153            .enter();
154        drop(inner);
155        assert!(released.load(Ordering::SeqCst));
156        assert_eq!(engine_context::<u32>().as_deref(), Some(&7));
157    }
158}