nntp-proxy 0.5.1

NNTP proxy server with per-command backend multiplexing, caching, metrics, and TUI dashboard
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
//! Connection pool provider implementation
//!
//! This module contains the `DeadpoolConnectionProvider` which manages a pool of
//! NNTP connections using the deadpool library. It provides:
//! - Connection pooling with configurable size
//! - Automatic connection recycling
//! - Periodic health checks for idle connections
//! - Graceful shutdown with QUIT commands

use super::connection_trait::ConnectionProvider;
use super::deadpool_connection::{Pool, TcpManager, TcpManagerOptions};
use super::health_check::{HealthCheckMetrics, check_date_response};
use crate::pool::PoolStatus;
use crate::tls::TlsConfig;
use anyhow::Result;
use deadpool::managed;
use futures::StreamExt;
use futures::stream::FuturesUnordered;
use std::sync::Arc;
use std::sync::atomic::Ordering;
use tokio::sync::broadcast;
use tracing::{debug, info, warn};

/// Connection provider using deadpool for connection pooling
#[derive(Debug, Clone)]
pub struct DeadpoolConnectionProvider {
    pool: Pool,
    name: Arc<str>,
    /// Shutdown signal sender for background health check task.
    /// Stored to keep the channel alive - when dropped, the background task will terminate.
    /// Used by `shutdown()` method to gracefully stop health checks.
    shutdown_tx: Option<broadcast::Sender<()>>,
    /// Metrics for health check operations (lock-free)
    pub health_check_metrics: Arc<HealthCheckMetrics>,
    /// Original max pool size (before any cooldown reductions)
    original_max_size: usize,
    /// Number of active cooldown timers reducing pool size
    active_cooldowns: Arc<std::sync::atomic::AtomicUsize>,
    /// Connection replacement cooldown duration (None = disabled)
    replacement_cooldown: Option<std::time::Duration>,
    /// Set once process shutdown begins so teardown doesn't look like backend damage.
    is_shutting_down: Arc<std::sync::atomic::AtomicBool>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DeadpoolStatusCounts {
    pub available: usize,
    pub size: usize,
    pub max_size: usize,
    pub waiting: usize,
}

/// Builder for constructing `DeadpoolConnectionProvider` instances
///
/// Provides a fluent API for creating connection providers with optional TLS configuration.
///
/// # Examples
///
/// ```no_run
/// use nntp_proxy::pool::DeadpoolConnectionProvider;
/// use nntp_proxy::tls::TlsConfig;
///
/// // Basic provider without TLS
/// let provider = DeadpoolConnectionProvider::builder("news.example.com", 119)
///     .name("Example Server")
///     .max_connections(10)
///     .build()
///     .unwrap();
///
/// // Provider with TLS and authentication
/// let tls_config = TlsConfig::builder()
///     .enabled(true)
///     .verify_cert(true)
///     .build();
///
/// let provider = DeadpoolConnectionProvider::builder("secure.example.com", 563)
///     .name("Secure Server")
///     .max_connections(20)
///     .username("user")
///     .password("pass")
///     .tls_config(tls_config)
///     .build()
///     .unwrap();
/// ```
pub struct Builder {
    host: String,
    port: u16,
    name: Option<String>,
    max_size: usize,
    username: Option<String>,
    password: Option<String>,
    tls_config: Option<TlsConfig>,
}

impl Builder {
    /// Create a new builder with required connection parameters
    ///
    /// # Arguments
    /// * `host` - Backend server hostname or IP address
    /// * `port` - Backend server port number
    #[must_use]
    pub fn new(host: impl Into<String>, port: u16) -> Self {
        Self {
            host: host.into(),
            port,
            name: None,
            max_size: 10, // Default max connections
            username: None,
            password: None,
            tls_config: None,
        }
    }

    /// Set a friendly name for logging (defaults to "host:port")
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Set the maximum number of concurrent connections in the pool
    #[must_use]
    pub const fn max_connections(mut self, max_size: usize) -> Self {
        self.max_size = max_size;
        self
    }

    /// Set authentication username
    #[must_use]
    pub fn username(mut self, username: impl Into<String>) -> Self {
        self.username = Some(username.into());
        self
    }

    /// Set authentication password
    #[must_use]
    pub fn password(mut self, password: impl Into<String>) -> Self {
        self.password = Some(password.into());
        self
    }

    /// Configure TLS settings for secure connections
    #[must_use]
    pub fn tls_config(mut self, config: TlsConfig) -> Self {
        self.tls_config = Some(config);
        self
    }

    /// Build the connection provider
    ///
    /// # Errors
    ///
    /// Returns an error if TLS initialization fails when TLS is enabled
    pub fn build(self) -> Result<DeadpoolConnectionProvider> {
        let name = self
            .name
            .unwrap_or_else(|| format!("{}:{}", self.host, self.port));

        let manager = TcpManager::new(
            self.host,
            self.port,
            name.clone(),
            TcpManagerOptions {
                username: self.username,
                password: self.password,
                tls_config: self.tls_config,
                ..TcpManagerOptions::default()
            },
        )?;

        Ok(DeadpoolConnectionProvider::from_manager(
            manager,
            name,
            self.max_size,
        ))
    }
}

impl DeadpoolConnectionProvider {
    /// Create a builder for constructing a connection provider
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nntp_proxy::pool::DeadpoolConnectionProvider;
    ///
    /// let provider = DeadpoolConnectionProvider::builder("news.example.com", 119)
    ///     .name("Example")
    ///     .max_connections(15)
    ///     .build()
    ///     .unwrap();
    /// ```
    #[must_use]
    pub fn builder(host: impl Into<String>, port: u16) -> Builder {
        Builder::new(host, port)
    }

