grpctestify 1.6.0

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
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
// Explain command - show detailed execution plan via Workflow

use crate::cli::args::HasFormat;
use anyhow::Result;
use serde::Serialize;
use std::path::Path;

use crate::cli::args::ExplainArgs;
use crate::execution::{ExecutionPlan, Workflow};
use crate::optimizer;
use crate::parser;
use crate::parser::ast::{SectionContent, SectionType};

fn optimization_hints_from_workflow(workflow: &Workflow) -> Vec<optimizer::OptimizationHint> {
    let mut hints = Vec::new();
    for event in workflow.optimization_hints() {
        if let crate::execution::WorkflowEvent::OptimizationFound { hints: ev_hints } = event {
            for hint in ev_hints {
                if let Ok(rule_id) = optimizer::RuleId::try_from(hint.rule_id.as_str()) {
                    hints.push(optimizer::OptimizationHint {
                        rule_id,
                        line: hint.line,
                        before: hint.before.clone(),
                        after: hint.after.clone(),
                        preconditions: None,
                        negative_cases: None,
                        proof_note: None,
                    });
                }
            }
        }
    }
    hints
}

fn validation_passed_from_workflow(workflow: &Workflow) -> bool {
    for event in workflow.validation_results() {
        if let crate::execution::WorkflowEvent::ValidationResult { passed, .. } = event {
            return *passed;
        }
    }
    true
}

fn sorted_key_values(map: &std::collections::HashMap<String, String>) -> Vec<(&str, &str)> {
    let mut pairs: Vec<(&str, &str)> = map.iter().map(|(k, v)| (k.as_str(), v.as_str())).collect();
    pairs.sort_by_key(|(ka, _)| *ka);
    pairs
}

#[derive(Serialize)]
struct ExplainJsonOutput {
    semantic_plan: ExecutionPlan,
    optimization_trace: Vec<optimizer::OptimizationHint>,
    optimized_plan: ExecutionPlan,
    execution_plan: ExecutionPlan,
}

#[derive(Serialize)]
struct MultiDocExplainJson {
    documents: Vec<DocumentPlan>,
    optimization_trace: Vec<optimizer::OptimizationHint>,
}

#[derive(Serialize)]
struct DocumentPlan {
    index: usize,
    endpoint: Option<String>,
    address: Option<String>,
    execution_plan: ExecutionPlan,
    variable_extractions: Vec<(String, String)>,
    has_streaming: bool,
    rpc_mode: String,
}

