grpctestify 1.8.6

gRPC testing utility written in Rust
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
use crate::bench::sources::index::SourceIndex;
use crate::bench::sources::index_builder::{
    build_index_for_source_with_progress, index_path_for_source,
};
use crate::bench::sources::{SourceDefinition, SourceUsageAnalyzer, effective_source_name};
use crate::cli::args::IndexArgs;
use crate::parser::ast::{SectionContent, SectionType};
use anyhow::{Context, Result};
use indicatif::{HumanBytes, MultiProgress, ProgressBar, ProgressStyle};
use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::time::Instant;

pub fn handle_index(args: &IndexArgs) -> Result<()> {
    // Stats mode: show index file metadata
    if args.stats {
        for path in &args.sources {
            if !path.exists() {
                eprintln!("File not found: {}", path.display());
                continue;
            }
            match SourceIndex::read_from_file(path) {
                Ok(index) => {
                    let file_size = std::fs::metadata(path).map(|m| m.len()).unwrap_or(0);
                    println!("File: {}", path.display());
                    println!("  Size: {} bytes", file_size);
                    println!("  Key column: {}", index.key_column());
                    println!("  Key type: {:?}", index.key_type());
                    println!("  Index version: {}", index.index_version());
                    println!("  Entry count: {}", index.entry_count());
                    println!();
                }
                Err(e) => {
                    eprintln!("Error reading {}: {e}", path.display());
                }
            }
        }
        return Ok(());
    }

    let files = resolve_bench_files(&args.sources)?;
    if files.is_empty() {
        anyhow::bail!("no .gctf files found in provided paths");
    }

    let started = Instant::now();
    let mp = Arc::new(MultiProgress::new());
    let overall = mp.add(ProgressBar::new(files.len() as u64));
    overall.set_style(progress_style(
        "{spinner:.green} indexing {bar:24.cyan/blue} {pos}/{len} elapsed:{elapsed_precise}",
    ));
    overall.enable_steady_tick(std::time::Duration::from_millis(120));

    let file_count = files.len();
    let args = Arc::new(args.clone());

    let results: Vec<(usize, IndexRunOutcome)> = std::thread::scope(|s| {
        let overall_ref = &overall;
        let mp_ref = &mp;
        let mut handles: Vec<std::thread::ScopedJoinHandle<(usize, IndexRunOutcome)>> =
            Vec::with_capacity(file_count);

        for (i, source_path) in files.iter().enumerate() {
            let args = Arc::clone(&args);
            let source_path = source_path.clone();
            let overall_pb = overall_ref.clone();
            let mp = mp_ref.clone();

            handles.push(s.spawn(move || {
                let current = mp.add(ProgressBar::new(100));
                current.set_style(progress_style(
                    "{spinner:.green} {msg:45} {bar:20.cyan/blue} {pos:>3}%",
                ));
                current.enable_steady_tick(std::time::Duration::from_millis(80));
                current.set_position(0);
                current.set_message(format!("analyze {}", compact_path(&source_path)));

                let outcome = handle_index_single(&args, &current, &source_path);
                overall_pb.inc(1);

                match outcome {
                    Ok(o) => {
                        current.finish_and_clear();
                        (i, o)
                    }
                    Err(e) => {
                        current.finish_and_clear();
                        (
                            i,
                            IndexRunOutcome::Error(format!(
                                "{}: {}",
                                compact_path(&source_path),
                                e
                            )),
                        )
                    }
                }
            }));
        }

        handles
            .into_iter()
            .map(|h| h.join().expect("index thread panicked"))
            .collect()
    });

    overall.finish_with_message("indexing complete");

    let mut processed = 0usize;
    let mut skipped = 0usize;
    let mut total_rebuilt = 0usize;
    let mut total_required = 0usize;
    let mut total_missing = 0usize;
    let mut file_reports: Vec<String> = Vec::new();
    let mut processed_stats: Vec<FileStats> = Vec::new();
    let mut problems: Vec<String> = Vec::new();
    let mut keep_index_paths: BTreeSet<PathBuf> = BTreeSet::new();

    let mut sorted = results;
    sorted.sort_by_key(|(i, _)| *i);

    for (i, outcome) in sorted {
        let source_path = &files[i];
        match outcome {
            IndexRunOutcome::Processed(stats) => {
                processed += 1;
                total_rebuilt += stats.rebuilt;
                total_required += stats.required;
                total_missing += stats.missing;
                file_reports.push(format!(
                    "OK   {} | required={} rebuilt={} reused={} missing={}",
                    compact_path(source_path),
                    stats.required,
                    stats.rebuilt,
                    stats.required.saturating_sub(stats.rebuilt + stats.missing),
                    stats.missing
                ));
                for d in &stats.details {
                    keep_index_paths.insert(d.index_path.clone());
                }
                processed_stats.push(stats);
            }
            IndexRunOutcome::Skipped(reason) => {
                skipped += 1;
                file_reports.push(format!("SKIP {} | {}", compact_path(source_path), reason));
            }
            IndexRunOutcome::Error(msg) => {
                problems.push(msg);
            }
        }
    }

    for line in file_reports {
        eprintln!("{}", line);
    }

    eprintln!("\nIndex summary:");
    eprintln!("  Scanned files: {}", files.len());
    eprintln!("  Processed: {}", processed);
    eprintln!("  Skipped: {}", skipped);
    eprintln!("  Required indexes: {}", total_required);
    eprintln!("  Rebuilt: {}", total_rebuilt);
    eprintln!(
        "  Reused: {}",
        total_required.saturating_sub(total_rebuilt + total_missing)
    );
    eprintln!("  Missing after run: {}", total_missing);
    eprintln!("  Duration: {:.2?}", started.elapsed());

    if processed == 0 {
        eprintln!(
            "Note: no BENCH files with valid BENCH.sources list were found in provided paths."
        );
    }

    if !processed_stats.is_empty() {
        eprintln!("\nFile details:");
        for fs in processed_stats {
            let total_index_bytes: u64 = fs.details.iter().map(|d| d.index_size).sum();
            eprintln!(
                "  {} | indexes={} total_index_size={}",
                fs.file,
                fs.details.len(),
                HumanBytes(total_index_bytes)
            );
            for d in fs.details {
                eprintln!(
                    "    - {}.{} | source={} rows={} unique={} index={}",
                    d.source,
                    d.column,
                    HumanBytes(d.source_size),
                    d.entries,
                    d.unique,
                    HumanBytes(d.index_size)
                );
            }
        }
    }

    if !problems.is_empty() {
        eprintln!("\nProblems:");
        for p in &problems {
            eprintln!("  - {}", p);
        }
        anyhow::bail!("indexing finished with {} error(s)", problems.len());
    }
    Ok(())
}