    /// Create a simple connection provider with defaults
    ///
    /// Useful for testing and simple use cases. Uses 10 connections, no auth.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nntp_proxy::pool::DeadpoolConnectionProvider;
    ///
    /// let provider = DeadpoolConnectionProvider::simple("news.example.com", 119)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns any validation or pool-construction error from the builder.
    pub fn simple(host: impl Into<String>, port: u16) -> Result<Self> {
        Self::builder(host, port).build()
    }

    /// Create a connection provider with authentication
    ///
    /// Convenience constructor for the common case of username/password auth.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nntp_proxy::pool::DeadpoolConnectionProvider;
    ///
    /// let provider = DeadpoolConnectionProvider::with_auth(
    ///     "news.example.com",
    ///     119,
    ///     "myuser",
    ///     "mypass",
    /// )?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns any validation or pool-construction error from the builder.
    pub fn with_auth(
        host: impl Into<String>,
        port: u16,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Result<Self> {
        Self::builder(host, port)
            .username(username)
            .password(password)
            .build()
    }

    /// Create a TLS-enabled connection provider
    ///
    /// Uses default TLS settings (verify certificates, system CA store).
    /// For NNTPS (port 563) or STARTTLS.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nntp_proxy::pool::DeadpoolConnectionProvider;
    ///
    /// let provider = DeadpoolConnectionProvider::with_tls("news.example.com", 563)?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns any TLS initialization, validation, or pool-construction error.
    pub fn with_tls(host: impl Into<String>, port: u16) -> Result<Self> {
        Self::builder(host, port)
            .tls_config(TlsConfig::default())
            .build()
    }

    /// Create a TLS-enabled connection provider with authentication
    ///
    /// Combines TLS with username/password auth - the most common setup
    /// for commercial Usenet providers.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// use nntp_proxy::pool::DeadpoolConnectionProvider;
    ///
    /// let provider = DeadpoolConnectionProvider::with_tls_auth(
    ///     "news.example.com",
    ///     563,
    ///     "myuser",
    ///     "mypass",
    /// )?;
    /// # Ok::<(), anyhow::Error>(())
    /// ```
    ///
    /// # Errors
    /// Returns any TLS initialization, validation, or pool-construction error.
    pub fn with_tls_auth(
        host: impl Into<String>,
        port: u16,
        username: impl Into<String>,
        password: impl Into<String>,
    ) -> Result<Self> {
        Self::builder(host, port)
            .username(username)
            .password(password)
            .tls_config(TlsConfig::default())
            .build()
    }

    /// Create a new connection provider (plain TCP, no TLS)
    ///
    /// For TLS support, use `new_with_tls()` or the builder API.
    #[must_use]
    ///
    /// # Panics
    /// Panics only if plain `TcpManager` construction unexpectedly becomes
    /// fallible or deadpool rejects the requested pool size.
    pub fn new(
        host: String,
        port: u16,
        name: String,
        max_size: usize,
        username: Option<String>,
        password: Option<String>,
    ) -> Self {
        // Plain TCP (no TLS) cannot fail during TcpManager construction
        Self::from_manager(
            TcpManager::new(
                host,
                port,
                name.clone(),
                TcpManagerOptions {
                    username,
                    password,
                    ..TcpManagerOptions::default()
                },
            )
            .expect("Plain TCP TcpManager creation cannot fail"),
            name,
            max_size,
        )
    }

    /// Create a new connection provider with TLS support
    ///
    /// # Errors
    /// Returns any TLS initialization or provider-construction error.
    pub fn new_with_tls(
        host: String,
        port: u16,
        name: String,
        max_size: usize,
        username: Option<String>,
        password: Option<String>,
        tls_config: TlsConfig,
    ) -> Result<Self> {
        let manager = TcpManager::new(
            host,
            port,
            name.clone(),
            TcpManagerOptions {
                username,
                password,
                tls_config: Some(tls_config),
                ..TcpManagerOptions::default()
            },
        )?;
        Ok(Self::from_manager(manager, name, max_size))
    }

    /// Construct a provider from a pre-built `TcpManager`
    fn from_manager(manager: TcpManager, name: String, max_size: usize) -> Self {
        let pool = Pool::builder(manager)
            .max_size(max_size)
            .build()
            .expect("Failed to create connection pool");

        Self {
            pool,
            name: Arc::from(name),
            shutdown_tx: None,
            health_check_metrics: Arc::new(HealthCheckMetrics::new()),
            original_max_size: max_size,
            active_cooldowns: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            replacement_cooldown: None, // Default: no cooldown
            is_shutting_down: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        }
    }

    /// Create a connection provider from a server configuration
    ///
    /// This avoids unnecessary cloning of individual fields.
    ///
    /// # Errors
    /// Returns any TLS initialization or manager-construction error implied by
    /// the server configuration.
    ///
    /// # Panics
    /// Panics only if deadpool rejects the validated pool size.
    pub fn from_server_config(
        server: &crate::config::Server,
        recv_buffer_size: usize,
        send_buffer_size: usize,
    ) -> Result<Self> {
        let tls_builder = TlsConfig::builder()
            .enabled(server.use_tls)
            .verify_cert(server.tls_verify_cert);

        // Use functional approach to conditionally add cert_path
        let tls_builder = server
            .tls_cert_path
            .as_ref()
            .map(|cert_path| tls_builder.clone().cert_path(cert_path.as_str()))
            .unwrap_or(tls_builder);

        let tls_config = tls_builder.build();

        let manager = TcpManager::new(
            server.host.to_string(),
            server.port.get(),
            server.name.to_string(),
            TcpManagerOptions {
                username: server.username.clone(),
                password: server.password.clone(),
                tls_config: Some(tls_config),
                recv_buffer_size,
                send_buffer_size,
                compress: server.compress,
                compress_level: server.compress_level,
                ..TcpManagerOptions::default()
            },
        )?;
        let max_size = server.max_connections.get();
        let pool = Pool::builder(manager)
            .max_size(max_size)
            .build()
            .expect("Failed to create connection pool");

        let keepalive_interval = server.connection_keepalive;

        // Create metrics and shutdown channel if keepalive is enabled
        let metrics = Arc::new(HealthCheckMetrics::new());
        let shutdown_tx = keepalive_interval.map_or_else(
            || None,
            |interval| {
                let (tx, rx) = broadcast::channel(1);

                // Spawn background health check task
                let pool_clone = pool.clone();
                let name_clone = server.name.to_string();
                let metrics_clone = metrics.clone();
                tokio::spawn(async move {
                    Self::run_periodic_health_checks(
                        pool_clone,
                        name_clone,
                        interval,
                        rx,
                        metrics_clone,
                    )
                    .await;
                });

                Some(tx)
            },
        );

        Ok(Self {
            pool,
            name: Arc::from(server.name.to_string()),
            shutdown_tx,
            health_check_metrics: metrics,
            original_max_size: max_size,
            active_cooldowns: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            replacement_cooldown: server.replacement_cooldown,
            is_shutting_down: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        })
    }

    /// Get a connection from the pool (automatically returned when dropped)
    ///
    /// # Errors
    /// Returns [`crate::connection_error::ConnectionError`] if deadpool cannot
    /// provide a healthy backend connection.
    pub async fn get_pooled_connection(
        &self,
    ) -> Result<managed::Object<TcpManager>, crate::connection_error::ConnectionError> {
        use crate::connection_error::ConnectionError;
        self.pool.get().await.map_err(|e| {
            let status = self.pool.status();
            let err = match e {
                deadpool::managed::PoolError::Backend(conn_err) => conn_err,
                _other => ConnectionError::PoolExhausted {
                    backend: self.name.to_string(),
                    max_size: status.max_size,
                },
            };
            warn!(
                pool = %self.name,
                max_size = status.max_size,
                available = status.available,
                current_size = status.size,
                waiting = status.waiting,
                error = %err,
                "Connection acquisition failed"
            );
            err
        })
    }

    /// Clear all idle connections from the pool
    ///
    /// This drops all idle connections by resizing the pool to 0 and back.
    /// Active (checked-out) connections are not affected - they will be discarded
    /// when returned instead of being recycled.
    ///
    /// Use this to clear potentially stale connections after an idle period.
    pub fn clear_idle_connections(&self) {
        let available = self.pool.status().available;

        if available > 0 {
            debug!(
                pool = %self.name,
                available = available,
                "Clearing idle connections from pool"
            );

            // Calculate target max based on original size minus active cooldowns
            let cooldowns = self.active_cooldowns.load(Ordering::Acquire);
            let target_max = self.original_max_size.saturating_sub(cooldowns).max(1);

            // Resize to 0 drops all idle connections
            self.pool.resize(0);
            // Resize back to target allows new connections
            self.pool.resize(target_max);
        }
    }

    /// Remove a connection without temporarily reducing pool size.
    ///
    /// Use this when the connection cannot be safely returned to the pool, but
    /// the backend did not fail. For example, a client disconnect can leave
    /// unread backend response bytes in flight, making the socket dirty without
    /// implying that replacement connections should be throttled.
    pub fn remove_without_cooldown(&self, conn: managed::Object<TcpManager>) {
        shutdown_and_drop(conn);
    }

    /// Remove a broken connection and temporarily reduce pool size.
    ///
    /// Gives the backend time to release the old connection's slot before
    /// deadpool creates a replacement. Prevents connection count from
    /// exceeding the backend's limit during high churn.
    ///
    /// If `replacement_cooldown` is None or `Duration::ZERO` (disabled), immediately drops
    /// the connection without cooldown (behaves like normal pool removal).
    ///
    /// CRITICAL: When cooldown is active, we resize the pool BEFORE dropping the
    /// connection. Otherwise, between `drop(conn)` and `pool.resize()`, any waiter
    /// calling `pool.get()` sees `size < max_size` and immediately creates a
    /// replacement — defeating the cooldown entirely.
    ///
    /// The ordering invariant is enforced at compile time: `conn` is moved into
    /// either [`shutdown_and_drop`] or [`resize_then_drop`], so the caller cannot
    /// accidentally `drop(conn)` before `pool.resize()`. Any attempt to reorder
    /// would be a use-after-move error.
    pub fn remove_with_cooldown(&self, conn: managed::Object<TcpManager>) {
        if self.is_shutting_down.load(Ordering::Acquire) {
            shutdown_and_drop(conn);
            return;
        }

        // If cooldown is disabled (None or zero duration), just shut down and drop
        let Some(cooldown) = self.replacement_cooldown.filter(|d| !d.is_zero()) else {
            shutdown_and_drop(conn);
            return;
        };

        // Cap cooldowns to prevent pool collapse: never reduce below half original size.
        // If >50% of connections fail simultaneously, it's a systemic backend issue
        // (restart, network partition). Continuing to reduce would starve all clients.
        // Better to keep half the pool and let failed connections return errors.
        let max_reduction = self.original_max_size / 2;
        let current = self.active_cooldowns.load(Ordering::Acquire);
        if current >= max_reduction {
            // Already at max reduction — just shut down and drop without further cooldown
            shutdown_and_drop(conn);
            return;
        }

        // Reduce pool max, THEN drop. `conn` is moved into `resize_then_drop`,
        // making it a compile error to drop conn before resize.
        let cooldowns = self.active_cooldowns.fetch_add(1, Ordering::AcqRel) + 1;
        let new_max = self.original_max_size.saturating_sub(cooldowns).max(1);
        resize_then_drop(&self.pool, conn, new_max);

        warn!(
            pool = %self.name,
            new_max_size = new_max,
            original_max_size = self.original_max_size,
            active_cooldowns = cooldowns,
            cooldown_secs = cooldown.as_secs(),
            "Connection removed, pool size temporarily reduced"
        );

        // Schedule restoration with Drop guard to ensure fetch_sub runs
        let active_cooldowns = self.active_cooldowns.clone();
        let pool = self.pool.clone();
        let original_max = self.original_max_size;
        let name = self.name.clone();
        tokio::spawn(async move {
            // Drop guard ensures fetch_sub runs even if task is cancelled
            struct CooldownGuard {
                active_cooldowns: Arc<std::sync::atomic::AtomicUsize>,
                pool: Pool,
                original_max: usize,
                name: Arc<str>,
            }
            impl Drop for CooldownGuard {
                fn drop(&mut self) {
                    let remaining = self.active_cooldowns.fetch_sub(1, Ordering::AcqRel) - 1;
                    let restored_max = self.original_max.saturating_sub(remaining);
                    self.pool.resize(restored_max);
                    debug!(
                        pool = %self.name,
                        restored_max_size = restored_max,
                        remaining_cooldowns = remaining,
                        "Connection cooldown expired, pool size restored"
                    );
                }
            }
            let _guard = CooldownGuard {
                active_cooldowns,
                pool,
                original_max,
                name,
            };
            tokio::time::sleep(cooldown).await;
            // _guard drops here, running fetch_sub + resize
        });
    }

    /// Get the maximum pool size
    #[must_use]
    #[inline]
    pub fn max_size(&self) -> usize {
        self.pool.status().max_size
    }

    /// Get the name/identifier of this connection pool
    #[must_use]
    #[inline]
    pub fn name(&self) -> &str {
        self.name.as_ref()
    }

    #[must_use]
    pub fn status_counts(&self) -> DeadpoolStatusCounts {
        let status = self.pool.status();
        DeadpoolStatusCounts {
            available: status.available,
            size: status.size,
            max_size: status.max_size,
            waiting: status.waiting,
        }
    }

    /// Get the backend host this pool connects to
    #[must_use]
    #[inline]
    pub fn host(&self) -> &str {
        &self.pool.manager().host
    }

    /// Get the backend port this pool connects to
    #[must_use]
    #[inline]
    pub fn port(&self) -> u16 {
        self.pool.manager().port
    }

    /// Get a reference to the health check metrics
    #[must_use]
    pub fn health_check_metrics(&self) -> &HealthCheckMetrics {
        &self.health_check_metrics
    }

    /// Gracefully shutdown the periodic health check task
    ///
    /// This sends a shutdown signal to the background health check task.
    /// The task will complete its current cycle and then terminate.
    pub fn shutdown(&self) {
        self.is_shutting_down.store(true, Ordering::Release);
        if let Some(tx) = &self.shutdown_tx {
            let _ = tx.send(());
        }
    }

    /// Run periodic health checks on idle connections
    ///
    /// This task runs in the background checking a limited number of idle connections
    /// each cycle. It can be gracefully shut down via the `shutdown_rx` channel.
    /// Health check metrics are recorded in the provided metrics object.
    async fn run_periodic_health_checks(
        pool: Pool,
        name: String,
        interval: std::time::Duration,
        mut shutdown_rx: broadcast::Receiver<()>,
        metrics: Arc<HealthCheckMetrics>,
    ) {
        use crate::constants::pool::{
            HEALTH_CHECK_POOL_TIMEOUT_MS, MAX_CONNECTIONS_PER_HEALTH_CHECK_CYCLE,
        };
        use tokio::time::{Duration, sleep};

        info!(
            pool = %name,
            interval_secs = interval.as_secs(),
            "Starting periodic health checks"
        );

        loop {
            tokio::select! {
                () = sleep(interval) => {
                    // Time to run health check
                }
                _ = shutdown_rx.recv() => {
                    info!(pool = %name, "Shutting down periodic health check task");
                    break;
                }
            }

            let status = pool.status();
            if status.available == 0 {
                continue;
            }

            debug!(
                pool = %name,
                available = status.available,
                max_check = MAX_CONNECTIONS_PER_HEALTH_CHECK_CYCLE,
                "Running health check cycle"
            );

            // Check up to MAX_CONNECTIONS_PER_HEALTH_CHECK_CYCLE idle connections per cycle
            let check_count =
                std::cmp::min(status.available, MAX_CONNECTIONS_PER_HEALTH_CHECK_CYCLE);
            let mut checked = 0;
            let mut failed = 0;

            let mut timeouts = managed::Timeouts::new();
            timeouts.wait = Some(Duration::from_millis(HEALTH_CHECK_POOL_TIMEOUT_MS));

            for _ in 0..check_count {
                if let Ok(mut conn_obj) = pool.timeout_get(&timeouts).await {
                    checked += 1;

                    // Perform DATE health check
                    if let Err(e) = check_date_response(&mut *conn_obj).await {
                        failed += 1;
                        warn!(
                            pool = %name,
                            error = %e,
                            "Health check failed, discarding connection"
                        );
                        // Shut down the raw TCP socket so recycle reliably detects it as dead
                        let _ = socket2::SockRef::from(conn_obj.underlying_tcp_stream())
                            .shutdown(std::net::Shutdown::Both);
                    }
                    // Return to pool normally — deadpool drops it before creating a replacement
                    drop(conn_obj);
                } else {
                    break;
                }
            }

            if checked > 0 {
                // Record metrics (lock-free)
                metrics.record_cycle(checked, failed);

                debug!(
                    pool = %name,
                    checked = checked,
                    failed = failed,
                    "Health check cycle complete"
                );
            }
        }

        info!(pool = %name, "Periodic health check task terminated");
    }

    /// Gracefully shutdown the pool
    pub async fn graceful_shutdown(&self) {
        use deadpool::managed::Object;
        use tokio::io::AsyncWriteExt;

        self.shutdown();

        let status = self.pool.status();
        info!(
            "Shutting down pool '{}' ({} idle connections)",
            self.name, status.available
        );

        // Send QUIT to idle connections with minimal timeout
        let mut timeouts = managed::Timeouts::new();
        timeouts.wait = Some(crate::constants::timeout::SHUTDOWN_POOL_GET);

        let mut idle_connections = Vec::with_capacity(status.available);
        for _ in 0..status.available {
            if let Ok(conn_obj) = self.pool.timeout_get(&timeouts).await {
                idle_connections.push(Object::take(conn_obj));
            } else {
                break;
            }
        }

        shutdown_connections_concurrently(idle_connections, |mut conn| async move {
            // Timeout the write: a half-closed backend connection can block indefinitely
            let _ = tokio::time::timeout(
                crate::constants::timeout::SHUTDOWN_QUIT_WRITE,
                conn.write_all(b"QUIT\r\n"),
            )
            .await;
        })
        .await;

        self.pool.close();
    }
}

async fn shutdown_connections_concurrently<T, F, Fut>(connections: Vec<T>, shutdown_one: F)
where
    F: FnMut(T) -> Fut,
    Fut: std::future::Future<Output = ()>,
{
    let mut pending = connections
        .into_iter()
        .map(shutdown_one)
        .collect::<FuturesUnordered<_>>();

    while pending.next().await.is_some() {}
}

/// Resize pool max THEN shut down and drop the connection.
///
/// **This function exists to make the wrong ordering a compile error.**
/// Because `conn` is moved in, the caller cannot `drop(conn)` before `pool.resize()`.
/// Any attempt to reorder operations would produce a use-after-move error.
///
/// The ordering matters: if we dropped first, waiters would see
/// `pool.size < pool.max_size` and immediately create a replacement,
/// defeating the cooldown.
fn resize_then_drop(pool: &Pool, conn: managed::Object<TcpManager>, new_max: usize) {
    pool.resize(new_max);
    shutdown_and_drop(conn);
}

fn shutdown_and_drop(conn: managed::Object<TcpManager>) {
    let _ = socket2::SockRef::from(conn.underlying_tcp_stream()).shutdown(std::net::Shutdown::Both);
    drop(conn);
}

impl ConnectionProvider for DeadpoolConnectionProvider {
    fn status(&self) -> PoolStatus {
        use crate::types::{AvailableConnections, CreatedConnections, MaxPoolSize};
        let status = self.pool.status();
        PoolStatus {
            available: AvailableConnections::new(status.available),
            max_size: MaxPoolSize::new(status.max_size),
            created: CreatedConnections::new(status.size),
        }
    }
}

#[cfg(test)]
#[allow(clippy::float_cmp)] // These tests compare exact derived failure-rate fixtures.
mod tests {
    use super::*;

