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
//! Configuration type definitions
//!
//! This module contains all the core configuration structures used by the proxy.

use super::defaults;
use crate::types::{
    CacheCapacity, HostName, MaxConnections, MaxErrors, Port, ServerName, ThreadCount,
    duration_serde, option_duration_serde,
};
use serde::{Deserialize, Serialize};
use std::time::Duration;

/// Routing mode for the proxy
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
#[value(rename_all = "kebab-case")]
pub enum RoutingMode {
    /// Stateful 1:1 mode - each client gets a dedicated backend connection
    Stateful,
    /// Per-command routing - each command can use a different backend (stateless only)
    #[serde(alias = "percommand")]
    PerCommand,
    /// Hybrid mode - starts in per-command routing, auto-switches to stateful on first stateful command
    Hybrid,
}

impl Default for RoutingMode {
    /// Default routing mode is Hybrid, which provides optimal performance and full protocol support.
    /// This mode automatically starts in per-command routing for efficiency and seamlessly switches
    /// to stateful mode when commands requiring group context are detected.
    fn default() -> Self {
        Self::Hybrid
    }
}

impl RoutingMode {
    /// Check if this mode supports per-command routing
    #[must_use]
    pub const fn supports_per_command_routing(&self) -> bool {
        matches!(self, Self::PerCommand | Self::Hybrid)
    }

    /// Check if this mode can handle stateful commands
    #[must_use]
    pub const fn supports_stateful_commands(&self) -> bool {
        matches!(self, Self::Stateful | Self::Hybrid)
    }

    /// Get short lowercase name for metrics/logging (no allocation)
    #[must_use]
    pub const fn short_name(&self) -> &'static str {
        match self {
            Self::Stateful => "stateful",
            Self::PerCommand => "per-command",
            Self::Hybrid => "hybrid",
        }
    }

    /// Get a human-readable description of this routing mode
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::Stateful => "stateful 1:1 mode",
            Self::PerCommand => "per-command routing mode (stateless)",
            Self::Hybrid => "hybrid routing mode",
        }
    }
}

impl std::fmt::Display for RoutingMode {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Backend selection strategy for load balancing
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "kebab-case")]
pub enum BackendSelectionStrategy {
    /// Weighted round-robin - distributes requests proportionally to `max_connections`
    #[serde(alias = "round-robin")]
    WeightedRoundRobin,
    /// Least-loaded - routes to backend with fewest pending requests
    #[serde(alias = "adaptive-weighted")]
    LeastLoaded,
}

impl Default for BackendSelectionStrategy {
    /// Default is least-loaded for optimal dynamic load distribution
    fn default() -> Self {
        Self::LeastLoaded
    }
}

impl BackendSelectionStrategy {
    /// Get a human-readable description
    #[must_use]
    pub const fn as_str(&self) -> &'static str {
        match self {
            Self::WeightedRoundRobin => "weighted round-robin",
            Self::LeastLoaded => "least-loaded",
        }
    }
}

impl std::fmt::Display for BackendSelectionStrategy {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(self.as_str())
    }
}

/// Main proxy configuration
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq, Default)]
pub struct Config {
    /// Proxy server settings
    #[serde(default)]
    pub proxy: Proxy,
    /// Routing configuration
    #[serde(default)]
    pub routing: Routing,
    /// Memory configuration
    #[serde(default)]
    pub memory: Memory,
    /// Cache configuration.
    ///
    /// The proxy uses the cache for backend availability-driven routing/retry
    /// decisions when the configured capacity can hold the fixed availability
    /// index. In availability-only mode, `store_article_bodies` only controls
    /// whether the cache also retains full article bodies.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub cache: Option<Cache>,
    /// Health check configuration
    #[serde(default)]
    pub health_check: HealthCheck,
    /// Client authentication configuration
    #[serde(default)]
    pub client_auth: ClientAuth,
    /// List of backend NNTP servers
    #[serde(default)]
    pub servers: Vec<Server>,
}

