reqres 1.0.0

A pure Rust async HTTP client library based on Tokio with HTTP/2, connection pooling, proxy, cookie, compression, benchmarks, and comprehensive tests
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
//! # HTTP 客户端
//!
//! 提供 HTTP 客户端功能,支持 HTTP/1.1、HTTP/2、连接池、Cookie、压缩等。
//!
//! ## 使用示例
//!
//! ```rust
//! use reqres::Client;
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // 创建默认客户端
//! let client = Client::new()?;
//!
//! // 使用 Builder 创建自定义客户端
//! let client = Client::builder()
//!     .timeout(std::time::Duration::from_secs(30))
//!     .enable_compression()
//!     .build()?;
//! # Ok(())
//! # }
//! ```

use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use tokio::time::timeout;
use tokio_rustls::{TlsConnector, client::TlsStream};
use rustls::{ClientConfig, RootCertStore};
use rustls::pki_types::ServerName;
use bytes::BytesMut;
use h2::client;
use http::method::Method;
use http::uri::{Scheme, Uri};
use http;

use crate::error::{ReqresError, Result};
use crate::request::Request;
use crate::response::Response;
use crate::pool::{ConnectionPool, PoolKey, PoolConfig, PooledConnection, StreamWrapper};
use crate::cookie::CookieJar;
use crate::compression::Decompressor;
use crate::proxy::Proxy;

/// HTTP 客户端配置
#[derive(Debug, Clone)]
pub struct ClientConfigInternal {
    /// 超时时间
    pub timeout: Duration,
    /// 是否跟随重定向
    pub follow_redirects: bool,
    /// 最大重定向次数
    pub max_redirects: u32,
    /// 默认 User-Agent
    pub user_agent: String,
    /// 是否启用 HTTP/2
    pub http2_enabled: bool,
    /// 是否启用连接池
    pub pooling_enabled: bool,
    /// 是否启用压缩(自动解压响应)
    pub compression_enabled: bool,
    /// 代理配置
    pub proxy: Option<Proxy>,
    /// Cookie 管理(只读,用于发送 Cookie)
    pub cookie_jar: Arc<CookieJar>,
    /// Cookie 管理器(可变,用于存储 Set-Cookie)
    cookie_jar_mut: Arc<std::sync::Mutex<CookieJar>>,
}

impl Default for ClientConfigInternal {
    fn default() -> Self {
        let jar = Arc::new(CookieJar::new());
        ClientConfigInternal {
            timeout: Duration::from_secs(30),
            follow_redirects: true,
            max_redirects: 10,
            user_agent: "reqres/0.6.0".to_string(),
            http2_enabled: true,
            pooling_enabled: true,
            compression_enabled: true,
            proxy: None,
            cookie_jar: jar.clone(),
            cookie_jar_mut: Arc::new(std::sync::Mutex::new((*jar).clone())),
        }
    }
}

/// HTTP 客户端构建器
#[derive(Debug)]
pub struct ClientBuilder {
    config: ClientConfigInternal,
}

impl ClientBuilder {
    /// 创建新的客户端构建器
    pub fn new() -> Self {
        ClientBuilder {
            config: ClientConfigInternal::default(),
        }
    }

    /// 设置超时时间
    pub fn timeout(mut self, duration: Duration) -> Self {
        self.config.timeout = duration;
        self
    }

    /// 设置是否跟随重定向
    pub fn follow_redirects(mut self, follow: bool) -> Self {
        self.config.follow_redirects = follow;
        self
    }

    /// 设置最大重定向次数
    pub fn max_redirects(mut self, max: u32) -> Self {
        self.config.max_redirects = max;
        self
    }

    /// 设置 User-Agent
    pub fn user_agent(mut self, agent: impl Into<String>) -> Self {
        self.config.user_agent = agent.into();
        self
    }

    /// 启用或禁用 HTTP/2
    pub fn http2_prior_knowledge(mut self) -> Self {
        self.config.http2_enabled = true;
        self
    }

    /// 禁用 HTTP/2,仅使用 HTTP/1.1
    pub fn http1_only(mut self) -> Self {
        self.config.http2_enabled = false;
        self
    }