    #[test]
    fn test_builder_new() {
        let builder = Builder::new("news.example.com", 119);
        assert_eq!(builder.host, "news.example.com");
        assert_eq!(builder.port, 119);
        assert_eq!(builder.max_size, 10); // Default
        assert!(builder.name.is_none());
        assert!(builder.username.is_none());
        assert!(builder.password.is_none());
        assert!(builder.tls_config.is_none());
    }

    #[test]
    fn test_builder_with_name() {
        let builder = Builder::new("example.com", 119).name("Test Server");
        assert_eq!(builder.name, Some("Test Server".to_string()));
    }

    #[test]
    fn test_builder_with_max_connections() {
        let builder = Builder::new("example.com", 119).max_connections(25);
        assert_eq!(builder.max_size, 25);
    }

    #[test]
    fn test_builder_with_username() {
        let builder = Builder::new("example.com", 119).username("testuser");
        assert_eq!(builder.username, Some("testuser".to_string()));
    }

    #[test]
    fn test_builder_with_password() {
        let builder = Builder::new("example.com", 119).password("testpass");
        assert_eq!(builder.password, Some("testpass".to_string()));
    }

    #[test]
    fn test_builder_with_tls_config() {
        let tls_config = TlsConfig::builder().enabled(true).build();
        let builder = Builder::new("example.com", 563).tls_config(tls_config);
        assert!(builder.tls_config.is_some());
    }