/// Proxy server settings
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Proxy {
    /// Host/IP to bind to (default: 0.0.0.0)
    pub host: String,
    /// Port to listen on (default: 8119)
    pub port: Port,
    /// Number of worker threads (default: 1, use 0 for CPU cores)
    pub threads: ThreadCount,
    /// Routing mode for the proxy
    #[serde(skip_serializing)]
    pub routing_mode: RoutingMode,
    /// Backend selection strategy for load balancing
    #[serde(skip_serializing)]
    pub backend_selection: BackendSelectionStrategy,
    /// Validate yEnc structure and checksums (default: true)
    pub validate_yenc: bool,
    /// Filter directives for the optional local-TUI `debug.log` appender (default: "warn")
    /// Accepts tracing filter directives: "error", "warn", "info", "debug", "trace"
    #[serde(default = "super::defaults::log_file_level")]
    pub log_file_level: String,
    /// Path to stats file for metric persistence (optional)
    /// When set, metrics are persisted to this file every 30 seconds and on shutdown
    /// Defaults to "stats.json" alongside the config file if not specified
    #[serde(default)]
    pub stats_file: Option<std::path::PathBuf>,
    /// Legacy buffer pool count retained for config migration compatibility.
    #[serde(default, skip_serializing)]
    pub buffer_pool_count: usize,
    /// Legacy capture pool count retained for config migration compatibility.
    #[serde(default, skip_serializing)]
    pub capture_pool_count: usize,
}

impl Proxy {
    /// Default listen host (all interfaces)
    pub const DEFAULT_HOST: &'static str = "0.0.0.0";
}

impl Default for Proxy {
    fn default() -> Self {
        Self {
            host: Self::DEFAULT_HOST.to_string(),
            port: Port::default(),
            threads: ThreadCount::default(),
            validate_yenc: true,
            log_file_level: defaults::log_file_level(),
            stats_file: None,
            routing_mode: RoutingMode::default(),
            backend_selection: BackendSelectionStrategy::default(),
            buffer_pool_count: defaults::buffer_pool_count(),
            capture_pool_count: defaults::capture_pool_count(),
        }
    }
}

/// Routing configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Routing {
    /// Routing mode for the proxy
    #[serde(rename = "mode", alias = "routing_mode")]
    pub routing_mode: RoutingMode,
    /// Backend selection strategy for load balancing
    #[serde(alias = "strategy")]
    pub backend_selection: BackendSelectionStrategy,
    /// Enable adaptive availability prechecking for STAT/HEAD commands (default: false)
    #[serde(default = "super::defaults::adaptive_precheck")]
    pub adaptive_precheck: bool,
}

impl Default for Routing {
    fn default() -> Self {
        Self {
            routing_mode: RoutingMode::default(),
            backend_selection: BackendSelectionStrategy::default(),
            adaptive_precheck: defaults::adaptive_precheck(),
        }
    }
}

/// Memory configuration for transport and buffer pools
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Memory {
    /// TCP socket receive buffer size for backend and client connections
    #[serde(default = "super::defaults::socket_recv_buffer_size")]
    pub socket_recv_buffer_size: usize,
    /// TCP socket send buffer size for backend and client connections
    #[serde(default = "super::defaults::socket_send_buffer_size")]
    pub socket_send_buffer_size: usize,
    /// Size of each pooled I/O buffer used for streaming
    #[serde(default = "super::defaults::buffer_pool_size")]
    pub buffer_pool_size: usize,
    /// Number of buffers in the main buffer pool
    #[serde(default = "super::defaults::buffer_pool_count")]
    pub buffer_pool_count: usize,
    /// Size of each capture buffer for caching and response assembly
    #[serde(default = "super::defaults::capture_pool_size")]
    pub capture_pool_size: usize,
    /// Number of buffers in the capture pool
    #[serde(default = "super::defaults::capture_pool_count")]
    pub capture_pool_count: usize,
}

impl Default for Memory {
    fn default() -> Self {
        Self {
            socket_recv_buffer_size: defaults::socket_recv_buffer_size(),
            socket_send_buffer_size: defaults::socket_send_buffer_size(),
            buffer_pool_size: defaults::buffer_pool_size(),
            buffer_pool_count: defaults::buffer_pool_count(),
            capture_pool_size: defaults::capture_pool_size(),
            capture_pool_count: defaults::capture_pool_count(),
        }
    }
}

