xore 1.2.0

XORE CLI - Command-line interface for search and data processing
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
//! Benchmark 命令实现
//!
//! 提供性能基准测试功能,用于测量各组件的性能。

use anyhow::Result;
use clap::ValueEnum;
use colored::*;
use std::io::{Read, Write};
use std::time::{Duration, Instant};

use crate::ui::{ICON_PENDING, ICON_SUCCESS};
use xore_search::{FileScanner, IndexBuilder, ScanConfig, Searcher};

/// 基准测试套件类型
#[derive(Debug, Clone, Copy, ValueEnum, Default)]
pub enum BenchmarkSuite {
    /// 运行所有基准测试
    #[default]
    All,
    /// 文件扫描性能测试
    Scan,
    /// 搜索性能测试(待实现)
    Search,
    /// 数据处理性能测试(待实现)
    Process,
    /// I/O 吞吐量测试
    Io,
    /// 内存分配性能测试
    Alloc,
}

/// 输出格式
#[derive(Debug, Clone, Copy, ValueEnum, Default)]
pub enum OutputFormat {
    /// 文本格式(默认)
    #[default]
    Text,
    /// JSON 格式
    Json,
    /// CSV 格式
    Csv,
}

/// Benchmark 命令参数
pub struct BenchmarkArgs {
    /// 测试套件
    pub suite: BenchmarkSuite,
    /// 输出格式
    pub output: OutputFormat,
    /// 迭代次数
    pub iterations: usize,
    /// 测试数据路径
    pub data_path: Option<String>,
    /// 预热次数
    pub warmup: usize,
}

/// 单个基准测试结果
#[derive(Debug, Clone)]
struct BenchmarkResult {
    name: String,
    duration_ms: f64,
    throughput: Option<String>,
    status: BenchmarkStatus,
}

#[derive(Debug, Clone)]
enum BenchmarkStatus {
    Success,
    Pending,
    Error(String),
}

/// 获取当前使用的分配器名称
fn allocator_name() -> &'static str {
    if cfg!(feature = "mimalloc") {
        "mimalloc"
    } else {
        "system"
    }
}

/// 执行基准测试命令
pub fn execute(args: BenchmarkArgs) -> Result<()> {
    let path = args.data_path.clone().unwrap_or_else(|| ".".to_string());

    println!("{}\n", format!("XORE 性能基准测试 (分配器: {})", allocator_name()).cyan().bold());
    println!(
        "测试路径: {}, 迭代次数: {}, 预热: {}\n",
        path.yellow(),
        args.iterations.to_string().cyan(),
        args.warmup.to_string().cyan()
    );

    let mut results = Vec::new();

    match args.suite {
        BenchmarkSuite::All => {
            results.extend(run_scan_benchmark(&path, args.iterations, args.warmup)?);
            results.extend(run_io_benchmark(&path, args.iterations, args.warmup)?);
            results.extend(run_alloc_benchmark(args.iterations)?);
            results.extend(run_search_benchmark(&path, args.iterations, args.warmup)?);
            results.extend(run_process_benchmark()?);
        }
        BenchmarkSuite::Scan => {
            results.extend(run_scan_benchmark(&path, args.iterations, args.warmup)?);
        }
        BenchmarkSuite::Search => {
            results.extend(run_search_benchmark(&path, args.iterations, args.warmup)?);
        }
        BenchmarkSuite::Process => {
            results.extend(run_process_benchmark()?);
        }
        BenchmarkSuite::Io => {
            results.extend(run_io_benchmark(&path, args.iterations, args.warmup)?);
        }
        BenchmarkSuite::Alloc => {
            results.extend(run_alloc_benchmark(args.iterations)?);
        }
    }

    // 输出结果
    match args.output {
        OutputFormat::Text => print_text_results(&results),
        OutputFormat::Json => print_json_results(&results)?,
        OutputFormat::Csv => print_csv_results(&results),
    }

    Ok(())
}