    #[test]
    fn test_builder_chaining() {
        let builder = Builder::new("news.example.com", 119)
            .name("Chained Server")
            .max_connections(30)
            .username("user")
            .password("pass");

        assert_eq!(builder.name, Some("Chained Server".to_string()));
        assert_eq!(builder.max_size, 30);
        assert_eq!(builder.username, Some("user".to_string()));
        assert_eq!(builder.password, Some("pass".to_string()));
    }

    #[test]
    fn test_builder_default_name_from_host_port() {
        let provider = Builder::new("test.example.com", 8119)
            .max_connections(5)
            .build()
            .unwrap();

        // Default name should be "host:port"
        assert_eq!(provider.name(), "test.example.com:8119");
    }

    #[test]
    fn test_builder_custom_name_used() {
        let provider = Builder::new("test.example.com", 8119)
            .name("Custom Name")
            .build()
            .unwrap();

        assert_eq!(provider.name(), "Custom Name");
    }

    #[test]
    fn test_provider_builder_method() {
        let builder = DeadpoolConnectionProvider::builder("example.com", 119);
        assert_eq!(builder.host, "example.com");
        assert_eq!(builder.port, 119);
    }

    #[test]
    fn test_provider_status_conversion() {
        let provider = DeadpoolConnectionProvider::builder("localhost", 119)
            .max_connections(15)
            .build()
            .unwrap();

        let status = ConnectionProvider::status(&provider);
        assert_eq!(status.max_size.get(), 15);
        // Initially no connections created
        assert_eq!(status.created.get(), 0);
    }