/// Article cache configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(default)]
pub struct Cache {
    /// Maximum article-cache size in bytes (memory tier for hybrid cache)
    ///
    /// Supports human-readable formats:
    /// - \"1gb\" = 1 GB
    /// - \"500mb\" = 500 MB
    /// - \"64mb\" = 64 MB (default)
    /// - 10000 = 10,000 bytes
    #[serde(
        default = "super::defaults::cache_max_capacity",
        rename = "article_cache_capacity",
        alias = "cache_capacity",
        alias = "max_capacity"
    )]
    pub article_cache_capacity: CacheCapacity,
    /// Time-to-live for the article cache
    #[serde(
        with = "duration_serde",
        default = "super::defaults::cache_ttl",
        rename = "article_cache_ttl_secs",
        alias = "cache_ttl",
        alias = "ttl_secs",
        alias = "ttl"
    )]
    pub article_cache_ttl_secs: Duration,
    /// Whether to store full article bodies in the article cache (default: false)
    ///
    /// When false:
    /// - Cache still tracks backend availability (smart routing, 430 retry)
    /// - Article bodies are NOT stored (saves ~750KB per article)
    /// - Uses the dedicated availability-only index with bounded LRU eviction
    /// - Useful for availability-only mode with limited memory
    ///
    /// When true:
    /// - Full caching mode (bodies + availability tracking)
    /// - Can serve articles from cache without backend query
    #[serde(
        default = "super::defaults::cache_articles",
        rename = "store_article_bodies",
        alias = "store_articles",
        alias = "cache_articles"
    )]
    pub store_article_bodies: bool,

    /// Disk cache configuration (requires `hybrid-cache` feature)
    ///
    /// When enabled, articles evicted from memory are written to disk,
    /// creating a two-tier cache (memory → disk → backend).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub disk: Option<DiskCache>,

    /// Path to the availability index persistence file (optional).
    ///
    /// This is only used in availability-only mode (`store_article_bodies = false`).
    /// When set, the proxy uses this path to persist backend availability state;
    /// otherwise it defaults to "availability.idx" alongside the config file.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        rename = "availability_index_path",
        alias = "availability_path",
        alias = "availability_file"
    )]
    pub availability_index_path: Option<std::path::PathBuf>,
    /// Legacy adaptive precheck retained for config migration compatibility.
    #[serde(default, skip_serializing)]
    pub adaptive_precheck: bool,
}

/// Compression codec for disk cache storage
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize, clap::ValueEnum)]
#[serde(rename_all = "lowercase")]
pub enum CompressionCodec {
    /// No compression (fastest, largest disk usage)
    None,
    /// LZ4 compression (fast, ~60% reduction for typical NNTP articles, default)
    ///
    /// Uses SIMD (SSE2/AVX2) auto-detection for maximum throughput.
    /// Compression level: fast mode (default).
    #[default]
    Lz4,
    /// Zstandard compression (better ratio, moderate CPU overhead)
    ///
    /// Uses SIMD (SSE2/AVX2/AVX512) auto-detection.
    /// Compression level: 3 (library default, balanced speed/ratio).
    Zstd,
}

impl std::fmt::Display for CompressionCodec {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::None => write!(f, "none"),
            Self::Lz4 => write!(f, "lz4"),
            Self::Zstd => write!(f, "zstd"),
        }
    }
}

/// Disk cache configuration for hybrid caching
///
/// When enabled, creates a two-tier cache:
/// - Hot articles in memory (fast, limited capacity)
/// - Cold articles on disk (slower, larger capacity)
///
/// Requires the `hybrid-cache` feature to be enabled.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct DiskCache {
    /// Path to disk cache directory
    ///
    /// Directory will be created if it doesn't exist.
    /// Recommended: Use a fast SSD or `NVMe` drive.
    #[serde(default = "super::defaults::disk_cache_path")]
    pub path: std::path::PathBuf,

    /// Maximum disk cache size in bytes
    ///
    /// Supports human-readable formats:
    /// - \"100gb\" = 100 GB
    /// - \"10gb\" = 10 GB (default)
    /// - \"1tb\" = 1 TB
    #[serde(default = "super::defaults::disk_cache_capacity")]
    pub capacity: CacheCapacity,

    /// Compression codec for disk storage (default: lz4)
    ///
    /// Options:
    /// - "lz4" (default): Fast compression (~60% reduction), minimal CPU overhead
    /// - "zstd": Better compression ratio, moderate CPU overhead
    /// - "none": No compression, fastest but largest disk usage
    ///
    /// For the "lz4" and "zstd" codecs, SIMD optimizations (SSE2/AVX2/AVX512) are
    /// auto-detected and enabled by default. When `compression = "none"`, no
    /// compression or SIMD acceleration is performed.
    #[serde(default = "super::defaults::disk_cache_compression_codec")]
    pub compression: CompressionCodec,

    /// Number of shards for concurrent disk access (default: 4)
    ///
    /// Higher values improve concurrency but use more file handles.
    #[serde(default = "super::defaults::disk_cache_shards")]
    pub shards: usize,
}

impl Default for DiskCache {
    fn default() -> Self {
        Self {
            path: defaults::disk_cache_path(),
            capacity: defaults::disk_cache_capacity(),
            compression: defaults::disk_cache_compression_codec(),
            shards: defaults::disk_cache_shards(),
        }
    }
}