/// 运行文件扫描基准测试
fn run_scan_benchmark(
    path: &str,
    iterations: usize,
    warmup: usize,
) -> Result<Vec<BenchmarkResult>> {
    let mut results = Vec::new();

    // 预热
    for _ in 0..warmup {
        let config = ScanConfig::new(path);
        let scanner = FileScanner::new(config);
        let _ = scanner.scan();
    }

    // 正式测试
    let mut durations = Vec::with_capacity(iterations);
    let mut total_files = 0u64;
    let mut total_dirs = 0u64;

    for _ in 0..iterations {
        let config = ScanConfig::new(path);
        let scanner = FileScanner::new(config);
        let start = Instant::now();
        let (files, stats) = scanner.scan()?;
        let elapsed = start.elapsed();

        durations.push(elapsed);
        total_files = stats.total_files as u64;
        total_dirs = stats.directories as u64;

        drop(files);
    }

    let avg_duration = average_duration(&durations);
    let files_per_sec = if avg_duration.as_secs_f64() > 0.0 {
        (total_files as f64 / avg_duration.as_secs_f64()) as u64
    } else {
        0
    };

    results.push(BenchmarkResult {
        name: format!("文件扫描 ({} 文件, {} 目录)", total_files, total_dirs),
        duration_ms: avg_duration.as_secs_f64() * 1000.0,
        throughput: Some(format!("{} files/s", format_number(files_per_sec))),
        status: BenchmarkStatus::Success,
    });

    // 深度遍历测试
    let config = ScanConfig::new(path).with_max_depth(10);
    let scanner = FileScanner::new(config);
    let start = Instant::now();
    let _ = scanner.scan()?;
    let elapsed = start.elapsed();

    results.push(BenchmarkResult {
        name: "目录遍历 (深度 10)".to_string(),
        duration_ms: elapsed.as_secs_f64() * 1000.0,
        throughput: None,
        status: BenchmarkStatus::Success,
    });

    Ok(results)
}

/// 运行 I/O 基准测试
fn run_io_benchmark(path: &str, iterations: usize, warmup: usize) -> Result<Vec<BenchmarkResult>> {
    let mut results = Vec::new();

    // 找一个测试文件
    let config = ScanConfig::new(path).with_max_depth(3);
    let scanner = FileScanner::new(config);
    let (files, _) = scanner.scan()?;

    // 找一个适合测试的文件(1KB - 100MB)
    let test_file =
        files.iter().find(|f| f.size > 1024 && f.size < 100 * 1024 * 1024).map(|f| f.path.clone());

    if let Some(file_path) = test_file {
        let file_size = std::fs::metadata(&file_path)?.len();

        // 预热
        for _ in 0..warmup {
            let mut file = std::fs::File::open(&file_path)?;
            let mut buffer = Vec::new();
            let _ = file.read_to_end(&mut buffer);
        }

        // 顺序读取测试
        let mut durations = Vec::with_capacity(iterations);

        for _ in 0..iterations {
            let mut file = std::fs::File::open(&file_path)?;
            let mut buffer = Vec::new();
            let start = Instant::now();
            file.read_to_end(&mut buffer)?;
            durations.push(start.elapsed());
        }

        let avg_duration = average_duration(&durations);
        let bytes_per_sec = if avg_duration.as_secs_f64() > 0.0 {
            (file_size as f64 / avg_duration.as_secs_f64()) as u64
        } else {
            0
        };

        results.push(BenchmarkResult {
            name: format!("顺序读取 ({})", format_bytes(file_size)),
            duration_ms: avg_duration.as_secs_f64() * 1000.0,
            throughput: Some(format!("{}/s", format_bytes(bytes_per_sec))),
            status: BenchmarkStatus::Success,
        });

        // 写入测试(临时文件)
        let temp_path = std::env::temp_dir().join("xore_benchmark_test");
        let test_data = vec![0u8; 1024 * 1024]; // 1MB

        let mut write_durations = Vec::with_capacity(iterations);
        for _ in 0..iterations {
            let start = Instant::now();
            let mut file = std::fs::File::create(&temp_path)?;
            file.write_all(&test_data)?;
            file.sync_all()?;
            write_durations.push(start.elapsed());
        }

        let _ = std::fs::remove_file(&temp_path);

        let avg_write = average_duration(&write_durations);
        let write_speed = if avg_write.as_secs_f64() > 0.0 {
            (1024.0 * 1024.0 / avg_write.as_secs_f64()) as u64
        } else {
            0
        };

        results.push(BenchmarkResult {
            name: "顺序写入 (1 MB)".to_string(),
            duration_ms: avg_write.as_secs_f64() * 1000.0,
            throughput: Some(format!("{}/s", format_bytes(write_speed))),
            status: BenchmarkStatus::Success,
        });
    } else {
        results.push(BenchmarkResult {
            name: "I/O 测试".to_string(),
            duration_ms: 0.0,
            throughput: None,
            status: BenchmarkStatus::Error("未找到合适的测试文件".to_string()),
        });
    }

    Ok(results)
}

