armature-core 0.8.1

High-performance async HTTP framework core - routing, handlers, middleware
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
//! Connection Tuning and Optimization
//!
//! This module provides comprehensive connection handling optimizations:
//!
//! - **HTTP/2 Priority**: Stream prioritization for efficient resource delivery
//! - **TCP Tuning**: Socket options for low latency and high throughput
//! - **Keep-Alive**: Optimized connection reuse and timeout handling
//!
//! # Performance Impact
//!
//! - HTTP/2 priority: Better page load times through smart resource ordering
//! - TCP_NODELAY: -40-80ms latency for small messages
//! - TCP_QUICKACK: -20-40ms latency on request start
//! - Keep-alive tuning: Reduced connection overhead, better resource utilization

use std::collections::HashMap;
use std::io;
use std::net::TcpStream;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::time::{Duration, Instant};

#[cfg(unix)]
use std::os::unix::io::AsRawFd;

// ============================================================================
// HTTP/2 Priority Handling
// ============================================================================

/// HTTP/2 stream priority weight (1-256, default 16).
pub type StreamWeight = u8;

/// Stream dependency for HTTP/2 priority tree.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct StreamDependency {
    /// Parent stream ID (0 = root)
    pub stream_id: u32,
    /// Whether this dependency is exclusive
    pub exclusive: bool,
}

/// HTTP/2 stream priority configuration.
#[derive(Debug, Clone)]
pub struct StreamPriority {
    /// Stream weight (1-256)
    pub weight: StreamWeight,
    /// Parent stream dependency
    pub dependency: StreamDependency,
}

impl Default for StreamPriority {
    fn default() -> Self {
        Self {
            weight: 16, // Default weight per HTTP/2 spec
            dependency: StreamDependency::default(),
        }
    }
}

impl StreamPriority {
    /// Create new priority with weight.
    pub fn with_weight(weight: StreamWeight) -> Self {
        Self {
            weight: weight.max(1), // Weight must be at least 1
            ..Default::default()
        }
    }

    /// Create priority dependent on another stream.
    pub fn dependent_on(stream_id: u32, exclusive: bool) -> Self {
        Self {
            weight: 16,
            dependency: StreamDependency {
                stream_id,
                exclusive,
            },
        }
    }

    /// Set weight.
    pub fn weight(mut self, weight: StreamWeight) -> Self {
        self.weight = weight.max(1);
        self
    }
}

/// Resource type for automatic priority assignment.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ResourceType {
    /// HTML document (highest priority)
    Html,
    /// CSS stylesheets (very high priority)
    Css,
    /// JavaScript files (high priority, blocks render)
    JavaScript,
    /// Fonts (medium-high priority)
    Font,
    /// Images (medium priority)
    Image,
    /// XHR/Fetch API requests (medium priority)
    Xhr,
    /// Prefetch resources (low priority)
    Prefetch,
    /// Other resources (default priority)
    Other,
}

impl ResourceType {
    /// Detect resource type from content-type header.
    pub fn from_content_type(content_type: &str) -> Self {
        let ct = content_type.to_lowercase();
        if ct.contains("text/html") {
            Self::Html
        } else if ct.contains("text/css") {
            Self::Css
        } else if ct.contains("javascript") || ct.contains("application/json") {
            Self::JavaScript
        } else if ct.contains("font") || ct.contains("woff") || ct.contains("ttf") {
            Self::Font
        } else if ct.contains("image/") {
            Self::Image
        } else {
            Self::Other
        }
    }

    /// Detect resource type from path extension.
    pub fn from_path(path: &str) -> Self {
        let path_lower = path.to_lowercase();
        if path_lower.ends_with(".html") || path_lower.ends_with(".htm") {
            Self::Html
        } else if path_lower.ends_with(".css") {
            Self::Css
        } else if path_lower.ends_with(".js") || path_lower.ends_with(".mjs") {
            Self::JavaScript
        } else if path_lower.ends_with(".woff")
            || path_lower.ends_with(".woff2")
            || path_lower.ends_with(".ttf")
            || path_lower.ends_with(".otf")
        {
            Self::Font
        } else if path_lower.ends_with(".png")
            || path_lower.ends_with(".jpg")
            || path_lower.ends_with(".jpeg")
            || path_lower.ends_with(".gif")
            || path_lower.ends_with(".webp")
            || path_lower.ends_with(".svg")
            || path_lower.ends_with(".ico")
        {
            Self::Image
        } else {
            Self::Other
        }
    }