impl Default for Cache {
    fn default() -> Self {
        Self {
            article_cache_capacity: defaults::cache_max_capacity(),
            article_cache_ttl_secs: defaults::cache_ttl(),
            store_article_bodies: defaults::cache_articles(),
            disk: None,
            availability_index_path: None,
            adaptive_precheck: defaults::adaptive_precheck(),
        }
    }
}

/// Health check configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct HealthCheck {
    /// Interval between health checks
    #[serde(
        with = "duration_serde",
        default = "super::defaults::health_check_interval"
    )]
    pub interval: Duration,
    /// Timeout for each health check
    #[serde(
        with = "duration_serde",
        default = "super::defaults::health_check_timeout"
    )]
    pub timeout: Duration,
    /// Number of consecutive failures before marking unhealthy
    #[serde(default = "super::defaults::unhealthy_threshold")]
    pub unhealthy_threshold: MaxErrors,
}

impl Default for HealthCheck {
    fn default() -> Self {
        Self {
            interval: super::defaults::health_check_interval(),
            timeout: super::defaults::health_check_timeout(),
            unhealthy_threshold: super::defaults::unhealthy_threshold(),
        }
    }
}

/// Client authentication configuration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Default)]
pub struct ClientAuth {
    /// Optional custom greeting message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub greeting: Option<String>,
    /// List of authorized users for client authentication
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub users: Vec<UserCredentials>,
}

/// Individual user credentials
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct UserCredentials {
    pub username: String,
    pub password: String,
}

impl ClientAuth {
    /// Check if authentication is enabled
    #[must_use]
    pub const fn is_enabled(&self) -> bool {
        !self.users.is_empty()
    }

    /// Get all users
    #[must_use]
    pub fn all_users(&self) -> Vec<(&str, &str)> {
        self.users
            .iter()
            .map(|user| (user.username.as_str(), user.password.as_str()))
            .collect()
    }
}

/// Configuration for a single backend server
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct Server {
    pub host: HostName,
    pub port: Port,
    pub name: ServerName,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub username: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub password: Option<String>,
    /// Maximum number of concurrent connections to this server
    #[serde(default = "super::defaults::max_connections")]
    pub max_connections: MaxConnections,

    /// Enable TLS/SSL for this backend connection
    #[serde(default)]
    pub use_tls: bool,
    /// Verify TLS certificates (recommended for production)
    #[serde(default = "super::defaults::tls_verify_cert")]
    pub tls_verify_cert: bool,
    /// Optional path to custom CA certificate
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tls_cert_path: Option<String>,
    /// Interval to send keep-alive commands (DATE) on idle connections
    /// None disables keep-alive (default)
    #[serde(
        with = "option_duration_serde",
        default,
        skip_serializing_if = "Option::is_none"
    )]
    pub connection_keepalive: Option<Duration>,
    /// How long to wait before replacing an actively-removed connection.
    /// This can damp backend connection churn after repeated failures, but it
    /// also temporarily reduces pool capacity on backend-error removals.
    /// Default: 30 seconds. Set to 0 to disable.
    #[serde(
        with = "option_duration_serde",
        default = "super::defaults::replacement_cooldown_option",
        skip_serializing_if = "Option::is_none"
    )]
    pub replacement_cooldown: Option<Duration>,
    /// Maximum number of connections to check per health check cycle
    /// Lower values reduce pool contention but may take longer to detect all stale connections
    #[serde(default = "super::defaults::health_check_max_per_cycle")]
    pub health_check_max_per_cycle: usize,
    /// Timeout when acquiring a connection for health checking
    /// Short timeout prevents blocking if pool is busy
    #[serde(
        with = "duration_serde",
        default = "super::defaults::health_check_pool_timeout"
    )]
    pub health_check_pool_timeout: Duration,
    /// Server tier for prioritization (lower = higher priority, default: 0)
    /// Servers with lower tier numbers are tried first; higher tiers only when lower exhausted
    #[serde(default)]
    pub tier: u8,
    /// Wire compression for backend connections (RFC 8054 COMPRESS DEFLATE)
    /// None (default) = auto-detect, Some(true) = require, Some(false) = disable
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compress: Option<bool>,
    /// Compression level (0-9). None = fast (level 1). Higher = better ratio, more CPU.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub compress_level: Option<u32>,

    /// Duration of proxy-wide inactivity after which this backend's idle connections are cleared.
    /// Prevents stale connections from accumulating during overnight idle periods.
    /// Default: 600 seconds (10 minutes). Set to 0 to disable.
    #[serde(
        with = "duration_serde",
        default = "super::defaults::backend_idle_timeout"
    )]
    pub backend_idle_timeout: Duration,
}