enum IndexRunOutcome {
    Processed(FileStats),
    Skipped(String),
    Error(String),
}

#[derive(Default)]
struct FileStats {
    file: String,
    required: usize,
    rebuilt: usize,
    missing: usize,
    details: Vec<IndexDetail>,
}

struct IndexDetail {
    source: String,
    column: String,
    index_path: PathBuf,
    source_size: u64,
    index_size: u64,
    entries: usize,
    unique: usize,
}

struct IndexTask {
    source_name: String,
    column: String,
    def: SourceDefinition,
    source_file: PathBuf,
    idx_path: PathBuf,
    needs_rebuild: bool,
}

enum IndexTaskResult {
    Ok { rebuilt: bool, detail: IndexDetail },
    Cached(IndexDetail),
    Failed(String),
}

fn execute_index_task(task: &IndexTask, source_path: &Path) -> IndexTaskResult {
    if task.needs_rebuild {
        match build_index_for_source_with_progress(&task.def, source_path, |_, _, _| {}) {
            Ok(_rebuilt_path) => {}
            Err(e) => {
                return IndexTaskResult::Failed(format!(
                    "failed to build index for {}.{}: {e}",
                    task.source_name, task.column
                ));
            }
        }
    }

    if !task.idx_path.exists() {
        return IndexTaskResult::Failed(format!(
            "index file missing after build: {}",
            task.idx_path.display()
        ));
    }

    let index = match SourceIndex::read_from_file(&task.idx_path) {
        Ok(idx) => idx,
        Err(e) => {
            return IndexTaskResult::Failed(format!(
                "failed to read index {}.{}: {e}",
                task.source_name, task.column
            ));
        }
    };
    let idx_meta = match std::fs::metadata(&task.idx_path) {
        Ok(m) => m,
        Err(e) => {
            return IndexTaskResult::Failed(format!(
                "failed to stat index {}: {e}",
                task.idx_path.display()
            ));
        }
    };
    let src_meta = match std::fs::metadata(&task.source_file) {
        Ok(m) => m,
        Err(e) => {
            return IndexTaskResult::Failed(format!(
                "failed to stat source {}: {e}",
                task.source_file.display()
            ));
        }
    };

    let detail = IndexDetail {
        source: task.source_name.clone(),
        column: task.column.clone(),
        index_path: task.idx_path.clone(),
        source_size: src_meta.len(),
        index_size: idx_meta.len(),
        entries: index.len(),
        unique: index.unique_keys_len(),
    };

    if task.needs_rebuild {
        IndexTaskResult::Ok {
            rebuilt: true,
            detail,
        }
    } else {
        IndexTaskResult::Cached(detail)
    }
}