    #[test]
    fn test_provider_inherent_methods() {
        let provider = DeadpoolConnectionProvider::builder("localhost", 119)
            .build()
            .unwrap();

        // Test inherent methods
        assert_eq!(provider.name(), "localhost:119");
        assert_eq!(provider.host(), "localhost");
        assert_eq!(provider.port(), 119);
    }

    #[test]
    fn test_provider_with_all_builder_options() {
        let tls_config = TlsConfig::builder().enabled(false).build();

        let provider = DeadpoolConnectionProvider::builder("news.test.com", 563)
            .name("Full Test")
            .max_connections(42)
            .username("testuser")
            .password("testpass")
            .tls_config(tls_config)
            .build()
            .unwrap();

        assert_eq!(provider.name(), "Full Test");
        assert_eq!(provider.host(), "news.test.com");
        assert_eq!(provider.port(), 563);

        let status = ConnectionProvider::status(&provider);
        assert_eq!(status.max_size.get(), 42);
    }

    #[test]
    fn test_health_check_metrics_initialization() {
        let provider = DeadpoolConnectionProvider::builder("localhost", 119)
            .build()
            .unwrap();

        let metrics = &provider.health_check_metrics;
        assert_eq!(metrics.cycles_run(), 0);
        assert_eq!(metrics.connections_checked(), 0);
        assert_eq!(metrics.connections_failed(), 0);
        assert_eq!(metrics.failure_rate(), 0.0);
    }