/// Builder for constructing `Server` instances
///
/// Provides a fluent API for creating server configurations, especially useful in tests
/// where creating Server with all 11+ fields is verbose.
///
/// # Examples
///
/// ```
/// use nntp_proxy::config::Server;
/// use nntp_proxy::types::{Port, MaxConnections};
///
/// // Minimal configuration
/// let config = Server::builder("news.example.com", Port::try_new(119).unwrap())
///     .build()
///     .unwrap();
///
/// // With authentication and TLS
/// let config = Server::builder("secure.example.com", Port::try_new(563).unwrap())
///     .name("Secure Server")
///     .username("user")
///     .password("pass")
///     .max_connections(MaxConnections::try_new(20).unwrap())
///     .use_tls(true)
///     .build()
///     .unwrap();
/// ```
pub struct ServerBuilder {
    host: String,
    port: Port,
    name: Option<String>,
    username: Option<String>,
    password: Option<String>,
    max_connections: Option<MaxConnections>,
    use_tls: bool,
    tls_verify_cert: bool,
    tls_cert_path: Option<String>,
    connection_keepalive: Option<Duration>,
    replacement_cooldown: Option<Duration>,
    health_check_max_per_cycle: Option<usize>,
    health_check_pool_timeout: Option<Duration>,
    tier: u8,
    compress: Option<bool>,
    compress_level: Option<u32>,
    backend_idle_timeout: Option<Duration>,
}

