|
| 1 | +use std::{ |
| 2 | + sync::{ |
| 3 | + atomic::{AtomicBool, AtomicUsize, Ordering}, |
| 4 | + Arc, |
| 5 | + }, |
| 6 | + time::Duration, |
| 7 | +}; |
| 8 | + |
| 9 | +use once_cell::sync::Lazy; |
| 10 | +use tokio::sync::{broadcast, Notify}; |
| 11 | +use tracing::{info, warn}; |
| 12 | + |
| 13 | +static SHUTDOWN_COORDINATOR: Lazy<Arc<ShutdownCoordinator>> = |
| 14 | + Lazy::new(|| Arc::new(ShutdownCoordinator::new())); |
| 15 | + |
| 16 | +pub struct ShutdownCoordinator { |
| 17 | + shutdown_sender: broadcast::Sender<()>, |
| 18 | + operations_complete: Arc<Notify>, |
| 19 | + active_operations: Arc<AtomicUsize>, |
| 20 | + shutdown_requested: Arc<AtomicBool>, |
| 21 | +} |
| 22 | + |
| 23 | +impl ShutdownCoordinator { |
| 24 | + fn new() -> Self { |
| 25 | + let (shutdown_sender, _) = broadcast::channel(16); |
| 26 | + Self { |
| 27 | + shutdown_sender, |
| 28 | + operations_complete: Arc::new(Notify::new()), |
| 29 | + active_operations: Arc::new(AtomicUsize::new(0)), |
| 30 | + shutdown_requested: Arc::new(AtomicBool::new(false)), |
| 31 | + } |
| 32 | + } |
| 33 | + |
| 34 | + #[cfg(test)] |
| 35 | + pub fn new_for_test() -> Self { |
| 36 | + Self::new() |
| 37 | + } |
| 38 | + |
| 39 | + pub fn subscribe(&self) -> broadcast::Receiver<()> { |
| 40 | + self.shutdown_sender.subscribe() |
| 41 | + } |
| 42 | + |
| 43 | + pub fn is_shutdown_requested(&self) -> bool { |
| 44 | + self.shutdown_requested.load(Ordering::Relaxed) |
| 45 | + } |
| 46 | + |
| 47 | + pub fn enter_operation(self: &Arc<Self>) -> Option<OperationGuard> { |
| 48 | + if self.is_shutdown_requested() { |
| 49 | + return None; |
| 50 | + } |
| 51 | + self.active_operations.fetch_add(1, Ordering::SeqCst); |
| 52 | + Some(OperationGuard { coordinator: Arc::clone(self) }) |
| 53 | + } |
| 54 | + |
| 55 | + fn exit_operation(&self) { |
| 56 | + let prev = self.active_operations.fetch_sub(1, Ordering::SeqCst); |
| 57 | + if prev == 1 { |
| 58 | + self.operations_complete.notify_waiters(); |
| 59 | + } |
| 60 | + } |
| 61 | + |
| 62 | + pub async fn request_shutdown(&self, timeout: Duration) -> bool { |
| 63 | + info!( |
| 64 | + "Graceful shutdown requested, waiting for {} active operations to complete", |
| 65 | + self.active_operations.load(Ordering::Relaxed) |
| 66 | + ); |
| 67 | + |
| 68 | + self.shutdown_requested.store(true, Ordering::SeqCst); |
| 69 | + |
| 70 | + let _ = self.shutdown_sender.send(()); |
| 71 | + |
| 72 | + tokio::select! { |
| 73 | + _ = self.wait_for_operations_complete() => { |
| 74 | + info!("All operations completed gracefully"); |
| 75 | + true |
| 76 | + } |
| 77 | + _ = tokio::time::sleep(timeout) => { |
| 78 | + warn!("Shutdown timeout reached, {} operations still active", |
| 79 | + self.active_operations.load(Ordering::Relaxed)); |
| 80 | + false |
| 81 | + } |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + async fn wait_for_operations_complete(&self) { |
| 86 | + while self.active_operations.load(Ordering::Relaxed) > 0 { |
| 87 | + self.operations_complete.notified().await; |
| 88 | + } |
| 89 | + } |
| 90 | + |
| 91 | + #[cfg(test)] |
| 92 | + pub fn active_operations_count(&self) -> usize { |
| 93 | + self.active_operations.load(Ordering::Relaxed) |
| 94 | + } |
| 95 | +} |
| 96 | + |
| 97 | +pub struct OperationGuard { |
| 98 | + coordinator: Arc<ShutdownCoordinator>, |
| 99 | +} |
| 100 | + |
| 101 | +impl Drop for OperationGuard { |
| 102 | + fn drop(&mut self) { |
| 103 | + self.coordinator.exit_operation(); |
| 104 | + } |
| 105 | +} |
| 106 | + |
| 107 | +pub fn shutdown_coordinator() -> Arc<ShutdownCoordinator> { |
| 108 | + Arc::clone(&SHUTDOWN_COORDINATOR) |
| 109 | +} |
| 110 | + |
| 111 | +pub async fn request_graceful_shutdown(timeout: Duration) -> bool { |
| 112 | + shutdown_coordinator().request_shutdown(timeout).await |
| 113 | +} |
| 114 | + |
| 115 | +pub fn is_shutdown_in_progress() -> bool { |
| 116 | + shutdown_coordinator().is_shutdown_requested() |
| 117 | +} |
| 118 | + |
| 119 | +pub fn enter_critical_operation() -> Option<OperationGuard> { |
| 120 | + let coordinator = shutdown_coordinator(); |
| 121 | + coordinator.enter_operation() |
| 122 | +} |
| 123 | + |
| 124 | +pub fn subscribe_to_shutdown() -> broadcast::Receiver<()> { |
| 125 | + shutdown_coordinator().subscribe() |
| 126 | +} |
| 127 | + |
| 128 | +#[cfg(test)] |
| 129 | +mod tests { |
| 130 | + use super::*; |
| 131 | + use std::{sync::Arc, time::Duration}; |
| 132 | + use tokio::time::sleep; |
| 133 | + |
| 134 | + #[tokio::test] |
| 135 | + async fn test_shutdown_coordination() { |
| 136 | + let coordinator = Arc::new(ShutdownCoordinator::new_for_test()); |
| 137 | + |
| 138 | + let guard1 = coordinator.enter_operation(); |
| 139 | + assert!(guard1.is_some()); |
| 140 | + |
| 141 | + let guard2 = coordinator.enter_operation(); |
| 142 | + assert!(guard2.is_some()); |
| 143 | + |
| 144 | + assert_eq!(coordinator.active_operations_count(), 2); |
| 145 | + |
| 146 | + let coordinator_clone = coordinator.clone(); |
| 147 | + let shutdown_task = tokio::spawn(async move { |
| 148 | + coordinator_clone.request_shutdown(Duration::from_millis(100)).await |
| 149 | + }); |
| 150 | + |
| 151 | + sleep(Duration::from_millis(10)).await; |
| 152 | + |
| 153 | + let guard3 = coordinator.enter_operation(); |
| 154 | + assert!(guard3.is_none()); |
| 155 | + |
| 156 | + assert_eq!(coordinator.active_operations_count(), 2); |
| 157 | + |
| 158 | + drop(guard1); |
| 159 | + assert_eq!(coordinator.active_operations_count(), 1); |
| 160 | + |
| 161 | + drop(guard2); |
| 162 | + |
| 163 | + let result = shutdown_task.await.unwrap(); |
| 164 | + assert!(result); |
| 165 | + assert_eq!(coordinator.active_operations_count(), 0); |
| 166 | + } |
| 167 | + |
| 168 | + #[tokio::test] |
| 169 | + async fn test_shutdown_timeout() { |
| 170 | + let coordinator = Arc::new(ShutdownCoordinator::new_for_test()); |
| 171 | + |
| 172 | + let _guard = coordinator.enter_operation(); |
| 173 | + assert!(_guard.is_some()); |
| 174 | + assert_eq!(coordinator.active_operations_count(), 1); |
| 175 | + |
| 176 | + let result = coordinator.request_shutdown(Duration::from_millis(10)).await; |
| 177 | + |
| 178 | + assert!(!result); |
| 179 | + assert_eq!(coordinator.active_operations_count(), 1); |
| 180 | + |
| 181 | + drop(_guard); |
| 182 | + assert_eq!(coordinator.active_operations_count(), 0); |
| 183 | + } |
| 184 | + |
| 185 | + #[tokio::test] |
| 186 | + async fn test_enter_critical_operation() { |
| 187 | + let guard = enter_critical_operation(); |
| 188 | + |
| 189 | + if guard.is_some() { |
| 190 | + drop(guard); |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + #[tokio::test] |
| 195 | + async fn test_operation_guard_lifecycle() { |
| 196 | + let coordinator = Arc::new(ShutdownCoordinator::new_for_test()); |
| 197 | + assert_eq!(coordinator.active_operations_count(), 0); |
| 198 | + |
| 199 | + { |
| 200 | + let _guard1 = coordinator.enter_operation(); |
| 201 | + assert_eq!(coordinator.active_operations_count(), 1); |
| 202 | + |
| 203 | + { |
| 204 | + let _guard2 = coordinator.enter_operation(); |
| 205 | + assert_eq!(coordinator.active_operations_count(), 2); |
| 206 | + } |
| 207 | + |
| 208 | + assert_eq!(coordinator.active_operations_count(), 1); |
| 209 | + } |
| 210 | + |
| 211 | + assert_eq!(coordinator.active_operations_count(), 0); |
| 212 | + } |
| 213 | + |
| 214 | + #[tokio::test] |
| 215 | + async fn test_shutdown_signal_propagation() { |
| 216 | + let coordinator = Arc::new(ShutdownCoordinator::new_for_test()); |
| 217 | + let mut rx = coordinator.subscribe(); |
| 218 | + |
| 219 | + let coordinator_clone = coordinator.clone(); |
| 220 | + tokio::spawn( |
| 221 | + async move { coordinator_clone.request_shutdown(Duration::from_millis(50)).await }, |
| 222 | + ); |
| 223 | + |
| 224 | + let result = tokio::time::timeout(Duration::from_millis(100), rx.recv()).await; |
| 225 | + assert!(result.is_ok()); |
| 226 | + assert!(result.unwrap().is_ok()); |
| 227 | + } |
| 228 | +} |
0 commit comments