    #[test]
    fn test_builder_accepts_string_types() {
        // Test that builder accepts &str
        let _ = Builder::new("example.com", 119);

        // Test that builder accepts String
        let _ = Builder::new(String::from("example.com"), 119);

        // Test that name accepts &str
        let _ = Builder::new("example.com", 119).name("test");

        // Test that name accepts String
        let _ = Builder::new("example.com", 119).name(String::from("test"));
    }

    #[test]
    fn test_builder_zero_max_connections() {
        // Should allow zero (deadpool will handle it)
        let provider = Builder::new("localhost", 119)
            .max_connections(0)
            .build()
            .unwrap();

        let status = ConnectionProvider::status(&provider);
        assert_eq!(status.max_size.get(), 0);
    }

    #[test]
    fn test_builder_large_max_connections() {
        let provider = Builder::new("localhost", 119)
            .max_connections(1000)
            .build()
            .unwrap();

        let status = ConnectionProvider::status(&provider);
        assert_eq!(status.max_size.get(), 1000);
    }

    #[test]
    fn test_provider_name_special_characters() {
        let provider = Builder::new("example.com", 119)
            .name("Server-123_Test.Name")
            .build()
            .unwrap();

        assert_eq!(provider.name(), "Server-123_Test.Name");
    }

    #[test]
    fn test_provider_name_unicode() {
        let provider = Builder::new("example.com", 119)
            .name("测试服务器")
            .build()
            .unwrap();

        assert_eq!(provider.name(), "测试服务器");
    }

