open-lark 0.14.0

Enterprise-grade Lark/Feishu Open API SDK with comprehensive Chinese documentation and advanced error handling
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
//! HTTP客户端性能优化和基准测试模块
//!
//! 本模块提供:
//! 1. HTTP客户端配置优化建议
//! 2. 性能基准测试工具
//! 3. 连接池管理
//! 4. 请求性能分析
//! 5. 内存分配优化

pub mod local;

// 重新导出主要类型
pub use local::LocalPerformanceTester;

use reqwest::{Client, ClientBuilder};
use serde::{Deserialize, Serialize};
use std::time::{Duration, Instant};
use tracing::{info, instrument, warn};

/// HTTP客户端性能配置优化
#[derive(Debug, Clone)]
pub struct OptimizedHttpConfig {
    /// 连接池最大空闲连接数 (默认: 90)
    pub pool_max_idle_per_host: usize,
    /// 连接池空闲连接超时 (默认: 90秒)
    pub pool_idle_timeout: Duration,
    /// TCP连接超时 (默认: 10秒)
    pub connect_timeout: Duration,
    /// 请求总超时 (默认: 30秒)
    pub request_timeout: Duration,
    /// 启用HTTP/2 (默认: true)
    pub http2_prior_knowledge: bool,
    /// HTTP/2自适应窗口 (默认: true)
    pub http2_adaptive_window: bool,
    /// 启用gzip压缩 (默认: true)
    pub gzip: bool,
    /// 启用brotli压缩 (默认: true)
    pub brotli: bool,
    /// User-Agent字符串
    pub user_agent: String,
}

impl Default for OptimizedHttpConfig {
    fn default() -> Self {
        Self {
            pool_max_idle_per_host: 90,
            pool_idle_timeout: Duration::from_secs(90),
            connect_timeout: Duration::from_secs(10),
            request_timeout: Duration::from_secs(30),
            http2_prior_knowledge: true,
            http2_adaptive_window: true,
            gzip: true,
            brotli: true,
            user_agent: format!("open-lark/{}", env!("CARGO_PKG_VERSION")),
        }
    }
}

impl OptimizedHttpConfig {
    /// 创建生产环境优化配置
    pub fn production() -> Self {
        Self {
            pool_max_idle_per_host: 100,
            pool_idle_timeout: Duration::from_secs(120),
            connect_timeout: Duration::from_secs(5),
            request_timeout: Duration::from_secs(30),
            http2_prior_knowledge: true,
            http2_adaptive_window: true,
            gzip: true,
            brotli: true,
            user_agent: format!("open-lark/{}", env!("CARGO_PKG_VERSION")),
        }
    }

    /// 创建高吞吐量配置
    pub fn high_throughput() -> Self {
        Self {
            pool_max_idle_per_host: 200,
            pool_idle_timeout: Duration::from_secs(180),
            connect_timeout: Duration::from_secs(3),
            request_timeout: Duration::from_secs(15),
            http2_prior_knowledge: true,
            http2_adaptive_window: true,
            gzip: true,
            brotli: true,
            user_agent: format!("open-lark/{}", env!("CARGO_PKG_VERSION")),
        }
    }

    /// 创建低延迟配置
    pub fn low_latency() -> Self {
        Self {
            pool_max_idle_per_host: 50,
            pool_idle_timeout: Duration::from_secs(60),
            connect_timeout: Duration::from_secs(2),
            request_timeout: Duration::from_secs(10),
            http2_prior_knowledge: true,
            http2_adaptive_window: true,
            gzip: false, // 减少CPU开销
            brotli: false,
            user_agent: format!("open-lark/{}", env!("CARGO_PKG_VERSION")),
        }
    }

    /// 根据配置构建优化的HTTP客户端
    pub fn build_client(&self) -> Result<Client, reqwest::Error> {
        let mut builder = ClientBuilder::new()
            .pool_max_idle_per_host(self.pool_max_idle_per_host)
            .pool_idle_timeout(self.pool_idle_timeout)
            .connect_timeout(self.connect_timeout)
            .timeout(self.request_timeout)
            .user_agent(&self.user_agent);

        // 注意: reqwest 0.12 中某些HTTP/2配置方法可能不可用
        // 我们使用可用的配置方法

        // 注意: reqwest 0.12 默认启用gzip和brotli
        // 如果需要禁用,可以使用 no_gzip() 和 no_brotli()
        if !self.gzip {
            builder = builder.no_gzip();
        }

        if !self.brotli {
            builder = builder.no_brotli();
        }

        builder.build()
    }
}