    /// Get recommended weight for this resource type.
    pub fn recommended_weight(&self) -> StreamWeight {
        match self {
            Self::Html => 255,       // Highest priority
            Self::Css => 220,        // Very high - blocks render
            Self::JavaScript => 180, // High - often blocks render
            Self::Font => 140,       // Medium-high - needed for FOUT prevention
            Self::Xhr => 120,        // Medium - application data
            Self::Image => 80,       // Medium-low - can load progressively
            Self::Prefetch => 20,    // Low - speculative
            Self::Other => 100,      // Default
        }
    }

    /// Get recommended stream group for this resource type.
    ///
    /// Resources in the same group compete for bandwidth.
    pub fn stream_group(&self) -> u32 {
        match self {
            Self::Html => 1,
            Self::Css => 2,
            Self::JavaScript => 3,
            Self::Font => 4,
            Self::Xhr => 5,
            Self::Image => 6,
            Self::Prefetch => 7,
            Self::Other => 0,
        }
    }
}

/// HTTP/2 priority manager for automatic priority assignment.
#[derive(Debug)]
pub struct PriorityManager {
    /// Custom priority overrides by path
    overrides: HashMap<String, StreamPriority>,
    /// Group root streams
    group_roots: HashMap<u32, u32>,
    /// Statistics
    stats: PriorityStats,
}

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

impl PriorityManager {
    /// Create new priority manager.
    pub fn new() -> Self {
        Self {
            overrides: HashMap::new(),
            group_roots: HashMap::new(),
            stats: PriorityStats::default(),
        }
    }

    /// Add priority override for a path pattern.
    pub fn override_path(&mut self, pattern: impl Into<String>, priority: StreamPriority) {
        self.overrides.insert(pattern.into(), priority);
    }

    /// Get priority for a request.
    pub fn get_priority(&self, path: &str, content_type: Option<&str>) -> StreamPriority {
        self.stats.lookups.fetch_add(1, Ordering::Relaxed);

        // Check overrides first
        if let Some(priority) = self.overrides.get(path) {
            self.stats.overrides_used.fetch_add(1, Ordering::Relaxed);
            return priority.clone();
        }

        // Determine resource type
        let resource_type = content_type
            .map(ResourceType::from_content_type)
            .unwrap_or_else(|| ResourceType::from_path(path));

        let weight = resource_type.recommended_weight();
        let group = resource_type.stream_group();

        // Create priority with group dependency
        let dependency = self
            .group_roots
            .get(&group)
            .map(|&root| StreamDependency {
                stream_id: root,
                exclusive: false,
            })
            .unwrap_or_default();

        StreamPriority { weight, dependency }
    }

    /// Register a stream as a group root.
    pub fn register_group_root(&mut self, group: u32, stream_id: u32) {
        self.group_roots.insert(group, stream_id);
    }

    /// Get statistics.
    pub fn stats(&self) -> &PriorityStats {
        &self.stats
    }
}

/// Priority statistics.
#[derive(Debug, Default)]
pub struct PriorityStats {
    lookups: AtomicU64,
    overrides_used: AtomicU64,
}

impl PriorityStats {
    /// Get total lookups.
    pub fn lookups(&self) -> u64 {
        self.lookups.load(Ordering::Relaxed)
    }

    /// Get override usage count.
    pub fn overrides_used(&self) -> u64 {
        self.overrides_used.load(Ordering::Relaxed)
    }
}

// ============================================================================
// TCP Tuning
// ============================================================================

/// TCP socket tuning configuration.
#[derive(Debug, Clone)]
pub struct TcpConfig {
    /// Enable TCP_NODELAY (disable Nagle's algorithm)
    ///
    /// Recommended for low-latency applications. Sends data immediately
    /// instead of waiting for more data to batch.
    pub nodelay: bool,

    /// Enable TCP_QUICKACK (Linux only)
    ///
    /// Immediately ACK incoming data instead of waiting for delayed ACK.
    /// Reduces latency at cost of slightly more ACK packets.
    pub quickack: bool,

