actix_rt/lib.rs
1//! Tokio-based single-threaded async runtime for the Actix ecosystem.
2//!
3//! In most parts of the the Actix ecosystem, it has been chosen to use !Send futures. For this
4//! reason, a single-threaded runtime is appropriate since it is guaranteed that futures will not
5//! be moved between threads. This can result in small performance improvements over cases where
6//! atomics would otherwise be needed.
7//!
8//! To achieve similar performance to multi-threaded, work-stealing runtimes, applications
9//! using `actix-rt` will create multiple, mostly disconnected, single-threaded runtimes.
10//! This approach has good performance characteristics for workloads where the majority of tasks
11//! have similar runtime expense.
12//!
13//! The disadvantage is that idle threads will not steal work from very busy, stuck or otherwise
14//! backlogged threads. Tasks that are disproportionately expensive should be offloaded to the
15//! blocking task thread-pool using [`task::spawn_blocking`].
16//!
17//! # Features
18//!
19//! The `macros`, `net`, and `signal` features are enabled by default. `net` enables
20//! socket types and `signal` enables OS signal handling. Disable default features to
21//! use the runtime without either facility, then enable the features you need.
22//!
23//! # Examples
24//! ```no_run
25//! use std::sync::mpsc;
26//! use actix_rt::{Arbiter, System};
27//!
28//! let _ = System::new();
29//!
30//! let (tx, rx) = mpsc::channel::<u32>();
31//!
32//! let arbiter = Arbiter::new();
33//! arbiter.spawn_fn(move || tx.send(42).unwrap());
34//!
35//! let num = rx.recv().unwrap();
36//! assert_eq!(num, 42);
37//!
38//! arbiter.stop();
39//! arbiter.join().unwrap();
40//! ```
41//!
42#![allow(clippy::type_complexity)]
43#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
44#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
45
46use std::future::Future;
47
48// Cannot define a main macro when compiled into test harness.
49// Workaround for https://github.com/rust-lang/rust/issues/62127.
50#[cfg(all(feature = "macros", not(test)))]
51pub use actix_macros::main;
52#[cfg(feature = "macros")]
53pub use actix_macros::test;
54
55mod arbiter;
56mod runtime;
57mod system;
58
59#[deprecated(since = "2.11.0", note = "Prefer `std::pin::pin!`.")]
60pub use tokio::pin;
61use tokio::task::JoinHandle;
62
63pub use self::{
64 arbiter::{Arbiter, ArbiterHandle},
65 runtime::Runtime,
66 system::{System, SystemRunner, SystemStop},
67};
68
69#[cfg(feature = "signal")]
70pub mod signal {
71 //! Asynchronous signal handling (Tokio re-exports).
72
73 #[cfg(unix)]
74 pub mod unix {
75 //! Unix specific signals (Tokio re-exports).
76 pub use tokio::signal::unix::*;
77 }
78 pub use tokio::signal::ctrl_c;
79}
80
81#[cfg(feature = "net")]
82pub mod net {
83 //! TCP/UDP/Unix bindings (mostly Tokio re-exports).
84
85 use std::{
86 future::Future,
87 io,
88 pin::pin,
89 task::{Context, Poll},
90 };
91
92 use tokio::io::{AsyncRead, AsyncWrite, BufReader, Interest};
93 #[cfg(unix)]
94 pub use tokio::net::{UnixDatagram, UnixListener, UnixStream};
95 pub use tokio::{
96 io::Ready,
97 net::{TcpListener, TcpSocket, TcpStream, UdpSocket},
98 };
99
100 /// Extension trait over async read+write types that can also signal readiness.
101 #[doc(hidden)]
102 pub trait ActixStream: AsyncRead + AsyncWrite + Unpin {
103 /// Poll stream and check read readiness of Self.
104 ///
105 /// See [tokio::net::TcpStream::poll_read_ready] for detail on intended use.
106 fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>;
107
108 /// Poll stream and check write readiness of Self.
109 ///
110 /// See [tokio::net::TcpStream::poll_write_ready] for detail on intended use.
111 fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>>;
112 }
113
114 impl ActixStream for TcpStream {
115 fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
116 let ready = self.ready(Interest::READABLE);
117 pin!(ready).poll(cx)
118 }
119
120 fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
121 let ready = self.ready(Interest::WRITABLE);
122 pin!(ready).poll(cx)
123 }
124 }
125
126 #[cfg(unix)]
127 impl ActixStream for UnixStream {
128 fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
129 let ready = self.ready(Interest::READABLE);
130 pin!(ready).poll(cx)
131 }
132
133 fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
134 let ready = self.ready(Interest::WRITABLE);
135 pin!(ready).poll(cx)
136 }
137 }
138
139 impl<Io: ActixStream + ?Sized> ActixStream for Box<Io> {
140 fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
141 (**self).poll_read_ready(cx)
142 }
143
144 fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
145 (**self).poll_write_ready(cx)
146 }
147 }
148
149 impl<Io: ActixStream> ActixStream for BufReader<Io> {
150 fn poll_read_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
151 self.get_ref().poll_read_ready(cx)
152 }
153
154 fn poll_write_ready(&self, cx: &mut Context<'_>) -> Poll<io::Result<Ready>> {
155 self.get_ref().poll_write_ready(cx)
156 }
157 }
158}
159
160pub mod time {
161 //! Utilities for tracking time (Tokio re-exports).
162
163 pub use tokio::time::{
164 interval, interval_at, sleep, sleep_until, timeout, Instant, Interval, Sleep, Timeout,
165 };
166}
167
168pub mod task {
169 //! Task management (Tokio re-exports).
170
171 pub use tokio::task::{spawn_blocking, yield_now, JoinError, JoinHandle};
172}
173
174/// Spawns a future on the current thread as a new task.
175///
176/// If not immediately awaited, the task can be cancelled using [`JoinHandle::abort`].
177///
178/// The provided future is spawned as a new task; therefore, panics are caught.
179///
180/// # Panics
181/// Panics if Actix system is not running.
182///
183/// # Examples
184/// ```
185/// # use std::time::Duration;
186/// # actix_rt::Runtime::new().unwrap().block_on(async {
187/// // task resolves successfully
188/// assert_eq!(actix_rt::spawn(async { 1 }).await.unwrap(), 1);
189///
190/// // task panics
191/// assert!(actix_rt::spawn(async {
192/// panic!("panic is caught at task boundary");
193/// })
194/// .await
195/// .unwrap_err()
196/// .is_panic());
197///
198/// // task is cancelled before completion
199/// let handle = actix_rt::spawn(actix_rt::time::sleep(Duration::from_secs(100)));
200/// handle.abort();
201/// assert!(handle.await.unwrap_err().is_cancelled());
202/// # });
203/// ```
204#[track_caller]
205#[inline]
206pub fn spawn<Fut>(f: Fut) -> JoinHandle<Fut::Output>
207where
208 Fut: Future + 'static,
209 Fut::Output: 'static,
210{
211 tokio::task::spawn_local(f)
212}