argentor-gateway 1.3.0

Axum-based HTTP gateway, REST API, and WebSocket server for Argentor
Documentation
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
//! Graceful shutdown manager with cleanup hooks and connection draining.
//!
//! Provides a structured way to register shutdown callbacks, drain active
//! connections, and ensure all cleanup runs within a configurable timeout.
//!
//! # Main types
//!
//! - [`ShutdownManager`] — Coordinates graceful shutdown with hooks.
//! - [`ShutdownHook`] — A named cleanup callback.
//! - [`ShutdownPhase`] — Ordered execution phases for hooks.
//! - [`ShutdownReport`] — Summary of what happened during shutdown.

use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::sync::{Notify, RwLock};
use tracing::{error, info, warn};

// ---------------------------------------------------------------------------
// ShutdownPhase
// ---------------------------------------------------------------------------

/// Ordered phases during graceful shutdown.
///
/// Hooks execute in phase order: `PreDrain` → `Drain` → `Cleanup` → `Final`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ShutdownPhase {
    /// Before draining — stop accepting new connections/requests.
    PreDrain,
    /// Drain active connections and in-flight requests.
    Drain,
    /// Clean up resources (flush buffers, close files, save state).
    Cleanup,
    /// Final actions (audit log entries, metric export).
    Final,
}

// ---------------------------------------------------------------------------
// ShutdownHook
// ---------------------------------------------------------------------------

/// A named cleanup callback to run during shutdown.
pub struct ShutdownHook {
    /// Human-readable name for logging.
    pub name: String,
    /// Which phase this hook should run in.
    pub phase: ShutdownPhase,
    /// The callback to execute.
    pub callback: Box<dyn Fn() -> Result<(), String> + Send + Sync>,
}

impl std::fmt::Debug for ShutdownHook {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ShutdownHook")
            .field("name", &self.name)
            .field("phase", &self.phase)
            .finish()
    }
}

// ---------------------------------------------------------------------------
// HookResult
// ---------------------------------------------------------------------------

/// Result of executing a single shutdown hook.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HookResult {
    /// Name of the hook.
    pub name: String,
    /// Phase the hook ran in.
    pub phase: ShutdownPhase,
    /// Whether the hook succeeded.
    pub success: bool,
    /// Error message if the hook failed.
    pub error: Option<String>,
    /// How long the hook took to run.
    pub duration_ms: u64,
}

// ---------------------------------------------------------------------------
// ShutdownReport
// ---------------------------------------------------------------------------

/// Summary of a graceful shutdown sequence.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ShutdownReport {
    /// Total wall-clock time for the shutdown sequence.
    pub total_duration_ms: u64,
    /// Number of hooks that ran successfully.
    pub hooks_succeeded: usize,
    /// Number of hooks that failed.
    pub hooks_failed: usize,
    /// Whether the shutdown completed within the timeout.
    pub completed_in_time: bool,
    /// Individual hook results.
    pub hook_results: Vec<HookResult>,
}

// ---------------------------------------------------------------------------
// ShutdownState
// ---------------------------------------------------------------------------

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum ShutdownState {
    Running,
    ShuttingDown,
    Completed,
}

// ---------------------------------------------------------------------------
// ShutdownManager
// ---------------------------------------------------------------------------

/// Coordinates graceful shutdown with ordered phases and cleanup hooks.
///
/// Clone is cheap (inner state is behind `Arc`).
#[derive(Clone)]
pub struct ShutdownManager {
    state: Arc<RwLock<ShutdownState>>,
    hooks: Arc<RwLock<Vec<ShutdownHook>>>,
    notify: Arc<Notify>,
    timeout: Duration,
}

impl std::fmt::Debug for ShutdownManager {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ShutdownManager")
            .field("timeout", &self.timeout)
            .finish()
    }
}

impl ShutdownManager {
    /// Create a new shutdown manager with the given timeout.
    pub fn new(timeout: Duration) -> Self {
        Self {
            state: Arc::new(RwLock::new(ShutdownState::Running)),
            hooks: Arc::new(RwLock::new(Vec::new())),
            notify: Arc::new(Notify::new()),
            timeout,
        }
    }