/// 性能基准测试指标
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PerformanceMetrics {
    /// 测试名称
    pub test_name: String,
    /// 总请求数
    pub total_requests: u64,
    /// 成功请求数
    pub successful_requests: u64,
    /// 失败请求数
    pub failed_requests: u64,
    /// 平均响应时间 (毫秒)
    pub avg_response_time_ms: f64,
    /// 95th百分位响应时间 (毫秒)
    pub p95_response_time_ms: f64,
    /// 99th百分位响应时间 (毫秒)
    pub p99_response_time_ms: f64,
    /// 最小响应时间 (毫秒)
    pub min_response_time_ms: f64,
    /// 最大响应时间 (毫秒)
    pub max_response_time_ms: f64,
    /// 每秒请求数 (RPS)
    pub requests_per_second: f64,
    /// 测试持续时间 (秒)
    pub duration_seconds: f64,
    /// 字节传输速率 (KB/s)
    pub throughput_kbps: f64,
    /// 错误率 (%)
    pub error_rate: f64,
}

impl PerformanceMetrics {
    /// 从响应时间列表计算性能指标
    pub fn calculate(
        test_name: String,
        response_times_ms: Vec<f64>,
        total_duration: Duration,
        total_bytes: u64,
    ) -> Self {
        let total_requests = response_times_ms.len() as u64;
        let failed_requests = response_times_ms.iter().filter(|&&t| t < 0.0).count() as u64;
        let successful_requests = total_requests - failed_requests;

        let mut sorted_times: Vec<f64> = response_times_ms
            .iter()
            .filter(|&&t| t >= 0.0)
            .copied()
            .collect();
        sorted_times.sort_by(|a, b| a.partial_cmp(b).unwrap());

        let avg_response_time_ms = if sorted_times.is_empty() {
            0.0
        } else {
            sorted_times.iter().sum::<f64>() / sorted_times.len() as f64
        };

        let p95_response_time_ms = if sorted_times.is_empty() {
            0.0
        } else {
            let index = ((sorted_times.len() as f64) * 0.95) as usize;
            sorted_times
                .get(index.saturating_sub(1))
                .copied()
                .unwrap_or(0.0)
        };

        let p99_response_time_ms = if sorted_times.is_empty() {
            0.0
        } else {
            let index = ((sorted_times.len() as f64) * 0.99) as usize;
            sorted_times
                .get(index.saturating_sub(1))
                .copied()
                .unwrap_or(0.0)
        };

        let min_response_time_ms = sorted_times.first().copied().unwrap_or(0.0);
        let max_response_time_ms = sorted_times.last().copied().unwrap_or(0.0);

        let duration_seconds = total_duration.as_secs_f64();
        let requests_per_second = if duration_seconds > 0.0 {
            total_requests as f64 / duration_seconds
        } else {
            0.0
        };

        let throughput_kbps = if duration_seconds > 0.0 {
            (total_bytes as f64) / (duration_seconds * 1024.0)
        } else {
            0.0
        };

        let error_rate = if total_requests > 0 {
            (failed_requests as f64 / total_requests as f64) * 100.0
        } else {
            0.0
        };

        Self {
            test_name,
            total_requests,
            successful_requests,
            failed_requests,
            avg_response_time_ms,
            p95_response_time_ms,
            p99_response_time_ms,
            min_response_time_ms,
            max_response_time_ms,
            requests_per_second,
            duration_seconds,
            throughput_kbps,
            error_rate,
        }
    }