    /// 启用连接池
    pub fn enable_pooling(mut self) -> Self {
        self.config.pooling_enabled = true;
        self
    }

    /// 禁用连接池
    pub fn disable_pooling(mut self) -> Self {
        self.config.pooling_enabled = false;
        self
    }

    /// 启用压缩(自动解压响应)
    pub fn enable_compression(mut self) -> Self {
        self.config.compression_enabled = true;
        self
    }

    /// 禁用压缩
    pub fn disable_compression(mut self) -> Self {
        self.config.compression_enabled = false;
        self
    }

    /// 设置代理
    pub fn proxy(mut self, proxy: Proxy) -> Self {
        self.config.proxy = Some(proxy);
        self
    }

    /// 设置 Cookie 管理器
    pub fn cookie_jar(mut self, jar: CookieJar) -> Self {
        self.config.cookie_jar = Arc::new(jar.clone());
        self.config.cookie_jar_mut = Arc::new(std::sync::Mutex::new(jar));
        self
    }

    /// 构建客户端
    pub fn build(self) -> Result<Client> {
        // 创建 TLS 配置
        let root_store = RootCertStore::from_iter(
            webpki_roots::TLS_SERVER_ROOTS.iter().cloned()
        );

        let mut config_builder = ClientConfig::builder()
            .with_root_certificates(root_store)
            .with_no_client_auth();

        // 如果启用 HTTP/2,配置 ALPN
        if self.config.http2_enabled {
            config_builder.alpn_protocols = vec!["h2".into(), "http/1.1".into()];
        } else {
            config_builder.alpn_protocols = vec!["http/1.1".into()];
        }

        let tls_config = config_builder;
        let tls_connector = TlsConnector::from(Arc::new(tls_config));

        // 创建连接池
        let pool = if self.config.pooling_enabled {
            Some(ConnectionPool::new(PoolConfig::default()))
        } else {
            None
        };

        let cookie_jar_mut = self.config.cookie_jar_mut.clone();

        Ok(Client {
            config: self.config,
            tls_connector,
            pool,
            cookie_jar_mut,
        })
    }
}

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

/// HTTP 客户端
pub struct Client {
    config: ClientConfigInternal,
    tls_connector: TlsConnector,
    pool: Option<ConnectionPool>,
    #[allow(dead_code)]
    cookie_jar_mut: Arc<std::sync::Mutex<CookieJar>>,  // 用于存储 Set-Cookie
}

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

impl Client {
    /// 创建一个新的客户端
    pub fn new() -> Result<Self> {
        ClientBuilder::new().build()
    }

    /// 创建客户端构建器
    pub fn builder() -> ClientBuilder {
        ClientBuilder::new()
    }

    /// 发送 HTTP 请求(支持重定向)
    pub async fn request(&self, request: Request) -> Result<Response> {
        self.request_with_redirects(request, 0).await
    }

    /// 发送请求(内部方法,带重定向计数)
    async fn request_with_redirects(&self, request: Request, redirect_count: u32) -> Result<Response> {
        let original_url = request.url.clone();
        let response = self.execute_request(request).await?;

        // 处理重定向
        if self.config.follow_redirects && response.is_redirect() {
            if redirect_count >= self.config.max_redirects {
                return Err(ReqresError::TooManyRedirects);
            }

            if let Some(location) = response.location() {
                // 处理相对 URL
                let new_url = if location.starts_with("http://") || location.starts_with("https://") {
                    location.clone()
                } else if location.starts_with('/') {
                    // 绝对路径,从原始 URL 提取 scheme 和 host
                    let (is_https, host, port, _) = parse_url(&original_url)?;
                    let scheme = if is_https { "https" } else { "http" };
                    if (is_https && port == 443) || (!is_https && port == 80) {
                        format!("{}://{}{}", scheme, host, location)
                    } else {
                        format!("{}://{}:{}{}", scheme, host, port, location)
                    }
                } else {
                    // 相对路径,需要更复杂的处理
                    return Err(ReqresError::InvalidResponse(format!("Unsupported relative redirect: {}", location)));
                };
                
                let new_request = crate::Request::get(new_url).build()?;
                return Box::pin(self.request_with_redirects(new_request, redirect_count + 1)).await;
            }
        }

        Ok(response)
    }

