amaters-server 0.2.0

AmateRS server binary
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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
//! Graceful shutdown handling
//!
//! This module provides signal handling for graceful server shutdown,
//! coordinating the shutdown of all components in the correct order.
//! It supports connection draining, phased shutdown, state persistence
//! via shutdown hooks, and detailed status reporting.
//! It also handles SIGHUP for hot configuration reload on Unix platforms.

use crate::config::ReloadableConfig;
use std::fmt;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};
use tokio::sync::{Mutex, broadcast, watch};
use tracing::{debug, error, info, warn};

// ---------------------------------------------------------------------------
// Shutdown phase
// ---------------------------------------------------------------------------

/// Phases of the shutdown lifecycle
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ShutdownPhase {
    /// Server is running normally and accepting requests
    Running,
    /// Server stopped accepting new connections; waiting for in-flight requests
    Draining,
    /// Executing shutdown hooks (WAL flush, memtable flush, metrics snapshot, etc.)
    FlushingState,
    /// Shutdown complete
    Terminated,
}

impl ShutdownPhase {
    /// Numeric representation for atomic storage
    fn as_u64(self) -> u64 {
        match self {
            Self::Running => 0,
            Self::Draining => 1,
            Self::FlushingState => 2,
            Self::Terminated => 3,
        }
    }

    fn from_u64(val: u64) -> Self {
        match val {
            0 => Self::Running,
            1 => Self::Draining,
            2 => Self::FlushingState,
            3 => Self::Terminated,
            _ => Self::Terminated,
        }
    }
}

impl fmt::Display for ShutdownPhase {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Running => write!(f, "Running"),
            Self::Draining => write!(f, "Draining"),
            Self::FlushingState => write!(f, "FlushingState"),
            Self::Terminated => write!(f, "Terminated"),
        }
    }
}

// ---------------------------------------------------------------------------
// Drain configuration
// ---------------------------------------------------------------------------

/// Configuration for connection draining behaviour
#[derive(Debug, Clone)]
pub struct DrainConfig {
    /// Maximum time to wait for in-flight requests to complete
    pub drain_timeout: Duration,
    /// Interval at which we log draining progress
    pub check_interval: Duration,
    /// Timeout for the flushing-state phase (hook execution)
    pub flush_timeout: Duration,
}

impl Default for DrainConfig {
    fn default() -> Self {
        Self {
            drain_timeout: Duration::from_secs(30),
            check_interval: Duration::from_secs(1),
            flush_timeout: Duration::from_secs(30),
        }
    }
}

// ---------------------------------------------------------------------------
// Shutdown hook trait
// ---------------------------------------------------------------------------

/// A hook that runs during the `FlushingState` phase of shutdown.
///
/// Implementors should perform any final persistence / cleanup work
/// (e.g. flushing WAL, memtable, metrics) in [`on_shutdown`](ShutdownHook::on_shutdown).
#[async_trait::async_trait]
pub trait ShutdownHook: Send + Sync {
    /// Human-readable name of this hook (used in logging)
    fn name(&self) -> &str;

    /// Execute the hook. Errors are logged but do **not** prevent other hooks
    /// from running.
    async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
}

// ---------------------------------------------------------------------------
// Storage integration traits
// ---------------------------------------------------------------------------

/// Trait for WAL sync operations during shutdown
pub trait WalWriter: Send + Sync {
    /// Sync all pending WAL data to disk
    fn sync(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>>;
    /// Return the current size of the WAL in bytes
    fn current_size(&self) -> u64;
}

/// Trait for memtable flush operations during shutdown
pub trait MemtableFlusher: Send + Sync {
    /// Flush the active memtable to an SSTable, returning the number of entries flushed
    fn flush_to_sstable(&self) -> Result<usize, Box<dyn std::error::Error + Send + Sync>>;
}

// ---------------------------------------------------------------------------
// Hook execution result
// ---------------------------------------------------------------------------

/// Result of a single shutdown hook execution
#[derive(Debug, Clone)]
pub struct HookExecutionResult {
    /// Name of the hook that was executed
    pub hook_name: String,
    /// Whether the hook completed successfully
    pub success: bool,
    /// How long the hook took to execute
    pub duration: Duration,
    /// Error message if the hook failed
    pub error: Option<String>,
}

// ---------------------------------------------------------------------------
// Built-in hooks
// ---------------------------------------------------------------------------

/// Flush the Write-Ahead Log to disk
pub struct WalFlushHook {
    /// Timeout for this individual hook
    pub timeout: Duration,
    /// Optional WAL writer for real storage integration
    writer: Option<Arc<dyn WalWriter>>,
}

impl WalFlushHook {
    /// Create a WAL flush hook with a real writer
    pub fn with_writer(writer: Arc<dyn WalWriter>, timeout: Duration) -> Self {
        Self {
            timeout,
            writer: Some(writer),
        }
    }
}

impl Default for WalFlushHook {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(10),
            writer: None,
        }
    }
}

#[async_trait::async_trait]
impl ShutdownHook for WalFlushHook {
    fn name(&self) -> &str {
        "WalFlush"
    }

    async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        match &self.writer {
            Some(writer) => {
                let size = writer.current_size();
                info!("Flushing WAL to disk ({} bytes)", size);
                writer.sync()?;
                info!("WAL flush complete ({} bytes synced)", size);
            }
            None => {
                info!("No WAL writer configured - skipping flush");
            }
        }
        Ok(())
    }
}

/// Flush the active memtable to an SSTable
pub struct MemtableFlushHook {
    /// Timeout for this individual hook
    pub timeout: Duration,
    /// Optional memtable flusher for real storage integration
    flusher: Option<Arc<dyn MemtableFlusher>>,
}

impl MemtableFlushHook {
    /// Create a memtable flush hook with a real flusher
    pub fn with_flusher(flusher: Arc<dyn MemtableFlusher>, timeout: Duration) -> Self {
        Self {
            timeout,
            flusher: Some(flusher),
        }
    }
}

