ntex_rt/builder.rs
1use std::{fmt, future::Future, io, marker::PhantomData, panic, rc::Rc, sync::Arc, time};
2
3use crate::{TaskCallbacks, driver::Runner, signals, system::System, system::SystemConfig};
4
5#[derive(Debug, Clone)]
6/// Builder for an ntex runtime system.
7///
8/// Obtain a builder from [`System::build`]. Use [`build`](Self::build) to create
9/// a [`SystemRunner`], then run the event loop or block on a future.
10#[allow(clippy::struct_excessive_bools)]
11pub struct Builder {
12 /// Name of the System. Defaults to "ntex" if unset.
13 name: String,
14 /// New thread stack size
15 stack_size: usize,
16 /// Arbiters ping interval
17 ping_interval: usize,
18 /// Arbiter ping response threshold
19 ping_threshold: usize,
20 /// Arbiter latency sampling interval
21 latency_interval: usize,
22 /// Signal handling
23 signals: bool,
24 /// Fatal signal handling
25 fatal_signals: bool,
26 /// Panic handling
27 panics: bool,
28 /// Thread pool config
29 pool_limit: usize,
30 pool_recv_timeout: time::Duration,
31 /// Timer wheel resolution in milliseconds
32 timer_resolution: u8,
33 /// testing flag
34 testing: bool,
35 /// Task instrumentation callbacks
36 task_callbacks: Option<fn() -> TaskCallbacks>,
37}
38
39impl Builder {
40 pub(super) fn new() -> Self {
41 Builder {
42 name: "ntex".into(),
43 stack_size: 0,
44 ping_interval: 2000,
45 ping_threshold: 1000,
46 latency_interval: 100,
47 signals: false,
48 fatal_signals: false,
49 panics: false,
50 testing: false,
51 pool_limit: 64,
52 pool_recv_timeout: time::Duration::from_mins(1),
53 timer_resolution: 16,
54 task_callbacks: None,
55 }
56 }
57
58 #[must_use]
59 /// Sets the system name, used when naming its threads.
60 ///
61 /// The default is `"ntex"`.
62 pub fn name<N: AsRef<str>>(mut self, name: N) -> Self {
63 self.name = name.as_ref().into();
64 self
65 }
66
67 #[must_use]
68 /// Enables or disables process signal handling.
69 ///
70 /// By default, signal handling is disabled. At startup the system attempts
71 /// to acquire process-wide ownership; another system's existing registration
72 /// is not replaced. See [`System::enable_signals`].
73 pub fn signals(mut self, enabled: bool) -> Self {
74 self.signals = enabled;
75 self
76 }
77
78 #[must_use]
79 /// Enables or disables installation of the process-wide panic hook at startup.
80 ///
81 /// When panic handling is enabled, the application can receive
82 /// `Signal::Panic(PanicSource::App(..))` signals while signal handling
83 /// is enabled. The previously installed panic hook is still called.
84 /// The hook is installed once and remains installed for the process lifetime;
85 /// `false` does not remove a hook installed earlier. By default, installation
86 /// is disabled.
87 pub fn panic_handling(mut self, enabled: bool) -> Self {
88 self.panics = enabled;
89 self
90 }
91
92 #[must_use]
93 /// Enables or disables installation of the process-wide `SIGSEGV` and
94 /// `SIGABRT` handlers at startup.
95 ///
96 /// When fatal signal handling is enabled, the application can receive
97 /// best-effort `Signal::Panic(PanicSource::Sig(..))` signals while signal
98 /// handling is enabled. The process still terminates as it would without
99 /// the handlers. The handlers are installed once and remain installed for
100 /// the process lifetime; `false` does not remove handlers installed earlier.
101 /// Has no effect on non-Unix platforms. By default, installation is disabled.
102 pub fn fatal_signals(mut self, enabled: bool) -> Self {
103 self.fatal_signals = enabled;
104 self
105 }
106
107 #[doc(hidden)]
108 #[must_use]
109 /// Disable signal handling.
110 ///
111 /// By default, signal handling is disabled.
112 pub fn disable_signals(mut self) -> Self {
113 self.signals = false;
114 self
115 }
116
117 #[doc(hidden)]
118 #[must_use]
119 /// Enable signal handling.
120 ///
121 /// By default, signal handling is disabled.
122 pub fn enable_signals(mut self) -> Self {
123 self.signals = true;
124 self
125 }
126
127 #[must_use]
128 /// Sets the stack size, in bytes, for newly spawned arbiter threads.
129 ///
130 /// The default is zero, which uses the standard library's thread stack size.
131 /// This does not change the primary arbiter's or blocking pool workers' stacks.
132 pub fn stack_size(mut self, size: usize) -> Self {
133 self.stack_size = size;
134 self
135 }
136
137 #[must_use]
138 /// Sets the ping interval for all registered arbiters, including the primary.
139 ///
140 /// The interval is specified in milliseconds and defaults to 2,000.
141 /// Set it to zero to disable pings.
142 pub fn ping_interval(mut self, interval: usize) -> Self {
143 self.ping_interval = interval;
144 self
145 }
146
147 #[must_use]
148 /// Sets the arbiter stall threshold.
149 ///
150 /// A watchdog thread marks an arbiter as stalled when its pending latency
151 /// sample is late by more than this threshold, see
152 /// [`LatencyMetrics::stalls`](crate::metrics::LatencyMetrics::stalls). On Linux and
153 /// Windows an attempt is made to create a backtrace for the stalled arbiter.
154 ///
155 /// The threshold is specified in milliseconds and defaults to 1,000.
156 pub fn ping_threshold(mut self, interval: usize) -> Self {
157 self.ping_threshold = interval;
158 self
159 }
160
161 #[must_use]
162 /// Sets the scheduling latency sampling interval for arbiters.
163 ///
164 /// Each arbiter runs a task that sleeps for the interval and records how
165 /// late it wakes up, see [`Arbiter::latency`](crate::Arbiter::latency).
166 ///
167 /// The interval is specified in milliseconds and defaults to 100.
168 /// Set it to zero to disable sampling and stall detection.
169 pub fn latency_interval(mut self, interval: usize) -> Self {
170 self.latency_interval = interval;
171 self
172 }
173
174 #[must_use]
175 /// Sets the maximum number of blocking thread-pool workers per arbiter.
176 ///
177 /// Each arbiter, including the primary one, has its own pool, see
178 /// [`System::spawn_blocking`](crate::System::spawn_blocking). The default
179 /// is 64. Zero is treated as one; excess work is queued.
180 pub fn thread_pool_limit(mut self, value: usize) -> Self {
181 self.pool_limit = value;
182 self
183 }
184
185 #[must_use]
186 /// Sets the resolution of the timer wheel, in milliseconds.
187 ///
188 /// Timers of the `ntex` time utilities fire on ticks of this length, a
189 /// timer may fire up to one tick late. A finer resolution reduces the
190 /// latency of short timers but wakes the timer driver more often and
191 /// shrinks the range of each wheel level.
192 ///
193 /// The resolution must be a power of two between 1 and 16. The default
194 /// is 16. Each thread reads the setting when its first timer is armed
195 /// and keeps it until the system stops.
196 ///
197 /// # Panics
198 ///
199 /// Panics if `millis` is not a power of two between 1 and 16.
200 pub fn timer_resolution(mut self, millis: u8) -> Self {
201 assert!(
202 millis.is_power_of_two() && millis <= 16,
203 "timer resolution must be a power of two between 1 and 16 ms, got {millis}"
204 );
205 self.timer_resolution = millis;
206 self
207 }
208
209 #[must_use]
210 /// Sets a factory of callbacks for instrumenting tasks spawned on the
211 /// system's threads.
212 ///
213 /// The factory is called on the system thread and on each of its arbiter
214 /// threads when the thread joins the system, so it can set up per-thread
215 /// state for its callbacks. See [`TaskCallbacks`] for when they are
216 /// called. By default, no callbacks are set.
217 pub fn task_callbacks(mut self, factory: fn() -> TaskCallbacks) -> Self {
218 self.task_callbacks = Some(factory);
219 self
220 }
221
222 #[must_use]
223 /// Configures the system for testing.
224 ///
225 /// Sets the testing flag and disables signal, fatal signal, and panic
226 /// handling on this builder. Subsequent calls can enable them again.
227 pub fn testing(mut self) -> Self {
228 self.testing = true;
229 self.signals = false;
230 self.fatal_signals = false;
231 self.panics = false;
232 self
233 }
234
235 #[must_use]
236 /// Sets how long an idle blocking worker waits before exiting.
237 ///
238 /// The default is 60 seconds.
239 pub fn thread_pool_recv_timeout<T>(mut self, timeout: T) -> Self
240 where
241 time::Duration: From<T>,
242 {
243 self.pool_recv_timeout = timeout.into();
244 self
245 }
246
247 /// Creates a system runner using the specified runtime runner.
248 ///
249 /// This stores configuration only; the system starts when the returned
250 /// [`SystemRunner`] is driven.
251 pub fn build<R: Runner>(self, runner: R) -> SystemRunner {
252 let config = SystemConfig {
253 name: self.name.clone(),
254 testing: self.testing,
255 stack_size: self.stack_size,
256 ping_interval: self.ping_interval,
257 ping_threshold: self.ping_threshold,
258 latency_interval: self.latency_interval,
259 pool_limit: self.pool_limit,
260 pool_recv_timeout: self.pool_recv_timeout,
261 timer_resolution: self.timer_resolution,
262 task_callbacks: self.task_callbacks,
263 runner: Arc::new(runner),
264 };
265 self.build_with(config)
266 }
267
268 /// Creates a system runner from an existing system configuration.
269 ///
270 /// The supplied configuration determines the name, runtime runner, and all
271 /// other system settings. Only this builder's signal, fatal signal, and
272 /// panic-handling settings are used. No event loop is started by this method.
273 pub fn build_with(self, config: SystemConfig) -> SystemRunner {
274 let runner = config.runner.clone();
275
276 // init system arbiter and run configuration method
277 SystemRunner {
278 config,
279 runner,
280 signals: self.signals,
281 fatal_signals: self.fatal_signals,
282 panics: self.panics,
283 _t: PhantomData,
284 }
285 }
286}
287
288/// A configured system that has not yet started its event loop.
289///
290/// Driving it installs a system and primary arbiter on the current thread.
291/// This value is neither `Send` nor `Sync`.
292#[must_use = "SystemRunner must be run"]
293pub struct SystemRunner {
294 config: SystemConfig,
295 runner: Arc<dyn Runner>,
296 signals: bool,
297 fatal_signals: bool,
298 panics: bool,
299 _t: PhantomData<Rc<()>>,
300}
301
302impl SystemRunner {
303 /// Runs the event loop until [`System::stop()`] is called.
304 ///
305 /// Equivalent to [`run`](Self::run) with an initialization callback that
306 /// returns `Ok(())`, including its error and panic behavior.
307 pub fn run_until_stop(self) -> io::Result<()> {
308 self.run(|| Ok(()))
309 }
310
311 /// Runs `f`, then drives the event loop until [`System::stop()`] is called.
312 ///
313 /// The callback runs inside the event loop with the system and its primary
314 /// arbiter installed. On exit, the system requests its arbiters to stop.
315 ///
316 /// # Errors
317 ///
318 /// Returns the initialization error from `f`, or an error if the system
319 /// stops with a nonzero exit code or its stop channel closes unexpectedly.
320 ///
321 /// # Panics
322 ///
323 /// Resumes panics from initialization or the runtime runner after cleanup.
324 /// Also panics if the runner returns successfully without completing its
325 /// supplied future.
326 pub fn run<F>(self, f: F) -> io::Result<()>
327 where
328 F: FnOnce() -> io::Result<()> + 'static,
329 {
330 log::info!("Starting {:?} system", self.config.name);
331
332 let SystemRunner {
333 config,
334 runner,
335 signals,
336 fatal_signals,
337 panics,
338 ..
339 } = self;
340
341 if fatal_signals {
342 signals::enable_fatal_signals();
343 }
344 if panics {
345 signals::enable_panic_handling();
346 }
347
348 // run loop
349 crate::driver::block_on_panic(runner.as_ref(), async move {
350 let (system, stop) = System::start(config);
351 let _guard = SystemGuard(system.clone());
352 if signals {
353 system.enable_signals();
354 }
355
356 f()?;
357
358 let result = stop.await;
359
360 match result {
361 Ok(code) => {
362 if code != 0 {
363 Err(io::Error::other(format!("Non-zero exit code: {code}")))
364 } else {
365 Ok(())
366 }
367 }
368 Err(_) => Err(io::Error::other("Closed")),
369 }
370 })
371 }
372
373 #[allow(clippy::missing_panics_doc)]
374 /// Runs the system until `fut` completes and returns its output.
375 ///
376 /// The future runs with the system and primary arbiter installed. Completion
377 /// requests all system arbiters to stop. Unlike [`run`](Self::run), this
378 /// waits for the future, not a stop request, and does not check the system's
379 /// exit code.
380 ///
381 /// # Panics
382 ///
383 /// Resumes panics from the future or runtime runner after cleanup. Also
384 /// panics if the runner returns without completing its supplied future.
385 pub fn block_on<F, R>(self, fut: F) -> R
386 where
387 F: Future<Output = R> + 'static,
388 R: 'static,
389 {
390 let SystemRunner {
391 config,
392 runner,
393 signals,
394 fatal_signals,
395 panics,
396 ..
397 } = self;
398
399 if fatal_signals {
400 signals::enable_fatal_signals();
401 }
402 if panics {
403 signals::enable_panic_handling();
404 }
405
406 crate::driver::block_on_panic(runner.as_ref(), async move {
407 let (system, _) = System::start(config);
408 let _guard = SystemGuard(system.clone());
409 if signals {
410 system.enable_signals();
411 }
412
413 let loc = current_location();
414 ntex_error::set_backtrace_start(loc.file(), loc.line() + 2);
415 fut.await
416 })
417 }
418
419 #[cfg(feature = "tokio")]
420 /// Runs the system's future in a local task set on an existing Tokio runtime.
421 ///
422 /// Does not invoke the configured [`Runner`] or apply the builder's signal
423 /// and panic-handling settings. The system and primary arbiter are installed
424 /// while the future runs, and shutdown callbacks are run on normal completion.
425 /// Like [`block_on`](Self::block_on), this waits for the future rather than
426 /// a stop request.
427 ///
428 /// # Panics
429 ///
430 /// Panics if used without a compatible Tokio runtime context. The runtime
431 /// must have timers enabled, otherwise the timer driver task panics.
432 /// Panics from the future propagate to the caller.
433 pub async fn run_local<F, R>(self, fut: F) -> R
434 where
435 F: Future<Output = R> + 'static,
436 R: 'static,
437 {
438 let SystemRunner { config, .. } = self;
439
440 // run loop
441 let result = tok_io::task::LocalSet::new()
442 .run_until(async move {
443 let (system, _) = System::start(config);
444 let _guard = SystemGuard(system);
445
446 let loc = current_location();
447 ntex_error::set_backtrace_start(loc.file(), loc.line() + 2);
448 fut.await
449 })
450 .await;
451
452 crate::arbiter::run_shutdown_callbacks();
453 // SAFETY: The local task set and shutdown callbacks have ended, releasing storage borrows.
454 unsafe {
455 crate::remove_all_items();
456 }
457 if let Some(arb) = crate::Arbiter::try_current() {
458 arb.finalize();
459 }
460 result
461 }
462}
463
464/// Stops the system's arbiters and releases the signals for other systems when
465/// the system's future completes, fails, panics or is dropped.
466struct SystemGuard(System);
467
468impl Drop for SystemGuard {
469 fn drop(&mut self) {
470 self.0.disable_signals();
471
472 if std::thread::panicking() {
473 // some executors (compio) abort the process if a task is woken
474 // while the thread unwinds, stop arbiters from another thread
475 let list = self.0.take_arbiters();
476 if !list.is_empty() {
477 let stopped = std::thread::Builder::new()
478 .spawn(move || list.into_iter().for_each(|arb| arb.stop()))
479 .map(std::thread::JoinHandle::join);
480 if let Ok(Err(payload)) = stopped {
481 std::mem::forget(payload);
482 crate::abort_on_second_panic();
483 }
484 }
485 } else {
486 self.0.stop_arbiters();
487 }
488 }
489}
490
491#[track_caller]
492pub(crate) fn current_location() -> &'static panic::Location<'static> {
493 panic::Location::caller()
494}
495
496impl fmt::Debug for SystemRunner {
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
498 f.debug_struct("SystemRunner")
499 .field("config", &self.config)
500 .finish()
501 }
502}
503
504#[cfg(test)]
505#[path = "../tests/unit/builder.rs"]
506mod tests;