    /// Send buffer size (SO_SNDBUF)
    ///
    /// Larger buffers improve throughput for high-bandwidth connections.
    /// None = use system default.
    pub send_buffer: Option<usize>,

    /// Receive buffer size (SO_RCVBUF)
    ///
    /// Larger buffers improve throughput for high-bandwidth connections.
    /// None = use system default.
    pub recv_buffer: Option<usize>,

    /// Keep-alive configuration
    pub keepalive: Option<TcpKeepalive>,

    /// SO_REUSEADDR - allow rapid rebinding
    pub reuse_addr: bool,

    /// SO_REUSEPORT - allow multiple listeners on same port
    pub reuse_port: bool,

    /// TCP_CORK (Linux) / TCP_NOPUSH (BSD)
    ///
    /// Buffer writes until explicitly uncorked or buffer is full.
    /// Useful for combining headers + body into fewer packets.
    pub cork: bool,

    /// IP_TOS - Type of Service / DSCP value
    ///
    /// Set traffic class for QoS. Common values:
    /// - 0x00: Best effort (default)
    /// - 0x10: Low delay
    /// - 0x08: High throughput
    /// - 0x04: High reliability
    pub tos: Option<u8>,

    /// TCP_DEFER_ACCEPT (Linux) / SO_ACCEPTFILTER (BSD)
    ///
    /// Don't complete accept() until data arrives. Reduces overhead
    /// from connections that never send data.
    pub defer_accept: Option<Duration>,
}

impl Default for TcpConfig {
    fn default() -> Self {
        Self {
            nodelay: true,
            quickack: false, // Disabled by default (Linux-only)
            send_buffer: None,
            recv_buffer: None,
            keepalive: Some(TcpKeepalive::default()),
            reuse_addr: true,
            reuse_port: false,
            cork: false,
            tos: None,
            defer_accept: None,
        }
    }
}

impl TcpConfig {
    /// Create configuration optimized for low latency.
    pub fn low_latency() -> Self {
        Self {
            nodelay: true,
            quickack: true,
            send_buffer: Some(32 * 1024), // 32KB
            recv_buffer: Some(32 * 1024),
            keepalive: Some(TcpKeepalive::aggressive()),
            reuse_addr: true,
            reuse_port: false,
            cork: false,
            tos: Some(0x10), // Low delay
            defer_accept: None,
        }
    }

    /// Create configuration optimized for high throughput.
    pub fn high_throughput() -> Self {
        Self {
            nodelay: false, // Allow Nagle's algorithm for batching
            quickack: false,
            send_buffer: Some(256 * 1024), // 256KB
            recv_buffer: Some(256 * 1024),
            keepalive: Some(TcpKeepalive::default()),
            reuse_addr: true,
            reuse_port: true, // Multi-accept for load distribution
            cork: true,       // Batch writes
            tos: Some(0x08),  // High throughput
            defer_accept: Some(Duration::from_secs(1)),
        }
    }