impl ServerBuilder {
    /// Create a new builder with required parameters
    ///
    /// # Arguments
    /// * `host` - Backend server hostname or IP address
    /// * `port` - Backend server port
    #[must_use]
    pub fn new(host: impl Into<String>, port: Port) -> Self {
        Self {
            host: host.into(),
            port,
            name: None,
            username: None,
            password: None,
            max_connections: None,
            use_tls: false,
            tls_verify_cert: true, // Secure by default
            tls_cert_path: None,
            connection_keepalive: None,
            replacement_cooldown: None,
            health_check_max_per_cycle: None,
            health_check_pool_timeout: None,
            tier: 0,
            compress: None,
            compress_level: None,
            backend_idle_timeout: 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 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
    }

    /// Set maximum number of concurrent connections
    #[must_use]
    pub const fn max_connections(mut self, max: MaxConnections) -> Self {
        self.max_connections = Some(max);
        self
    }

    /// Enable TLS/SSL for this backend connection
    #[must_use]
    pub const fn use_tls(mut self, enabled: bool) -> Self {
        self.use_tls = enabled;
        self
    }

    /// Set whether to verify TLS certificates
    #[must_use]
    pub const fn tls_verify_cert(mut self, verify: bool) -> Self {
        self.tls_verify_cert = verify;
        self
    }

    /// Set path to custom CA certificate
    #[must_use]
    pub fn tls_cert_path(mut self, path: impl Into<String>) -> Self {
        self.tls_cert_path = Some(path.into());
        self
    }

    /// Set keep-alive interval for idle connections
    #[must_use]
    pub const fn connection_keepalive(mut self, interval: Duration) -> Self {
        self.connection_keepalive = Some(interval);
        self
    }

    /// Set connection replacement cooldown duration
    #[must_use]
    pub const fn replacement_cooldown(mut self, cooldown: Duration) -> Self {
        self.replacement_cooldown = Some(cooldown);
        self
    }

    /// Set maximum connections to check per health check cycle
    #[must_use]
    pub const fn health_check_max_per_cycle(mut self, max: usize) -> Self {
        self.health_check_max_per_cycle = Some(max);
        self
    }

    /// Set timeout for acquiring connections during health checks
    #[must_use]
    pub const fn health_check_pool_timeout(mut self, timeout: Duration) -> Self {
        self.health_check_pool_timeout = Some(timeout);
        self
    }

    /// Set server tier for prioritization (lower = higher priority)
    #[must_use]
    pub const fn tier(mut self, tier: u8) -> Self {
        self.tier = tier;
        self
    }

    /// Set wire compression mode (RFC 8054 COMPRESS DEFLATE)
    #[must_use]
    pub const fn compress(mut self, compress: Option<bool>) -> Self {
        self.compress = compress;
        self
    }

    /// Set compression level (0-9, default: 1 = fast)
    ///
    /// # Panics
    ///
    /// Panics if `level` is greater than 9.
    #[must_use]
    pub fn compress_level(mut self, level: u32) -> Self {
        assert!(level <= 9, "compress_level must be 0-9, got {level}");
        self.compress_level = Some(level);
        self
    }

    /// Set the backend idle timeout duration
    ///
    /// Connections to this backend are cleared after this duration of proxy-wide inactivity.
    /// Default: 10 minutes.
    #[must_use]
    pub const fn backend_idle_timeout(mut self, timeout: Duration) -> Self {
        self.backend_idle_timeout = Some(timeout);
        self
    }

    /// Build the Server
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Host is empty or invalid
    /// - Port is 0
    /// - Name is empty (when explicitly set)
    /// - Max connections is 0 (when explicitly set)
    pub fn build(self) -> Result<Server, anyhow::Error> {
        use crate::types::{HostName, ServerName};

        let host = HostName::try_new(self.host.clone())?;
        let port = self.port; // Already a Port type
        let name_str = self
            .name
            .unwrap_or_else(|| format!("{}:{}", self.host, self.port.get()));
        let name = ServerName::try_new(name_str)?;

        let max_connections = self
            .max_connections
            .unwrap_or_else(super::defaults::max_connections);

        let health_check_max_per_cycle = self
            .health_check_max_per_cycle
            .unwrap_or_else(super::defaults::health_check_max_per_cycle);

        let health_check_pool_timeout = self
            .health_check_pool_timeout
            .unwrap_or_else(super::defaults::health_check_pool_timeout);

        Ok(Server {
            host,
            port,
            name,
            username: self.username,
            password: self.password,
            max_connections,
            use_tls: self.use_tls,
            tls_verify_cert: self.tls_verify_cert,
            tls_cert_path: self.tls_cert_path,
            connection_keepalive: self.connection_keepalive,
            replacement_cooldown: self
                .replacement_cooldown
                .or_else(super::defaults::replacement_cooldown_option),
            health_check_max_per_cycle,
            health_check_pool_timeout,
            tier: self.tier,
            compress: self.compress,
            compress_level: self.compress_level,
            backend_idle_timeout: self
                .backend_idle_timeout
                .unwrap_or_else(super::defaults::backend_idle_timeout),
        })
    }
}

impl Server {
    /// Create a builder for configuring a backend server
    ///
    /// # Example
    ///
    /// ```
    /// use nntp_proxy::config::Server;
    /// use nntp_proxy::types::{Port, MaxConnections};
    ///
    /// let config = Server::builder("news.example.com", Port::try_new(119).unwrap())
    ///     .name("Example Server")
    ///     .max_connections(MaxConnections::try_new(15).unwrap())
    ///     .build()
    ///     .unwrap();
    /// ```
    #[must_use]
    pub fn builder(host: impl Into<String>, port: Port) -> ServerBuilder {
        ServerBuilder::new(host, port)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // RoutingMode tests
    #[test]
    fn test_routing_mode_default() {
        assert_eq!(RoutingMode::default(), RoutingMode::Hybrid);
    }

    #[test]
    fn test_routing_mode_supports_per_command() {
        assert!(RoutingMode::PerCommand.supports_per_command_routing());
        assert!(RoutingMode::Hybrid.supports_per_command_routing());
        assert!(!RoutingMode::Stateful.supports_per_command_routing());
    }

    #[test]
    fn test_routing_mode_supports_stateful() {
        assert!(RoutingMode::Stateful.supports_stateful_commands());
        assert!(RoutingMode::Hybrid.supports_stateful_commands());
        assert!(!RoutingMode::PerCommand.supports_stateful_commands());
    }

    #[test]
    fn test_routing_mode_as_str() {
        assert_eq!(RoutingMode::Stateful.as_str(), "stateful 1:1 mode");
        assert_eq!(
            RoutingMode::PerCommand.as_str(),
            "per-command routing mode (stateless)"
        );
        assert_eq!(RoutingMode::Hybrid.as_str(), "hybrid routing mode");
    }

    #[test]
    fn test_routing_mode_display() {
        assert_eq!(RoutingMode::Stateful.to_string(), "stateful 1:1 mode");
        assert_eq!(RoutingMode::Hybrid.to_string(), "hybrid routing mode");
    }

    // Proxy tests
    #[test]
    fn test_proxy_default() {
        let proxy = Proxy::default();
        assert_eq!(proxy.host, "0.0.0.0");
        assert_eq!(proxy.port.get(), 8119);
    }

    #[test]
    fn test_proxy_default_host_constant() {
        assert_eq!(Proxy::DEFAULT_HOST, "0.0.0.0");
    }

    // Cache tests
    #[test]
    fn test_cache_default() {
        let cache = Cache::default();
        assert_eq!(cache.article_cache_capacity.get(), 64 * 1024 * 1024); // 64 MB
        assert_eq!(
            cache.article_cache_ttl_secs,
            crate::constants::duration_polyfill::from_hours(1)
        );
        assert!(!cache.store_article_bodies);
    }

    #[test]
    fn test_memory_default() {
        let memory = Memory::default();
        assert_eq!(
            memory.socket_recv_buffer_size,
            crate::constants::socket::HIGH_THROUGHPUT_RECV_BUFFER
        );
        assert_eq!(
            memory.socket_send_buffer_size,
            crate::constants::socket::HIGH_THROUGHPUT_SEND_BUFFER
        );
        assert_eq!(memory.buffer_pool_size, crate::constants::buffer::POOL);
        assert_eq!(
            memory.buffer_pool_count,
            crate::constants::buffer::POOL_COUNT
        );
        assert_eq!(memory.capture_pool_size, crate::constants::buffer::CAPTURE);
        assert_eq!(
            memory.capture_pool_count,
            crate::constants::buffer::CAPTURE_COUNT
        );
    }

    // HealthCheck tests
    #[test]
    fn test_health_check_default() {
        let hc = HealthCheck::default();
        assert_eq!(hc.interval, Duration::from_secs(30));
        assert_eq!(hc.timeout, Duration::from_secs(5));
        assert_eq!(hc.unhealthy_threshold.get(), 3);
    }

    // ClientAuth tests
    #[test]
    fn test_client_auth_is_enabled() {
        let mut auth = ClientAuth::default();
        assert!(!auth.is_enabled());

        auth.users.push(UserCredentials {
            username: "user".to_string(),
            password: "pass".to_string(),
        });
        assert!(auth.is_enabled());
    }

    #[test]
    fn test_client_auth_is_enabled_multi_user() {
        let mut auth = ClientAuth::default();
        auth.users.push(UserCredentials {
            username: "alice".to_string(),
            password: "secret".to_string(),
        });
        assert!(auth.is_enabled());
    }

    #[test]
    fn test_client_auth_all_users_single() {
        let mut auth = ClientAuth::default();
        auth.users.push(UserCredentials {
            username: "user".to_string(),
            password: "pass".to_string(),
        });

        let users = auth.all_users();
        assert_eq!(users.len(), 1);
        assert_eq!(users[0], ("user", "pass"));
    }

    #[test]
    fn test_client_auth_all_users_multi() {
        let mut auth = ClientAuth::default();
        auth.users.push(UserCredentials {
            username: "alice".to_string(),
            password: "alice_pw".to_string(),
        });
        auth.users.push(UserCredentials {
            username: "bob".to_string(),
            password: "bob_pw".to_string(),
        });

        let users = auth.all_users();
        assert_eq!(users.len(), 2);
        assert_eq!(users[0], ("alice", "alice_pw"));
        assert_eq!(users[1], ("bob", "bob_pw"));
    }

    // ServerBuilder tests
    #[test]
    fn test_server_builder_minimal() {
        let server = Server::builder("news.example.com", Port::try_new(119).unwrap())
            .build()
            .unwrap();

        assert_eq!(server.host.as_str(), "news.example.com");
        assert_eq!(server.port.get(), 119);
        assert_eq!(server.name.as_str(), "news.example.com:119");
        assert_eq!(server.max_connections.get(), 10);
        assert!(!server.use_tls);
        assert!(server.tls_verify_cert); // Secure by default
    }

    #[test]
    fn test_server_builder_with_name() {
        let server = Server::builder("localhost", Port::try_new(119).unwrap())
            .name("Test Server")
            .build()
            .unwrap();

        assert_eq!(server.name.as_str(), "Test Server");
    }

    #[test]
    fn test_server_builder_with_auth() {
        let server = Server::builder("news.example.com", Port::try_new(119).unwrap())
            .username("testuser")
            .password("testpass")
            .build()
            .unwrap();

        assert_eq!(server.username.as_ref().unwrap(), "testuser");
        assert_eq!(server.password.as_ref().unwrap(), "testpass");
    }

    #[test]
    fn test_server_builder_with_max_connections() {
        let server = Server::builder("localhost", Port::try_new(119).unwrap())
            .max_connections(MaxConnections::try_new(20).unwrap())
            .build()
            .unwrap();

        assert_eq!(server.max_connections.get(), 20);
    }

    #[test]
    fn test_server_builder_with_tls() {
        let server = Server::builder("secure.example.com", Port::try_new(563).unwrap())
            .use_tls(true)
            .tls_verify_cert(false)
            .tls_cert_path("/path/to/cert.pem")
            .build()
            .unwrap();

        assert!(server.use_tls);
        assert!(!server.tls_verify_cert);
        assert_eq!(server.tls_cert_path.as_ref().unwrap(), "/path/to/cert.pem");
    }

    #[test]
    fn test_server_builder_with_keepalive() {
        let keepalive = crate::constants::duration_polyfill::from_minutes(5);
        let server = Server::builder("localhost", Port::try_new(119).unwrap())
            .connection_keepalive(keepalive)
            .build()
            .unwrap();

        assert_eq!(server.connection_keepalive, Some(keepalive));
    }

    #[test]
    fn test_server_builder_default_replacement_cooldown() {
        let server = Server::builder("localhost", Port::try_new(119).unwrap())
            .build()
            .unwrap();

        assert_eq!(
            server.replacement_cooldown,
            super::defaults::replacement_cooldown_option()
        );
    }

    #[test]
    fn test_server_builder_with_replacement_cooldown() {
        let cooldown = Duration::from_secs(31);
        let server = Server::builder("localhost", Port::try_new(119).unwrap())
            .replacement_cooldown(cooldown)
            .build()
            .unwrap();

        assert_eq!(server.replacement_cooldown, Some(cooldown));
    }

    #[test]
    fn test_server_builder_with_health_check_settings() {
        let timeout = Duration::from_millis(500);
        let server = Server::builder("localhost", Port::try_new(119).unwrap())
            .health_check_max_per_cycle(5)
            .health_check_pool_timeout(timeout)
            .build()
            .unwrap();

        assert_eq!(server.health_check_max_per_cycle, 5);
        assert_eq!(server.health_check_pool_timeout, timeout);
    }

    #[test]
    fn test_server_builder_chaining() {
        let server = Server::builder("news.example.com", Port::try_new(563).unwrap())
            .name("Production Server")
            .username("admin")
            .password("secret")
            .max_connections(MaxConnections::try_new(25).unwrap())
            .use_tls(true)
            .tls_verify_cert(true)
            .build()
            .unwrap();

        assert_eq!(server.name.as_str(), "Production Server");
        assert_eq!(server.max_connections.get(), 25);
        assert!(server.use_tls);
    }

    // Config tests
    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert!(config.servers.is_empty());
        assert_eq!(config.proxy.host, "0.0.0.0");
        assert!(config.cache.is_none());
        assert!(!config.client_auth.is_enabled());
    }