    /// 执行单次 HTTP 请求
    async fn execute_request(&self, request: Request) -> Result<Response> {
        // 解析 URL
        let (is_https, host, port, path) = parse_url(&request.url)?;
        let pool_key = PoolKey::new(host.clone(), port);

        // 如果启用连接池且不是 HTTP/2,尝试复用连接
        if is_https && self.config.http2_enabled {
            // HTTP/2 模式:不使用连接池(HTTP/2 本身支持多路复用)
            eprintln!("Creating new HTTP/2 connection to {}:{}", host, port);
            let stream = self.create_new_connection(&host, port, is_https).await?;
            
            // 检查是否是 HTTP/2
            if let StreamWrapper::Tls(tls_stream) = &stream {
                let negotiated_protocol = tls_stream.get_ref().1.alpn_protocol();
                let is_h2 = negotiated_protocol.as_deref() == Some(b"h2");
                
                if is_h2 {
                    eprintln!("Using HTTP/2 for {}:{}", host, path);
                    // 提取 tls_stream 的所有权
                    let tls_stream_owned = if let StreamWrapper::Tls(tls) = stream {
                        tls
                    } else {
                        unreachable!("Expected TlsStream")
                    };
                    
                    return self.execute_h2_request(tls_stream_owned, request, host.clone(), path).await;
                }
            }
            
            // 降级到 HTTP/1.1
            return self.execute_h1_request(stream, request, &host).await;
        }

        // HTTP/1.1 模式:尝试使用连接池
        let stream = if let Some(ref pool) = self.pool {
            match pool.acquire(pool_key.clone()).await {
                Some(pooled_conn) => {
                    eprintln!("Reusing pooled connection to {}:{}", host, port);
                    pooled_conn.stream
                }
                None => {
                    eprintln!("Creating new connection to {}:{}", host, port);
                    self.create_new_connection(&host, port, is_https).await?
                }
            }
        } else {
            eprintln!("Creating new connection to {}:{}", host, port);
            self.create_new_connection(&host, port, is_https).await?
        };

        let response = self.execute_h1_request(stream, request, &host).await?;

        // HTTP/1.1 连接可以复用
        if let Some(ref pool) = self.pool {
            let mut pooled_conn = PooledConnection::new(self.create_new_connection(&host, port, is_https).await?);
            pooled_conn.is_active = false;
            pool.release(pool_key, pooled_conn).await;
        }

        Ok(response)
    }

    /// 创建新连接
    async fn create_new_connection(&self, host: &str, port: u16, is_https: bool) -> Result<StreamWrapper> {
        // 建立 TCP 连接
        let addr = format!("{}:{}", host, port);
        let tcp_stream = timeout(
            self.config.timeout,
            TcpStream::connect(&addr)
        ).await.map_err(|_| ReqresError::Timeout)??;

        // 如果是 HTTPS,进行 TLS 握手
        if is_https {
            let server_name = ServerName::try_from(host.to_string())
                .map_err(|e| ReqresError::Tls(format!("Invalid server name: {}", e)))?;

            let tls_stream = timeout(
                self.config.timeout,
                self.tls_connector.connect(server_name, tcp_stream)
            ).await.map_err(|_| ReqresError::Timeout)??;

            Ok(StreamWrapper::Tls(tls_stream))
        } else {
            Ok(StreamWrapper::Plain(tcp_stream))
        }
    }

