|
6 | 6 | // accordance with one or both of these licenses. |
7 | 7 |
|
8 | 8 | use std::future::Future; |
| 9 | +use std::io; |
| 10 | +use std::sync::atomic::{AtomicUsize, Ordering}; |
9 | 11 | use std::sync::{Arc, Mutex}; |
10 | 12 | use std::time::Duration; |
11 | 13 |
|
@@ -223,6 +225,60 @@ enum RuntimeMode { |
223 | 225 | Handle(tokio::runtime::Handle), |
224 | 226 | } |
225 | 227 |
|
| 228 | +pub(crate) struct StoreRuntime { |
| 229 | + runtime: Option<tokio::runtime::Runtime>, |
| 230 | +} |
| 231 | + |
| 232 | +impl StoreRuntime { |
| 233 | + pub(crate) fn new( |
| 234 | + thread_name_prefix: &'static str, worker_threads: usize, runtime_name: &'static str, |
| 235 | + ) -> io::Result<Self> { |
| 236 | + let runtime = tokio::runtime::Builder::new_multi_thread() |
| 237 | + .enable_all() |
| 238 | + .thread_name_fn(move || { |
| 239 | + static ATOMIC_ID: AtomicUsize = AtomicUsize::new(0); |
| 240 | + let id = ATOMIC_ID.fetch_add(1, Ordering::SeqCst); |
| 241 | + format!("{}-{}", thread_name_prefix, id) |
| 242 | + }) |
| 243 | + .worker_threads(worker_threads) |
| 244 | + .max_blocking_threads(worker_threads) |
| 245 | + .build() |
| 246 | + .map_err(|e| { |
| 247 | + io::Error::new( |
| 248 | + io::ErrorKind::Other, |
| 249 | + format!("Failed to build {runtime_name} runtime: {e}"), |
| 250 | + ) |
| 251 | + })?; |
| 252 | + Ok(Self { runtime: Some(runtime) }) |
| 253 | + } |
| 254 | + |
| 255 | + pub(crate) fn handle(&self) -> &tokio::runtime::Handle { |
| 256 | + self.runtime.as_ref().expect("store runtime must be available").handle() |
| 257 | + } |
| 258 | + |
| 259 | + pub(crate) fn spawn<F>(&self, future: F) -> JoinHandle<F::Output> |
| 260 | + where |
| 261 | + F: Future + Send + 'static, |
| 262 | + F::Output: Send + 'static, |
| 263 | + { |
| 264 | + self.handle().spawn(future) |
| 265 | + } |
| 266 | + |
| 267 | + pub(crate) fn shutdown_background(mut self) { |
| 268 | + if let Some(runtime) = self.runtime.take() { |
| 269 | + runtime.shutdown_background(); |
| 270 | + } |
| 271 | + } |
| 272 | +} |
| 273 | + |
| 274 | +impl Drop for StoreRuntime { |
| 275 | + fn drop(&mut self) { |
| 276 | + if let Some(runtime) = self.runtime.take() { |
| 277 | + runtime.shutdown_background(); |
| 278 | + } |
| 279 | + } |
| 280 | +} |
| 281 | + |
226 | 282 | pub(crate) struct RuntimeSpawner { |
227 | 283 | runtime: Arc<Runtime>, |
228 | 284 | } |
|
0 commit comments