fn handle_index_single(
    args: &IndexArgs,
    current: &ProgressBar,
    source_path: &Path,
) -> Result<IndexRunOutcome> {
    if !source_path.exists() {
        anyhow::bail!("source file not found: {}", source_path.display());
    }

    if !is_bench_file(source_path) {
        anyhow::bail!("index command expects a .gctf file with BENCH.sources");
    }

    let Some(defs) = parse_sources_from_bench_file(source_path)? else {
        return Ok(IndexRunOutcome::Skipped(
            "BENCH.sources is missing or not a YAML list".to_string(),
        ));
    };
    if defs.is_empty() {
        return Ok(IndexRunOutcome::Skipped(
            "BENCH.sources is empty".to_string(),
        ));
    }

    let parse_result = crate::parser::parse_with_recovery(source_path);
    let usage_plan = SourceUsageAnalyzer::analyze(&parse_result.document, &defs);

    let mut defs_by_name: BTreeMap<String, SourceDefinition> = BTreeMap::new();
    for (i, def) in defs.iter().enumerate() {
        defs_by_name.insert(effective_source_name(def, i), def.clone());
    }

    let mut required: BTreeSet<(String, String)> = BTreeSet::new();
    for req in &usage_plan.required_indexes {
        required.insert((req.source.clone(), req.column.clone()));
    }

    let mut tasks: Vec<IndexTask> = Vec::with_capacity(usage_plan.required_indexes.len());
    for req in &usage_plan.required_indexes {
        let Some(def) = defs_by_name.get(&req.source) else {
            continue;
        };
        let source_file =
            crate::utils::file::FileUtils::resolve_relative_path(source_path, &def.file);
        let idx_path = index_path_for_source(&source_file, &req.column);
        let state = index_state(&idx_path, &source_file);
        let needs_rebuild = args.force || !matches!(state, IndexState::Fresh);
        tasks.push(IndexTask {
            source_name: req.source.clone(),
            column: req.column.clone(),
            def: def.clone(),
            source_file,
            idx_path,
            needs_rebuild,
        });
    }

    current.set_message(format!(
        "build {} indexes for {}",
        tasks.len(),
        compact_path(source_path)
    ));

    let task_count = tasks.len();
    let results: Vec<IndexTaskResult> = if task_count <= 1 {
        tasks
            .into_iter()
            .map(|t| execute_index_task(&t, source_path))
            .collect()
    } else {
        std::thread::scope(|s| {
            tasks
                .into_iter()
                .map(|t| {
                    let source_path = source_path.to_path_buf();
                    s.spawn(move || execute_index_task(&t, &source_path))
                })
                .collect::<Vec<_>>()
                .into_iter()
                .map(|h| h.join().expect("index task panicked"))
                .collect()
        })
    };

    current.set_position(100);
    current.set_message(format!("done {}", compact_path(source_path)));

    let mut stats = FileStats {
        file: compact_path(source_path),
        required: required.len(),
        rebuilt: 0,
        missing: 0,
        details: Vec::new(),
    };
    let mut present: BTreeSet<(String, String)> = BTreeSet::new();

    for r in results {
        match r {
            IndexTaskResult::Ok { rebuilt, detail } => {
                if rebuilt {
                    stats.rebuilt += 1;
                }
                present.insert((detail.source.clone(), detail.column.clone()));
                stats.details.push(detail);
            }
            IndexTaskResult::Cached(detail) => {
                present.insert((detail.source.clone(), detail.column.clone()));
                stats.details.push(detail);
            }
            IndexTaskResult::Failed(msg) => {
                return Err(anyhow::anyhow!("{msg}"));
            }
        }
    }

    let missing: BTreeSet<_> = required.difference(&present).cloned().collect();
    if !missing.is_empty() {
        stats.missing = missing.len();
    }
    Ok(IndexRunOutcome::Processed(stats))
}