    /// Apply configuration to a TCP stream.
    #[cfg(unix)]
    pub fn apply(&self, stream: &TcpStream) -> io::Result<()> {
        use libc::{
            IP_TOS, IPPROTO_IP, IPPROTO_TCP, SO_KEEPALIVE, SO_RCVBUF, SO_REUSEADDR, SO_SNDBUF,
            SOL_SOCKET, TCP_NODELAY,
        };

        /// Set an integer socket option, logging a warning on failure.
        fn set_opt(
            fd: std::os::unix::io::RawFd,
            level: libc::c_int,
            option: libc::c_int,
            value: libc::c_int,
            name: &str,
        ) {
            let ret = unsafe {
                libc::setsockopt(
                    fd,
                    level,
                    option,
                    &value as *const _ as *const libc::c_void,
                    std::mem::size_of::<libc::c_int>() as libc::socklen_t,
                )
            };
            if ret != 0 {
                tracing::warn!(
                    option = name,
                    value,
                    error = %io::Error::last_os_error(),
                    "failed to apply TCP socket option"
                );
            }
        }

        let fd = stream.as_raw_fd();

        // TCP_NODELAY
        if self.nodelay {
            set_opt(fd, IPPROTO_TCP, TCP_NODELAY, 1, "TCP_NODELAY");
        }

        // TCP_QUICKACK (Linux only)
        #[cfg(target_os = "linux")]
        if self.quickack {
            const TCP_QUICKACK: libc::c_int = 12;
            set_opt(fd, IPPROTO_TCP, TCP_QUICKACK, 1, "TCP_QUICKACK");
        }

        // SO_SNDBUF
        if let Some(size) = self.send_buffer {
            set_opt(fd, SOL_SOCKET, SO_SNDBUF, size as libc::c_int, "SO_SNDBUF");
        }

        // SO_RCVBUF
        if let Some(size) = self.recv_buffer {
            set_opt(fd, SOL_SOCKET, SO_RCVBUF, size as libc::c_int, "SO_RCVBUF");
        }

        // SO_REUSEADDR
        if self.reuse_addr {
            set_opt(fd, SOL_SOCKET, SO_REUSEADDR, 1, "SO_REUSEADDR");
        }

        // SO_REUSEPORT (Linux)
        #[cfg(target_os = "linux")]
        if self.reuse_port {
            const SO_REUSEPORT: libc::c_int = 15;
            set_opt(fd, SOL_SOCKET, SO_REUSEPORT, 1, "SO_REUSEPORT");
        }

        // TCP_CORK (Linux)
        #[cfg(target_os = "linux")]
        if self.cork {
            const TCP_CORK: libc::c_int = 3;
            set_opt(fd, IPPROTO_TCP, TCP_CORK, 1, "TCP_CORK");
        }

        // IP_TOS - traffic class for QoS
        if let Some(tos) = self.tos {
            set_opt(fd, IPPROTO_IP, IP_TOS, tos as libc::c_int, "IP_TOS");
        }

        // TCP_DEFER_ACCEPT (Linux): don't complete accept() until data arrives
        #[cfg(target_os = "linux")]
        if let Some(timeout) = self.defer_accept {
            // Kernel takes seconds; clamp to at least 1 so a sub-second
            // duration doesn't silently disable the option.
            let secs = timeout.as_secs().max(1) as libc::c_int;
            set_opt(
                fd,
                IPPROTO_TCP,
                libc::TCP_DEFER_ACCEPT,
                secs,
                "TCP_DEFER_ACCEPT",
            );
        }

        // SO_KEEPALIVE
        if let Some(ref keepalive) = self.keepalive {
            set_opt(fd, SOL_SOCKET, SO_KEEPALIVE, 1, "SO_KEEPALIVE");

            // Apply keepalive settings
            keepalive.apply_to_fd(fd);
        }

        TCP_STATS
            .connections_configured
            .fetch_add(1, Ordering::Relaxed);

        Ok(())
    }

    /// Apply configuration (non-Unix stub).
    #[cfg(not(unix))]
    pub fn apply(&self, stream: &TcpStream) -> io::Result<()> {
        stream.set_nodelay(self.nodelay)?;
        TCP_STATS
            .connections_configured
            .fetch_add(1, Ordering::Relaxed);
        Ok(())
    }
}

/// TCP keep-alive configuration.
#[derive(Debug, Clone)]
pub struct TcpKeepalive {
    /// Time before first probe (idle time)
    pub time: Duration,
    /// Interval between probes
    pub interval: Duration,
    /// Number of probes before giving up
    pub retries: u32,
}

impl Default for TcpKeepalive {
    fn default() -> Self {
        Self {
            time: Duration::from_secs(60),
            interval: Duration::from_secs(10),
            retries: 6,
        }
    }
}

impl TcpKeepalive {
    /// Create aggressive keepalive (detect dead connections quickly).
    pub fn aggressive() -> Self {
        Self {
            time: Duration::from_secs(10),
            interval: Duration::from_secs(3),
            retries: 3,
        }
    }

    /// Create relaxed keepalive (fewer probes, longer timeout).
    pub fn relaxed() -> Self {
        Self {
            time: Duration::from_secs(300), // 5 minutes
            interval: Duration::from_secs(30),
            retries: 10,
        }
    }