/// 运行搜索基准测试
fn run_search_benchmark(
    path: &str,
    iterations: usize,
    warmup: usize,
) -> Result<Vec<BenchmarkResult>> {
    let results = vec![
        // 1. 索引构建性能测试
        benchmark_index_building(path, iterations, warmup)?,
        // 2. 标准搜索性能测试
        benchmark_standard_search(path, iterations)?,
        // 3. 前缀搜索性能测试
        benchmark_prefix_search(path, iterations)?,
        // 4. 模糊搜索性能测试
        benchmark_fuzzy_search(path, iterations)?,
    ];

    Ok(results)
}

/// 索引构建基准测试
fn benchmark_index_building(
    path: &str,
    iterations: usize,
    warmup: usize,
) -> Result<BenchmarkResult> {
    let index_path = std::env::temp_dir().join("xore_bench_index");

    // 预热
    for _ in 0..warmup {
        let _ = std::fs::remove_dir_all(&index_path);
        let mut builder = IndexBuilder::new(&index_path)?;
        let scanner = FileScanner::new(ScanConfig::new(path));
        let (files, _) = scanner.scan()?;
        builder.add_documents_batch(&files)?;
        builder.build()?;
    }

    // 实际测试
    let mut durations = Vec::new();
    let mut total_size = 0u64;
    let mut total_files = 0;

    for _ in 0..iterations {
        let _ = std::fs::remove_dir_all(&index_path);

        let start = Instant::now();
        let mut builder = IndexBuilder::new(&index_path)?;
        let scanner = FileScanner::new(ScanConfig::new(path));
        let (files, stats) = scanner.scan()?;

        total_files = stats.matched_files;
        total_size = files.iter().map(|f| f.size).sum();

        builder.add_documents_batch(&files)?;
        builder.build()?;

        durations.push(start.elapsed());
    }

    let avg_duration = average_duration(&durations);
    let throughput_mbs = (total_size as f64 / 1024.0 / 1024.0) / avg_duration.as_secs_f64();

    Ok(BenchmarkResult {
        name: format!(
            "索引构建 ({} 文件, {:.2} MB)",
            total_files,
            total_size as f64 / 1024.0 / 1024.0
        ),
        duration_ms: avg_duration.as_secs_f64() * 1000.0,
        throughput: Some(format!("{:.2} MB/s", throughput_mbs)),
        status: BenchmarkStatus::Success,
    })
}

/// 标准搜索基准测试
fn benchmark_standard_search(_path: &str, iterations: usize) -> Result<BenchmarkResult> {
    let index_path = std::env::temp_dir().join("xore_bench_index");
    let searcher = Searcher::new(&index_path)?;

    let queries = vec!["error", "warning", "config", "database", "user"];
    let mut durations = Vec::new();
    let mut total_results = 0;

    for _ in 0..iterations {
        for query in &queries {
            let start = Instant::now();
            let results = searcher.search(query)?;
            durations.push(start.elapsed());
            total_results += results.len();
        }
    }

    let avg_duration = average_duration(&durations);
    let p50 = percentile(&durations, 50);
    let p95 = percentile(&durations, 95);
    let p99 = percentile(&durations, 99);

    Ok(BenchmarkResult {
        name: format!("标准搜索 (平均 {} 结果)", total_results / durations.len()),
        duration_ms: avg_duration.as_secs_f64() * 1000.0,
        throughput: Some(format!(
            "p50={:.1}ms, p95={:.1}ms, p99={:.1}ms",
            p50.as_secs_f64() * 1000.0,
            p95.as_secs_f64() * 1000.0,
            p99.as_secs_f64() * 1000.0
        )),
        status: BenchmarkStatus::Success,
    })
}