    /// 打印性能报告
    pub fn print_report(&self) {
        info!("╔══════════════════════════════════════════════════════════╗");
        info!("║                    性能测试报告                          ║");
        info!("╠══════════════════════════════════════════════════════════╣");
        info!("║ 测试名称: {:<45} ║", self.test_name);
        info!("║ 总请求数: {:<45} ║", self.total_requests);
        info!("║ 成功请求: {:<45} ║", self.successful_requests);
        info!("║ 失败请求: {:<45} ║", self.failed_requests);
        info!("║ 错误率:   {:<43.2}% ║", self.error_rate);
        info!("╠══════════════════════════════════════════════════════════╣");
        info!("║ 平均响应时间: {:<39.2}ms ║", self.avg_response_time_ms);
        info!("║ 95th百分位:   {:<39.2}ms ║", self.p95_response_time_ms);
        info!("║ 99th百分位:   {:<39.2}ms ║", self.p99_response_time_ms);
        info!("║ 最小响应时间: {:<39.2}ms ║", self.min_response_time_ms);
        info!("║ 最大响应时间: {:<39.2}ms ║", self.max_response_time_ms);
        info!("╠══════════════════════════════════════════════════════════╣");
        info!("║ 吞吐量:       {:<39.2}RPS ║", self.requests_per_second);
        info!("║ 数据传输率:   {:<37.2}KB/s ║", self.throughput_kbps);
        info!("║ 测试时长:     {:<39.2}s ║", self.duration_seconds);
        info!("╚══════════════════════════════════════════════════════════╝");
    }
}

/// 基准测试配置
#[derive(Debug, Clone)]
pub struct BenchmarkConfig {
    /// 并发连接数
    pub concurrent_connections: usize,
    /// 每个连接的请求数
    pub requests_per_connection: usize,
    /// 预热请求数
    pub warmup_requests: usize,
    /// 测试URL
    pub target_url: String,
    /// 请求头
    pub headers: std::collections::HashMap<String, String>,
}

impl Default for BenchmarkConfig {
    fn default() -> Self {
        Self {
            concurrent_connections: 10,
            requests_per_connection: 100,
            warmup_requests: 10,
            target_url: "https://httpbin.org/json".to_string(),
            headers: std::collections::HashMap::new(),
        }
    }
}

/// HTTP客户端基准测试器
pub struct HttpBenchmark {
    client: Client,
    config: BenchmarkConfig,
}

impl HttpBenchmark {
    /// 创建新的基准测试器
    pub fn new(client: Client, config: BenchmarkConfig) -> Self {
        Self { client, config }
    }

    /// 执行基准测试
    #[instrument(skip(self), fields(
        concurrent_connections = self.config.concurrent_connections,
        requests_per_connection = self.config.requests_per_connection,
        target_url = %self.config.target_url
    ))]
    pub async fn run_benchmark(
        &self,
    ) -> Result<PerformanceMetrics, Box<dyn std::error::Error + Send + Sync>> {
        info!("开始HTTP客户端基准测试...");
        info!("目标URL: {}", self.config.target_url);
        info!("并发连接数: {}", self.config.concurrent_connections);
        info!("每连接请求数: {}", self.config.requests_per_connection);

        // 预热
        if self.config.warmup_requests > 0 {
            info!("预热阶段: {} 个请求", self.config.warmup_requests);
            for _ in 0..self.config.warmup_requests {
                let _ = self.make_request().await;
            }
            info!("预热完成");
        }

        let start_time = Instant::now();
        let mut tasks = Vec::new();
        let mut total_bytes = 0u64;

        // 创建并发任务
        for connection_id in 0..self.config.concurrent_connections {
            let client = self.client.clone();
            let config = self.config.clone();

            let task = tokio::spawn(async move {
                let mut response_times = Vec::new();
                let mut bytes_transferred = 0u64;

                for request_id in 0..config.requests_per_connection {
                    let request_start = Instant::now();

                    match Self::make_single_request(&client, &config.target_url, &config.headers)
                        .await
                    {
                        Ok(bytes) => {
                            let elapsed = request_start.elapsed().as_secs_f64() * 1000.0;
                            response_times.push(elapsed);
                            bytes_transferred += bytes;
                        }
                        Err(e) => {
                            warn!("连接 {} 请求 {} 失败: {}", connection_id, request_id, e);
                            response_times.push(-1.0); // 标记为失败
                        }
                    }
                }

                (response_times, bytes_transferred)
            });

            tasks.push(task);
        }

        // 等待所有任务完成
        let mut all_response_times = Vec::new();
        for task in tasks {
            match task.await {
                Ok((response_times, bytes)) => {
                    all_response_times.extend(response_times);
                    total_bytes += bytes;
                }
                Err(e) => {
                    warn!("任务执行失败: {}", e);
                }
            }
        }

        let total_duration = start_time.elapsed();
        let metrics = PerformanceMetrics::calculate(
            "HTTP客户端基准测试".to_string(),
            all_response_times,
            total_duration,
            total_bytes,
        );

        info!("基准测试完成");
        metrics.print_report();

        Ok(metrics)
    }

    /// 执行单个请求
    async fn make_request(&self) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        Self::make_single_request(&self.client, &self.config.target_url, &self.config.headers).await
    }

    /// 执行单个HTTP请求
    async fn make_single_request(
        client: &Client,
        url: &str,
        headers: &std::collections::HashMap<String, String>,
    ) -> Result<u64, Box<dyn std::error::Error + Send + Sync>> {
        let mut request = client.get(url);

        for (key, value) in headers {
            request = request.header(key, value);
        }

        let response = request.send().await?;
        let bytes = response.content_length().unwrap_or(0);
        let _body = response.bytes().await?;

        Ok(bytes)
    }
}

