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