nautilus_common/
runtime.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2025 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! The centralized Tokio runtime for a running Nautilus system.
17
18use std::sync::OnceLock;
19
20use tokio::runtime::Builder;
21
22static RUNTIME: OnceLock<tokio::runtime::Runtime> = OnceLock::new();
23
24/// Environment variable name to configure the number of OS threads for the common runtime.
25/// If not set or if the value cannot be parsed as a positive integer, the default value is used.
26const NAUTILUS_WORKER_THREADS: &str = "NAUTILUS_WORKER_THREADS";
27
28/// The default number of OS threads to use if the environment variable is not set.
29///
30/// 0 means Tokio will use the default (number of logical CPUs).
31const DEFAULT_OS_THREADS: usize = 0;
32
33/// Creates and configures a new multi-threaded Tokio runtime.
34///
35/// The number of OS threads is configured using the `NAUTILUS_WORKER_THREADS`
36/// environment variable. If not set, all available logical CPUs will be used.
37///
38/// # Panics
39///
40/// Panics if the runtime could not be created, which typically indicates
41/// an inability to spawn threads or allocate necessary resources.
42fn initialize_runtime() -> tokio::runtime::Runtime {
43    let worker_threads = std::env::var(NAUTILUS_WORKER_THREADS)
44        .ok()
45        .and_then(|val| val.parse::<usize>().ok())
46        .unwrap_or(DEFAULT_OS_THREADS);
47
48    let mut builder = Builder::new_multi_thread();
49
50    let builder = if worker_threads > 0 {
51        builder.worker_threads(worker_threads)
52    } else {
53        &mut builder
54    };
55
56    builder
57        .enable_all()
58        .build()
59        .expect("Failed to create tokio runtime")
60}
61
62/// Returns a reference to the global Nautilus Tokio runtime.
63///
64/// The runtime is lazily initialized on the first call and reused thereafter.
65/// Intended for use cases where passing a runtime around is impractical.
66pub fn get_runtime() -> &'static tokio::runtime::Runtime {
67    RUNTIME.get_or_init(initialize_runtime)
68}