impl Default for MemtableFlushHook {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(15),
            flusher: None,
        }
    }
}

#[async_trait::async_trait]
impl ShutdownHook for MemtableFlushHook {
    fn name(&self) -> &str {
        "MemtableFlush"
    }

    async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        match &self.flusher {
            Some(flusher) => {
                info!("Flushing active memtable to SSTable");
                let entries = flusher.flush_to_sstable()?;
                info!("Memtable flush complete ({} entries flushed)", entries);
            }
            None => {
                info!("No memtable flusher configured - skipping flush");
            }
        }
        Ok(())
    }
}

/// Drain active connections before shutdown
pub struct ConnectionDrainHook {
    /// Shared counter of active connections
    active_connections: Arc<AtomicUsize>,
    /// Maximum time to wait for connections to drain
    drain_timeout: Duration,
    /// Interval between polling the connection counter
    poll_interval: Duration,
}

impl ConnectionDrainHook {
    /// Create a new connection drain hook
    ///
    /// # Arguments
    /// * `active_connections` - Shared atomic counter of active connections
    /// * `drain_timeout` - Maximum time to wait for all connections to close
    pub fn new(active_connections: Arc<AtomicUsize>, drain_timeout: Duration) -> Self {
        Self {
            active_connections,
            drain_timeout,
            poll_interval: Duration::from_millis(100),
        }
    }

    /// Set a custom poll interval (default is 100ms)
    pub fn with_poll_interval(mut self, interval: Duration) -> Self {
        self.poll_interval = interval;
        self
    }
}

#[async_trait::async_trait]
impl ShutdownHook for ConnectionDrainHook {
    fn name(&self) -> &str {
        "ConnectionDrain"
    }

    async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        let deadline = Instant::now() + self.drain_timeout;

        loop {
            let remaining = self.active_connections.load(Ordering::SeqCst);
            if remaining == 0 {
                info!("All connections drained");
                return Ok(());
            }

            if Instant::now() >= deadline {
                warn!(
                    "Connection drain timeout ({:?}) exceeded with {} connections remaining",
                    self.drain_timeout, remaining
                );
                return Err(format!(
                    "connection drain timed out with {} connections remaining",
                    remaining
                )
                .into());
            }

            info!("Draining connections: {} remaining", remaining);
            tokio::time::sleep(self.poll_interval).await;
        }
    }
}

/// Save a final metrics snapshot
pub struct MetricsSnapshotHook {
    /// Timeout for this individual hook
    pub timeout: Duration,
    /// Optional path to write metrics data to
    metrics_path: Option<PathBuf>,
    /// Optional provider that produces metrics data as bytes
    metrics_provider: Option<Arc<dyn Fn() -> Vec<u8> + Send + Sync>>,
}

impl MetricsSnapshotHook {
    /// Create a metrics snapshot hook with a provider and output path
    pub fn with_provider(
        provider: Arc<dyn Fn() -> Vec<u8> + Send + Sync>,
        path: PathBuf,
        timeout: Duration,
    ) -> Self {
        Self {
            timeout,
            metrics_path: Some(path),
            metrics_provider: Some(provider),
        }
    }
}

impl Default for MetricsSnapshotHook {
    fn default() -> Self {
        Self {
            timeout: Duration::from_secs(5),
            metrics_path: None,
            metrics_provider: None,
        }
    }
}

#[async_trait::async_trait]
impl ShutdownHook for MetricsSnapshotHook {
    fn name(&self) -> &str {
        "MetricsSnapshot"
    }

    async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        match (&self.metrics_provider, &self.metrics_path) {
            (Some(provider), Some(path)) => {
                let data = provider();
                info!(
                    "Writing {} bytes of metrics to {}",
                    data.len(),
                    path.display()
                );
                std::fs::write(path, &data)?;
                info!("Metrics snapshot saved successfully");
            }
            _ => {
                info!("No metrics provider/path configured - skipping snapshot");
            }
        }
        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Shutdown status
// ---------------------------------------------------------------------------

/// Snapshot of the current shutdown progress
#[derive(Debug, Clone)]
pub struct ShutdownStatus {
    /// Current phase
    pub phase: ShutdownPhase,
    /// Number of in-flight requests still being processed
    pub active_requests: usize,
    /// Number of hooks that have completed (successfully or not)
    pub hooks_completed: usize,
    /// Total registered hooks
    pub hooks_total: usize,
    /// Milliseconds elapsed since shutdown was initiated (0 if not yet initiated)
    pub elapsed_ms: u64,
}

// ---------------------------------------------------------------------------
// Shutdown coordinator
// ---------------------------------------------------------------------------

/// Shutdown coordinator
///
/// Manages graceful shutdown across all server components, including connection
/// draining, phased shutdown, and hook execution.
#[derive(Clone)]
pub struct ShutdownCoordinator {
    inner: Arc<ShutdownInner>,
}

struct ShutdownInner {
    /// Broadcast channel for the initial shutdown signal
    sender: broadcast::Sender<()>,
    /// Watch channel so late subscribers can observe phase changes
    phase_tx: watch::Sender<ShutdownPhase>,
    phase_rx: watch::Receiver<ShutdownPhase>,
    /// Atomic flag indicating shutdown initiated (idempotent)
    shutdown_initiated: AtomicBool,
    /// Current phase stored atomically for lock-free reads
    phase: AtomicU64,
    /// Number of active (in-flight) requests
    active_requests: AtomicUsize,
    /// Registered shutdown hooks (protected by Mutex for append + iteration)
    hooks: Mutex<Vec<Box<dyn ShutdownHook>>>,
    /// Number of hooks completed so far
    hooks_completed: AtomicUsize,
    /// Results from hook execution
    hook_results: Mutex<Vec<HookExecutionResult>>,
    /// Drain configuration
    drain_config: DrainConfig,
    /// Instant when shutdown was initiated (set once, then read-only)
    shutdown_start: Mutex<Option<Instant>>,
}

impl ShutdownCoordinator {
    /// Create a new shutdown coordinator with default drain configuration
    pub fn new() -> Self {
        Self::with_config(DrainConfig::default())
    }