    #[test]
    fn test_provider_empty_name() {
        let provider = Builder::new("example.com", 119).name("").build().unwrap();

        assert_eq!(provider.name(), "");
    }

    #[test]
    fn test_builder_idempotent_chaining() {
        // Setting the same value multiple times should use the last value
        let builder = Builder::new("example.com", 119)
            .name("First")
            .name("Second")
            .max_connections(10)
            .max_connections(20);

        assert_eq!(builder.name, Some("Second".to_string()));
        assert_eq!(builder.max_size, 20);
    }

    /// Helper: spawn a mock NNTP server that greets each connection and keeps it alive.
    /// Returns the address to connect to.
    async fn spawn_mock_nntp_server() -> std::net::SocketAddr {
        use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
        use tokio::net::TcpListener;

        let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();

        tokio::spawn(async move {
            while let Ok((stream, _)) = listener.accept().await {
                tokio::spawn(async move {
                    let (read_half, mut write_half) = stream.into_split();
                    let mut reader = BufReader::new(read_half);

                    let _ = write_half.write_all(b"200 mock\r\n").await;

                    let mut line = String::new();
                    loop {
                        line.clear();
                        match reader.read_line(&mut line).await {
                            Ok(0) | Err(_) => break,
                            Ok(_) => {
                                let cmd = line.trim().to_ascii_uppercase();
                                if cmd == "COMPRESS DEFLATE" {
                                    let _ = write_half.write_all(b"500 Not supported\r\n").await;
                                } else if cmd.starts_with("MODE") {
                                    let _ = write_half.write_all(b"200 Posting allowed\r\n").await;
                                } else if cmd.starts_with("QUIT") {
                                    let _ = write_half.write_all(b"205 Goodbye\r\n").await;
                                    break;
                                } else if cmd.starts_with("DATE") {
                                    let _ = write_half.write_all(b"111 20240101000000\r\n").await;
                                } else {
                                    let _ = write_half.write_all(b"200 OK\r\n").await;
                                }
                            }
                        }
                    }
                });
            }
        });

        addr
    }

    /// Helper: create a provider with cooldown for testing
    fn provider_with_cooldown(
        addr: std::net::SocketAddr,
        max_size: usize,
        cooldown: Option<std::time::Duration>,
    ) -> DeadpoolConnectionProvider {
        let manager = TcpManager::new(
            addr.ip().to_string(),
            addr.port(),
            format!("test-{}", addr.port()),
            TcpManagerOptions {
                compress: Some(false), // Disable compression — mock doesn't handle it
                ..TcpManagerOptions::default()
            },
        )
        .unwrap();

        let pool = Pool::builder(manager).max_size(max_size).build().unwrap();

        DeadpoolConnectionProvider {
            pool,
            name: Arc::from(format!("test-{}", addr.port())),
            shutdown_tx: None,
            health_check_metrics: Arc::new(crate::pool::health_check::HealthCheckMetrics::new()),
            original_max_size: max_size,
            active_cooldowns: Arc::new(std::sync::atomic::AtomicUsize::new(0)),
            replacement_cooldown: cooldown,
            is_shutting_down: Arc::new(std::sync::atomic::AtomicBool::new(false)),
        }
    }

    /// Verify that `remove_with_cooldown` reduces pool `max_size` BEFORE releasing
    /// the connection. This is the fix for the race where waiters would see
    /// size < `max_size` and create a replacement connection.
    #[tokio::test]
    async fn test_remove_with_cooldown_resize_before_drop() {
        let addr = spawn_mock_nntp_server().await;
        let cooldown = std::time::Duration::from_secs(10);
        let max_size = 4;
        let provider = provider_with_cooldown(addr, max_size, Some(cooldown));

        let conn = provider.get_pooled_connection().await.unwrap();
        assert_eq!(provider.pool.status().max_size, max_size);

        // Remove with cooldown — this should reduce max_size BEFORE dropping conn
        provider.remove_with_cooldown(conn);

        // After remove_with_cooldown, max_size must be reduced immediately
        let status = provider.pool.status();
        assert_eq!(
            status.max_size,
            max_size - 1,
            "Pool max_size should be reduced to {} after remove_with_cooldown, got {}",
            max_size - 1,
            status.max_size
        );
        assert_eq!(provider.active_cooldowns.load(Ordering::Acquire), 1);
    }

