Skip to main content

actix_rt/
arbiter.rs

1use std::{
2    cell::RefCell,
3    fmt,
4    future::Future,
5    io,
6    pin::Pin,
7    sync::atomic::{AtomicUsize, Ordering},
8    task::{Context, Poll},
9    thread,
10};
11
12use futures_core::ready;
13use tokio::sync::mpsc;
14
15use crate::system::{System, SystemCommand};
16
17pub(crate) static COUNT: AtomicUsize = AtomicUsize::new(0);
18
19thread_local!(
20    static HANDLE: RefCell<Option<ArbiterHandle>> = const { RefCell::new(None) };
21);
22
23pub(crate) enum ArbiterCommand {
24    Stop,
25    Execute(Pin<Box<dyn Future<Output = ()> + Send>>),
26}
27
28impl fmt::Debug for ArbiterCommand {
29    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
30        match self {
31            ArbiterCommand::Stop => write!(f, "ArbiterCommand::Stop"),
32            ArbiterCommand::Execute(_) => write!(f, "ArbiterCommand::Execute"),
33        }
34    }
35}
36
37/// A handle for sending spawn and stop messages to an [Arbiter].
38#[derive(Debug, Clone)]
39pub struct ArbiterHandle {
40    tx: mpsc::UnboundedSender<ArbiterCommand>,
41}
42
43impl ArbiterHandle {
44    pub(crate) fn new(tx: mpsc::UnboundedSender<ArbiterCommand>) -> Self {
45        Self { tx }
46    }
47
48    /// Send a future to the [Arbiter]'s thread and spawn it.
49    ///
50    /// If you require a result, include a response channel in the future.
51    ///
52    /// Returns true if future was sent successfully and false if the [Arbiter] has died.
53    pub fn spawn<Fut>(&self, future: Fut) -> bool
54    where
55        Fut: Future<Output = ()> + Send + 'static,
56    {
57        self.tx
58            .send(ArbiterCommand::Execute(Box::pin(future)))
59            .is_ok()
60    }
61
62    /// Send a function to the [Arbiter]'s thread and execute it.
63    ///
64    /// Any result from the function is discarded. If you require a result, include a response
65    /// channel in the function.
66    ///
67    /// Returns true if function was sent successfully and false if the [Arbiter] has died.
68    pub fn spawn_fn<F>(&self, f: F) -> bool
69    where
70        F: FnOnce() + Send + 'static,
71    {
72        self.spawn(async { f() })
73    }
74
75    /// Returns true if the [Arbiter]'s command channel is still open.
76    ///
77    /// The Arbiter can stop after this check, so this does not guarantee that a subsequent spawn
78    /// call will succeed.
79    pub fn alive(&self) -> bool {
80        !self.tx.is_closed()
81    }
82
83    /// Instruct [Arbiter] to stop processing it's event loop.
84    ///
85    /// Returns true if stop message was sent successfully and false if the [Arbiter] has
86    /// been dropped.
87    pub fn stop(&self) -> bool {
88        self.tx.send(ArbiterCommand::Stop).is_ok()
89    }
90}
91
92/// An Arbiter represents a thread that provides an asynchronous execution environment for futures
93/// and functions.
94///
95/// When an arbiter is created, it spawns a new [OS thread](thread), and hosts an event loop.
96#[derive(Debug)]
97pub struct Arbiter {
98    tx: mpsc::UnboundedSender<ArbiterCommand>,
99    thread_handle: thread::JoinHandle<()>,
100}
101
102impl Arbiter {
103    /// Create an [ArbiterBuilder] to configure and spawn a new Arbiter thread.
104    pub fn builder() -> ArbiterBuilder {
105        ArbiterBuilder::new()
106    }
107
108    /// Spawn a new Arbiter thread and start its event loop.
109    ///
110    /// # Panics
111    /// Panics if a [System] is not registered on the current thread, or if creating the Arbiter's
112    /// thread or Tokio runtime fails.
113    #[allow(clippy::new_without_default)]
114    pub fn new() -> Arbiter {
115        Self::try_new().expect("Failed to create new Arbiter")
116    }
117
118    /// Try to spawn a new Arbiter thread and start its event loop with the default Tokio runtime.
119    ///
120    /// # Panics
121    /// Panics if a [System] is not registered on the current thread.
122    ///
123    /// # Errors
124    /// Returns an `io::Error` if creating the underlying OS thread or Tokio runtime fails.
125    pub fn try_new() -> io::Result<Arbiter> {
126        Self::try_with_tokio_rt(crate::runtime::default_tokio_runtime)
127    }
128
129    /// Spawn a new Arbiter using the [Tokio Runtime](tokio-runtime) returned from a closure.
130    ///
131    /// The closure may return any type that can be converted into [`Runtime`], such as
132    /// `tokio::runtime::Runtime`, `Arc<tokio::runtime::Runtime>`, or
133    /// `&'static tokio::runtime::Runtime`.
134    ///
135    /// # Panics
136    /// Panics if a [System] is not registered on the current thread, or if creating the Arbiter's
137    /// thread or Tokio runtime fails.
138    ///
139    /// [tokio-runtime]: tokio::runtime::Runtime
140    /// [`Runtime`]: crate::Runtime
141    pub fn with_tokio_rt<F, R>(runtime_factory: F) -> Arbiter
142    where
143        F: FnOnce() -> R + Send + 'static,
144        R: Into<crate::runtime::Runtime> + Send + 'static,
145    {
146        Self::try_with_tokio_rt(|| Ok(runtime_factory())).expect("Failed to create new Arbiter")
147    }
148
149    /// Try to spawn a new Arbiter using the [Tokio Runtime](tokio-runtime) returned from a closure.
150    ///
151    /// The closure may return any `Result` whose success value can be converted into [`Runtime`],
152    /// such as `tokio::runtime::Runtime`, `Arc<tokio::runtime::Runtime>`, or
153    /// `&'static tokio::runtime::Runtime`.
154    ///
155    /// # Panics
156    /// Panics if a [System] is not registered on the current thread.
157    ///
158    /// # Errors
159    /// Returns an `io::Error` if creating the underlying OS thread or Tokio runtime fails.
160    ///
161    /// [tokio-runtime]: tokio::runtime::Runtime
162    /// [`Runtime`]: crate::Runtime
163    pub fn try_with_tokio_rt<F, R>(runtime_factory: F) -> io::Result<Arbiter>
164    where
165        F: FnOnce() -> io::Result<R> + Send + 'static,
166        R: Into<crate::runtime::Runtime> + Send + 'static,
167    {
168        ArbiterBuilder::new().runtime(runtime_factory).try_build()
169    }
170
171    /// Sets up an Arbiter runner in a new System using the environment's local set.
172    pub(crate) fn in_new_system() -> ArbiterHandle {
173        let (tx, rx) = mpsc::unbounded_channel();
174
175        let hnd = ArbiterHandle::new(tx);
176
177        HANDLE.with(|cell| *cell.borrow_mut() = Some(hnd.clone()));
178
179        crate::spawn(ArbiterRunner { rx });
180
181        hnd
182    }
183
184    /// Return a handle to the this Arbiter's message sender.
185    pub fn handle(&self) -> ArbiterHandle {
186        ArbiterHandle::new(self.tx.clone())
187    }
188
189    /// Return a handle to the current thread's Arbiter's message sender.
190    ///
191    /// # Panics
192    /// Panics if no Arbiter is running on the current thread.
193    pub fn current() -> ArbiterHandle {
194        HANDLE.with(|cell| match *cell.borrow() {
195            Some(ref hnd) => hnd.clone(),
196            None => panic!("Arbiter is not running."),
197        })
198    }
199
200    /// Try to get current running arbiter handle.
201    ///
202    /// Returns `None` if no Arbiter has been started.
203    ///
204    /// Unlike [`current`](Self::current), this never panics.
205    pub fn try_current() -> Option<ArbiterHandle> {
206        HANDLE.with(|cell| cell.borrow().clone())
207    }
208
209    /// Stop Arbiter from continuing it's event loop.
210    ///
211    /// Returns true if stop message was sent successfully and false if the Arbiter has been dropped.
212    pub fn stop(&self) -> bool {
213        self.tx.send(ArbiterCommand::Stop).is_ok()
214    }
215
216    /// Send a future to the Arbiter's thread and spawn it.
217    ///
218    /// If you require a result, include a response channel in the future.
219    ///
220    /// Returns true if future was sent successfully and false if the Arbiter has died.
221    #[track_caller]
222    pub fn spawn<Fut>(&self, future: Fut) -> bool
223    where
224        Fut: Future<Output = ()> + Send + 'static,
225    {
226        self.tx
227            .send(ArbiterCommand::Execute(Box::pin(future)))
228            .is_ok()
229    }
230
231    /// Send a function to the Arbiter's thread and execute it.
232    ///
233    /// Any result from the function is discarded. If you require a result, include a response
234    /// channel in the function.
235    ///
236    /// Returns true if function was sent successfully and false if the Arbiter has died.
237    #[track_caller]
238    pub fn spawn_fn<F>(&self, f: F) -> bool
239    where
240        F: FnOnce() + Send + 'static,
241    {
242        self.spawn(async { f() })
243    }
244
245    /// Returns true if the Arbiter's command channel is still open.
246    ///
247    /// The Arbiter can stop after this check, so this does not guarantee that a subsequent spawn
248    /// call will succeed.
249    pub fn alive(&self) -> bool {
250        !self.tx.is_closed()
251    }
252
253    /// Wait for Arbiter's event loop to complete.
254    ///
255    /// Joins the underlying OS thread handle. See [`JoinHandle::join`](thread::JoinHandle::join).
256    pub fn join(self) -> thread::Result<()> {
257        self.thread_handle.join()
258    }
259}
260
261/// A persistent future that processes [Arbiter] commands.
262struct ArbiterRunner {
263    rx: mpsc::UnboundedReceiver<ArbiterCommand>,
264}
265
266impl Future for ArbiterRunner {
267    type Output = ();
268
269    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
270        // process all items currently buffered in channel
271        loop {
272            match ready!(self.rx.poll_recv(cx)) {
273                // channel closed; no more messages can be received
274                None => return Poll::Ready(()),
275
276                // process arbiter command
277                Some(item) => match item {
278                    ArbiterCommand::Stop => {
279                        return Poll::Ready(());
280                    }
281                    ArbiterCommand::Execute(task_fut) => {
282                        tokio::task::spawn_local(task_fut);
283                    }
284                },
285            }
286        }
287    }
288}
289
290/// A builder for configuring and spawning a new [Arbiter] thread.
291pub struct ArbiterBuilder {
292    name_factory: Option<Box<dyn Fn(usize, usize) -> String + 'static>>,
293    runtime_factory:
294        Option<Box<dyn FnOnce() -> io::Result<crate::runtime::Runtime> + Send + 'static>>,
295}
296
297impl ArbiterBuilder {
298    /// Create a new [ArbiterBuilder].
299    #[allow(clippy::new_without_default)]
300    pub fn new() -> Self {
301        Self {
302            name_factory: None,
303            runtime_factory: None,
304        }
305    }
306
307    /// Specify a factory function for generating the name of the Arbiter thread.
308    ///
309    /// Defaults to `actix-rt|system:<system_id>|arbiter:<arb_id>`
310    ///
311    /// # Example
312    ///
313    /// ```no_run
314    /// let _ = actix_rt::System::new();
315    /// actix_rt::ArbiterBuilder::new()
316    ///     .name(|system_id, arb_id| {
317    ///         format!("some-prefix|system:{}|arbiter:{}", system_id, arb_id)
318    ///     })
319    ///     .build();
320    /// ```
321    pub fn name<F>(mut self, name_factory: F) -> ArbiterBuilder
322    where
323        F: Fn(usize, usize) -> String + 'static,
324    {
325        self.name_factory = Some(Box::new(name_factory));
326        self
327    }
328
329    /// Specify a factory function for generating the [Tokio Runtime](tokio-runtime) used by the Arbiter.
330    ///
331    /// [tokio-runtime]: tokio::runtime::Runtime
332    pub fn runtime<F, R>(mut self, runtime_factory: F) -> ArbiterBuilder
333    where
334        F: FnOnce() -> io::Result<R> + Send + 'static,
335        R: Into<crate::runtime::Runtime> + Send + 'static,
336    {
337        self.runtime_factory = Some(Box::new(move || runtime_factory().map(|rt| rt.into())));
338        self
339    }
340
341    /// Spawn a new Arbiter thread and start its event loop.
342    ///
343    /// # Panics
344    /// Panics if a [System] is not registered on the current thread.
345    pub fn build(self) -> Arbiter {
346        self.try_build()
347            .unwrap_or_else(|err| panic!("Cannot create new Arbiter: {err:?}"))
348    }
349
350    /// Try spawning a new Arbiter thread and start its event loop.
351    pub fn try_build(self) -> io::Result<Arbiter> {
352        let sys = System::current();
353        let system_id = sys.id();
354        let arb_id = COUNT.fetch_add(1, Ordering::Relaxed);
355
356        let name = match self.name_factory {
357            Some(nf) => nf(system_id, arb_id),
358            None => format!("actix-rt|system:{}|arbiter:{}", system_id, arb_id),
359        };
360        let runtime_factory = self.runtime_factory.unwrap_or_else(|| {
361            Box::new(|| crate::runtime::default_tokio_runtime().map(|rt| rt.into()))
362        });
363        let (tx, rx) = mpsc::unbounded_channel();
364
365        let (ready_tx, ready_rx) = std::sync::mpsc::channel::<io::Result<()>>();
366
367        let thread_handle = thread::Builder::new().name(name.clone()).spawn({
368            let tx = tx.clone();
369            move || {
370                let rt = match runtime_factory() {
371                    Ok(rt) => rt,
372                    Err(err) => {
373                        let _ = ready_tx.send(Err(err));
374                        return;
375                    }
376                };
377
378                let hnd = ArbiterHandle::new(tx);
379
380                System::set_current(sys);
381
382                HANDLE.with(|cell| *cell.borrow_mut() = Some(hnd.clone()));
383
384                // register arbiter
385                let _ = System::current()
386                    .tx()
387                    .send(SystemCommand::RegisterArbiter(arb_id, hnd));
388
389                if ready_tx.send(Ok(())).is_err() {
390                    unreachable!("Arbiter ready signal receiver should not be dropped before send");
391                }
392
393                // run arbiter event processing loop
394                rt.block_on(ArbiterRunner { rx });
395
396                // deregister arbiter
397                let _ = System::current()
398                    .tx()
399                    .send(SystemCommand::DeregisterArbiter(arb_id));
400            }
401        })?;
402
403        match ready_rx.recv() {
404            Ok(Ok(())) => Ok(Arbiter { tx, thread_handle }),
405            Ok(Err(err)) => {
406                let _ = thread_handle.join();
407                Err(err)
408            }
409            Err(_) => {
410                let _ = thread_handle.join();
411                Err(io::Error::other(format!(
412                    "Arbiter thread {name} panicked during initialization"
413                )))
414            }
415        }
416    }
417}