    /// Create a new shutdown coordinator with the given drain configuration
    pub fn with_config(config: DrainConfig) -> Self {
        let (sender, _) = broadcast::channel(16);
        let (phase_tx, phase_rx) = watch::channel(ShutdownPhase::Running);

        Self {
            inner: Arc::new(ShutdownInner {
                sender,
                phase_tx,
                phase_rx,
                shutdown_initiated: AtomicBool::new(false),
                phase: AtomicU64::new(ShutdownPhase::Running.as_u64()),
                active_requests: AtomicUsize::new(0),
                hooks: Mutex::new(Vec::new()),
                hooks_completed: AtomicUsize::new(0),
                hook_results: Mutex::new(Vec::new()),
                drain_config: config,
                shutdown_start: Mutex::new(None),
            }),
        }
    }

    // -- Subscription -------------------------------------------------------

    /// Subscribe to the initial shutdown broadcast signal
    pub fn subscribe(&self) -> broadcast::Receiver<()> {
        self.inner.sender.subscribe()
    }

    /// Subscribe to phase changes via a `watch` channel
    pub fn phase_watch(&self) -> watch::Receiver<ShutdownPhase> {
        self.inner.phase_rx.clone()
    }

    // -- Active request tracking --------------------------------------------

    /// Increment the active request counter (called when a new request arrives)
    pub fn request_start(&self) {
        self.inner.active_requests.fetch_add(1, Ordering::SeqCst);
    }

    /// Decrement the active request counter (called when a request completes)
    pub fn request_end(&self) {
        self.inner.active_requests.fetch_sub(1, Ordering::SeqCst);
    }

    /// Current number of active (in-flight) requests
    pub fn active_request_count(&self) -> usize {
        self.inner.active_requests.load(Ordering::SeqCst)
    }

    // -- Hook registration --------------------------------------------------

    /// Register a shutdown hook that will run during the `FlushingState` phase
    pub async fn register_shutdown_hook(&self, hook: Box<dyn ShutdownHook>) {
        let mut hooks = self.inner.hooks.lock().await;
        info!("Registered shutdown hook: {}", hook.name());
        hooks.push(hook);
    }

    // -- Phase management ---------------------------------------------------

    /// Get the current shutdown phase
    pub fn current_phase(&self) -> ShutdownPhase {
        ShutdownPhase::from_u64(self.inner.phase.load(Ordering::SeqCst))
    }

    /// Whether we are currently accepting new connections
    pub fn is_accepting(&self) -> bool {
        self.current_phase() == ShutdownPhase::Running
    }

    fn set_phase(&self, phase: ShutdownPhase) {
        self.inner.phase.store(phase.as_u64(), Ordering::SeqCst);
        // Ignore send error -- it only fails when there are no receivers
        let _ = self.inner.phase_tx.send(phase);
        info!("Shutdown phase: {}", phase);
    }

    // -- Query --------------------------------------------------------------

    /// Check if shutdown has been initiated
    pub fn is_shutting_down(&self) -> bool {
        self.inner.shutdown_initiated.load(Ordering::SeqCst)
    }

    /// Returns `"shutting_down"` when draining/flushing/terminated, otherwise `"ok"`.
    ///
    /// Load balancers can poll this to detect that the server is shutting down
    /// and stop routing new requests.
    pub fn health_status_label(&self) -> &'static str {
        match self.current_phase() {
            ShutdownPhase::Running => "ok",
            _ => "shutting_down",
        }
    }

    /// Build a [`ShutdownStatus`] snapshot
    pub fn status(&self) -> ShutdownStatus {
        let elapsed_ms = {
            // Try-lock: if the mutex is contended we just report 0
            if let Ok(guard) = self.inner.shutdown_start.try_lock() {
                guard.map(|s| s.elapsed().as_millis() as u64).unwrap_or(0)
            } else {
                0
            }
        };

        let hooks_total = if let Ok(hooks) = self.inner.hooks.try_lock() {
            hooks.len()
        } else {
            0
        };

        ShutdownStatus {
            phase: self.current_phase(),
            active_requests: self.active_request_count(),
            hooks_completed: self.inner.hooks_completed.load(Ordering::SeqCst),
            hooks_total,
            elapsed_ms,
        }
    }

    // -- Initiate shutdown --------------------------------------------------

    /// Initiate a graceful shutdown.
    ///
    /// This is idempotent -- calling it more than once is a no-op.
    /// The method broadcasts the shutdown signal, then (in a spawned task)
    /// drives the phase machine: Draining -> FlushingState -> Terminated.
    pub fn shutdown(&self) {
        if self.inner.shutdown_initiated.swap(true, Ordering::SeqCst) {
            // Already initiated
            debug!("Shutdown already initiated - ignoring duplicate signal");
            return;
        }

        info!("Initiating graceful shutdown");

        // Record start time
        if let Ok(mut guard) = self.inner.shutdown_start.try_lock() {
            *guard = Some(Instant::now());
        }

        // Broadcast to legacy subscribers
        if let Err(e) = self.inner.sender.send(()) {
            warn!("Failed to broadcast shutdown signal: {}", e);
        }

        // Spawn the phase-driver task
        let coord = self.clone();
        tokio::spawn(async move {
            coord.run_shutdown_sequence().await;
        });
    }

    /// Execute the full shutdown sequence: Draining -> FlushingState -> Terminated
    async fn run_shutdown_sequence(&self) {
        // ---- Phase 1: Draining ----
        self.set_phase(ShutdownPhase::Draining);
        self.drain_connections().await;

        // ---- Phase 2: Flushing state (run hooks) ----
        self.set_phase(ShutdownPhase::FlushingState);
        self.run_hooks().await;

        // ---- Phase 3: Terminated ----
        self.set_phase(ShutdownPhase::Terminated);
        info!("Shutdown complete");
    }