fn progress_style(template: &str) -> ProgressStyle {
    ProgressStyle::with_template(template).unwrap_or_else(|_| ProgressStyle::default_spinner())
}

fn compact_path(path: &Path) -> String {
    path.display().to_string()
}

fn resolve_bench_files(inputs: &[PathBuf]) -> Result<Vec<PathBuf>> {
    let mut out = Vec::new();
    for input in inputs {
        if !input.exists() {
            anyhow::bail!("path not found: {}", input.display());
        }
        if input.is_file() {
            if is_bench_file(input) {
                out.push(input.clone());
            }
            continue;
        }

        for entry in walkdir::WalkDir::new(input)
            .into_iter()
            .filter_map(|e| e.ok())
            .filter(|e| e.file_type().is_file())
        {
            let p = entry.path();
            if is_bench_file(p) {
                out.push(p.to_path_buf());
            }
        }
    }
    out.sort();
    out.dedup();
    Ok(out)
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IndexState {
    Missing,
    Fresh,
    Stale,
    Corrupted,
}

fn index_state(index_path: &Path, source_path: &Path) -> IndexState {
    if !index_path.exists() {
        return IndexState::Missing;
    }

    if SourceIndex::read_from_file(index_path).is_err() {
        return IndexState::Corrupted;
    }

    let idx_meta = match std::fs::metadata(index_path) {
        Ok(m) => m,
        Err(_) => return IndexState::Corrupted,
    };
    let src_meta = match std::fs::metadata(source_path) {
        Ok(m) => m,
        Err(_) => return IndexState::Corrupted,
    };
    match (idx_meta.modified(), src_meta.modified()) {
        (Ok(i), Ok(s)) if i < s => IndexState::Stale,
        (Ok(_), Ok(_)) => IndexState::Fresh,
        _ => IndexState::Fresh,
    }
}

fn is_bench_file(path: &Path) -> bool {
    path.extension()
        .is_some_and(|e| e.eq_ignore_ascii_case("gctf"))
}

fn parse_sources_from_bench_file(path: &Path) -> Result<Option<Vec<SourceDefinition>>> {
    let parse_result = crate::parser::parse_with_recovery(path);
    let document = parse_result.document;
    let Some(bench_section) = document
        .sections
        .iter()
        .find(|s| s.section_type == SectionType::Bench)
    else {
        return Ok(None);
    };

    let Some(bench) = (match &bench_section.content {
        SectionContent::KeyValues(kv) => Some(kv),
        _ => None,
    }) else {
        return Ok(None);
    };

    let Some(raw) = bench.get("sources") else {
        return Ok(None);
    };

    if raw.trim().is_empty() {
        return Ok(None);
    }

    let defs: Vec<SourceDefinition> = serde_yaml_ng::from_str(raw).with_context(|| {
        format!(
            "failed to parse BENCH.sources as YAML array in {}",
            path.display()
        )
    })?;
    Ok(Some(defs))
}