    /// Apply keepalive settings to file descriptor.
    #[cfg(target_os = "linux")]
    fn apply_to_fd(&self, fd: std::os::unix::io::RawFd) {
        use libc::{IPPROTO_TCP, setsockopt};

        const TCP_KEEPIDLE: libc::c_int = 4;
        const TCP_KEEPINTVL: libc::c_int = 5;
        const TCP_KEEPCNT: libc::c_int = 6;

        unsafe {
            let idle = self.time.as_secs() as libc::c_int;
            setsockopt(
                fd,
                IPPROTO_TCP,
                TCP_KEEPIDLE,
                &idle as *const _ as *const libc::c_void,
                std::mem::size_of::<libc::c_int>() as libc::socklen_t,
            );

            let interval = self.interval.as_secs() as libc::c_int;
            setsockopt(
                fd,
                IPPROTO_TCP,
                TCP_KEEPINTVL,
                &interval as *const _ as *const libc::c_void,
                std::mem::size_of::<libc::c_int>() as libc::socklen_t,
            );

            let retries = self.retries as libc::c_int;
            setsockopt(
                fd,
                IPPROTO_TCP,
                TCP_KEEPCNT,
                &retries as *const _ as *const libc::c_void,
                std::mem::size_of::<libc::c_int>() as libc::socklen_t,
            );
        }
    }

    /// Apply keepalive settings (non-Linux Unix stub).
    #[cfg(all(unix, not(target_os = "linux")))]
    fn apply_to_fd(&self, _fd: std::os::unix::io::RawFd) {
        // Platform-specific implementation would go here for macOS/BSD
    }
}

// ============================================================================
// Connection Keep-Alive Management
// ============================================================================

/// Keep-alive policy for connection management.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum KeepAlivePolicy {
    /// Always keep connections alive until timeout
    Always,
    /// Keep alive only for same-origin requests
    SameOrigin,
    /// Close after each request (HTTP/1.0 behavior)
    Never,
    /// Adaptive based on server load
    #[default]
    Adaptive,
}

/// Connection keep-alive configuration.
#[derive(Debug, Clone)]
pub struct KeepAliveConfig {
    /// Keep-alive policy
    pub policy: KeepAlivePolicy,

    /// Idle timeout before closing
    pub idle_timeout: Duration,

    /// Maximum requests per connection
    pub max_requests: Option<u64>,

    /// Maximum connection age
    pub max_age: Option<Duration>,

    /// Timeout for initial request (after accept)
    pub request_timeout: Duration,

    /// Timeout for reading request headers
    pub header_timeout: Duration,

    /// Timeout for reading request body
    pub body_timeout: Duration,

    /// Adaptive load threshold (connections per worker)
    /// Above this, new connections may be rejected
    pub adaptive_threshold: usize,
}

impl Default for KeepAliveConfig {
    fn default() -> Self {
        Self {
            policy: KeepAlivePolicy::Adaptive,
            idle_timeout: Duration::from_secs(60),
            max_requests: Some(10_000),
            max_age: Some(Duration::from_secs(3600)), // 1 hour
            request_timeout: Duration::from_secs(30),
            header_timeout: Duration::from_secs(10),
            body_timeout: Duration::from_secs(60),
            adaptive_threshold: 1000,
        }
    }
}

impl KeepAliveConfig {
    /// Create config for high-concurrency servers.
    pub fn high_concurrency() -> Self {
        Self {
            policy: KeepAlivePolicy::Adaptive,
            idle_timeout: Duration::from_secs(30),
            max_requests: Some(1_000),
            max_age: Some(Duration::from_secs(300)), // 5 minutes
            request_timeout: Duration::from_secs(15),
            header_timeout: Duration::from_secs(5),
            body_timeout: Duration::from_secs(30),
            adaptive_threshold: 500,
        }
    }

    /// Create config for long-lived connections (websockets, SSE).
    pub fn long_lived() -> Self {
        Self {
            policy: KeepAlivePolicy::Always,
            idle_timeout: Duration::from_secs(300), // 5 minutes
            max_requests: None,
            max_age: None,
            request_timeout: Duration::from_secs(120),
            header_timeout: Duration::from_secs(30),
            body_timeout: Duration::from_secs(300),
            adaptive_threshold: 10_000,
        }
    }
}