/// 前缀搜索基准测试
fn benchmark_prefix_search(_path: &str, iterations: usize) -> Result<BenchmarkResult> {
    let index_path = std::env::temp_dir().join("xore_bench_index");
    let searcher = Searcher::new(&index_path)?;

    let queries = vec!["err", "warn", "conf", "data", "use"];
    let mut durations = Vec::new();

    for _ in 0..iterations {
        for query in &queries {
            let start = Instant::now();
            let _ = searcher.search_prefix(query, 100)?;
            durations.push(start.elapsed());
        }
    }

    let avg_duration = average_duration(&durations);
    let p99 = percentile(&durations, 99);

    Ok(BenchmarkResult {
        name: "前缀搜索".to_string(),
        duration_ms: avg_duration.as_secs_f64() * 1000.0,
        throughput: Some(format!("p99={:.1}ms", p99.as_secs_f64() * 1000.0)),
        status: BenchmarkStatus::Success,
    })
}

/// 模糊搜索基准测试
fn benchmark_fuzzy_search(_path: &str, iterations: usize) -> Result<BenchmarkResult> {
    let index_path = std::env::temp_dir().join("xore_bench_index");
    let searcher = Searcher::new(&index_path)?;

    // 故意拼写错误的查询
    let queries = vec!["eror", "warining", "confg", "databse", "usr"];
    let mut durations = Vec::new();

    for _ in 0..iterations {
        for query in &queries {
            let start = Instant::now();
            let _ = searcher.search_fuzzy(query, 100)?;
            durations.push(start.elapsed());
        }
    }

    let avg_duration = average_duration(&durations);
    let p99 = percentile(&durations, 99);

    Ok(BenchmarkResult {
        name: "模糊搜索".to_string(),
        duration_ms: avg_duration.as_secs_f64() * 1000.0,
        throughput: Some(format!("p99={:.1}ms", p99.as_secs_f64() * 1000.0)),
        status: BenchmarkStatus::Success,
    })
}

/// 计算百分位数
fn percentile(durations: &[Duration], p: usize) -> Duration {
    if durations.is_empty() {
        return Duration::ZERO;
    }
    let mut sorted = durations.to_vec();
    sorted.sort();
    let index = (sorted.len() * p / 100).min(sorted.len() - 1);
    sorted[index]
}

/// 运行数据处理基准测试(待实现)
fn run_process_benchmark() -> Result<Vec<BenchmarkResult>> {
    Ok(vec![BenchmarkResult {
        name: "数据处理".to_string(),
        duration_ms: 0.0,
        throughput: None,
        status: BenchmarkStatus::Pending,
    }])
}

/// 运行内存分配基准测试
fn run_alloc_benchmark(iterations: usize) -> Result<Vec<BenchmarkResult>> {
    let mut results = Vec::new();

    // Vec<String> 分配测试
    let mut durations = Vec::with_capacity(iterations);
    for _ in 0..iterations {
        let start = Instant::now();
        let mut v: Vec<String> = Vec::with_capacity(100_000);
        for i in 0..100_000 {
            v.push(format!("path/to/file_{}.txt", i));
        }
        drop(v);
        durations.push(start.elapsed());
    }

    let avg = average_duration(&durations);
    let allocs_per_sec =
        if avg.as_secs_f64() > 0.0 { (100_000.0 / avg.as_secs_f64()) as u64 } else { 0 };

    results.push(BenchmarkResult {
        name: "Vec<String> 分配 (100K 元素)".to_string(),
        duration_ms: avg.as_secs_f64() * 1000.0,
        throughput: Some(format!("{} allocs/s", format_number(allocs_per_sec))),
        status: BenchmarkStatus::Success,
    });

    // HashMap 分配测试
    let mut durations = Vec::with_capacity(iterations);
    for _ in 0..iterations {
        let start = Instant::now();
        let mut map: std::collections::HashMap<String, usize> =
            std::collections::HashMap::with_capacity(50_000);
        for i in 0..50_000 {
            map.insert(format!("key_{}", i), i);
        }
        drop(map);
        durations.push(start.elapsed());
    }

    let avg = average_duration(&durations);
    let ops_per_sec =
        if avg.as_secs_f64() > 0.0 { (50_000.0 / avg.as_secs_f64()) as u64 } else { 0 };

    results.push(BenchmarkResult {
        name: "HashMap<String, usize> (50K 条目)".to_string(),
        duration_ms: avg.as_secs_f64() * 1000.0,
        throughput: Some(format!("{} ops/s", format_number(ops_per_sec))),
        status: BenchmarkStatus::Success,
    });

    // 小字符串频繁分配释放测试
    let mut durations = Vec::with_capacity(iterations);
    for _ in 0..iterations {
        let start = Instant::now();
        for i in 0..50_000 {
            let s = format!("temp_string_{}", i);
            std::hint::black_box(&s);
        }
        durations.push(start.elapsed());
    }

    let avg = average_duration(&durations);
    let allocs_per_sec =
        if avg.as_secs_f64() > 0.0 { (50_000.0 / avg.as_secs_f64()) as u64 } else { 0 };

    results.push(BenchmarkResult {
        name: "小字符串分配/释放 (50K 次)".to_string(),
        duration_ms: avg.as_secs_f64() * 1000.0,
        throughput: Some(format!("{} allocs/s", format_number(allocs_per_sec))),
        status: BenchmarkStatus::Success,
    });

    Ok(results)
}