pub async fn handle_explain(args: &ExplainArgs) -> Result<()> {
    let file_path = &args.file;
    if !file_path.exists() {
        return Err(anyhow::anyhow!("File not found: {}", file_path.display()));
    }

    let parse_start = std::time::Instant::now();

    let parse_result = parser::parse_with_recovery(file_path);
    let doc = parse_result.document;

    let parse_ms = parse_start.elapsed().as_secs_f64() * 1000.0;

    if !parse_result.diagnostics.is_empty() {
        eprintln!();
        eprintln!("PARSE DIAGNOSTICS");
        eprintln!("=================");
        eprintln!("File: {}", file_path.display());
        eprintln!("Recovered sections: {}", parse_result.recovered_sections);
        eprintln!("Failed sections: {}", parse_result.failed_sections);
        eprintln!();
        for d in &parse_result.diagnostics.diagnostics {
            crate::commands::print_diagnostic(d);
            eprintln!();
        }
    }

    if args.is_json() {
        // Backward compatible: single doc uses original format
        if doc.is_single_document() {
            let workflow = Workflow::from_document_with_analysis(&doc);
            let semantic_plan = ExecutionPlan::from_document(&doc);
            let optimization_trace = optimization_hints_from_workflow(&workflow);
            let optimized_plan = semantic_plan.clone();
            let execution_plan = optimized_plan.clone();
            let output = ExplainJsonOutput {
                semantic_plan,
                optimization_trace,
                optimized_plan,
                execution_plan,
            };
            println!("{}", serde_json::to_string_pretty(&output)?);
        } else {
            // Multi-doc: extended format
            let mut documents = Vec::new();
            let mut all_optimizations: Vec<optimizer::OptimizationHint> = Vec::new();

            for (doc_idx, d) in doc.iter_chain().enumerate() {
                let workflow = Workflow::from_document_with_analysis(d);
                let plan = ExecutionPlan::from_document(d);

                let mut extractions: Vec<(String, String)> = Vec::new();
                for section in &d.sections {
                    if section.section_type == SectionType::Extract
                        && let SectionContent::Extract(map) = &section.content
                    {
                        for (name, expr) in map {
                            extractions.push((name.clone(), expr.clone()));
                        }
                    }
                }
                extractions.sort_by(|a, b| a.0.cmp(&b.0));

                all_optimizations.extend(optimization_hints_from_workflow(&workflow));

                documents.push(DocumentPlan {
                    index: doc_idx + 1,
                    endpoint: d.get_endpoint(),
                    address: d.get_address(None),
                    execution_plan: plan,
                    variable_extractions: extractions,
                    has_streaming: workflow.has_streaming(),
                    rpc_mode: workflow.rpc_mode_name().to_string(),
                });
            }

            let output = MultiDocExplainJson {
                documents,
                optimization_trace: all_optimizations,
            };
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
    } else {
        // Text output
        let total_docs = doc.document_count();

        if total_docs > 1 {
            println!();
            println!("MULTI-DOCUMENT EXECUTION PLAN");
            println!("==============================");
            println!("File: {}", file_path.display());
            println!("Documents: {}", total_docs);
            println!();
        } else {
            println!();
            println!("EXECUTION PLAN");
            println!("==============");
            println!();
        }

        // Print META once at file level (before documents)
        if total_docs > 1 {
            for section in &doc.sections {
                if section.section_type == SectionType::Meta
                    && let SectionContent::Meta(m) = &section.content
                {
                    println!("META");
                    println!("----");
                    if !m.tags.is_empty() {
                        println!("  tags: {:?}", m.tags);
                    }
                    println!();
                    break;
                }
            }
        }

        // Print each document via workflow
        for (doc_idx, d) in doc.iter_chain().enumerate() {
            if total_docs > 1 {
                print_doc_scenario(doc_idx + 1, d);
            } else {
                print_single_doc_workflow(d, file_path);
            }
        }

        // Collect all optimizer hints
        let mut all_optimizations: Vec<optimizer::OptimizationHint> = Vec::new();
        for d in doc.iter_chain() {
            let workflow = Workflow::from_document_with_analysis(d);
            all_optimizations.extend(optimization_hints_from_workflow(&workflow));
        }

        println!("OPTIMIZATION TRACE:");
        if all_optimizations.is_empty() {
            println!("  (no safe rewrites found)");
        } else {
            for hint in &all_optimizations {
                println!(
                    "  - [{}] line {}: {} -> {}",
                    hint.rule_id, hint.line, hint.before, hint.after
                );
            }
        }
        println!();

        // Validation summary
        println!("VALIDATION:");
        let mut all_valid = true;
        for d in doc.iter_chain() {
            let workflow = Workflow::from_document_with_analysis(d);
            if !validation_passed_from_workflow(&workflow) {
                if let Some(crate::execution::WorkflowEvent::ValidationResult { errors, .. }) =
                    workflow.validation_results().first().copied()
                {
                    for e in errors {
                        println!("  FAILED: {}", e);
                    }
                }
                all_valid = false;
            }
        }
        if all_valid {
            println!("  OK - All documents structurally valid.");
        }
        println!();

        println!("TIMING:");
        println!("  Parse:      {:.3}ms", parse_ms);
    }

    Ok(())
}

fn print_doc_scenario(doc_idx: usize, doc: &parser::GctfDocument) {
    let endpoint = doc.get_endpoint().unwrap_or_else(|| "unknown".to_string());
    println!("SCENARIO {}: {}", doc_idx, endpoint);
    println!("  {}", "-".repeat(60));

    // Connection
    if let Some(addr) = doc.get_address(None) {
        println!("  → Connect: {}", addr);
    }

    // Request headers
    if let Some(headers) = doc.get_request_headers() {
        println!("  → Request headers:");
        for (key, value) in sorted_key_values(&headers) {
            println!("    {}: {}", key, value);
        }
    }

    // Options
    if let Some(options) = doc.get_options()
        && !options.is_empty()
    {
        println!("  → Options:");
        for (key, value) in sorted_key_values(&options) {
            println!("    {}: {}", key, value);
        }
    }

    // TLS
    if let Some(tls) = doc.get_tls_config()
        && !tls.is_empty()
    {
        println!("  → TLS config:");
        for (key, value) in sorted_key_values(&tls) {
            println!("    {}: {}", key, value);
        }
    }

    // Proto
    if let Some(proto) = doc.get_proto_config()
        && !proto.is_empty()
    {
        println!("  → Proto config:");
        for (key, value) in sorted_key_values(&proto) {
            println!("    {}: {}", key, value);
        }
    }

    // Requests
    let requests = doc.get_requests();
    if !requests.is_empty() {
        if requests.len() == 1 {
            let json_str = serde_json::to_string_pretty(&requests[0])
                .unwrap_or_else(|_| requests[0].to_string());
            println!("  → Send:");
            for line in json_str.lines() {
                println!("    {}", line);
            }
        } else {
            println!("  → Send {} request(s) (client streaming):", requests.len());
            for (i, req) in requests.iter().enumerate() {
                let json_str =
                    serde_json::to_string_pretty(req).unwrap_or_else(|_| req.to_string());
                println!("    Request #{}:", i + 1);
                for line in json_str.lines() {
                    println!("      {}", line);
                }
            }
        }
    }

    // Expected response
    for section in &doc.sections {
        match section.section_type {
            SectionType::Response => {
                match &section.content {
                    SectionContent::Json(value) => {
                        let json_str = serde_json::to_string_pretty(value)
                            .unwrap_or_else(|_| value.to_string());
                        println!("  ← Expect response:");
                        for line in json_str.lines() {
                            println!("    {}", line);
                        }
                    }
                    SectionContent::JsonLines(values) => {
                        println!(
                            "  ← Expect {} response(s) (server streaming):",
                            values.len()
                        );
                        for (i, v) in values.iter().enumerate() {
                            let json_str =
                                serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string());
                            println!("    Response #{}:", i + 1);
                            for line in json_str.lines() {
                                println!("      {}", line);
                            }
                        }
                    }
                    _ => {}
                }
                if section.inline_options.with_asserts {
                    println!("    [with_asserts]");
                }
                if section.inline_options.partial {
                    println!("    [partial]");
                }
            }
            SectionType::Error => {
                if let SectionContent::Json(value) = &section.content {
                    let json_str =
                        serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string());
                    println!("  ← Expect error:");
                    for line in json_str.lines() {
                        println!("    {}", line);
                    }
                }
                if section.inline_options.with_asserts {
                    println!("    [with_asserts]");
                }
                if section.inline_options.partial {
                    println!("    [partial]");
                }
            }
            _ => {}
        }
    }

    // Extract
    let extractions: Vec<_> = doc
        .sections
        .iter()
        .filter(|s| s.section_type == SectionType::Extract)
        .flat_map(|s| match &s.content {
            SectionContent::Extract(map) => map
                .iter()
                .map(|(k, v)| (k.clone(), v.clone()))
                .collect::<Vec<_>>(),
            _ => Vec::new(),
        })
        .collect();

    if !extractions.is_empty() {
        println!("  ↓ Extract:");
        for (name, expr) in &extractions {
            println!("    {} = {}", name, expr);
        }
    }

    // Assertions from workflow
    let workflow = Workflow::from_document_with_analysis(doc);
    for event in &workflow.events {
        if let crate::execution::WorkflowEvent::Assert {
            count, line_range, ..
        } = event
        {
            println!(
                "{} assertion(s) at lines {}-{}",
                count,
                line_range.0 + 1,
                line_range.1 + 1
            );
        }
        if let crate::execution::WorkflowEvent::SemanticAnalysis {
            type_mismatches,
            unknown_plugins,
        } = event
            && (!type_mismatches.is_empty() || !unknown_plugins.is_empty())
        {
            println!("  ⚠ Semantic issues:");
            for m in type_mismatches {
                println!("    - {}", m.message);
            }
            for u in unknown_plugins {
                println!("    - {}", u.message);
            }
        }
    }

    for section in &doc.sections {
        if section.section_type == SectionType::Asserts
            && let SectionContent::Assertions(assertions) = &section.content
        {
            for (i, a) in assertions.iter().enumerate() {
                let rewritten = optimizer::rewrite_assertion_expression_fixed_point(a);
                println!("    {}. {}", i + 1, rewritten);
            }
        }
    }

    println!();
}