    /// 使用 HTTP/2 执行请求
    async fn execute_h2_request(
        &self,
        tls_stream: TlsStream<TcpStream>,
        request: Request,
        host: String,
        path: String,
    ) -> Result<Response> {
        // 构建 h2 客户端
        let (mut h2_client, conn) = client::handshake(tls_stream).await
            .map_err(|e| ReqresError::Connection(format!("HTTP/2 handshake failed: {}", e)))?;

        // 在后台驱动连接
        let _conn_task = tokio::spawn(async move {
            if let Err(e) = conn.await {
                eprintln!("HTTP/2 connection error: {:?}", e);
            }
        });

        // 构建 HTTP/2 请求
        let uri = Uri::builder()
            .scheme(Scheme::HTTPS)
            .authority(host.clone())
            .path_and_query(&path)
            .build()
            .map_err(|e| ReqresError::InvalidUrl(format!("Invalid URI: {}", e)))?;

        let method = match request.method {
            crate::request::Method::GET => Method::GET,
            crate::request::Method::POST => Method::POST,
            crate::request::Method::PUT => Method::PUT,
            crate::request::Method::DELETE => Method::DELETE,
            crate::request::Method::HEAD => Method::HEAD,
            crate::request::Method::OPTIONS => Method::OPTIONS,
            crate::request::Method::PATCH => Method::PATCH,
        };

        let mut h2_req = http::Request::builder()
            .method(method)
            .uri(uri)
            .version(http::Version::HTTP_2);

        // 添加请求头
        for (key, value) in &request.headers {
            let key_lower = key.to_lowercase();
            // 跳过会在后面添加的头
            if key_lower != "host" && key_lower != "cookie" && key_lower != "accept-encoding" {
                h2_req = h2_req.header(key, value);
            }
        }

        // 添加 Cookie 头(从可变 jar 读取,包含新存储的 cookie)
        if let Ok(jar) = self.cookie_jar_mut.lock() {
            if !jar.is_empty() {
                h2_req = h2_req.header("Cookie", jar.build_cookie_header());
            }
        }

        // 添加 Accept-Encoding 头(启用压缩)
        if self.config.compression_enabled {
            h2_req = h2_req.header("Accept-Encoding", "gzip, deflate, br");
        }

        let h2_req = h2_req.body(())?;

        // 发送请求
        let (response_future, mut send_stream) = h2_client.send_request(h2_req, false)
            .map_err(|e| ReqresError::Connection(format!("HTTP/2 send request failed: {}", e)))?;

        // 如果有请求体,发送数据
        if !request.body.is_empty() {
            let body_data = request.body.as_bytes();
            send_stream.send_data(body_data.into(), true)
                .map_err(|e| ReqresError::Connection(format!("HTTP/2 send data failed: {}", e)))?;
        } else {
            // 如果没有请求体,关闭发送流
            send_stream.send_data(bytes::Bytes::new(), true)
                .map_err(|e| ReqresError::Connection(format!("HTTP/2 close stream failed: {}", e)))?;
        }

        // 等待响应
        let http2_response = response_future.await
            .map_err(|e| ReqresError::Connection(format!("HTTP/2 response failed: {}", e)))?;

        // 获取响应头和状态信息
        let headers = http2_response.headers().clone();
        let status = http2_response.status().as_u16();
        let status_text = http2_response.status().canonical_reason().unwrap_or("Unknown").to_string();

        // 读取响应体
        let mut response_body = http2_response.into_body();
        let mut buffer = BytesMut::with_capacity(8192);
        loop {
            match response_body.data().await {
                Some(Ok(chunk)) => {
                    buffer.extend_from_slice(&chunk);
                    let _ = response_body.flow_control().release_capacity(chunk.len());
                }
                Some(Err(e)) => {
                    return Err(ReqresError::Connection(format!("HTTP/2 read body failed: {}", e)));
                }
                None => break,
            }
        }

        // 构建响应
        let mut response_headers = std::collections::HashMap::new();
        for (key, value) in headers.iter() {
            if let Ok(value_str) = value.to_str() {
                response_headers.insert(key.as_str().to_string(), value_str.to_string());
            }
        }

        // 处理 Cookie:存储响应中的 Set-Cookie
        if let Ok(mut jar) = self.cookie_jar_mut.lock() {
            jar.parse_from_headers(&response_headers);
        }

        // 处理压缩:自动解压响应
        let mut body = buffer.freeze();
        if self.config.compression_enabled {
            if let Some(content_encoding) = response_headers.get("content-encoding") {
                if let Ok(decompressed) = Decompressor::auto_decompress(
                    body.clone(),
                    Some(content_encoding)
                ) {
                    body = decompressed;
                    // 更新响应头:移除 Content-Encoding
                    response_headers.remove("content-encoding");
                }
            }
        }

        Ok(Response {
            version: "HTTP/2.0".to_string(),
            status,
            status_text,
            headers: response_headers,
            body,
        })
    }