/// 计算平均耗时
fn average_duration(durations: &[Duration]) -> Duration {
    if durations.is_empty() {
        return Duration::ZERO;
    }
    let total: Duration = durations.iter().sum();
    total / durations.len() as u32
}

/// 格式化数字(添加千分位分隔符)
fn format_number(n: u64) -> String {
    let s = n.to_string();
    let mut result = String::new();
    for (i, c) in s.chars().rev().enumerate() {
        if i > 0 && i % 3 == 0 {
            result.insert(0, ',');
        }
        result.insert(0, c);
    }
    result
}

/// 格式化字节大小
fn format_bytes(bytes: u64) -> String {
    const KB: u64 = 1024;
    const MB: u64 = KB * 1024;
    const GB: u64 = MB * 1024;

    if bytes >= GB {
        format!("{:.2} GB", bytes as f64 / GB as f64)
    } else if bytes >= MB {
        format!("{:.2} MB", bytes as f64 / MB as f64)
    } else if bytes >= KB {
        format!("{:.2} KB", bytes as f64 / KB as f64)
    } else {
        format!("{} B", bytes)
    }
}

/// 打印文本格式结果
fn print_text_results(results: &[BenchmarkResult]) {
    println!("{}", "测试结果".bold());
    println!("{}", "".repeat(60));

    for result in results {
        let (icon, status_color) = match &result.status {
            BenchmarkStatus::Success => (ICON_SUCCESS, "green"),
            BenchmarkStatus::Pending => (ICON_PENDING, "yellow"),
            BenchmarkStatus::Error(_) => ("", "red"),
        };

        let icon_colored = match status_color {
            "green" => icon.green().to_string(),
            "yellow" => icon.yellow().to_string(),
            "red" => icon.red().to_string(),
            _ => icon.to_string(),
        };

        match &result.status {
            BenchmarkStatus::Success => {
                let duration = format!("{:.1}ms", result.duration_ms);
                let throughput = result
                    .throughput
                    .as_ref()
                    .map(|t| format!(" ({})", t.cyan()))
                    .unwrap_or_default();

                println!("{} {}: {}{}", icon_colored, result.name, duration.yellow(), throughput);
            }
            BenchmarkStatus::Pending => {
                println!("{} {}: {}", icon_colored, result.name, "待实现".dimmed());
            }
            BenchmarkStatus::Error(msg) => {
                println!("{} {}: {}", icon_colored, result.name, msg.red());
            }
        }
    }

    println!();
}

/// 打印 JSON 格式结果
fn print_json_results(results: &[BenchmarkResult]) -> Result<()> {
    let json_results: Vec<serde_json::Value> = results
        .iter()
        .map(|r| {
            serde_json::json!({
                "name": r.name,
                "duration_ms": r.duration_ms,
                "throughput": r.throughput,
                "status": match &r.status {
                    BenchmarkStatus::Success => "success",
                    BenchmarkStatus::Pending => "pending",
                    BenchmarkStatus::Error(_) => "error",
                }
            })
        })
        .collect();

    let output = serde_json::to_string_pretty(&json_results)?;
    println!("{}", output);
    Ok(())
}

/// 打印 CSV 格式结果
fn print_csv_results(results: &[BenchmarkResult]) {
    println!("name,duration_ms,throughput,status");
    for result in results {
        let status = match &result.status {
            BenchmarkStatus::Success => "success",
            BenchmarkStatus::Pending => "pending",
            BenchmarkStatus::Error(_) => "error",
        };
        println!(
            "\"{}\",{:.2},{},{}",
            result.name,
            result.duration_ms,
            result.throughput.as_deref().unwrap_or(""),
            status
        );
    }
}