fn print_single_doc_workflow(doc: &parser::GctfDocument, file_path: &Path) {
    println!("FILE: {}", file_path.display());
    println!();

    // META section (if present)
    for section in &doc.sections {
        if section.section_type == SectionType::Meta
            && let SectionContent::Meta(m) = &section.content
        {
            println!("META");
            println!("----");
            if let Some(name) = &m.name {
                println!("  name: {}", name);
            }
            if let Some(summary) = &m.summary {
                println!("  summary: {}", summary);
            }
            if !m.tags.is_empty() {
                println!("  tags: {:?}", m.tags);
            }
            if let Some(owner) = &m.owner {
                println!("  owner: {}", owner);
            }
            if !m.links.is_empty() {
                println!("  links: {:?}", m.links);
            }
            println!();
            break;
        }
    }

    // Connection info
    println!("CONNECTION");
    println!("----------");
    if let Some(addr) = doc.get_address(None) {
        println!("  Address: {}", addr);
    } else {
        println!("  Address: (from GRPCTESTIFY_ADDRESS env or default)");
    }
    println!();

    // Endpoint
    println!("TARGET ENDPOINT");
    println!("---------------");
    if let Some(endpoint) = doc.get_endpoint() {
        println!("  Endpoint: {}", endpoint);
        if let Some((pkg, svc, method)) = doc.parse_endpoint() {
            if !pkg.is_empty() {
                println!("  Package: {}", pkg);
            }
            println!("  Service: {}", svc);
            println!("  Method:  {}", method);
        }
    }
    println!();

    // Workflow
    let workflow = Workflow::from_document_with_analysis(doc);

    println!("EXECUTION WORKFLOW");
    println!("------------------");

    // Headers
    if let Some(headers) = doc.get_request_headers() {
        println!();
        println!("REQUEST HEADERS");
        for (key, value) in sorted_key_values(&headers) {
            println!("  {}: {}", key, value);
        }
    }

    let mut step = 1;
    for section in &doc.sections {
        match section.section_type {
            SectionType::Address => {
                if let SectionContent::Single(addr) = &section.content {
                    println!();
                    println!(
                        "Step {}: ADDRESS [lines {}-{}]",
                        step,
                        section.start_line + 1,
                        section.end_line + 1
                    );
                    println!("  {}", addr);
                    step += 1;
                }
            }
            SectionType::Endpoint => {
                if let SectionContent::Single(endpoint) = &section.content {
                    println!();
                    println!(
                        "Step {}: ENDPOINT [lines {}-{}]",
                        step,
                        section.start_line + 1,
                        section.end_line + 1
                    );
                    println!("  {}", endpoint);
                    step += 1;
                }
            }
            SectionType::RequestHeaders => {
                println!();
                println!(
                    "Step {}: REQUEST HEADERS [lines {}-{}]",
                    step,
                    section.start_line + 1,
                    section.end_line + 1
                );
                if let SectionContent::KeyValues(headers) = &section.content {
                    for (key, value) in sorted_key_values(headers) {
                        println!("  {}: {}", key, value);
                    }
                }
                step += 1;
            }
            SectionType::Request => {
                println!();
                println!(
                    "Step {}: REQUEST [lines {}-{}]",
                    step,
                    section.start_line + 1,
                    section.end_line + 1
                );
                match &section.content {
                    SectionContent::Json(value) => {
                        let json_str = serde_json::to_string_pretty(value)
                            .unwrap_or_else(|_| value.to_string());
                        for line in json_str.lines() {
                            println!("  {}", line);
                        }
                    }
                    SectionContent::Empty => {
                        println!("  {{}} (empty request)");
                    }
                    _ => {}
                }
                step += 1;
            }
            SectionType::Response => {
                println!();
                println!(
                    "Step {}: RESPONSE [lines {}-{}]",
                    step,
                    section.start_line + 1,
                    section.end_line + 1
                );
                match &section.content {
                    SectionContent::Json(value) => {
                        let json_str = serde_json::to_string_pretty(value)
                            .unwrap_or_else(|_| value.to_string());
                        println!("  Expected:");
                        for line in json_str.lines() {
                            println!("    {}", line);
                        }
                    }
                    SectionContent::JsonLines(values) => {
                        println!("  Expected {} response(s):", values.len());
                        for (i, v) in values.iter().enumerate() {
                            let json_str =
                                serde_json::to_string_pretty(v).unwrap_or_else(|_| v.to_string());
                            println!("    {}. {}", i + 1, json_str);
                        }
                    }
                    _ => {}
                }
                let mut opts = Vec::new();
                if section.inline_options.with_asserts {
                    opts.push("with_asserts");
                }
                if section.inline_options.partial {
                    opts.push("partial");
                }
                if !opts.is_empty() {
                    println!("  Options: {}", opts.join(", "));
                }
                step += 1;
            }
            SectionType::Error => {
                println!();
                println!(
                    "Step {}: EXPECTED ERROR [lines {}-{}]",
                    step,
                    section.start_line + 1,
                    section.end_line + 1
                );
                if let SectionContent::Json(value) = &section.content {
                    let json_str =
                        serde_json::to_string_pretty(value).unwrap_or_else(|_| value.to_string());
                    println!("  Expected error:");
                    for line in json_str.lines() {
                        println!("    {}", line);
                    }
                } else if matches!(section.content, SectionContent::Empty) {
                    println!("  Expected error (no body, assertions-only)");
                }
                let mut opts = Vec::new();
                if section.inline_options.with_asserts {
                    opts.push("with_asserts");
                }
                if section.inline_options.partial {
                    opts.push("partial");
                }
                if !opts.is_empty() {
                    println!("  Options: {}", opts.join(", "));
                }
                step += 1;
            }
            SectionType::Extract => {
                println!();
                println!(
                    "Step {}: EXTRACT [lines {}-{}]",
                    step,
                    section.start_line + 1,
                    section.end_line + 1
                );
                if let SectionContent::Extract(extractions) = &section.content {
                    for (name, expr) in sorted_key_values(extractions) {
                        println!("  ${{ {} }} = {}", name, expr);
                    }
                }
                step += 1;
            }
            SectionType::Asserts => {
                println!();
                println!(
                    "Step {}: ASSERTS [lines {}-{}]",
                    step,
                    section.start_line + 1,
                    section.end_line + 1
                );
                if let SectionContent::Assertions(assertions) = &section.content {
                    for (i, a) in assertions.iter().enumerate() {
                        let rewritten = optimizer::rewrite_assertion_expression_fixed_point(a);
                        println!("  {}. {}", i + 1, rewritten);
                    }
                }
                step += 1;
            }
            SectionType::Options => {
                println!();
                println!(
                    "Step {}: OPTIONS [lines {}-{}]",
                    step,
                    section.start_line + 1,
                    section.end_line + 1
                );
                if let SectionContent::KeyValues(options) = &section.content {
                    if options.is_empty() {
                        println!("  (no runtime overrides)");
                    } else {
                        println!("  Runtime overrides:");
                        for (key, value) in sorted_key_values(options) {
                            println!("    {}: {}", key, value);
                        }
                    }
                }
                step += 1;
            }
            SectionType::Tls | SectionType::Proto => {
                println!();
                println!(
                    "Step {}: {} [lines {}-{}]",
                    step,
                    section.section_type.as_str(),
                    section.start_line + 1,
                    section.end_line + 1
                );
                println!("  (configuration section)");
                step += 1;
            }
            SectionType::Meta => {}
        }
    }

    // Summary
    println!();
    println!("EXECUTION SUMMARY");
    println!("-----------------");
    println!("  RPC Mode: {}", workflow.rpc_mode_name());
    if workflow.has_streaming() {
        println!("  Streaming: enabled");
    }
}