    /// 使用 HTTP/1.1 执行请求
    async fn execute_h1_request(
        &self,
        stream: StreamWrapper,
        request: Request,
        host: &str,
    ) -> Result<Response> {
        // 构建 HTTP 请求(从可变 jar 读取,包含新存储的 cookie)
        let cookie_jar = self.cookie_jar_mut.lock().unwrap();
        let http_request = build_http_request(
            &request,
            &host,
            &cookie_jar,
            self.config.compression_enabled,
        );
        drop(cookie_jar);

        // 发送请求和读取响应
        let buffer = match stream {
            #[cfg(test)]
            StreamWrapper::Dummy => unreachable!("Dummy stream should not be used in production"),
            StreamWrapper::Plain(mut s) => {
                timeout(
                    self.config.timeout,
                    s.write_all(&http_request)
                ).await.map_err(|_| ReqresError::Timeout)??;

                let mut buffer = BytesMut::with_capacity(8192);
                let mut temp_buf = vec![0u8; 4096];

                loop {
                    match timeout(
                        self.config.timeout,
                        s.read(&mut temp_buf)
                    ).await {
                        Ok(Ok(0)) => break,
                        Ok(Ok(n)) => buffer.extend_from_slice(&temp_buf[..n]),
                        Ok(Err(e)) => return Err(e.into()),
                        Err(_) => return Err(ReqresError::Timeout),
                    }
                }
                buffer
            }
            StreamWrapper::Tls(mut s) => {
                timeout(
                    self.config.timeout,
                    s.write_all(&http_request)
                ).await.map_err(|_| ReqresError::Timeout)??;

                let mut buffer = BytesMut::with_capacity(8192);
                let mut temp_buf = vec![0u8; 4096];

                loop {
                    match timeout(
                        self.config.timeout,
                        s.read(&mut temp_buf)
                    ).await {
                        Ok(Ok(0)) => break,
                        Ok(Ok(n)) => buffer.extend_from_slice(&temp_buf[..n]),
                        Ok(Err(e)) => {
                            if is_tls_close_notify_error(&e) {
                                break;
                            }
                            return Err(e.into());
                        }
                        Err(_) => return Err(ReqresError::Timeout),
                    }
                }
                buffer
            }
        };

        // 解析响应
        let response_str = String::from_utf8_lossy(&buffer).to_string();
        let buffer_bytes = buffer.freeze();
        let mut response = parse_http_response(&response_str, buffer_bytes)?;

        // 处理 Cookie:存储响应中的 Set-Cookie
        if let Ok(mut jar) = self.cookie_jar_mut.lock() {
            jar.parse_from_headers(&response.headers);
        }

        // 处理压缩:自动解压响应
        if self.config.compression_enabled {
            if let Some(content_encoding) = response.headers.get("content-encoding") {
                if let Ok(decompressed) = Decompressor::auto_decompress(
                    response.body.clone(),
                    Some(content_encoding)
                ) {
                    response.body = decompressed;
                    // 更新响应头:移除 Content-Encoding
                    response.headers.remove("content-encoding");
                    // 更新 Content-Length
                    if let Some(_) = response.headers.remove("content-length") {
                        response.headers.insert(
                            "content-length".to_string(),
                            response.body.len().to_string(),
                        );
                    }
                }
            }
        }

        Ok(response)
    }

    /// 发送 GET 请求
    pub async fn get(&self, url: impl Into<String>) -> Result<Response> {
        let request = Request::get(url).build()?;
        self.request(request).await
    }

    /// 发送 POST 请求
    pub async fn post(&self, url: impl Into<String>, body: impl Into<String>) -> Result<Response> {
        let request = Request::post(url)
            .content_type("text/plain")
            .body(body)
            .build()?;
        self.request(request).await
    }

    /// 发送 JSON POST 请求
    pub async fn post_json(&self, url: impl Into<String>, json: impl serde::Serialize) -> Result<Response> {
        let request = Request::post(url)
            .json(json)?
            .build()?;
        self.request(request).await
    }

