daemon_base/
concurrency.rs

1//! Concurrency models for the daemon library.
2//!
3//! This module provides functionality to support both multi-threaded and
4//! asynchronous operations.
5
6use std::thread;
7use log::info;
8use crate::error::DaemonError;
9
10/// Represents a concurrency model.
11pub enum ConcurrencyModel {
12    MultiThreaded,
13    Async,
14}
15
16/// Executes a task using the specified concurrency model.
17pub fn execute_task<F>(model: ConcurrencyModel, task: F) -> Result<(), DaemonError>
18where
19    F: FnOnce() -> Result<(), DaemonError> + Send + 'static,
20{
21    match model {
22        ConcurrencyModel::MultiThreaded => {
23            info!("Executing task in multi-threaded mode.");
24            let handle = thread::spawn(move || {
25                if let Err(e) = task() {
26                    log::error!("Task failed: {}", e);
27                }
28            });
29            handle.join().map_err(|_| DaemonError::CustomError("Thread panicked".to_string()))?;
30        }
31        ConcurrencyModel::Async => {
32            #[cfg(feature = "async")]
33            {
34                info!("Executing task in async mode.");
35                let runtime = tokio::runtime::Runtime::new()
36                    .map_err(|e| DaemonError::CustomError(format!("Failed to create runtime: {}", e)))?;
37                runtime.block_on(async {
38                    if let Err(e) = task() {
39                        log::error!("Task failed: {}", e);
40                    }
41                });
42            }
43            #[cfg(not(feature = "async"))]
44            {
45                return Err(DaemonError::CustomError("Async feature is not enabled".to_string()));
46            }
47        }
48    }
49    Ok(())
50}