Skip to main content

moirai_core/executor/
mod.rs

1//! Executor trait and implementations.
2//!
3//! This module provides the core executor abstraction for the Moirai runtime.
4//! It defines traits for task spawning, management, and lifecycle control.
5
6pub mod builder;
7pub mod config;
8pub mod control;
9pub mod manager;
10pub mod spawner;
11
12pub use builder::ExecutorBuilder;
13pub use config::{CleanupConfig, ExecutorConfig, MemoryConfig, PreemptionConfig};
14pub use control::ExecutorControl;
15pub use manager::{TaskManager, TaskStats, TaskStatus};
16pub use spawner::TaskSpawner;
17
18/// Combined executor trait with all capabilities.
19///
20/// This trait combines all executor capabilities into a single interface
21/// for convenience while maintaining the segregated design internally.
22///
23/// # Design Philosophy
24/// - Composition over inheritance
25/// - Single interface for complete functionality
26/// - Maintains internal separation of concerns
27/// - Enables easy mocking and testing
28pub trait Executor: TaskSpawner + TaskManager + ExecutorControl {
29    /// Get comprehensive executor statistics.
30    ///
31    /// # Behavior Guarantees
32    /// - Returns current snapshot of all executor metrics
33    /// - Statistics are eventually consistent
34    /// - Available only when metrics feature is enabled
35    /// - Includes worker, queue, memory, and task statistics
36    ///
37    /// # Performance Characteristics
38    /// - Collection overhead: < 1μs for full statistics
39    /// - Memory: ~1KB for complete statistics snapshot
40    /// - Thread safety: Atomic operations for consistency
41    #[cfg(feature = "metrics")]
42    fn stats(&self) -> ExecutorStats;
43}
44
45/// Executor statistics (basic implementation when metrics feature is disabled)
46#[cfg(not(feature = "metrics"))]
47#[derive(Debug, Clone, Default)]
48pub struct ExecutorStats;
49
50/// Executor statistics with full metrics
51#[cfg(feature = "metrics")]
52#[derive(Debug, Clone, Default)]
53pub struct ExecutorStats {
54    /// Number of tasks executed
55    pub tasks_executed: u64,
56    /// Number of tasks in queue
57    pub tasks_queued: usize,
58    /// Average task execution time
59    pub avg_execution_time_ns: u64,
60}
61
62// Helper function to get number of CPUs
63pub(crate) fn num_cpus() -> usize {
64    #[cfg(feature = "std")]
65    {
66        std::thread::available_parallelism().map_or(1, std::num::NonZeroUsize::get)
67    }
68    #[cfg(not(feature = "std"))]
69    {
70        4 // Reasonable default for no_std
71    }
72}