brinkhaustools/
shutdown.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
use std::sync::{Arc, Condvar, Mutex};
use std::thread;
use std::time::{Duration, Instant};

/// Cheaply cloneable handle to a ShutdownHandler.
#[derive(Clone)]
pub struct ShutdownToken {
    inner: Arc<ShutdownInner>,
}

impl ShutdownToken {
    /// Returns `true` once shutdown has been triggered.
    pub fn is_shutdown(&self) -> bool {
        *self.inner.flag.lock().unwrap()
    }

    /// Block until shutdown is triggered.
    pub fn wait(&self) {
        let mut flag = self.inner.flag.lock().unwrap();
        while !*flag {
            flag = self.inner.condvar.wait(flag).unwrap();
        }
    }

    /// Block until shutdown or timeout. Returns `true` if shutdown was triggered.
    pub fn wait_timeout(&self, timeout: Duration) -> bool {
        let deadline = Instant::now() + timeout;
        let mut flag = self.inner.flag.lock().unwrap();
        while !*flag {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return false;
            }
            let (guard, _timeout_result) = self.inner.condvar.wait_timeout(flag, remaining).unwrap();
            flag = guard;
        }
        true
    }
}

struct ShutdownInner {
    flag: Mutex<bool>,
    condvar: Condvar,
    #[allow(clippy::type_complexity)]
    hooks: Mutex<Option<Vec<Box<dyn FnOnce() + Send>>>>,
}

/// Coordinates graceful shutdown with signal handling and interruptible sleep.
///
/// Thread-safe and cloneable via [`ShutdownToken`].
#[derive(Clone)]
pub struct ShutdownHandler {
    inner: Arc<ShutdownInner>,
}

impl ShutdownHandler {
    /// Create a new ShutdownHandler without signal handlers.
    pub fn new() -> Self {
        Self {
            inner: Arc::new(ShutdownInner {
                flag: Mutex::new(false),
                condvar: Condvar::new(),
                hooks: Mutex::new(Some(Vec::new())),
            }),
        }
    }

    /// Create a new ShutdownHandler that installs signal handlers: SIGINT
    /// (Ctrl+C), SIGTERM and SIGHUP on Unix; every console control event
    /// (Ctrl+C, Ctrl+Break, closing the console) on Windows. SIGTERM is what
    /// `docker stop` and systemd send; as PID 1 in a container an uncaught
    /// SIGTERM is ignored and the process ends in SIGKILL without running any
    /// hook.
    #[cfg(feature = "signals")]
    pub fn with_signal_handlers() -> Self {
        let handler = Self::new();
        let token = handler.token();
        ctrlc::set_handler(move || {
            token.inner.run_hooks_and_set(&token.inner);
        })
        .expect("Failed to install Ctrl+C handler");
        handler
    }

    /// Trigger shutdown immediately. Hooks are called exactly once.
    pub fn trigger(&self) {
        self.inner.run_hooks_and_set(&self.inner);
    }

    /// Trigger shutdown after a delay. The delay runs in a background thread.
    pub fn trigger_delayed(&self, delay: Duration) {
        let inner = self.inner.clone();
        thread::spawn(move || {
            thread::sleep(delay);
            inner.run_hooks_and_set(&inner);
        });
    }

    /// Returns `true` once shutdown has been triggered.
    pub fn is_shutdown(&self) -> bool {
        *self.inner.flag.lock().unwrap()
    }

    /// Block until shutdown is triggered.
    pub fn wait(&self) {
        let mut flag = self.inner.flag.lock().unwrap();
        while !*flag {
            flag = self.inner.condvar.wait(flag).unwrap();
        }
    }

    /// Block until shutdown or timeout. Returns `true` if shutdown was triggered.
    pub fn wait_timeout(&self, timeout: Duration) -> bool {
        let deadline = Instant::now() + timeout;
        let mut flag = self.inner.flag.lock().unwrap();
        while !*flag {
            let remaining = deadline.saturating_duration_since(Instant::now());
            if remaining.is_zero() {
                return false;
            }
            let (guard, _) = self.inner.condvar.wait_timeout(flag, remaining).unwrap();
            flag = guard;
        }
        true
    }

    /// Interruptible sleep. Returns `true` if interrupted by shutdown.
    pub fn sleep(&self, duration: Duration) -> bool {
        self.wait_timeout(duration)
    }

    /// Register a cleanup hook. Called exactly once when shutdown is triggered.
    /// If shutdown has already occurred, the hook is called immediately.
    pub fn register_hook<F: FnOnce() + Send + 'static>(&self, hook: F) {
        let mut hooks_guard = self.inner.hooks.lock().unwrap();
        if let Some(hooks) = hooks_guard.as_mut() {
            hooks.push(Box::new(hook));
        } else {
            // Shutdown already happened — run immediately
            drop(hooks_guard);
            hook();
        }
    }

    /// Get a cheaply cloneable token that shares shutdown state.
    pub fn token(&self) -> ShutdownToken {
        ShutdownToken {
            inner: self.inner.clone(),
        }
    }

    /// Reset for testing purposes only. Clears the shutdown flag and re-enables hooks.
    pub fn reset_for_testing(&self) {
        let mut flag = self.inner.flag.lock().unwrap();
        *flag = false;
        let mut hooks = self.inner.hooks.lock().unwrap();
        *hooks = Some(Vec::new());
    }
}