    /// Verify the cooldown cap: never reduce below half original size
    #[tokio::test]
    async fn test_remove_with_cooldown_cap() {
        let addr = spawn_mock_nntp_server().await;
        let cooldown = std::time::Duration::from_secs(10);
        let max_size = 4;
        let provider = provider_with_cooldown(addr, max_size, Some(cooldown));

        // max_reduction = 4 / 2 = 2, so after 2 cooldowns it should stop reducing
        let conn1 = provider.get_pooled_connection().await.unwrap();
        let conn2 = provider.get_pooled_connection().await.unwrap();
        let conn3 = provider.get_pooled_connection().await.unwrap();

        provider.remove_with_cooldown(conn1);
        assert_eq!(provider.pool.status().max_size, 3);

        provider.remove_with_cooldown(conn2);
        assert_eq!(provider.pool.status().max_size, 2);

        // Third removal should NOT further reduce (at cap)
        provider.remove_with_cooldown(conn3);
        assert_eq!(
            provider.pool.status().max_size,
            2,
            "Pool max_size should not drop below half (2) of original (4)"
        );
    }

    /// Verify no cooldown when cooldown is disabled (None)
    #[tokio::test]
    async fn test_remove_with_cooldown_disabled() {
        let addr = spawn_mock_nntp_server().await;
        let max_size = 4;
        let provider = provider_with_cooldown(addr, max_size, None);

        let conn = provider.get_pooled_connection().await.unwrap();
        provider.remove_with_cooldown(conn);

        // With cooldown disabled, max_size should NOT be reduced
        assert_eq!(provider.pool.status().max_size, max_size);
        assert_eq!(provider.active_cooldowns.load(Ordering::Acquire), 0);
    }

    /// Verify explicit no-cooldown removal closes a dirty connection without
    /// reducing capacity even when replacement cooldown is configured.
    #[tokio::test]
    async fn test_remove_without_cooldown_preserves_pool_size() {
        let addr = spawn_mock_nntp_server().await;
        let cooldown = std::time::Duration::from_secs(10);
        let max_size = 4;
        let provider = provider_with_cooldown(addr, max_size, Some(cooldown));

        let conn = provider.get_pooled_connection().await.unwrap();
        provider.remove_without_cooldown(conn);

        assert_eq!(provider.pool.status().max_size, max_size);
        assert_eq!(provider.active_cooldowns.load(Ordering::Acquire), 0);
    }

    /// Verify cooldown restoration after timer expires.
    ///
    /// Note: Cannot use `start_paused = true` here because the mock NNTP server
    /// uses real TCP I/O which doesn't work with paused time (auto-advance
    /// would resolve the Notify/sleep before the TCP handshake completes).
    /// Instead we use a very short real cooldown.
    #[tokio::test]
    async fn test_remove_with_cooldown_restores_after_timer() {
        let addr = spawn_mock_nntp_server().await;
        let cooldown = std::time::Duration::from_millis(100);
        let max_size = 4;
        let provider = provider_with_cooldown(addr, max_size, Some(cooldown));

        let conn = provider.get_pooled_connection().await.unwrap();
        provider.remove_with_cooldown(conn);

        assert_eq!(provider.pool.status().max_size, 3);
        assert_eq!(provider.active_cooldowns.load(Ordering::Acquire), 1);

        // Wait for the cooldown timer to restore the pool
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;

        assert_eq!(
            provider.pool.status().max_size,
            max_size,
            "Pool max_size should be restored after cooldown expires"
        );
        assert_eq!(provider.active_cooldowns.load(Ordering::Acquire), 0);
    }

    #[tokio::test]
    async fn test_remove_with_cooldown_skips_reduction_during_shutdown() {
        let addr = spawn_mock_nntp_server().await;
        let cooldown = std::time::Duration::from_secs(10);
        let max_size = 4;
        let provider = provider_with_cooldown(addr, max_size, Some(cooldown));

        provider.shutdown();

        let conn = provider.get_pooled_connection().await.unwrap();
        provider.remove_with_cooldown(conn);

        assert_eq!(provider.pool.status().max_size, max_size);
        assert_eq!(provider.active_cooldowns.load(Ordering::Acquire), 0);
        assert!(provider.is_shutting_down.load(Ordering::Acquire));
    }

    #[tokio::test(start_paused = true)]
    async fn test_shutdown_connections_concurrently_runs_all_writes_together() {
        use std::sync::Arc;
        use std::sync::atomic::{AtomicUsize, Ordering as AtomicOrdering};

        let completed = Arc::new(AtomicUsize::new(0));
        let completed_clone = completed.clone();
        let task = tokio::spawn(async move {
            shutdown_connections_concurrently(vec![1_u8, 2, 3], move |_| {
                let completed = completed_clone.clone();
                async move {
                    tokio::time::sleep(std::time::Duration::from_millis(500)).await;
                    completed.fetch_add(1, AtomicOrdering::Relaxed);
                }
            })
            .await;
        });

        tokio::task::yield_now().await;
        tokio::time::advance(std::time::Duration::from_millis(499)).await;
        assert_eq!(completed.load(AtomicOrdering::Relaxed), 0);
        assert!(!task.is_finished());

        tokio::time::advance(std::time::Duration::from_millis(1)).await;
        task.await.unwrap();
        assert_eq!(completed.load(AtomicOrdering::Relaxed), 3);
    }
}