/// 客户端配置比较工具
pub struct ClientComparison;

impl ClientComparison {
    /// 比较不同HTTP客户端配置的性能
    #[instrument]
    pub async fn compare_configurations(
        configs: Vec<(&str, OptimizedHttpConfig)>,
        benchmark_config: BenchmarkConfig,
    ) -> Result<Vec<(String, PerformanceMetrics)>, Box<dyn std::error::Error + Send + Sync>> {
        let mut results = Vec::new();

        for (config_name, http_config) in configs {
            info!("测试配置: {}", config_name);

            let client = http_config.build_client()?;
            let benchmark = HttpBenchmark::new(client, benchmark_config.clone());

            match benchmark.run_benchmark().await {
                Ok(metrics) => {
                    let mut named_metrics = metrics;
                    named_metrics.test_name = config_name.to_string();
                    results.push((config_name.to_string(), named_metrics));
                }
                Err(e) => {
                    warn!("配置 {} 测试失败: {}", config_name, e);
                }
            }

            // 在配置测试之间短暂休息
            tokio::time::sleep(Duration::from_secs(2)).await;
        }

        Self::print_comparison_report(&results);
        Ok(results)
    }

    /// 打印配置比较报告
    fn print_comparison_report(results: &[(String, PerformanceMetrics)]) {
        if results.is_empty() {
            warn!("没有可比较的结果");
            return;
        }

        info!("╔══════════════════════════════════════════════════════════════════════════╗");
        info!("║                            配置性能比较报告                              ║");
        info!("╠══════════════════════════════════════════════════════════════════════════╣");
        info!("║ 配置名称        │ RPS     │ 平均延迟(ms) │ P95(ms) │ P99(ms) │ 错误率(%) ║");
        info!("╠═════════════════╪═════════╪══════════════╪═════════╪═════════╪═══════════╣");

        for (name, metrics) in results {
            info!(
                "║ {:<15} │ {:>7.1} │ {:>12.2} │ {:>7.2} │ {:>7.2} │ {:>9.2} ║",
                name.chars().take(15).collect::<String>(),
                metrics.requests_per_second,
                metrics.avg_response_time_ms,
                metrics.p95_response_time_ms,
                metrics.p99_response_time_ms,
                metrics.error_rate
            );
        }

        info!("╚═════════════════╧═════════╧══════════════╧═════════╧═════════╧═══════════╝");

        // 找出最佳性能配置
        if let Some((best_name, best_metrics)) = results.iter().max_by(|a, b| {
            a.1.requests_per_second
                .partial_cmp(&b.1.requests_per_second)
                .unwrap()
        }) {
            info!(
                "🏆 最佳吞吐量配置: {} ({:.1} RPS)",
                best_name, best_metrics.requests_per_second
            );
        }

        if let Some((best_name, best_metrics)) = results.iter().min_by(|a, b| {
            a.1.avg_response_time_ms
                .partial_cmp(&b.1.avg_response_time_ms)
                .unwrap()
        }) {
            info!(
                "🚀 最低延迟配置: {} ({:.2}ms 平均延迟)",
                best_name, best_metrics.avg_response_time_ms
            );
        }
    }
}

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

    #[test]
    fn test_optimized_http_config_default() {
        let config = OptimizedHttpConfig::default();
        assert_eq!(config.pool_max_idle_per_host, 90);
        assert_eq!(config.connect_timeout, Duration::from_secs(10));
        assert!(config.http2_prior_knowledge);
        assert!(config.gzip);
    }

    #[test]
    fn test_optimized_http_config_production() {
        let config = OptimizedHttpConfig::production();
        assert_eq!(config.pool_max_idle_per_host, 100);
        assert_eq!(config.connect_timeout, Duration::from_secs(5));
        assert_eq!(config.request_timeout, Duration::from_secs(30));
    }

    #[test]
    fn test_optimized_http_config_high_throughput() {
        let config = OptimizedHttpConfig::high_throughput();
        assert_eq!(config.pool_max_idle_per_host, 200);
        assert_eq!(config.connect_timeout, Duration::from_secs(3));
        assert_eq!(config.request_timeout, Duration::from_secs(15));
    }

    #[test]
    fn test_optimized_http_config_low_latency() {
        let config = OptimizedHttpConfig::low_latency();
        assert_eq!(config.pool_max_idle_per_host, 50);
        assert_eq!(config.connect_timeout, Duration::from_secs(2));
        assert!(!config.gzip); // 低延迟配置应该禁用压缩
        assert!(!config.brotli);
    }

    #[test]
    fn test_performance_metrics_calculation() {
        let response_times = vec![100.0, 200.0, 150.0, 300.0, 250.0];
        let duration = Duration::from_secs(5);
        let total_bytes = 1024 * 5; // 5KB

        let metrics = PerformanceMetrics::calculate(
            "test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 5);
        assert_eq!(metrics.successful_requests, 5);
        assert_eq!(metrics.failed_requests, 0);
        assert_eq!(metrics.avg_response_time_ms, 200.0);
        assert_eq!(metrics.min_response_time_ms, 100.0);
        assert_eq!(metrics.max_response_time_ms, 300.0);
        assert_eq!(metrics.requests_per_second, 1.0);
        assert_eq!(metrics.throughput_kbps, 1.0); // 5KB / 5s = 1KB/s
        assert_eq!(metrics.error_rate, 0.0);
    }

    #[test]
    fn test_performance_metrics_with_failures() {
        let response_times = vec![100.0, -1.0, 150.0, -1.0, 250.0]; // 2 failures
        let duration = Duration::from_secs(5);
        let total_bytes = 1024 * 3; // Only successful requests transfer data

        let metrics = PerformanceMetrics::calculate(
            "test_with_failures".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 5);
        assert_eq!(metrics.successful_requests, 3);
        assert_eq!(metrics.failed_requests, 2);
        assert_eq!(metrics.error_rate, 40.0); // 2/5 = 40%
        assert_eq!(metrics.avg_response_time_ms, (100.0 + 150.0 + 250.0) / 3.0);
    }

    #[test]
    fn test_benchmark_config_default() {
        let config = BenchmarkConfig::default();
        assert_eq!(config.concurrent_connections, 10);
        assert_eq!(config.requests_per_connection, 100);
        assert_eq!(config.warmup_requests, 10);
        assert_eq!(config.target_url, "https://httpbin.org/json");
    }

    #[tokio::test]
    async fn test_http_config_build_client() {
        let config = OptimizedHttpConfig::default();
        let client = config.build_client();
        assert!(client.is_ok(), "应该能够成功构建HTTP客户端");
    }

    #[test]
    fn test_performance_metrics_empty_response_times() {
        let response_times: Vec<f64> = vec![];
        let duration = Duration::from_secs(1);
        let total_bytes = 0;

        let metrics = PerformanceMetrics::calculate(
            "empty_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 0);
        assert_eq!(metrics.avg_response_time_ms, 0.0);
        assert_eq!(metrics.requests_per_second, 0.0);
    }

    #[test]
    fn test_performance_metrics_percentiles() {
        let response_times = (1..=100).map(|i| i as f64).collect::<Vec<_>>();
        let duration = Duration::from_secs(10);
        let total_bytes = 10240;

        let metrics = PerformanceMetrics::calculate(
            "percentile_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 100);
        assert_eq!(metrics.min_response_time_ms, 1.0);
        assert_eq!(metrics.max_response_time_ms, 100.0);
        // P95应该接近95,P99应该接近99
        assert!((metrics.p95_response_time_ms - 95.0).abs() < 2.0);
        assert!((metrics.p99_response_time_ms - 99.0).abs() < 2.0);
    }

    // Additional comprehensive tests for better coverage

    #[test]
    fn test_optimized_http_config_clone() {
        let config = OptimizedHttpConfig::production();
        let cloned_config = config.clone();

        assert_eq!(
            config.pool_max_idle_per_host,
            cloned_config.pool_max_idle_per_host
        );
        assert_eq!(config.connect_timeout, cloned_config.connect_timeout);
        assert_eq!(config.user_agent, cloned_config.user_agent);
    }

    #[test]
    fn test_optimized_http_config_debug() {
        let config = OptimizedHttpConfig::default();
        let debug_str = format!("{:?}", config);

        assert!(debug_str.contains("OptimizedHttpConfig"));
        assert!(debug_str.contains("pool_max_idle_per_host"));
        assert!(debug_str.contains("user_agent"));
    }

    #[test]
    fn test_optimized_http_config_custom_user_agent() {
        let config = OptimizedHttpConfig {
            user_agent: "custom-agent/1.0".to_string(),
            ..Default::default()
        };

        assert_eq!(config.user_agent, "custom-agent/1.0");
    }

    #[test]
    fn test_optimized_http_config_compression_settings() {
        let low_latency = OptimizedHttpConfig::low_latency();
        assert!(!low_latency.gzip);
        assert!(!low_latency.brotli);

        let production = OptimizedHttpConfig::production();
        assert!(production.gzip);
        assert!(production.brotli);
    }

    #[tokio::test]
    async fn test_http_config_build_client_with_no_compression() {
        let config = OptimizedHttpConfig {
            gzip: false,
            brotli: false,
            ..Default::default()
        };

        let client = config.build_client();
        assert!(client.is_ok());
    }

    #[test]
    fn test_performance_metrics_zero_duration() {
        let response_times = vec![100.0, 200.0, 150.0];
        let duration = Duration::from_secs(0);
        let total_bytes = 1024;

        let metrics = PerformanceMetrics::calculate(
            "zero_duration_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.duration_seconds, 0.0);
        assert_eq!(metrics.requests_per_second, 0.0);
        assert_eq!(metrics.throughput_kbps, 0.0);
    }

    #[test]
    fn test_performance_metrics_single_request() {
        let response_times = vec![123.45];
        let duration = Duration::from_secs(1);
        let total_bytes = 512;

        let metrics = PerformanceMetrics::calculate(
            "single_request_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 1);
        assert_eq!(metrics.successful_requests, 1);
        assert_eq!(metrics.failed_requests, 0);
        assert_eq!(metrics.avg_response_time_ms, 123.45);
        assert_eq!(metrics.min_response_time_ms, 123.45);
        assert_eq!(metrics.max_response_time_ms, 123.45);
        assert_eq!(metrics.p95_response_time_ms, 123.45);
        assert_eq!(metrics.p99_response_time_ms, 123.45);
        assert_eq!(metrics.requests_per_second, 1.0);
        assert_eq!(metrics.error_rate, 0.0);
    }

    #[test]
    fn test_performance_metrics_all_failures() {
        let response_times = vec![-1.0, -1.0, -1.0];
        let duration = Duration::from_secs(3);
        let total_bytes = 0;

        let metrics = PerformanceMetrics::calculate(
            "all_failures_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 3);
        assert_eq!(metrics.successful_requests, 0);
        assert_eq!(metrics.failed_requests, 3);
        assert_eq!(metrics.error_rate, 100.0);
        assert_eq!(metrics.avg_response_time_ms, 0.0);
        assert_eq!(metrics.min_response_time_ms, 0.0);
        assert_eq!(metrics.max_response_time_ms, 0.0);
    }

    #[test]
    fn test_performance_metrics_large_dataset() {
        let response_times: Vec<f64> = (1..=1000).map(|i| i as f64).collect();
        let duration = Duration::from_secs(100);
        let total_bytes = 1024 * 1000;

        let metrics = PerformanceMetrics::calculate(
            "large_dataset_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 1000);
        assert_eq!(metrics.successful_requests, 1000);
        assert_eq!(metrics.avg_response_time_ms, 500.5); // Average of 1..=1000
        assert_eq!(metrics.min_response_time_ms, 1.0);
        assert_eq!(metrics.max_response_time_ms, 1000.0);
        assert!((metrics.p95_response_time_ms - 950.0).abs() < 5.0);
        assert!((metrics.p99_response_time_ms - 990.0).abs() < 5.0);
        assert_eq!(metrics.requests_per_second, 10.0);
        assert_eq!(metrics.throughput_kbps, 10.0); // 1000KB / 100s = 10KB/s
    }

    #[test]
    fn test_performance_metrics_mixed_results() {
        let response_times = vec![50.0, -1.0, 75.0, 100.0, -1.0, 125.0, 150.0];
        let duration = Duration::from_secs(7);
        let total_bytes = 2048;

        let metrics = PerformanceMetrics::calculate(
            "mixed_results_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 7);
        assert_eq!(metrics.successful_requests, 5);
        assert_eq!(metrics.failed_requests, 2);
        assert_eq!(metrics.error_rate, (2.0 / 7.0) * 100.0);
        assert_eq!(
            metrics.avg_response_time_ms,
            (50.0 + 75.0 + 100.0 + 125.0 + 150.0) / 5.0
        );
        assert_eq!(metrics.min_response_time_ms, 50.0);
        assert_eq!(metrics.max_response_time_ms, 150.0);
    }

    #[test]
    fn test_benchmark_config_clone() {
        let config = BenchmarkConfig::default();
        let cloned_config = config.clone();

        assert_eq!(
            config.concurrent_connections,
            cloned_config.concurrent_connections
        );
        assert_eq!(
            config.requests_per_connection,
            cloned_config.requests_per_connection
        );
        assert_eq!(config.target_url, cloned_config.target_url);
        assert_eq!(config.headers.len(), cloned_config.headers.len());
    }

    #[test]
    fn test_benchmark_config_debug() {
        let config = BenchmarkConfig::default();
        let debug_str = format!("{:?}", config);

        assert!(debug_str.contains("BenchmarkConfig"));
        assert!(debug_str.contains("concurrent_connections"));
        assert!(debug_str.contains("target_url"));
    }

    #[test]
    fn test_benchmark_config_custom_headers() {
        let mut config = BenchmarkConfig::default();
        config
            .headers
            .insert("Authorization".to_string(), "Bearer token".to_string());
        config
            .headers
            .insert("Content-Type".to_string(), "application/json".to_string());

        assert_eq!(config.headers.len(), 2);
        assert_eq!(
            config.headers.get("Authorization"),
            Some(&"Bearer token".to_string())
        );
        assert_eq!(
            config.headers.get("Content-Type"),
            Some(&"application/json".to_string())
        );
    }

    #[test]
    fn test_benchmark_config_custom_values() {
        let config = BenchmarkConfig {
            concurrent_connections: 50,
            requests_per_connection: 200,
            warmup_requests: 25,
            target_url: "https://example.com/api".to_string(),
            ..Default::default()
        };

        assert_eq!(config.concurrent_connections, 50);
        assert_eq!(config.requests_per_connection, 200);
        assert_eq!(config.warmup_requests, 25);
        assert_eq!(config.target_url, "https://example.com/api");
    }

    #[test]
    fn test_performance_metrics_serialize_deserialize() {
        let metrics = PerformanceMetrics {
            test_name: "serialize_test".to_string(),
            total_requests: 100,
            successful_requests: 95,
            failed_requests: 5,
            avg_response_time_ms: 123.45,
            p95_response_time_ms: 200.0,
            p99_response_time_ms: 250.0,
            min_response_time_ms: 50.0,
            max_response_time_ms: 300.0,
            requests_per_second: 10.5,
            duration_seconds: 9.52,
            throughput_kbps: 15.3,
            error_rate: 5.0,
        };

        // Test serialization
        let serialized = serde_json::to_string(&metrics);
        assert!(serialized.is_ok());

        // Test deserialization
        let deserialized: Result<PerformanceMetrics, _> =
            serde_json::from_str(&serialized.unwrap());
        assert!(deserialized.is_ok());

        let deserialized_metrics = deserialized.unwrap();
        assert_eq!(metrics.test_name, deserialized_metrics.test_name);
        assert_eq!(metrics.total_requests, deserialized_metrics.total_requests);
        assert_eq!(
            metrics.avg_response_time_ms,
            deserialized_metrics.avg_response_time_ms
        );
    }

    #[test]
    fn test_performance_metrics_edge_case_percentiles() {
        // Test edge case where we have exactly 1 request
        let response_times = vec![42.0];
        let duration = Duration::from_secs(1);
        let total_bytes = 100;

        let metrics = PerformanceMetrics::calculate(
            "single_percentile_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.p95_response_time_ms, 42.0);
        assert_eq!(metrics.p99_response_time_ms, 42.0);
    }

    #[test]
    fn test_performance_metrics_edge_case_small_dataset() {
        // Test edge case with 2 requests for percentile calculation
        let response_times = vec![10.0, 20.0];
        let duration = Duration::from_secs(1);
        let total_bytes = 200;

        let metrics = PerformanceMetrics::calculate(
            "small_dataset_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.total_requests, 2);
        assert_eq!(metrics.avg_response_time_ms, 15.0);
        // With 2 elements, P95 index = 1.9 -> index 0 (first element)
        // With 2 elements, P99 index = 1.98 -> index 0 (first element)
        assert_eq!(metrics.p95_response_time_ms, 10.0);
        assert_eq!(metrics.p99_response_time_ms, 10.0);
    }

    #[test]
    fn test_optimized_http_config_extreme_values() {
        let config = OptimizedHttpConfig {
            pool_max_idle_per_host: 0,
            pool_idle_timeout: Duration::from_secs(0),
            connect_timeout: Duration::from_millis(1),
            request_timeout: Duration::from_millis(1),
            ..Default::default()
        };

        // Should still be able to build a client with extreme values
        let client = config.build_client();
        assert!(client.is_ok());
    }

    #[test]
    fn test_optimized_http_config_very_large_values() {
        let config = OptimizedHttpConfig {
            pool_max_idle_per_host: 10000,
            pool_idle_timeout: Duration::from_secs(86400), // 1 day
            connect_timeout: Duration::from_secs(300),     // 5 minutes
            request_timeout: Duration::from_secs(3600),    // 1 hour
            ..Default::default()
        };

        let client = config.build_client();
        assert!(client.is_ok());
    }

    #[test]
    fn test_performance_metrics_precision() {
        let response_times = vec![0.001, 0.002, 0.003]; // Very small times
        let duration = Duration::from_millis(1);
        let total_bytes = 1;

        let metrics = PerformanceMetrics::calculate(
            "precision_test".to_string(),
            response_times,
            duration,
            total_bytes,
        );

        assert_eq!(metrics.avg_response_time_ms, 0.002);
        assert_eq!(metrics.min_response_time_ms, 0.001);
        assert_eq!(metrics.max_response_time_ms, 0.003);
    }

    #[test]
    fn test_performance_metrics_user_agent_format() {
        let default_config = OptimizedHttpConfig::default();
        let production_config = OptimizedHttpConfig::production();
        let high_throughput_config = OptimizedHttpConfig::high_throughput();
        let low_latency_config = OptimizedHttpConfig::low_latency();

        // All configs should have the same user agent format
        let version = env!("CARGO_PKG_VERSION");
        let expected_user_agent = format!("open-lark/{}", version);

        assert_eq!(default_config.user_agent, expected_user_agent);
        assert_eq!(production_config.user_agent, expected_user_agent);
        assert_eq!(high_throughput_config.user_agent, expected_user_agent);
        assert_eq!(low_latency_config.user_agent, expected_user_agent);
    }
}