    /// 发送 PUT 请求
    pub async fn put(&self, url: impl Into<String>, body: impl Into<String>) -> Result<Response> {
        let request = Request::put(url)
            .content_type("text/plain")
            .body(body)
            .build()?;
        self.request(request).await
    }

    /// 发送 DELETE 请求
    pub async fn delete(&self, url: impl Into<String>) -> Result<Response> {
        let request = Request::delete(url).build()?;
        self.request(request).await
    }

    /// 获取连接池统计信息
    pub async fn pool_stats(&self) -> Option<crate::pool::PoolStats> {
        if let Some(ref pool) = self.pool {
            Some(pool.stats().await)
        } else {
            None
        }
    }

    /// 获取连接池命中率
    pub async fn pool_hit_rate(&self) -> Option<f64> {
        if let Some(ref pool) = self.pool {
            Some(pool.hit_rate().await)
        } else {
            None
        }
    }

    /// 清理所有过期连接
    pub async fn cleanup_pool(&self) {
        if let Some(ref pool) = self.pool {
            pool.cleanup_all().await;
        }
    }
}

impl Default for Client {
    fn default() -> Self {
        Self::new().expect("Failed to create default client")
    }
}

/// 检查是否是 TLS close_notify 错误
fn is_tls_close_notify_error(error: &std::io::Error) -> bool {
    let error_msg = error.to_string().to_lowercase();
    error_msg.contains("close_notify") ||
    error_msg.contains("unexpected eof") ||
    error_msg.contains("peer closed")
}

/// 解析 URL,返回 (is_https, host, port, path)
fn parse_url(url: &str) -> Result<(bool, String, u16, String)> {
    let (is_https, rest) = if url.starts_with("https://") {
        (true, &url[8..])
    } else if url.starts_with("http://") {
        (false, &url[7..])
    } else {
        return Err(ReqresError::InvalidUrl(
            "URL must start with http:// or https://".to_string(),
        ));
    };

    // 分离 host:port 和 path
    let (host_port, path) = if let Some(slash_pos) = rest.find('/') {
        let (hp, p) = rest.split_at(slash_pos);
        (hp, p.to_string())
    } else {
        (rest, "/".to_string())
    };

    // 解析 host 和 port
    let (host, port) = if let Some(colon_pos) = host_port.find(':') {
        let (h, p) = host_port.split_at(colon_pos);
        let port_num: u16 = p[1..].parse().map_err(|_| {
            ReqresError::InvalidUrl(format!("Invalid port in URL: {}", url))
        })?;
        (h.to_string(), port_num)
    } else {
        let default_port = if is_https { 443 } else { 80 };
        (host_port.to_string(), default_port)
    };

    Ok((is_https, host, port, path))
}

/// 构建 HTTP 请求字符串
fn build_http_request(
    request: &Request,
    host: &str,
    cookie_jar: &CookieJar,
    compression_enabled: bool,
) -> Vec<u8> {
    // 解析 URL 获取 path
    let (_, _, _, path) = parse_url(&request.url).unwrap_or((false, host.to_string(), 80, "/".to_string()));

    let mut http_request = format!(
        "{} {} HTTP/1.1\r\n",
        request.method.as_str(),
        path
    );

    // 添加 Host 头
    http_request.push_str(&format!("Host: {}\r\n", host));

    // 添加 Cookie 头
    if !cookie_jar.is_empty() {
        http_request.push_str(&format!("Cookie: {}\r\n", cookie_jar.build_cookie_header()));
    }

    // 添加 Accept-Encoding 头(启用压缩)
    if compression_enabled {
        http_request.push_str("Accept-Encoding: gzip, deflate, br\r\n");
    }

    // 添加其他请求头
    for (key, value) in &request.headers {
        let key_lower = key.to_lowercase();
        if key_lower != "host" && key_lower != "connection" &&
           key_lower != "cookie" && key_lower != "accept-encoding" {
            http_request.push_str(&format!("{}: {}\r\n", key, value));
        }
    }

    // 添加 Connection: close
    http_request.push_str("Connection: close\r\n");

    // 空行
    http_request.push_str("\r\n");

    // 合并请求体
    let mut result = http_request.into_bytes();
    result.extend_from_slice(&request.body.as_bytes());

    result
}