    /// Register a shutdown hook.
    pub async fn register_hook(&self, hook: ShutdownHook) {
        let mut hooks = self.hooks.write().await;
        info!(name = %hook.name, phase = ?hook.phase, "Shutdown hook registered");
        hooks.push(hook);
    }

    /// Register a simple shutdown hook with a name, phase, and closure.
    pub async fn on_shutdown(
        &self,
        name: impl Into<String>,
        phase: ShutdownPhase,
        callback: impl Fn() -> Result<(), String> + Send + Sync + 'static,
    ) {
        self.register_hook(ShutdownHook {
            name: name.into(),
            phase,
            callback: Box::new(callback),
        })
        .await;
    }

    /// Check if shutdown has been initiated.
    pub async fn is_shutting_down(&self) -> bool {
        let state = self.state.read().await;
        *state != ShutdownState::Running
    }

    /// Get a future that resolves when shutdown is initiated.
    ///
    /// This can be used as a signal in `tokio::select!` loops.
    pub fn shutdown_signal(&self) -> Arc<Notify> {
        self.notify.clone()
    }

    /// Initiate graceful shutdown, running all hooks in phase order.
    ///
    /// Returns a report of what happened.
    pub async fn shutdown(&self) -> ShutdownReport {
        let start = Instant::now();

        // Mark as shutting down
        {
            let mut state = self.state.write().await;
            if *state != ShutdownState::Running {
                return ShutdownReport {
                    total_duration_ms: 0,
                    hooks_succeeded: 0,
                    hooks_failed: 0,
                    completed_in_time: true,
                    hook_results: Vec::new(),
                };
            }
            *state = ShutdownState::ShuttingDown;
        }

        // Notify waiting tasks
        self.notify.notify_waiters();
        info!("Graceful shutdown initiated");

        let mut all_results = Vec::new();
        let mut succeeded = 0;
        let mut failed = 0;

        // Execute hooks in phase order
        let phases = [
            ShutdownPhase::PreDrain,
            ShutdownPhase::Drain,
            ShutdownPhase::Cleanup,
            ShutdownPhase::Final,
        ];

        let hooks = self.hooks.read().await;

        for phase in &phases {
            if start.elapsed() > self.timeout {
                warn!(phase = ?phase, "Shutdown timeout reached, skipping remaining hooks");
                break;
            }

            let phase_hooks: Vec<&ShutdownHook> =
                hooks.iter().filter(|h| h.phase == *phase).collect();

            if !phase_hooks.is_empty() {
                info!(phase = ?phase, count = phase_hooks.len(), "Executing shutdown phase");
            }

            for hook in phase_hooks {
                let hook_start = Instant::now();
                let result = (hook.callback)();
                let duration_ms = hook_start.elapsed().as_millis() as u64;

                match result {
                    Ok(()) => {
                        info!(name = %hook.name, duration_ms, "Shutdown hook completed");
                        succeeded += 1;
                        all_results.push(HookResult {
                            name: hook.name.clone(),
                            phase: *phase,
                            success: true,
                            error: None,
                            duration_ms,
                        });
                    }
                    Err(e) => {
                        error!(name = %hook.name, error = %e, "Shutdown hook failed");
                        failed += 1;
                        all_results.push(HookResult {
                            name: hook.name.clone(),
                            phase: *phase,
                            success: false,
                            error: Some(e),
                            duration_ms,
                        });
                    }
                }
            }
        }

        let total_duration_ms = start.elapsed().as_millis() as u64;
        let completed_in_time = start.elapsed() <= self.timeout;

        // Mark as completed
        {
            let mut state = self.state.write().await;
            *state = ShutdownState::Completed;
        }

        info!(
            total_ms = total_duration_ms,
            succeeded, failed, "Graceful shutdown complete"
        );

        ShutdownReport {
            total_duration_ms,
            hooks_succeeded: succeeded,
            hooks_failed: failed,
            completed_in_time,
            hook_results: all_results,
        }
    }

    /// Get the number of registered hooks.
    pub async fn hook_count(&self) -> usize {
        self.hooks.read().await.len()
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};

    fn manager() -> ShutdownManager {
        ShutdownManager::new(Duration::from_secs(5))
    }

