rustkernel_core/runtime/mod.rs
1//! Runtime Lifecycle Management
2//!
3//! This module provides runtime lifecycle management for RustKernels, including:
4//! - Runtime configuration and initialization
5//! - Graceful shutdown with drain periods
6//! - Hot configuration reload
7//! - Runtime state machine management
8//!
9//! # Architecture
10//!
11//! The runtime is built on ringkernel 0.3.1's `RingKernelRuntime` with additional
12//! enterprise features for production deployments:
13//!
14//! - **Lifecycle States**: `Created` → `Starting` → `Running` → `Draining` → `Stopped`
15//! - **Configuration**: Environment variables, files, and programmatic configuration
16//! - **Graceful Shutdown**: Configurable drain period to complete in-flight requests
17//!
18//! # Example
19//!
20//! ```rust,ignore
21//! use rustkernel_core::runtime::{KernelRuntime, RuntimeConfig};
22//!
23//! #[tokio::main]
24//! async fn main() -> Result<(), Box<dyn std::error::Error>> {
25//! // Create runtime with production configuration
26//! let runtime = KernelRuntime::builder()
27//! .production()
28//! .with_drain_timeout(Duration::from_secs(30))
29//! .build()
30//! .await?;
31//!
32//! // Start the runtime
33//! runtime.start().await?;
34//!
35//! // ... use runtime ...
36//!
37//! // Graceful shutdown
38//! runtime.shutdown().await?;
39//! Ok(())
40//! }
41//! ```
42
43pub mod config;
44pub mod lifecycle;
45
46pub use config::{BackendConfig, RuntimeConfig, RuntimeConfigBuilder};
47pub use lifecycle::{KernelRuntime, LifecycleState, RuntimeBuilder, RuntimeHandle};
48
49use std::sync::Arc;
50use std::time::Duration;
51
52/// Default drain timeout for graceful shutdown
53pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
54
55/// Default health check interval
56pub const DEFAULT_HEALTH_CHECK_INTERVAL: Duration = Duration::from_secs(10);
57
58/// Runtime presets for common deployment scenarios
59#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60pub enum RuntimePreset {
61 /// Development mode - minimal overhead, verbose logging
62 Development,
63 /// Production mode - optimized settings, structured logging
64 Production,
65 /// High-performance mode - maximum throughput, minimal overhead
66 HighPerformance,
67 /// Testing mode - deterministic behavior, mock backends
68 Testing,
69}
70
71impl RuntimePreset {
72 /// Convert preset to configuration
73 pub fn to_config(&self) -> RuntimeConfig {
74 match self {
75 Self::Development => RuntimeConfig::development(),
76 Self::Production => RuntimeConfig::production(),
77 Self::HighPerformance => RuntimeConfig::high_performance(),
78 Self::Testing => RuntimeConfig::testing(),
79 }
80 }
81}
82
83/// Runtime statistics
84#[derive(Debug, Clone, Default)]
85pub struct RuntimeStats {
86 /// Total kernels registered
87 pub kernels_registered: usize,
88 /// Active kernel instances
89 pub kernels_active: usize,
90 /// Total messages processed
91 pub messages_processed: u64,
92 /// Messages currently in flight
93 pub messages_in_flight: u64,
94 /// Current GPU memory usage in bytes
95 pub gpu_memory_bytes: u64,
96 /// Peak GPU memory usage in bytes
97 pub gpu_memory_peak_bytes: u64,
98 /// Runtime uptime in seconds
99 pub uptime_secs: u64,
100}
101
102/// Shutdown signal receiver
103pub type ShutdownSignal = tokio::sync::watch::Receiver<bool>;
104
105/// Create a shutdown signal channel
106pub fn shutdown_channel() -> (tokio::sync::watch::Sender<bool>, ShutdownSignal) {
107 tokio::sync::watch::channel(false)
108}
109
110/// Runtime event types for lifecycle hooks
111#[derive(Debug, Clone)]
112pub enum RuntimeEvent {
113 /// Runtime is starting
114 Starting,
115 /// Runtime has started successfully
116 Started,
117 /// Runtime is beginning to drain (graceful shutdown)
118 Draining,
119 /// Runtime has stopped
120 Stopped,
121 /// A kernel was registered
122 KernelRegistered {
123 /// The ID of the registered kernel
124 id: String,
125 },
126 /// A kernel was unregistered
127 KernelUnregistered {
128 /// The ID of the unregistered kernel
129 id: String,
130 },
131 /// Configuration was reloaded
132 ConfigReloaded,
133 /// Health check completed
134 HealthCheckCompleted {
135 /// Whether the health check passed
136 healthy: bool,
137 },
138}
139
140/// Callback for runtime events
141pub type RuntimeEventCallback = Arc<dyn Fn(RuntimeEvent) + Send + Sync>;
142
143#[cfg(test)]
144mod tests {
145 use super::*;
146
147 #[test]
148 fn test_runtime_preset_to_config() {
149 let dev_config = RuntimePreset::Development.to_config();
150 assert!(!dev_config.gpu_enabled);
151
152 let prod_config = RuntimePreset::Production.to_config();
153 assert!(prod_config.gpu_enabled);
154 }
155
156 #[test]
157 fn test_shutdown_channel() {
158 let (tx, rx) = shutdown_channel();
159 assert!(!*rx.borrow());
160
161 tx.send(true).unwrap();
162 assert!(*rx.borrow());
163 }
164}