/// Connection state tracker.
#[derive(Debug)]
pub struct ConnectionTracker {
    /// Connection creation time
    created_at: Instant,
    /// Last activity time
    last_activity: Instant,
    /// Requests processed
    requests: u64,
    /// Bytes received
    bytes_in: u64,
    /// Bytes sent
    bytes_out: u64,
}

impl ConnectionTracker {
    /// Create new tracker.
    pub fn new() -> Self {
        let now = Instant::now();
        Self {
            created_at: now,
            last_activity: now,
            requests: 0,
            bytes_in: 0,
            bytes_out: 0,
        }
    }

    /// Record activity.
    #[inline]
    pub fn record_activity(&mut self) {
        self.last_activity = Instant::now();
    }

    /// Record request.
    #[inline]
    pub fn record_request(&mut self, bytes_in: usize, bytes_out: usize) {
        self.requests += 1;
        self.bytes_in += bytes_in as u64;
        self.bytes_out += bytes_out as u64;
        self.record_activity();
    }

    /// Get connection age.
    #[inline]
    pub fn age(&self) -> Duration {
        self.created_at.elapsed()
    }

    /// Get idle time.
    #[inline]
    pub fn idle_time(&self) -> Duration {
        self.last_activity.elapsed()
    }

    /// Get request count.
    #[inline]
    pub fn requests(&self) -> u64 {
        self.requests
    }

    /// Check if connection should be kept alive.
    pub fn should_keep_alive(&self, config: &KeepAliveConfig) -> bool {
        // Check idle timeout
        if self.idle_time() > config.idle_timeout {
            return false;
        }

        // Check max requests
        if let Some(max) = config.max_requests
            && self.requests >= max
        {
            return false;
        }

        // Check max age
        if let Some(max_age) = config.max_age
            && self.age() > max_age
        {
            return false;
        }

        true
    }
}

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

/// Adaptive keep-alive manager.
#[derive(Debug)]
pub struct AdaptiveKeepAlive {
    config: KeepAliveConfig,
    active_connections: AtomicUsize,
    stats: KeepAliveStats,
}

impl AdaptiveKeepAlive {
    /// Create new adaptive manager.
    pub fn new(config: KeepAliveConfig) -> Self {
        Self {
            config,
            active_connections: AtomicUsize::new(0),
            stats: KeepAliveStats::default(),
        }
    }

    /// Register new connection.
    pub fn connection_opened(&self) -> bool {
        let count = self.active_connections.fetch_add(1, Ordering::Relaxed);
        self.stats
            .connections_opened
            .fetch_add(1, Ordering::Relaxed);

        if self.config.policy == KeepAlivePolicy::Adaptive {
            // Reject if over threshold
            if count >= self.config.adaptive_threshold {
                self.stats
                    .connections_rejected
                    .fetch_add(1, Ordering::Relaxed);
                self.active_connections.fetch_sub(1, Ordering::Relaxed);
                return false;
            }
        }

        true
    }

    /// Unregister connection.
    pub fn connection_closed(&self) {
        self.active_connections.fetch_sub(1, Ordering::Relaxed);
        self.stats
            .connections_closed
            .fetch_add(1, Ordering::Relaxed);
    }

    /// Check if keep-alive is allowed for current load.
    pub fn allow_keep_alive(&self) -> bool {
        match self.config.policy {
            KeepAlivePolicy::Always => true,
            KeepAlivePolicy::Never => false,
            KeepAlivePolicy::SameOrigin => true, // Caller must verify origin
            KeepAlivePolicy::Adaptive => {
                let count = self.active_connections.load(Ordering::Relaxed);
                count < self.config.adaptive_threshold
            }
        }
    }

    /// Get current load factor (0.0 - 1.0+).
    pub fn load_factor(&self) -> f64 {
        let count = self.active_connections.load(Ordering::Relaxed) as f64;
        count / self.config.adaptive_threshold as f64
    }

    /// Get statistics.
    pub fn stats(&self) -> &KeepAliveStats {
        &self.stats
    }

    /// Get active connection count.
    pub fn active_connections(&self) -> usize {
        self.active_connections.load(Ordering::Relaxed)
    }

    /// Get config.
    pub fn config(&self) -> &KeepAliveConfig {
        &self.config
    }
}

// ============================================================================
// Statistics
// ============================================================================

/// TCP configuration statistics.
#[derive(Debug, Default)]
pub struct TcpStats {
    connections_configured: AtomicU64,
}