    // 1. New manager is in running state
    #[tokio::test]
    async fn test_initial_state() {
        let mgr = manager();
        assert!(!mgr.is_shutting_down().await);
    }

    // 2. Shutdown changes state
    #[tokio::test]
    async fn test_shutdown_changes_state() {
        let mgr = manager();
        let _report = mgr.shutdown().await;
        assert!(mgr.is_shutting_down().await);
    }

    // 3. Hooks run on shutdown
    #[tokio::test]
    async fn test_hooks_run() {
        let mgr = manager();
        let ran = Arc::new(AtomicBool::new(false));
        let ran_clone = ran.clone();

        mgr.on_shutdown("test-hook", ShutdownPhase::Cleanup, move || {
            ran_clone.store(true, Ordering::SeqCst);
            Ok(())
        })
        .await;

        let report = mgr.shutdown().await;
        assert!(ran.load(Ordering::SeqCst));
        assert_eq!(report.hooks_succeeded, 1);
        assert_eq!(report.hooks_failed, 0);
    }

    // 4. Failed hooks are tracked
    #[tokio::test]
    async fn test_failed_hooks() {
        let mgr = manager();
        mgr.on_shutdown("fail-hook", ShutdownPhase::Cleanup, || {
            Err("intentional failure".to_string())
        })
        .await;

        let report = mgr.shutdown().await;
        assert_eq!(report.hooks_failed, 1);
        assert_eq!(report.hooks_succeeded, 0);
        assert!(report.hook_results[0].error.is_some());
    }

    // 5. Hooks execute in phase order
    #[tokio::test]
    async fn test_phase_order() {
        let mgr = manager();
        let order = Arc::new(std::sync::Mutex::new(Vec::new()));

        for (name, phase) in [
            ("final", ShutdownPhase::Final),
            ("pre-drain", ShutdownPhase::PreDrain),
            ("cleanup", ShutdownPhase::Cleanup),
            ("drain", ShutdownPhase::Drain),
        ] {
            let order_clone = order.clone();
            let name_str = name.to_string();
            mgr.on_shutdown(name, phase, move || {
                order_clone.lock().unwrap().push(name_str.clone());
                Ok(())
            })
            .await;
        }

        mgr.shutdown().await;

        let order = order.lock().unwrap();
        assert_eq!(&*order, &["pre-drain", "drain", "cleanup", "final"]);
    }

    // 6. Multiple hooks per phase
    #[tokio::test]
    async fn test_multiple_hooks_per_phase() {
        let mgr = manager();
        let counter = Arc::new(AtomicU32::new(0));

        for i in 0..3 {
            let c = counter.clone();
            mgr.on_shutdown(format!("hook-{i}"), ShutdownPhase::Cleanup, move || {
                c.fetch_add(1, Ordering::SeqCst);
                Ok(())
            })
            .await;
        }

        let report = mgr.shutdown().await;
        assert_eq!(counter.load(Ordering::SeqCst), 3);
        assert_eq!(report.hooks_succeeded, 3);
    }

    // 7. Double shutdown is safe (no-op)
    #[tokio::test]
    async fn test_double_shutdown() {
        let mgr = manager();
        let counter = Arc::new(AtomicU32::new(0));
        let c = counter.clone();

        mgr.on_shutdown("once", ShutdownPhase::Cleanup, move || {
            c.fetch_add(1, Ordering::SeqCst);
            Ok(())
        })
        .await;

        mgr.shutdown().await;
        let report2 = mgr.shutdown().await;

        assert_eq!(counter.load(Ordering::SeqCst), 1);
        assert_eq!(report2.hooks_succeeded, 0);
    }

    // 8. Report includes timing
    #[tokio::test]
    async fn test_report_timing() {
        let mgr = manager();
        let report = mgr.shutdown().await;
        assert!(report.completed_in_time);
        // Duration should be very small for empty shutdown
        assert!(report.total_duration_ms < 1000);
    }