    /// Wait for all active requests to drain, up to `drain_timeout`.
    async fn drain_connections(&self) {
        let cfg = &self.inner.drain_config;
        let deadline = Instant::now() + cfg.drain_timeout;

        loop {
            let remaining = self.active_request_count();
            if remaining == 0 {
                info!("All in-flight requests drained");
                return;
            }

            if Instant::now() >= deadline {
                warn!(
                    "Drain timeout ({:?}) exceeded with {} requests remaining - force-closing",
                    cfg.drain_timeout, remaining
                );
                return;
            }

            info!("Draining: {} requests remaining", remaining);
            tokio::time::sleep(cfg.check_interval).await;
        }
    }

    /// Retrieve the results from all executed hooks.
    ///
    /// Returns an empty vector if shutdown has not been initiated or hooks
    /// have not yet finished executing.
    pub async fn hook_results(&self) -> Vec<HookExecutionResult> {
        self.inner.hook_results.lock().await.clone()
    }

    /// Execute all registered shutdown hooks, each with the global flush timeout.
    async fn run_hooks(&self) {
        let hooks = {
            let mut guard = self.inner.hooks.lock().await;
            std::mem::take(&mut *guard)
        };

        if hooks.is_empty() {
            info!("No shutdown hooks registered");
            return;
        }

        let flush_timeout = self.inner.drain_config.flush_timeout;
        info!("Executing {} shutdown hook(s)", hooks.len());

        for hook in &hooks {
            let name = hook.name().to_string();
            info!("Running shutdown hook: {}", name);

            let start = Instant::now();
            let result = match tokio::time::timeout(flush_timeout, hook.on_shutdown()).await {
                Ok(Ok(())) => {
                    info!("Shutdown hook '{}' completed successfully", name);
                    HookExecutionResult {
                        hook_name: name,
                        success: true,
                        duration: start.elapsed(),
                        error: None,
                    }
                }
                Ok(Err(e)) => {
                    let msg = e.to_string();
                    error!("Shutdown hook '{}' failed: {}", name, msg);
                    HookExecutionResult {
                        hook_name: name,
                        success: false,
                        duration: start.elapsed(),
                        error: Some(msg),
                    }
                }
                Err(_) => {
                    let msg = format!("timed out after {:?}", flush_timeout);
                    error!("Shutdown hook '{}' {}", name, msg);
                    HookExecutionResult {
                        hook_name: name,
                        success: false,
                        duration: start.elapsed(),
                        error: Some(msg),
                    }
                }
            };

            {
                let mut results = self.inner.hook_results.lock().await;
                results.push(result);
            }
            self.inner.hooks_completed.fetch_add(1, Ordering::SeqCst);
        }

        info!(
            "All shutdown hooks processed ({} total)",
            self.inner.hooks_completed.load(Ordering::SeqCst)
        );
    }
}

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

// ---------------------------------------------------------------------------
// Signal handler setup
// ---------------------------------------------------------------------------

/// Setup signal handlers for graceful shutdown
///
/// Listens for SIGTERM and SIGINT signals and triggers shutdown
pub async fn setup_signal_handlers(coordinator: ShutdownCoordinator) {
    tokio::spawn(async move {
        if let Err(e) = wait_for_signal().await {
            warn!("Error setting up signal handlers: {}", e);
            return;
        }

        info!("Received shutdown signal");
        coordinator.shutdown();
    });
}

/// Setup SIGHUP handler for hot configuration reload (Unix only)
///
/// On SIGHUP, reloads configuration from the stored config file path.
/// On non-Unix platforms, this is a no-op; use `ReloadableConfig::manual_reload()` instead.
#[cfg(unix)]
pub async fn setup_sighup_handler(config: ReloadableConfig) {
    tokio::spawn(async move {
        let mut sighup = match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())
        {
            Ok(s) => s,
            Err(e) => {
                warn!("Failed to setup SIGHUP handler: {}", e);
                return;
            }
        };

        loop {
            sighup.recv().await;
            info!("Received SIGHUP - reloading configuration");

            match config.reload_from_stored_path() {
                Ok(report) => {
                    if report.success {
                        info!("Configuration reload completed: {}", report);
                    } else {
                        error!("Configuration reload failed: {}", report);
                    }
                }
                Err(e) => {
                    error!("Configuration reload error: {}", e);
                }
            }
        }
    });
}

/// No-op SIGHUP handler for non-Unix platforms.
///
/// Use `ReloadableConfig::manual_reload()` as an alternative.
#[cfg(not(unix))]
pub async fn setup_sighup_handler(_config: ReloadableConfig) {
    info!("SIGHUP handler not available on this platform; use manual_reload() instead");
}

/// Wait for shutdown signal (SIGTERM or SIGINT)
async fn wait_for_signal() -> Result<(), std::io::Error> {
    #[cfg(unix)]
    {
        use tokio::signal::unix::{SignalKind, signal};

        let mut sigterm = signal(SignalKind::terminate())?;
        let mut sigint = signal(SignalKind::interrupt())?;

        tokio::select! {
            _ = sigterm.recv() => {
                info!("Received SIGTERM");
            }
            _ = sigint.recv() => {
                info!("Received SIGINT");
            }
        }
    }

    #[cfg(not(unix))]
    {
        use tokio::signal;
        signal::ctrl_c().await?;
        info!("Received Ctrl+C");
    }

    Ok(())
}

// ---------------------------------------------------------------------------
// Shutdown guard
// ---------------------------------------------------------------------------

/// Shutdown guard for automatic cleanup
///
/// Triggers shutdown when dropped (useful for panic recovery)
pub struct ShutdownGuard {
    coordinator: ShutdownCoordinator,
    disarmed: Arc<AtomicBool>,
}

impl ShutdownGuard {
    /// Create a new shutdown guard
    pub fn new(coordinator: ShutdownCoordinator) -> Self {
        Self {
            coordinator,
            disarmed: Arc::new(AtomicBool::new(false)),
        }
    }