impl TcpStats {
    /// Get configured connection count.
    pub fn connections_configured(&self) -> u64 {
        self.connections_configured.load(Ordering::Relaxed)
    }
}

/// Keep-alive statistics.
#[derive(Debug, Default)]
pub struct KeepAliveStats {
    connections_opened: AtomicU64,
    connections_closed: AtomicU64,
    connections_rejected: AtomicU64,
}

impl KeepAliveStats {
    /// Get opened connection count.
    pub fn connections_opened(&self) -> u64 {
        self.connections_opened.load(Ordering::Relaxed)
    }

    /// Get closed connection count.
    pub fn connections_closed(&self) -> u64 {
        self.connections_closed.load(Ordering::Relaxed)
    }

    /// Get rejected connection count.
    pub fn connections_rejected(&self) -> u64 {
        self.connections_rejected.load(Ordering::Relaxed)
    }
}

/// Global TCP statistics.
static TCP_STATS: TcpStats = TcpStats {
    connections_configured: AtomicU64::new(0),
};

/// Get global TCP stats.
pub fn tcp_stats() -> &'static TcpStats {
    &TCP_STATS
}

// ============================================================================
// HTTP/2 Settings
// ============================================================================

/// HTTP/2 connection settings.
#[derive(Debug, Clone)]
pub struct Http2Settings {
    /// Maximum concurrent streams
    pub max_concurrent_streams: u32,

    /// Initial window size (flow control)
    pub initial_window_size: u32,

    /// Maximum frame size
    pub max_frame_size: u32,

    /// Maximum header list size
    pub max_header_list_size: u32,

    /// Enable server push
    pub enable_push: bool,

    /// Connection-level flow control window
    pub connection_window_size: u32,

    /// Enable HPACK dynamic table
    pub header_table_size: u32,
}

impl Default for Http2Settings {
    fn default() -> Self {
        Self {
            max_concurrent_streams: 128,
            initial_window_size: 65535, // 64KB - 1
            max_frame_size: 16384,      // 16KB (minimum required)
            max_header_list_size: 16384,
            enable_push: false, // Server push is generally not recommended
            connection_window_size: 1024 * 1024, // 1MB
            header_table_size: 4096,
        }
    }
}

impl Http2Settings {
    /// Create high-performance settings.
    pub fn high_performance() -> Self {
        Self {
            max_concurrent_streams: 256,
            initial_window_size: 1024 * 1024, // 1MB
            max_frame_size: 65535,            // Max allowed
            max_header_list_size: 65535,
            enable_push: false,
            connection_window_size: 16 * 1024 * 1024, // 16MB
            header_table_size: 65535,
        }
    }

    /// Create low-memory settings.
    pub fn low_memory() -> Self {
        Self {
            max_concurrent_streams: 32,
            initial_window_size: 16384,
            max_frame_size: 16384,
            max_header_list_size: 8192,
            enable_push: false,
            connection_window_size: 65535,
            header_table_size: 4096,
        }
    }
}