    // 9. Hook count tracking
    #[tokio::test]
    async fn test_hook_count() {
        let mgr = manager();
        assert_eq!(mgr.hook_count().await, 0);

        mgr.on_shutdown("h1", ShutdownPhase::Cleanup, || Ok(()))
            .await;
        mgr.on_shutdown("h2", ShutdownPhase::Final, || Ok(())).await;
        assert_eq!(mgr.hook_count().await, 2);
    }

    // 10. Shutdown signal notifies waiters
    #[tokio::test]
    async fn test_shutdown_signal() {
        let mgr = manager();
        let signal = mgr.shutdown_signal();
        let notified = Arc::new(AtomicBool::new(false));
        let notified_clone = notified.clone();

        let handle = tokio::spawn(async move {
            signal.notified().await;
            notified_clone.store(true, Ordering::SeqCst);
        });

        // Small delay to ensure the task is waiting
        tokio::time::sleep(Duration::from_millis(10)).await;
        mgr.shutdown().await;

        handle.await.unwrap();
        assert!(notified.load(Ordering::SeqCst));
    }

    // 11. Report serializable
    #[tokio::test]
    async fn test_report_serializable() {
        let mgr = manager();
        mgr.on_shutdown("ser", ShutdownPhase::Cleanup, || Ok(()))
            .await;
        let report = mgr.shutdown().await;

        let json = serde_json::to_string(&report).unwrap();
        assert!(json.contains("\"hooks_succeeded\":1"));

        let restored: ShutdownReport = serde_json::from_str(&json).unwrap();
        assert_eq!(restored.hooks_succeeded, 1);
    }

    // 12. ShutdownPhase ordering
    #[test]
    fn test_phase_ordering() {
        assert!(ShutdownPhase::PreDrain < ShutdownPhase::Drain);
        assert!(ShutdownPhase::Drain < ShutdownPhase::Cleanup);
        assert!(ShutdownPhase::Cleanup < ShutdownPhase::Final);
    }

    // 13. Hook result tracks duration
    #[tokio::test]
    async fn test_hook_duration() {
        let mgr = manager();
        mgr.on_shutdown("slow", ShutdownPhase::Cleanup, || {
            std::thread::sleep(Duration::from_millis(10));
            Ok(())
        })
        .await;

        let report = mgr.shutdown().await;
        assert!(report.hook_results[0].duration_ms >= 5);
    }

    // 14. Mixed success and failure
    #[tokio::test]
    async fn test_mixed_results() {
        let mgr = manager();
        mgr.on_shutdown("ok1", ShutdownPhase::PreDrain, || Ok(()))
            .await;
        mgr.on_shutdown("fail1", ShutdownPhase::Drain, || Err("oops".to_string()))
            .await;
        mgr.on_shutdown("ok2", ShutdownPhase::Cleanup, || Ok(()))
            .await;
        mgr.on_shutdown("fail2", ShutdownPhase::Final, || Err("boom".to_string()))
            .await;

        let report = mgr.shutdown().await;
        assert_eq!(report.hooks_succeeded, 2);
        assert_eq!(report.hooks_failed, 2);
    }

    // 15. Clone shares state
    #[tokio::test]
    async fn test_clone_shares_state() {
        let mgr1 = manager();
        let mgr2 = mgr1.clone();

        mgr1.on_shutdown("shared", ShutdownPhase::Cleanup, || Ok(()))
            .await;

        assert_eq!(mgr2.hook_count().await, 1);

        mgr2.shutdown().await;
        assert!(mgr1.is_shutting_down().await);
    }

    // 16. PreDrain hooks run before Cleanup
    #[tokio::test]
    async fn test_predrain_before_cleanup() {
        let mgr = manager();
        let val = Arc::new(std::sync::Mutex::new(0u32));
        let val1 = val.clone();
        let val2 = val.clone();

        mgr.on_shutdown("cleanup", ShutdownPhase::Cleanup, move || {
            let v = *val1.lock().unwrap();
            // PreDrain should have already set this to 1
            assert_eq!(v, 1);
            Ok(())
        })
        .await;

        mgr.on_shutdown("predrain", ShutdownPhase::PreDrain, move || {
            *val2.lock().unwrap() = 1;
            Ok(())
        })
        .await;

        let report = mgr.shutdown().await;
        assert_eq!(report.hooks_succeeded, 2);
    }
}