    /// Disarm the guard (won't trigger shutdown on drop)
    pub fn disarm(&self) {
        self.disarmed.store(true, Ordering::SeqCst);
    }
}

impl Drop for ShutdownGuard {
    fn drop(&mut self) {
        if !self.disarmed.load(Ordering::SeqCst) {
            warn!("ShutdownGuard dropped without disarming - triggering shutdown");
            self.coordinator.shutdown();
        }
    }
}

// ---------------------------------------------------------------------------
// Request guard (RAII active-request tracking)
// ---------------------------------------------------------------------------

/// RAII guard that tracks an active request.
///
/// Calls `request_start()` on creation and `request_end()` on drop,
/// ensuring the active-request counter stays accurate even if the
/// request handler panics.
pub struct RequestGuard {
    coordinator: ShutdownCoordinator,
}

impl RequestGuard {
    /// Create a new request guard, incrementing the active request count
    pub fn new(coordinator: ShutdownCoordinator) -> Self {
        coordinator.request_start();
        Self { coordinator }
    }
}

impl Drop for RequestGuard {
    fn drop(&mut self) {
        self.coordinator.request_end();
    }
}

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

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::AtomicBool as StdAtomicBool;
    use std::time::Duration;
    use tokio::time::timeout;

    /// Helper: wait for a coordinator to reach Terminated phase (with timeout)
    async fn wait_terminated(coordinator: &ShutdownCoordinator, dur: Duration) {
        let mut watcher = coordinator.phase_watch();
        let _ = timeout(dur, async {
            loop {
                if *watcher.borrow() == ShutdownPhase::Terminated {
                    return;
                }
                if watcher.changed().await.is_err() {
                    return;
                }
            }
        })
        .await;
    }

    #[tokio::test]
    async fn test_shutdown_coordinator() {
        let coordinator = ShutdownCoordinator::new();
        let mut receiver = coordinator.subscribe();

        assert!(!coordinator.is_shutting_down());
        assert_eq!(coordinator.current_phase(), ShutdownPhase::Running);

        coordinator.shutdown();

        assert!(coordinator.is_shutting_down());

        // Should receive shutdown signal
        let result = timeout(Duration::from_millis(100), receiver.recv()).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_multiple_subscribers() {
        let coordinator = ShutdownCoordinator::new();
        let mut rx1 = coordinator.subscribe();
        let mut rx2 = coordinator.subscribe();
        let mut rx3 = coordinator.subscribe();

        coordinator.shutdown();

        assert!(
            timeout(Duration::from_millis(100), rx1.recv())
                .await
                .is_ok()
        );
        assert!(
            timeout(Duration::from_millis(100), rx2.recv())
                .await
                .is_ok()
        );
        assert!(
            timeout(Duration::from_millis(100), rx3.recv())
                .await
                .is_ok()
        );
    }

    #[tokio::test]
    async fn test_shutdown_idempotent() {
        let coordinator = ShutdownCoordinator::new();

        coordinator.shutdown();
        coordinator.shutdown(); // Second call should be a no-op

        assert!(coordinator.is_shutting_down());

        // Let the phase driver complete
        wait_terminated(&coordinator, Duration::from_secs(2)).await;
        assert_eq!(coordinator.current_phase(), ShutdownPhase::Terminated);
    }

    #[test]
    fn test_shutdown_guard_disarm() {
        let coordinator = ShutdownCoordinator::new();
        let guard = ShutdownGuard::new(coordinator.clone());

        guard.disarm();
        drop(guard);

        assert!(!coordinator.is_shutting_down());
    }

    #[tokio::test]
    async fn test_shutdown_guard_trigger() {
        let coordinator = ShutdownCoordinator::new();
        let guard = ShutdownGuard::new(coordinator.clone());

        drop(guard);

        assert!(coordinator.is_shutting_down());

        // Let the spawned phase-driver complete
        wait_terminated(&coordinator, Duration::from_secs(2)).await;
    }

    // -- Phase transition tests ---------------------------------------------

    #[tokio::test]
    async fn test_phase_transitions() {
        let config = DrainConfig {
            drain_timeout: Duration::from_millis(200),
            check_interval: Duration::from_millis(50),
            flush_timeout: Duration::from_millis(200),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        assert_eq!(coordinator.current_phase(), ShutdownPhase::Running);

        coordinator.shutdown();

        wait_terminated(&coordinator, Duration::from_secs(2)).await;
        assert_eq!(coordinator.current_phase(), ShutdownPhase::Terminated);
    }

    #[tokio::test]
    async fn test_drain_waits_for_in_flight_requests() {
        let config = DrainConfig {
            drain_timeout: Duration::from_secs(2),
            check_interval: Duration::from_millis(50),
            flush_timeout: Duration::from_millis(200),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        // Simulate 3 in-flight requests
        coordinator.request_start();
        coordinator.request_start();
        coordinator.request_start();
        assert_eq!(coordinator.active_request_count(), 3);

        coordinator.shutdown();

        // Give the drainer a moment to start
        tokio::time::sleep(Duration::from_millis(80)).await;
        assert_eq!(coordinator.current_phase(), ShutdownPhase::Draining);

        // Complete requests one by one
        coordinator.request_end();
        tokio::time::sleep(Duration::from_millis(60)).await;
        coordinator.request_end();
        tokio::time::sleep(Duration::from_millis(60)).await;
        coordinator.request_end();

        wait_terminated(&coordinator, Duration::from_secs(2)).await;
        assert_eq!(coordinator.current_phase(), ShutdownPhase::Terminated);
    }

    #[tokio::test]
    async fn test_drain_timeout_forces_termination() {
        let config = DrainConfig {
            drain_timeout: Duration::from_millis(150),
            check_interval: Duration::from_millis(30),
            flush_timeout: Duration::from_millis(100),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        // Simulate a request that never finishes
        coordinator.request_start();

        coordinator.shutdown();

        wait_terminated(&coordinator, Duration::from_secs(2)).await;
        assert_eq!(coordinator.current_phase(), ShutdownPhase::Terminated);
        // The stuck request is still counted
        assert_eq!(coordinator.active_request_count(), 1);
    }

    #[tokio::test]
    async fn test_shutdown_hooks_execute_in_order() {
        let config = DrainConfig {
            drain_timeout: Duration::from_millis(100),
            check_interval: Duration::from_millis(20),
            flush_timeout: Duration::from_secs(1),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        let order = Arc::new(Mutex::new(Vec::<String>::new()));

        struct OrderHook {
            hook_name: String,
            order: Arc<Mutex<Vec<String>>>,
        }

        #[async_trait::async_trait]
        impl ShutdownHook for OrderHook {
            fn name(&self) -> &str {
                &self.hook_name
            }
            async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                let mut guard = self.order.lock().await;
                guard.push(self.hook_name.clone());
                Ok(())
            }
        }

        coordinator
            .register_shutdown_hook(Box::new(OrderHook {
                hook_name: "first".to_string(),
                order: order.clone(),
            }))
            .await;
        coordinator
            .register_shutdown_hook(Box::new(OrderHook {
                hook_name: "second".to_string(),
                order: order.clone(),
            }))
            .await;
        coordinator
            .register_shutdown_hook(Box::new(OrderHook {
                hook_name: "third".to_string(),
                order: order.clone(),
            }))
            .await;

        coordinator.shutdown();
        wait_terminated(&coordinator, Duration::from_secs(2)).await;

        let executed = order.lock().await;
        assert_eq!(*executed, vec!["first", "second", "third"]);
    }

    #[tokio::test]
    async fn test_hook_failure_does_not_block_others() {
        let config = DrainConfig {
            drain_timeout: Duration::from_millis(50),
            check_interval: Duration::from_millis(10),
            flush_timeout: Duration::from_secs(1),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        let completed = Arc::new(StdAtomicBool::new(false));

        struct FailingHook;

        #[async_trait::async_trait]
        impl ShutdownHook for FailingHook {
            fn name(&self) -> &str {
                "failing"
            }
            async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                Err("intentional failure".into())
            }
        }

        struct SuccessHook {
            completed: Arc<StdAtomicBool>,
        }

        #[async_trait::async_trait]
        impl ShutdownHook for SuccessHook {
            fn name(&self) -> &str {
                "success_after_failure"
            }
            async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                self.completed.store(true, Ordering::SeqCst);
                Ok(())
            }
        }

        coordinator
            .register_shutdown_hook(Box::new(FailingHook))
            .await;
        coordinator
            .register_shutdown_hook(Box::new(SuccessHook {
                completed: completed.clone(),
            }))
            .await;

        coordinator.shutdown();
        wait_terminated(&coordinator, Duration::from_secs(2)).await;

        assert!(
            completed.load(Ordering::SeqCst),
            "Hook after failing hook should still run"
        );
        assert_eq!(coordinator.inner.hooks_completed.load(Ordering::SeqCst), 2);
    }

    #[tokio::test]
    async fn test_status_reporting() {
        let config = DrainConfig {
            drain_timeout: Duration::from_secs(1),
            check_interval: Duration::from_millis(50),
            flush_timeout: Duration::from_millis(200),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        // Before shutdown
        let st = coordinator.status();
        assert_eq!(st.phase, ShutdownPhase::Running);
        assert_eq!(st.active_requests, 0);
        assert_eq!(st.hooks_completed, 0);
        assert_eq!(st.elapsed_ms, 0);

        coordinator.request_start();
        coordinator.request_start();

        let st = coordinator.status();
        assert_eq!(st.active_requests, 2);

        coordinator.request_end();
        coordinator.request_end();

        coordinator.shutdown();

        // Give it a moment so elapsed_ms is measurably > 0
        tokio::time::sleep(Duration::from_millis(20)).await;

        // Check while still running or after completion
        let st = coordinator.status();
        assert!(st.elapsed_ms > 0, "elapsed_ms should be > 0 after shutdown");

        // Wait for full completion
        wait_terminated(&coordinator, Duration::from_secs(2)).await;

        let st = coordinator.status();
        assert_eq!(st.phase, ShutdownPhase::Terminated);
    }

    #[tokio::test]
    async fn test_zero_active_requests_fast_shutdown() {
        let config = DrainConfig {
            drain_timeout: Duration::from_secs(30),
            check_interval: Duration::from_millis(50),
            flush_timeout: Duration::from_millis(100),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        let start = Instant::now();
        coordinator.shutdown();

        wait_terminated(&coordinator, Duration::from_secs(1)).await;

        assert_eq!(coordinator.current_phase(), ShutdownPhase::Terminated);
        // With zero requests the drain phase should be nearly instant
        let elapsed = start.elapsed();
        assert!(
            elapsed < Duration::from_secs(1),
            "Fast shutdown should complete quickly, took {:?}",
            elapsed
        );
    }

    #[tokio::test]
    async fn test_health_status_label() {
        let coordinator = ShutdownCoordinator::new();
        assert_eq!(coordinator.health_status_label(), "ok");

        coordinator.shutdown();
        tokio::time::sleep(Duration::from_millis(50)).await;

        // Once shutdown begins, label changes
        assert_eq!(coordinator.health_status_label(), "shutting_down");
    }

    #[tokio::test]
    async fn test_request_guard_raii() {
        let coordinator = ShutdownCoordinator::new();
        assert_eq!(coordinator.active_request_count(), 0);

        {
            let _g1 = RequestGuard::new(coordinator.clone());
            assert_eq!(coordinator.active_request_count(), 1);
            {
                let _g2 = RequestGuard::new(coordinator.clone());
                assert_eq!(coordinator.active_request_count(), 2);
            }
            // g2 dropped
            assert_eq!(coordinator.active_request_count(), 1);
        }
        // g1 dropped
        assert_eq!(coordinator.active_request_count(), 0);
    }

    #[tokio::test]
    async fn test_is_accepting() {
        let coordinator = ShutdownCoordinator::new();
        assert!(coordinator.is_accepting());

        coordinator.shutdown();
        tokio::time::sleep(Duration::from_millis(50)).await;

        assert!(!coordinator.is_accepting());
    }

    #[tokio::test]
    async fn test_built_in_hooks() {
        let config = DrainConfig {
            drain_timeout: Duration::from_millis(50),
            check_interval: Duration::from_millis(10),
            flush_timeout: Duration::from_secs(5),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        coordinator
            .register_shutdown_hook(Box::new(WalFlushHook::default()))
            .await;
        coordinator
            .register_shutdown_hook(Box::new(MemtableFlushHook::default()))
            .await;
        coordinator
            .register_shutdown_hook(Box::new(MetricsSnapshotHook::default()))
            .await;

        let st = coordinator.status();
        assert_eq!(st.hooks_total, 3);

        coordinator.shutdown();
        wait_terminated(&coordinator, Duration::from_secs(2)).await;

        assert_eq!(coordinator.inner.hooks_completed.load(Ordering::SeqCst), 3);
    }

    #[tokio::test]
    async fn test_multiple_shutdown_signals_idempotent() {
        let coordinator = ShutdownCoordinator::new();
        let mut rx = coordinator.subscribe();

        // First call should succeed
        coordinator.shutdown();
        let recv_result = timeout(Duration::from_millis(100), rx.recv()).await;
        assert!(recv_result.is_ok());

        // Subsequent calls are no-ops (no additional broadcast)
        coordinator.shutdown();
        coordinator.shutdown();
        coordinator.shutdown();

        assert!(coordinator.is_shutting_down());

        wait_terminated(&coordinator, Duration::from_secs(2)).await;
        assert_eq!(coordinator.current_phase(), ShutdownPhase::Terminated);
    }

    #[tokio::test]
    async fn test_drain_config_default() {
        let cfg = DrainConfig::default();
        assert_eq!(cfg.drain_timeout, Duration::from_secs(30));
        assert_eq!(cfg.check_interval, Duration::from_secs(1));
        assert_eq!(cfg.flush_timeout, Duration::from_secs(30));
    }

    #[tokio::test]
    async fn test_phase_display() {
        assert_eq!(format!("{}", ShutdownPhase::Running), "Running");
        assert_eq!(format!("{}", ShutdownPhase::Draining), "Draining");
        assert_eq!(format!("{}", ShutdownPhase::FlushingState), "FlushingState");
        assert_eq!(format!("{}", ShutdownPhase::Terminated), "Terminated");
    }

    // -- Storage integration hook tests -------------------------------------

    /// Mock WalWriter for testing
    struct MockWalWriter {
        sync_called: Arc<StdAtomicBool>,
        size: u64,
        should_fail: bool,
    }

    impl WalWriter for MockWalWriter {
        fn sync(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
            self.sync_called.store(true, Ordering::SeqCst);
            if self.should_fail {
                return Err("WAL sync failed".into());
            }
            Ok(())
        }

        fn current_size(&self) -> u64 {
            self.size
        }
    }

    /// Mock MemtableFlusher for testing
    struct MockMemtableFlusher {
        flush_called: Arc<StdAtomicBool>,
        entries: usize,
        should_fail: bool,
    }

    impl MemtableFlusher for MockMemtableFlusher {
        fn flush_to_sstable(&self) -> Result<usize, Box<dyn std::error::Error + Send + Sync>> {
            self.flush_called.store(true, Ordering::SeqCst);
            if self.should_fail {
                return Err("memtable flush failed".into());
            }
            Ok(self.entries)
        }
    }

    #[tokio::test]
    async fn test_wal_flush_hook_calls_sync() {
        let sync_called = Arc::new(StdAtomicBool::new(false));
        let writer = Arc::new(MockWalWriter {
            sync_called: sync_called.clone(),
            size: 4096,
            should_fail: false,
        });

        let hook = WalFlushHook::with_writer(writer, Duration::from_secs(5));
        let result = hook.on_shutdown().await;

        assert!(result.is_ok());
        assert!(
            sync_called.load(Ordering::SeqCst),
            "sync() should have been called"
        );
    }

    #[tokio::test]
    async fn test_wal_flush_hook_no_writer() {
        let hook = WalFlushHook::default();
        let result = hook.on_shutdown().await;
        assert!(result.is_ok(), "no-writer hook should succeed");
    }

    #[tokio::test]
    async fn test_wal_flush_hook_error() {
        let sync_called = Arc::new(StdAtomicBool::new(false));
        let writer = Arc::new(MockWalWriter {
            sync_called: sync_called.clone(),
            size: 1024,
            should_fail: true,
        });

        let hook = WalFlushHook::with_writer(writer, Duration::from_secs(5));
        let result = hook.on_shutdown().await;

        assert!(result.is_err());
        assert!(
            sync_called.load(Ordering::SeqCst),
            "sync() should have been called even on failure"
        );
        let err_msg = result.expect_err("should be error").to_string();
        assert!(
            err_msg.contains("WAL sync failed"),
            "error message should propagate"
        );
    }

    #[tokio::test]
    async fn test_memtable_flush_hook_calls_flush() {
        let flush_called = Arc::new(StdAtomicBool::new(false));
        let flusher = Arc::new(MockMemtableFlusher {
            flush_called: flush_called.clone(),
            entries: 42,
            should_fail: false,
        });

        let hook = MemtableFlushHook::with_flusher(flusher, Duration::from_secs(5));
        let result = hook.on_shutdown().await;

        assert!(result.is_ok());
        assert!(
            flush_called.load(Ordering::SeqCst),
            "flush_to_sstable() should have been called"
        );
    }

    #[tokio::test]
    async fn test_memtable_flush_hook_no_flusher() {
        let hook = MemtableFlushHook::default();
        let result = hook.on_shutdown().await;
        assert!(result.is_ok(), "no-flusher hook should succeed");
    }

    #[tokio::test]
    async fn test_connection_drain_immediate() {
        let conns = Arc::new(AtomicUsize::new(0));
        let hook = ConnectionDrainHook::new(conns, Duration::from_secs(5));

        let start = Instant::now();
        let result = hook.on_shutdown().await;
        let elapsed = start.elapsed();

        assert!(result.is_ok());
        assert!(
            elapsed < Duration::from_millis(50),
            "should return immediately with 0 connections, took {:?}",
            elapsed
        );
    }

    #[tokio::test]
    async fn test_connection_drain_waits_for_zero() {
        let conns = Arc::new(AtomicUsize::new(5));
        let hook = ConnectionDrainHook::new(conns.clone(), Duration::from_secs(5))
            .with_poll_interval(Duration::from_millis(50));

        // Spawn a task that decrements connections over time
        let conns_clone = conns.clone();
        tokio::spawn(async move {
            for _ in 0..5 {
                tokio::time::sleep(Duration::from_millis(30)).await;
                conns_clone.fetch_sub(1, Ordering::SeqCst);
            }
        });

        let result = hook.on_shutdown().await;
        assert!(result.is_ok());
        assert_eq!(conns.load(Ordering::SeqCst), 0);
    }

    #[tokio::test]
    async fn test_connection_drain_timeout() {
        let conns = Arc::new(AtomicUsize::new(10));
        let hook = ConnectionDrainHook::new(conns.clone(), Duration::from_millis(200))
            .with_poll_interval(Duration::from_millis(50));

        let start = Instant::now();
        let result = hook.on_shutdown().await;
        let elapsed = start.elapsed();

        assert!(result.is_err(), "should error on timeout");
        let err_msg = result.expect_err("should be error").to_string();
        assert!(
            err_msg.contains("timed out"),
            "error should mention timeout"
        );
        assert!(
            elapsed >= Duration::from_millis(200),
            "should have waited at least the timeout duration, elapsed {:?}",
            elapsed
        );
    }

    #[tokio::test]
    async fn test_hook_execution_result_captured() {
        let config = DrainConfig {
            drain_timeout: Duration::from_millis(50),
            check_interval: Duration::from_millis(10),
            flush_timeout: Duration::from_secs(1),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        struct NamedHook {
            hook_name: String,
        }

        #[async_trait::async_trait]
        impl ShutdownHook for NamedHook {
            fn name(&self) -> &str {
                &self.hook_name
            }
            async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                Ok(())
            }
        }

        coordinator
            .register_shutdown_hook(Box::new(NamedHook {
                hook_name: "test_hook".to_string(),
            }))
            .await;

        coordinator.shutdown();
        wait_terminated(&coordinator, Duration::from_secs(2)).await;

        let results = coordinator.hook_results().await;
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].hook_name, "test_hook");
        assert!(results[0].success);
        assert!(results[0].error.is_none());
        assert!(results[0].duration < Duration::from_secs(1));
    }

    #[tokio::test]
    async fn test_hook_error_result() {
        let config = DrainConfig {
            drain_timeout: Duration::from_millis(50),
            check_interval: Duration::from_millis(10),
            flush_timeout: Duration::from_secs(1),
        };
        let coordinator = ShutdownCoordinator::with_config(config);

        struct FailHook;

        #[async_trait::async_trait]
        impl ShutdownHook for FailHook {
            fn name(&self) -> &str {
                "fail_hook"
            }
            async fn on_shutdown(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
                Err("catastrophic failure".into())
            }
        }

        coordinator.register_shutdown_hook(Box::new(FailHook)).await;

        coordinator.shutdown();
        wait_terminated(&coordinator, Duration::from_secs(2)).await;

        let results = coordinator.hook_results().await;
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].hook_name, "fail_hook");
        assert!(!results[0].success);
        assert!(results[0].error.is_some());
        let err = results[0].error.as_ref().expect("error should be present");
        assert!(
            err.contains("catastrophic failure"),
            "error should contain the failure message"
        );
    }

    #[tokio::test]
    async fn test_metrics_snapshot_writes_file() {
        let dir = tempfile::tempdir().expect("failed to create temp dir");
        let path = dir.path().join("metrics.bin");

        let expected_data = b"metric1=42\nmetric2=100\n".to_vec();
        let expected_clone = expected_data.clone();
        let provider: Arc<dyn Fn() -> Vec<u8> + Send + Sync> =
            Arc::new(move || expected_clone.clone());

        let hook =
            MetricsSnapshotHook::with_provider(provider, path.clone(), Duration::from_secs(5));
        let result = hook.on_shutdown().await;

        assert!(result.is_ok());
        let written = std::fs::read(&path).expect("should be able to read metrics file");
        assert_eq!(written, expected_data);
    }

    #[tokio::test]
    async fn test_metrics_snapshot_no_provider() {
        let hook = MetricsSnapshotHook::default();
        let result = hook.on_shutdown().await;
        assert!(result.is_ok(), "no-provider hook should succeed");
    }

    #[tokio::test]
    async fn test_connection_drain_poll_interval() {
        // Use a connection count that will require multiple polls
        let conns = Arc::new(AtomicUsize::new(1));
        let poll_interval = Duration::from_millis(80);
        let hook = ConnectionDrainHook::new(conns.clone(), Duration::from_secs(5))
            .with_poll_interval(poll_interval);

        // Spawn task to zero out connections after ~150ms
        let conns_clone = conns.clone();
        tokio::spawn(async move {
            tokio::time::sleep(Duration::from_millis(150)).await;
            conns_clone.store(0, Ordering::SeqCst);
        });

        let start = Instant::now();
        let result = hook.on_shutdown().await;
        let elapsed = start.elapsed();

        assert!(result.is_ok());
        // Should have polled at least once (~80ms) before connections hit 0 at ~150ms
        assert!(
            elapsed >= Duration::from_millis(100),
            "should have polled at least once before completion, elapsed {:?}",
            elapsed
        );
    }
}