// ============================================================================
// Tests
// ============================================================================

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

    #[test]
    fn test_stream_priority_default() {
        let priority = StreamPriority::default();
        assert_eq!(priority.weight, 16);
        assert_eq!(priority.dependency.stream_id, 0);
    }

    #[test]
    fn test_stream_priority_with_weight() {
        let priority = StreamPriority::with_weight(200);
        assert_eq!(priority.weight, 200);
    }

    #[test]
    fn test_resource_type_detection() {
        assert_eq!(ResourceType::from_path("/index.html"), ResourceType::Html);
        assert_eq!(ResourceType::from_path("/style.css"), ResourceType::Css);
        assert_eq!(ResourceType::from_path("/app.js"), ResourceType::JavaScript);
        assert_eq!(ResourceType::from_path("/logo.png"), ResourceType::Image);
        assert_eq!(ResourceType::from_path("/font.woff2"), ResourceType::Font);
    }

    #[test]
    fn test_resource_type_weights() {
        assert!(ResourceType::Html.recommended_weight() > ResourceType::Css.recommended_weight());
        assert!(
            ResourceType::Css.recommended_weight() > ResourceType::JavaScript.recommended_weight()
        );
        assert!(
            ResourceType::JavaScript.recommended_weight()
                > ResourceType::Image.recommended_weight()
        );
    }

    #[test]
    fn test_priority_manager() {
        let mut manager = PriorityManager::new();
        manager.override_path("/api/critical", StreamPriority::with_weight(255));

        let priority = manager.get_priority("/api/critical", None);
        assert_eq!(priority.weight, 255);

        let priority = manager.get_priority("/style.css", None);
        assert_eq!(priority.weight, ResourceType::Css.recommended_weight());
    }

    #[test]
    fn test_tcp_config_default() {
        let config = TcpConfig::default();
        assert!(config.nodelay);
        assert!(config.reuse_addr);
    }

    #[test]
    fn test_tcp_config_low_latency() {
        let config = TcpConfig::low_latency();
        assert!(config.nodelay);
        assert!(config.quickack);
        assert_eq!(config.tos, Some(0x10));
    }

    #[test]
    fn test_tcp_config_high_throughput() {
        let config = TcpConfig::high_throughput();
        assert!(!config.nodelay); // Nagle's allowed for batching
        assert!(config.cork);
        assert!(config.reuse_port);
    }

    #[cfg(target_os = "linux")]
    #[test]
    fn test_tcp_config_apply_sets_tos() {
        use std::net::TcpListener;
        use std::os::unix::io::AsRawFd;

        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        let stream = TcpStream::connect(addr).unwrap();
        let _accepted = listener.accept().unwrap();

        let config = TcpConfig::low_latency();
        config.apply(&stream).unwrap();

        // Read back IP_TOS to verify the preset value was actually applied
        let mut tos: libc::c_int = 0;
        let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
        let ret = unsafe {
            libc::getsockopt(
                stream.as_raw_fd(),
                libc::IPPROTO_IP,
                libc::IP_TOS,
                &mut tos as *mut _ as *mut libc::c_void,
                &mut len,
            )
        };
        assert_eq!(ret, 0);
        assert_eq!(tos, 0x10);
    }

    #[test]
    fn test_keepalive_default() {
        let keepalive = TcpKeepalive::default();
        assert_eq!(keepalive.time, Duration::from_secs(60));
        assert_eq!(keepalive.retries, 6);
    }

    #[test]
    fn test_connection_tracker() {
        let mut tracker = ConnectionTracker::new();
        assert_eq!(tracker.requests(), 0);

        tracker.record_request(100, 200);
        assert_eq!(tracker.requests(), 1);
        assert_eq!(tracker.bytes_in, 100);
        assert_eq!(tracker.bytes_out, 200);
    }

    #[test]
    fn test_connection_tracker_keep_alive() {
        let tracker = ConnectionTracker::new();
        let config = KeepAliveConfig::default();

        assert!(tracker.should_keep_alive(&config));
    }

    #[test]
    fn test_adaptive_keep_alive() {
        let config = KeepAliveConfig {
            adaptive_threshold: 10,
            ..Default::default()
        };
        let manager = AdaptiveKeepAlive::new(config);

        // Open 10 connections
        for _ in 0..10 {
            assert!(manager.connection_opened());
        }

        // 11th should be rejected in adaptive mode
        assert!(!manager.connection_opened());

        // Close one
        manager.connection_closed();

        // Now we can open another
        assert!(manager.connection_opened());
    }

    #[test]
    fn test_adaptive_load_factor() {
        let config = KeepAliveConfig {
            adaptive_threshold: 100,
            ..Default::default()
        };
        let manager = AdaptiveKeepAlive::new(config);

        assert_eq!(manager.load_factor(), 0.0);

        for _ in 0..50 {
            manager.connection_opened();
        }

        assert_eq!(manager.load_factor(), 0.5);
    }

    #[test]
    fn test_http2_settings_default() {
        let settings = Http2Settings::default();
        assert_eq!(settings.max_concurrent_streams, 128);
        assert!(!settings.enable_push);
    }

    #[test]
    fn test_http2_settings_high_performance() {
        let settings = Http2Settings::high_performance();
        assert!(settings.max_concurrent_streams > Http2Settings::default().max_concurrent_streams);
        assert!(settings.initial_window_size > Http2Settings::default().initial_window_size);
    }
}