Skip to main content

ntex_rt/
arbiter.rs

1#![allow(clippy::missing_panics_doc)]
2use std::sync::{Arc, atomic::AtomicBool, atomic::AtomicUsize, atomic::Ordering};
3use std::{any::Any, any::TypeId, cell::RefCell, fmt, mem, panic, pin::Pin, thread};
4
5use async_channel::{Receiver, Sender, unbounded};
6use parking_lot::Mutex;
7
8use crate::{Handle, HashMap, Id, System};
9
10thread_local!(
11    static ADDR: RefCell<Option<Arbiter>> = const { RefCell::new(None) };
12    static STORAGE: RefCell<HashMap<TypeId, Box<dyn Any>>> = RefCell::new(HashMap::default());
13);
14
15pub(super) static COUNT: AtomicUsize = AtomicUsize::new(99);
16
17pub(super) enum ArbiterCommand {
18    Stop,
19    #[allow(dead_code)]
20    Execute(Pin<Box<dyn Future<Output = ()> + Send>>),
21}
22
23/// An asynchronous execution environment running on one OS thread.
24///
25/// Creating an arbiter starts a thread with its own local event loop. Futures
26/// spawned on that event loop are not required to implement `Send`.
27pub struct Arbiter(pub(crate) Arc<ArbiterInner>);
28
29type OnCloseStorage = Arc<Mutex<Vec<Box<dyn Fn() + Send + Sync>>>>;
30
31pub(crate) struct ArbiterInner {
32    id: usize,
33    name: Arc<String>,
34    sys_id: usize,
35    hnd: Option<Handle>,
36    pub(crate) sender: Sender<ArbiterCommand>,
37    thread_handle: Mutex<Option<thread::JoinHandle<()>>>,
38    on_stop: OnCloseStorage,
39    running: AtomicBool,
40    #[cfg(target_os = "linux")]
41    tid: i32,
42}
43
44impl fmt::Debug for Arbiter {
45    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
46        write!(f, "Arbiter({:?})", self.0.name.as_ref())
47    }
48}
49
50impl Clone for Arbiter {
51    fn clone(&self) -> Self {
52        Self(self.0.clone())
53    }
54}
55
56impl Default for Arbiter {
57    fn default() -> Self {
58        Self::new()
59    }
60}
61
62impl Arbiter {
63    #[allow(clippy::borrowed_box)]
64    pub(super) fn new_system(id: usize, name: String) -> (Self, ArbiterController) {
65        let (tx, rx) = unbounded();
66
67        let aid = COUNT.fetch_add(1, Ordering::Relaxed);
68        let arb = Arbiter::with_sender(id, aid, Arc::new(name), tx, Arc::default());
69        ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
70        STORAGE.with(|cell| cell.borrow_mut().clear());
71
72        (
73            arb,
74            ArbiterController {
75                rx,
76                sys: None,
77                stop: None,
78            },
79        )
80    }
81
82    /// Returns the arbiter running on the current thread.
83    ///
84    /// # Panics
85    ///
86    /// Panics if no arbiter is running on the current thread.
87    pub fn current() -> Arbiter {
88        ADDR.with(|cell| match *cell.borrow() {
89            Some(ref addr) => addr.clone(),
90            None => panic!("Arbiter is not running"),
91        })
92    }
93
94    /// Requests that the arbiter stop its event loop.
95    pub fn stop(&self) {
96        let _ = self.0.sender.try_send(ArbiterCommand::Stop);
97    }
98
99    /// Starts an arbiter on a new thread with an automatically generated name.
100    pub fn new() -> Arbiter {
101        let id = COUNT.load(Ordering::Relaxed) + 1;
102        Arbiter::with_name(format!("{}:arb:{}", System::current().name(), id))
103    }
104
105    /// Starts an arbiter on a new thread with the specified name.
106    pub fn with_name(name: String) -> Arbiter {
107        let id = COUNT.fetch_add(1, Ordering::Relaxed);
108        let sys = System::current();
109        let name2 = Arc::new(name.clone());
110        let config = sys.config();
111        let (arb_tx, arb_rx) = unbounded();
112
113        let builder = if sys.config().stack_size > 0 {
114            thread::Builder::new()
115                .name(name)
116                .stack_size(sys.config().stack_size)
117        } else {
118            thread::Builder::new().name(name)
119        };
120
121        let name = name2.clone();
122        let sys_id = sys.id();
123        let (arb_hnd_tx, arb_hnd_rx) = oneshot::channel();
124
125        let handle = builder
126            .spawn(move || {
127                let name3 = name2.clone();
128                log::info!("Starting {name3:?} arbiter");
129
130                let sys2 = sys.clone();
131                let (stop, stop_rx) = oneshot::channel();
132                STORAGE.with(|cell| cell.borrow_mut().clear());
133
134                let on_stop = Arc::new(Mutex::new(Vec::new()));
135                let on_stop2 = on_stop.clone();
136
137                let result = crate::driver::block_on(config.runner.as_ref(), async move {
138                    let arb = Arbiter::with_sender(sys_id.0, id, name2, arb_tx, on_stop);
139                    sys.register_arbiter(arb.clone());
140                    arb_hnd_tx
141                        .send(arb.clone())
142                        .expect("Controller thread has gone");
143
144                    // start arbiter controller
145                    crate::spawn(
146                        ArbiterController {
147                            sys: None,
148                            stop: Some(stop),
149                            rx: arb_rx,
150                        }
151                        .run(sys),
152                    );
153                    ADDR.with(|cell| *cell.borrow_mut() = Some(arb.clone()));
154
155                    // run loop
156                    let _ = stop_rx.await;
157
158                    // mark as not running
159                    arb.0.running.store(false, Ordering::Relaxed);
160                });
161
162                let on_stop = mem::take(&mut *on_stop2.lock());
163                for f in on_stop {
164                    f();
165                }
166
167                // unregister arbiter
168                sys2.unregister_arbiter(Id(id));
169                unsafe {
170                    remove_all_items();
171                }
172
173                if let Err(e) = result {
174                    log::error!("Arbiter {name3:?} has panicked.");
175                    panic::resume_unwind(e);
176                }
177                log::info!("Arbiter {name3:?} has stopped");
178            })
179            .unwrap_or_else(|err| panic!("Cannot spawn an arbiter's thread {name:?}: {err:?}"));
180
181        let arb = arb_hnd_rx.recv().expect("Could not start new arbiter");
182        *arb.0.thread_handle.lock() = Some(handle);
183        arb
184    }
185
186    fn with_sender(
187        sys_id: usize,
188        id: usize,
189        name: Arc<String>,
190        sender: Sender<ArbiterCommand>,
191        on_stop: OnCloseStorage,
192    ) -> Self {
193        #[cfg(feature = "tokio")]
194        let hnd = { Handle::new(sender.clone()) };
195
196        #[cfg(feature = "compio")]
197        let hnd = { Handle::new(sender.clone()) };
198
199        #[cfg(all(not(feature = "compio"), not(feature = "tokio")))]
200        let hnd = { Handle::current() };
201
202        Self(Arc::new(ArbiterInner {
203            id,
204            sys_id,
205            name,
206            sender,
207            on_stop,
208            hnd: Some(hnd),
209            thread_handle: Mutex::new(None),
210            running: AtomicBool::new(true),
211            #[cfg(target_os = "linux")]
212            #[allow(clippy::cast_possible_truncation)]
213            tid: unsafe { libc::syscall(libc::SYS_gettid) } as i32,
214        }))
215    }
216
217    /// Returns the arbiter identifier.
218    pub fn id(&self) -> Id {
219        Id(self.0.id)
220    }
221
222    #[cfg(target_os = "linux")]
223    /// TID of the arbiter
224    pub(crate) fn tid(&self) -> i32 {
225        self.0.tid
226    }
227
228    /// Returns the arbiter name.
229    pub fn name(&self) -> &str {
230        self.0.name.as_ref()
231    }
232
233    #[inline]
234    /// Returns a handle to the arbiter's runtime.
235    pub fn handle(&self) -> &Handle {
236        self.0.hnd.as_ref().unwrap()
237    }
238
239    #[inline]
240    /// Returns whether the arbiter is running.
241    pub fn is_running(&self) -> bool {
242        self.0.running.load(Ordering::Relaxed)
243    }
244
245    /// Returns a value from thread-local arbiter storage, inserting it if absent.
246    pub fn get_value<T, F>(f: F) -> T
247    where
248        T: Clone + 'static,
249        F: FnOnce() -> T,
250    {
251        STORAGE.with(move |cell| {
252            let mut st = cell.borrow_mut();
253            if let Some(boxed) = st.get(&TypeId::of::<T>())
254                && let Some(val) = (&**boxed as &(dyn Any + 'static)).downcast_ref::<T>()
255            {
256                return val.clone();
257            }
258            let val = f();
259            st.insert(TypeId::of::<T>(), Box::new(val.clone()));
260            val
261        })
262    }
263
264    #[must_use]
265    /// Adds a callback to run after the arbiter stops.
266    pub fn on_stop<F>(self, f: F) -> Self
267    where
268        F: Fn() + Send + Sync + 'static,
269    {
270        self.0.on_stop.lock().push(Box::new(f));
271        self
272    }
273
274    /// Waits for the arbiter's thread to stop.
275    ///
276    /// This returns immediately for an arbiter that does not own a thread
277    /// handle, including the system's primary arbiter.
278    pub fn join(&mut self) -> thread::Result<()> {
279        if let Some(thread_handle) = self.0.thread_handle.lock().take() {
280            thread_handle.join()
281        } else {
282            Ok(())
283        }
284    }
285}
286
287impl Eq for Arbiter {}
288
289impl PartialEq for Arbiter {
290    fn eq(&self, other: &Self) -> bool {
291        self.0.id == other.0.id && self.0.sys_id == other.0.sys_id
292    }
293}
294
295pub(crate) struct ArbiterController {
296    sys: Option<System>,
297    rx: Receiver<ArbiterCommand>,
298    stop: Option<oneshot::Sender<i32>>,
299}
300
301impl ArbiterController {
302    pub(super) async fn run(mut self, sys: System) {
303        self.sys = Some(sys);
304        loop {
305            match self.rx.recv().await {
306                Ok(ArbiterCommand::Stop) => {
307                    if let Some(stop) = self.stop.take() {
308                        let _ = stop.send(0);
309                    }
310                }
311                Ok(ArbiterCommand::Execute(fut)) => {
312                    crate::spawn(fut);
313                }
314                Err(_) => break,
315            }
316        }
317    }
318}
319
320/// Inserts a value into the current arbiter's thread-local storage.
321pub fn set_item<T: 'static>(item: T) {
322    STORAGE.with(move |cell| cell.borrow_mut().insert(TypeId::of::<T>(), Box::new(item)));
323}
324
325/// Returns a cloned value from the current arbiter's thread-local storage.
326pub fn get_item<T: Clone + 'static>() -> Option<T> {
327    STORAGE.with(move |cell| {
328        cell.borrow()
329            .get(&TypeId::of::<T>())
330            .and_then(|boxed| boxed.downcast_ref())
331            .cloned()
332    })
333}
334
335/// Provides access to a value in the current arbiter's thread-local storage.
336///
337/// A default value is inserted if the requested type is not already present.
338pub fn with_item<T: Default + 'static, F, R>(f: F) -> R
339where
340    F: FnOnce(&T) -> R,
341{
342    STORAGE.with(move |cell| {
343        // SAFETY: value of T is stored in heap, manipulation
344        // with STORAGE are not affected location of T
345        let val: &T = unsafe {
346            let mut st = cell.borrow_mut();
347            if let Some(boxed) = st.get(&TypeId::of::<T>()) {
348                std::mem::transmute::<&T, &T>(boxed.downcast_ref::<T>().unwrap())
349            } else {
350                st.insert(TypeId::of::<T>(), Box::new(T::default()));
351                let boxed = st.get(&TypeId::of::<T>()).unwrap();
352                std::mem::transmute::<&T, &T>(boxed.downcast_ref::<T>().unwrap())
353            }
354        };
355        f(val)
356    })
357}
358
359#[doc(hidden)]
360/// Remove all items from storage.
361///
362/// # Safety
363///
364/// All outstanding calls to [`with_item`] must have completed.
365pub unsafe fn remove_all_items() {
366    STORAGE.with(move |cell| {
367        loop {
368            let mut items = cell.borrow_mut();
369            let Some(key) = items.keys().next().copied() else {
370                break;
371            };
372            items.remove(&key);
373            drop(items);
374        }
375    });
376    System::remove_current();
377}