|
| 1 | +use crate::{Decoder, NifResult, Term}; |
| 2 | +use once_cell::sync::OnceCell; |
| 3 | +use std::sync::Arc; |
| 4 | +use tokio::runtime::Runtime; |
| 5 | + |
| 6 | +/// Global tokio runtime for async NIFs. |
| 7 | +/// |
| 8 | +/// This runtime can be configured via `configure_runtime()` in your NIF's `load` callback, |
| 9 | +/// or will be lazily initialized with default settings on first use. |
| 10 | +static TOKIO_RUNTIME: OnceCell<Arc<Runtime>> = OnceCell::new(); |
| 11 | + |
| 12 | +/// Error type for runtime configuration failures. |
| 13 | +#[derive(Debug)] |
| 14 | +pub enum ConfigError { |
| 15 | + /// The runtime has already been initialized (either by configuration or first use). |
| 16 | + AlreadyInitialized, |
| 17 | + /// Failed to build the Tokio runtime. |
| 18 | + BuildFailed(std::io::Error), |
| 19 | +} |
| 20 | + |
| 21 | +impl std::fmt::Display for ConfigError { |
| 22 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 23 | + match self { |
| 24 | + ConfigError::AlreadyInitialized => { |
| 25 | + write!(f, "Tokio runtime already initialized") |
| 26 | + } |
| 27 | + ConfigError::BuildFailed(e) => { |
| 28 | + write!(f, "Failed to build Tokio runtime: {}", e) |
| 29 | + } |
| 30 | + } |
| 31 | + } |
| 32 | +} |
| 33 | + |
| 34 | +impl std::error::Error for ConfigError {} |
| 35 | + |
| 36 | +/// Configuration options for the Tokio runtime. |
| 37 | +/// |
| 38 | +/// These can be passed from Elixir via the `load_data` option: |
| 39 | +/// |
| 40 | +/// ```elixir |
| 41 | +/// use Rustler, |
| 42 | +/// otp_app: :my_app, |
| 43 | +/// crate: :my_nif, |
| 44 | +/// load_data: [ |
| 45 | +/// worker_threads: 4, |
| 46 | +/// thread_name: "my-runtime" |
| 47 | +/// ] |
| 48 | +/// ``` |
| 49 | +#[derive(Debug, Clone)] |
| 50 | +pub struct RuntimeConfig { |
| 51 | + /// Number of worker threads for the runtime. |
| 52 | + /// If not specified, uses Tokio's default (number of CPU cores). |
| 53 | + pub worker_threads: Option<usize>, |
| 54 | + |
| 55 | + /// Thread name prefix for worker threads. |
| 56 | + /// If not specified, uses "rustler-tokio". |
| 57 | + pub thread_name: Option<String>, |
| 58 | + |
| 59 | + /// Stack size for worker threads in bytes. |
| 60 | + /// If not specified, uses Tokio's default. |
| 61 | + pub thread_stack_size: Option<usize>, |
| 62 | +} |
| 63 | + |
| 64 | +impl Default for RuntimeConfig { |
| 65 | + fn default() -> Self { |
| 66 | + RuntimeConfig { |
| 67 | + worker_threads: None, |
| 68 | + thread_name: Some("rustler-tokio".to_string()), |
| 69 | + thread_stack_size: None, |
| 70 | + } |
| 71 | + } |
| 72 | +} |
| 73 | + |
| 74 | +impl<'a> Decoder<'a> for RuntimeConfig { |
| 75 | + fn decode(term: Term<'a>) -> NifResult<Self> { |
| 76 | + use crate::types::map::MapIterator; |
| 77 | + use crate::Error; |
| 78 | + |
| 79 | + let mut config = RuntimeConfig::default(); |
| 80 | + |
| 81 | + // Try to decode as a map/keyword list |
| 82 | + let map_iter = MapIterator::new(term).ok_or(Error::BadArg)?; |
| 83 | + |
| 84 | + for (key, value) in map_iter { |
| 85 | + let key_str: String = key.decode()?; |
| 86 | + |
| 87 | + match key_str.as_str() { |
| 88 | + "worker_threads" => { |
| 89 | + config.worker_threads = Some(value.decode()?); |
| 90 | + } |
| 91 | + "thread_name" => { |
| 92 | + config.thread_name = Some(value.decode()?); |
| 93 | + } |
| 94 | + "thread_stack_size" => { |
| 95 | + config.thread_stack_size = Some(value.decode()?); |
| 96 | + } |
| 97 | + _ => { |
| 98 | + // Ignore unknown options for forward compatibility |
| 99 | + } |
| 100 | + } |
| 101 | + } |
| 102 | + |
| 103 | + Ok(config) |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +/// Configure the global Tokio runtime from Elixir load_data. |
| 108 | +/// |
| 109 | +/// This is the recommended way to configure the runtime, allowing Elixir application |
| 110 | +/// developers to tune the runtime without recompiling the NIF. |
| 111 | +/// |
| 112 | +/// # Example |
| 113 | +/// |
| 114 | +/// ```ignore |
| 115 | +/// use rustler::{Env, Term}; |
| 116 | +/// |
| 117 | +/// fn load(_env: Env, load_info: Term) -> bool { |
| 118 | +/// // Try to decode runtime config from load_info |
| 119 | +/// if let Ok(config) = load_info.decode::<rustler::tokio::RuntimeConfig>() { |
| 120 | +/// rustler::tokio::configure(config) |
| 121 | +/// .expect("Failed to configure Tokio runtime"); |
| 122 | +/// } |
| 123 | +/// true |
| 124 | +/// } |
| 125 | +/// ``` |
| 126 | +/// |
| 127 | +/// In your Elixir config: |
| 128 | +/// |
| 129 | +/// ```elixir |
| 130 | +/// # config/config.exs |
| 131 | +/// config :my_app, MyNif, |
| 132 | +/// load_data: [ |
| 133 | +/// worker_threads: 4, |
| 134 | +/// thread_name: "my-runtime" |
| 135 | +/// ] |
| 136 | +/// ``` |
| 137 | +pub fn configure(config: RuntimeConfig) -> Result<(), ConfigError> { |
| 138 | + let mut builder = tokio::runtime::Builder::new_multi_thread(); |
| 139 | + builder.enable_all(); |
| 140 | + |
| 141 | + // Apply configuration |
| 142 | + if let Some(threads) = config.worker_threads { |
| 143 | + builder.worker_threads(threads); |
| 144 | + } |
| 145 | + |
| 146 | + if let Some(name) = config.thread_name { |
| 147 | + builder.thread_name(name); |
| 148 | + } |
| 149 | + |
| 150 | + if let Some(stack_size) = config.thread_stack_size { |
| 151 | + builder.thread_stack_size(stack_size); |
| 152 | + } |
| 153 | + |
| 154 | + let runtime = builder.build().map_err(ConfigError::BuildFailed)?; |
| 155 | + |
| 156 | + TOKIO_RUNTIME |
| 157 | + .set(Arc::new(runtime)) |
| 158 | + .map_err(|_| ConfigError::AlreadyInitialized) |
| 159 | +} |
| 160 | + |
| 161 | +/// Configure the global Tokio runtime programmatically. |
| 162 | +/// |
| 163 | +/// This provides direct access to the Tokio Builder API for advanced use cases. |
| 164 | +/// For most applications, prefer `configure_runtime_from_term` which allows |
| 165 | +/// configuration from Elixir. |
| 166 | +/// |
| 167 | +/// # Example |
| 168 | +/// |
| 169 | +/// ```ignore |
| 170 | +/// use rustler::{Env, Term}; |
| 171 | +/// |
| 172 | +/// fn load(_env: Env, _: Term) -> bool { |
| 173 | +/// rustler::tokio::configure_runtime(|builder| { |
| 174 | +/// builder |
| 175 | +/// .worker_threads(4) |
| 176 | +/// .thread_name("myapp-tokio") |
| 177 | +/// .thread_stack_size(3 * 1024 * 1024); |
| 178 | +/// }).expect("Failed to configure Tokio runtime"); |
| 179 | +/// |
| 180 | +/// true |
| 181 | +/// } |
| 182 | +/// ``` |
| 183 | +pub fn configure_runtime<F>(config_fn: F) -> Result<(), ConfigError> |
| 184 | +where |
| 185 | + F: FnOnce(&mut tokio::runtime::Builder), |
| 186 | +{ |
| 187 | + let mut builder = tokio::runtime::Builder::new_multi_thread(); |
| 188 | + builder.enable_all(); |
| 189 | + |
| 190 | + // Allow user to customize |
| 191 | + config_fn(&mut builder); |
| 192 | + |
| 193 | + let runtime = builder.build().map_err(ConfigError::BuildFailed)?; |
| 194 | + |
| 195 | + TOKIO_RUNTIME |
| 196 | + .set(Arc::new(runtime)) |
| 197 | + .map_err(|_| ConfigError::AlreadyInitialized) |
| 198 | +} |
| 199 | + |
| 200 | +/// Get a handle to the global tokio runtime, or the current runtime if already inside one. |
| 201 | +pub fn runtime_handle() -> tokio::runtime::Handle { |
| 202 | + // Try to get the current runtime handle first (if already in a tokio context) |
| 203 | + tokio::runtime::Handle::try_current().unwrap_or_else(|_| { |
| 204 | + // Get or initialize with default configuration |
| 205 | + TOKIO_RUNTIME |
| 206 | + .get_or_init(|| { |
| 207 | + Arc::new( |
| 208 | + tokio::runtime::Builder::new_multi_thread() |
| 209 | + .enable_all() |
| 210 | + .thread_name("rustler-tokio") |
| 211 | + .build() |
| 212 | + .expect("Failed to create default tokio runtime for async NIFs"), |
| 213 | + ) |
| 214 | + }) |
| 215 | + .handle() |
| 216 | + .clone() |
| 217 | + }) |
| 218 | +} |
0 commit comments