    // CompressionCodec tests
    #[test]
    fn test_compression_codec_serde_lz4() {
        let json = r#""lz4""#;
        let codec: CompressionCodec = serde_json::from_str(json).unwrap();
        assert_eq!(codec, CompressionCodec::Lz4);
        assert_eq!(serde_json::to_string(&codec).unwrap(), json);
    }

    #[test]
    fn test_compression_codec_serde_zstd() {
        let json = r#""zstd""#;
        let codec: CompressionCodec = serde_json::from_str(json).unwrap();
        assert_eq!(codec, CompressionCodec::Zstd);
    }

    #[test]
    fn test_compression_codec_serde_none() {
        let json = r#""none""#;
        let codec: CompressionCodec = serde_json::from_str(json).unwrap();
        assert_eq!(codec, CompressionCodec::None);
    }

    #[test]
    fn test_compression_codec_default_is_lz4() {
        assert_eq!(CompressionCodec::default(), CompressionCodec::Lz4);
    }

    #[test]
    fn test_compression_codec_display() {
        assert_eq!(CompressionCodec::Lz4.to_string(), "lz4");
        assert_eq!(CompressionCodec::Zstd.to_string(), "zstd");
        assert_eq!(CompressionCodec::None.to_string(), "none");
    }

    // DiskCache tests with compression codec
    #[test]
    fn test_disk_cache_default_compression_is_lz4() {
        let disk_cache = DiskCache::default();
        assert_eq!(disk_cache.compression, CompressionCodec::Lz4);
    }

    #[test]
    fn test_disk_cache_deserialize_compression_codec() {
        let toml = r#"
            path = "/tmp/cache"
            capacity = "100mb"
            compression = "zstd"
            shards = 4
        "#;
        let disk_cache: DiskCache = toml::from_str(toml).unwrap();
        assert_eq!(disk_cache.compression, CompressionCodec::Zstd);
    }

    #[test]
    fn test_disk_cache_deserialize_compression_none() {
        let toml = r#"
            path = "/tmp/cache"
            capacity = "100mb"
            compression = "none"
            shards = 4
        "#;
        let disk_cache: DiskCache = toml::from_str(toml).unwrap();
        assert_eq!(disk_cache.compression, CompressionCodec::None);
    }
}