/// 解析 HTTP 响应
fn parse_http_response(response_str: &str, full_buffer: bytes::Bytes) -> Result<Response> {
    let mut lines = response_str.lines();

    // 解析状态行
    let status_line = lines.next().ok_or("Empty response")?;
    let parts: Vec<&str> = status_line.split_whitespace().collect();
    
    if parts.len() < 3 {
        return Err(ReqresError::InvalidResponse(
            "Invalid status line".to_string(),
        ));
    }

    let version = parts[0].to_string();
    let status: u16 = parts[1].parse().map_err(|_| {
        ReqresError::InvalidResponse(format!("Invalid status code: {}", parts[1]))
    })?;
    let status_text = parts[2..].join(" ");

    // 解析响应头,找到 body 的起始位置
    let mut headers = std::collections::HashMap::new();
    let mut header_end_pos = 0;
    let mut in_headers = true;

    for (idx, line) in response_str.lines().enumerate() {
        if in_headers {
            if line.is_empty() {
                // 计算 body 在原始 buffer 中的起始位置
                let lines_before: String = response_str.lines().take(idx + 1).collect::<Vec<_>>().join("\n");
                header_end_pos = lines_before.len() + 1; // +1 for the newline
                in_headers = false;
            } else if idx > 0 { // 跳过状态行
                if let Some(colon_pos) = line.find(':') {
                    let (key, value) = line.split_at(colon_pos);
                    let value = value[1..].trim();
                    headers.insert(key.trim().to_string(), value.to_string());
                }
            }
        }
    }

    // 提取 body
    let body = if header_end_pos > 0 && header_end_pos < full_buffer.len() {
        full_buffer.slice(header_end_pos..)
    } else {
        bytes::Bytes::new()
    };

    Ok(Response {
        version,
        status,
        status_text,
        headers,
        body,
    })
}

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

    // ClientConfigInternal tests
    #[test]
    fn test_config_default() {
        let config = ClientConfigInternal::default();
        assert_eq!(config.timeout, Duration::from_secs(30));
        assert_eq!(config.follow_redirects, true);
        assert_eq!(config.max_redirects, 10);
        assert_eq!(config.user_agent, "reqres/0.6.0");
        assert_eq!(config.http2_enabled, true);
        assert_eq!(config.pooling_enabled, true);
        assert_eq!(config.compression_enabled, true);
        assert!(config.proxy.is_none());
    }

    // ClientBuilder tests
    #[test]
    fn test_builder_new() {
        let builder = ClientBuilder::new();
        assert_eq!(builder.config.timeout, Duration::from_secs(30));
        assert_eq!(builder.config.follow_redirects, true);
    }

    #[test]
    fn test_builder_default() {
        let builder = ClientBuilder::default();
        assert_eq!(builder.config.timeout, Duration::from_secs(30));
    }

    #[test]
    fn test_builder_timeout() {
        let builder = ClientBuilder::new().timeout(Duration::from_secs(60));
        assert_eq!(builder.config.timeout, Duration::from_secs(60));
    }

    #[test]
    fn test_builder_follow_redirects() {
        let builder = ClientBuilder::new().follow_redirects(false);
        assert_eq!(builder.config.follow_redirects, false);
    }

    #[test]
    fn test_builder_max_redirects() {
        let builder = ClientBuilder::new().max_redirects(5);
        assert_eq!(builder.config.max_redirects, 5);
    }

    #[test]
    fn test_builder_user_agent() {
        let builder = ClientBuilder::new().user_agent("MyApp/1.0");
        assert_eq!(builder.config.user_agent, "MyApp/1.0");
    }

    #[test]
    fn test_builder_http2_prior_knowledge() {
        let builder = ClientBuilder::new().http2_prior_knowledge();
        assert_eq!(builder.config.http2_enabled, true);
    }

    #[test]
    fn test_builder_http1_only() {
        let builder = ClientBuilder::new().http1_only();
        assert_eq!(builder.config.http2_enabled, false);
    }

    #[test]
    fn test_builder_enable_pooling() {
        let builder = ClientBuilder::new().enable_pooling();
        assert_eq!(builder.config.pooling_enabled, true);
    }

    #[test]
    fn test_builder_disable_pooling() {
        let builder = ClientBuilder::new().disable_pooling();
        assert_eq!(builder.config.pooling_enabled, false);
    }

    #[test]
    fn test_builder_enable_compression() {
        let builder = ClientBuilder::new().enable_compression();
        assert_eq!(builder.config.compression_enabled, true);
    }

    #[test]
    fn test_builder_disable_compression() {
        let builder = ClientBuilder::new().disable_compression();
        assert_eq!(builder.config.compression_enabled, false);
    }

    #[test]
    fn test_builder_cookie_jar() {
        let jar = CookieJar::new();
        let builder = ClientBuilder::new().cookie_jar(jar);
        // Cookie jars should be set
        assert_eq!(Arc::strong_count(&builder.config.cookie_jar), 1);
    }

    #[test]
    fn test_builder_chain() {
        let builder = ClientBuilder::new()
            .timeout(Duration::from_secs(60))
            .follow_redirects(false)
            .max_redirects(5)
            .user_agent("Test/1.0")
            .http2_prior_knowledge()
            .enable_pooling()
            .enable_compression();

        assert_eq!(builder.config.timeout, Duration::from_secs(60));
        assert_eq!(builder.config.follow_redirects, false);
        assert_eq!(builder.config.max_redirects, 5);
        assert_eq!(builder.config.user_agent, "Test/1.0");
        assert_eq!(builder.config.http2_enabled, true);
        assert_eq!(builder.config.pooling_enabled, true);
        assert_eq!(builder.config.compression_enabled, true);
    }

    #[test]
    fn test_builder_build() {
        let builder = ClientBuilder::new()
            .timeout(Duration::from_secs(60))
            .http1_only()
            .disable_pooling()
            .disable_compression();

        let client = builder.build();
        assert!(client.is_ok());
        let client = client.unwrap();

        // Check config is set correctly
        assert_eq!(client.config.timeout, Duration::from_secs(60));
        assert_eq!(client.config.http2_enabled, false);
        assert_eq!(client.config.pooling_enabled, false);
        assert_eq!(client.config.compression_enabled, false);
    }

    // Client tests
    #[test]
    fn test_client_new() {
        let client = Client::new();
        assert!(client.is_ok());
        let client = client.unwrap();
        assert_eq!(client.config.timeout, Duration::from_secs(30));
        assert_eq!(client.config.http2_enabled, true);
    }

    #[test]
    fn test_client_builder() {
        let builder = Client::builder();
        let client = builder.timeout(Duration::from_secs(45)).build();
        assert!(client.is_ok());
        let client = client.unwrap();
        assert_eq!(client.config.timeout, Duration::from_secs(45));
    }

    // URL parsing tests
    #[test]
    fn test_parse_url_valid() {
        let result = parse_url("https://example.com/path?query=value");
        assert!(result.is_ok());
        let (is_https, host, port, path) = result.unwrap();
        assert_eq!(is_https, true);
        assert_eq!(host, "example.com");
        assert_eq!(port, 443);
        assert_eq!(path, "/path?query=value");
    }

    #[test]
    fn test_parse_url_http() {
        let result = parse_url("http://example.com/test");
        assert!(result.is_ok());
        let (is_https, host, port, path) = result.unwrap();
        assert_eq!(is_https, false);
        assert_eq!(host, "example.com");
        assert_eq!(port, 80);
        assert_eq!(path, "/test");
    }

    #[test]
    fn test_parse_url_with_port() {
        let result = parse_url("https://example.com:8443/api");
        assert!(result.is_ok());
        let (is_https, host, port, path) = result.unwrap();
        assert_eq!(is_https, true);
        assert_eq!(host, "example.com");
        assert_eq!(port, 8443);
        assert_eq!(path, "/api");
    }

    #[test]
    fn test_parse_url_invalid_scheme() {
        let result = parse_url("ftp://example.com/test");
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_url_invalid_format() {
        let result = parse_url("not a url");
        assert!(result.is_err());
    }
}