impl Default for ShutdownHandler {
    fn default() -> Self {
        Self::new()
    }
}

impl ShutdownInner {
    fn run_hooks_and_set(&self, _inner: &Arc<ShutdownInner>) {
        // Take hooks (None means already executed)
        let hooks = {
            let mut hooks_guard = self.hooks.lock().unwrap();
            hooks_guard.take()
        };

        if let Some(hooks) = hooks {
            // Run all hooks
            for hook in hooks {
                hook();
            }
        }

        // Set flag and notify all waiters
        let mut flag = self.flag.lock().unwrap();
        *flag = true;
        self.condvar.notify_all();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn test_initial_state() {
        let h = ShutdownHandler::new();
        assert!(!h.is_shutdown());
    }

    #[test]
    fn test_trigger_immediate() {
        let h = ShutdownHandler::new();
        h.trigger();
        assert!(h.is_shutdown());
    }

    #[test]
    fn test_trigger_delayed() {
        let h = ShutdownHandler::new();
        h.trigger_delayed(Duration::from_millis(100));
        assert!(!h.is_shutdown());
        thread::sleep(Duration::from_millis(250));
        assert!(h.is_shutdown());
    }

    #[test]
    fn test_hook_called_on_shutdown() {
        let h = ShutdownHandler::new();
        let called = Arc::new(AtomicUsize::new(0));
        let called_clone = called.clone();
        h.register_hook(move || {
            called_clone.fetch_add(1, Ordering::SeqCst);
        });
        h.trigger();
        assert_eq!(called.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_hooks_execute_only_once() {
        let h = ShutdownHandler::new();
        let counter = Arc::new(AtomicUsize::new(0));
        let counter_clone = counter.clone();
        h.register_hook(move || {
            counter_clone.fetch_add(1, Ordering::SeqCst);
        });
        h.trigger();
        h.trigger();
        assert_eq!(counter.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_sleep_interrupted_by_shutdown() {
        let h = ShutdownHandler::new();
        let h2 = h.clone();
        thread::spawn(move || {
            thread::sleep(Duration::from_millis(100));
            h2.trigger();
        });
        let start = Instant::now();
        let interrupted = h.sleep(Duration::from_secs(5));
        let elapsed = start.elapsed();
        assert!(interrupted);
        assert!(elapsed < Duration::from_secs(1));
    }

    #[test]
    fn test_sleep_completes_normally() {
        let h = ShutdownHandler::new();
        let interrupted = h.sleep(Duration::from_millis(50));
        assert!(!interrupted);
    }

    #[test]
    fn test_wait_blocks_until_shutdown() {
        let h = ShutdownHandler::new();
        let h2 = h.clone();
        let done = Arc::new(AtomicUsize::new(0));
        let done_clone = done.clone();
        thread::spawn(move || {
            h2.wait();
            done_clone.fetch_add(1, Ordering::SeqCst);
        });
        thread::sleep(Duration::from_millis(50));
        assert_eq!(done.load(Ordering::SeqCst), 0);
        h.trigger();
        thread::sleep(Duration::from_millis(50));
        assert_eq!(done.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_wait_timeout_expires() {
        let h = ShutdownHandler::new();
        let result = h.wait_timeout(Duration::from_millis(100));
        assert!(!result);
    }

    #[test]
    fn test_wait_timeout_returns_true() {
        let h = ShutdownHandler::new();
        let h2 = h.clone();
        thread::spawn(move || {
            thread::sleep(Duration::from_millis(50));
            h2.trigger();
        });
        let result = h.wait_timeout(Duration::from_secs(5));
        assert!(result);
    }

    #[test]
    fn test_multiple_hooks_all_called() {
        let h = ShutdownHandler::new();
        let counter = Arc::new(AtomicUsize::new(0));
        for _ in 0..3 {
            let c = counter.clone();
            h.register_hook(move || {
                c.fetch_add(1, Ordering::SeqCst);
            });
        }
        h.trigger();
        assert_eq!(counter.load(Ordering::SeqCst), 3);
    }

    #[test]
    fn test_hook_registered_after_shutdown() {
        let h = ShutdownHandler::new();
        h.trigger();
        let called = Arc::new(AtomicUsize::new(0));
        let called_clone = called.clone();
        h.register_hook(move || {
            called_clone.fetch_add(1, Ordering::SeqCst);
        });
        assert_eq!(called.load(Ordering::SeqCst), 1);
    }

    #[test]
    fn test_clone_token_shares_state() {
        let h = ShutdownHandler::new();
        let token = h.token();
        assert!(!token.is_shutdown());
        h.trigger();
        assert!(token.is_shutdown());
    }

    #[test]
    fn test_reset_for_testing() {
        let h = ShutdownHandler::new();
        h.trigger();
        assert!(h.is_shutdown());
        h.reset_for_testing();
        assert!(!h.is_shutdown());
    }
}