mockforge-cli 0.3.116

CLI interface for MockForge
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
//! Orchestrate and Suggest commands
//!
//! CLI commands for chaos orchestration and AI-powered spec suggestion.

use clap::Subcommand;
use std::path::PathBuf;

#[derive(Subcommand)]
pub(crate) enum OrchestrateCommands {
    /// Start a chaos orchestration from file
    ///
    /// Example:
    ///   mockforge orchestrate start --file orchestration.yaml --base-url http://localhost:3000
    #[command(verbatim_doc_comment)]
    Start {
        /// Orchestration file (JSON or YAML)
        #[arg(short, long)]
        file: PathBuf,

        /// Base URL for API requests
        #[arg(long, default_value = "http://localhost:3000")]
        base_url: String,
    },

    /// Get orchestration status
    Status {
        /// Base URL for API requests
        #[arg(long, default_value = "http://localhost:3000")]
        base_url: String,
    },

    /// Stop running orchestration
    Stop {
        /// Base URL for API requests
        #[arg(long, default_value = "http://localhost:3000")]
        base_url: String,
    },

    /// Validate an orchestration file
    Validate {
        /// Orchestration file (JSON or YAML)
        #[arg(short, long)]
        file: PathBuf,
    },

    /// Export an orchestration template
    ///
    /// Example:
    ///   mockforge orchestrate template --output my_orchestration.yaml --format yaml
    #[command(verbatim_doc_comment)]
    Template {
        /// Output file path
        #[arg(short, long)]
        output: PathBuf,

        /// Format (json or yaml)
        #[arg(long, default_value = "yaml")]
        format: String,
    },
}

pub(crate) async fn handle_orchestrate(
    command: OrchestrateCommands,
) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    match command {
        OrchestrateCommands::Start { file, base_url } => {
            println!("\u{1f680} Starting chaos orchestration from: {}", file.display());

            // Read orchestration file
            let content = std::fs::read_to_string(&file)?;
            let format = if file.extension().and_then(|s| s.to_str()) == Some("json") {
                "json"
            } else {
                "yaml"
            };

            // Send to API
            let client = reqwest::Client::new();
            let url = format!("{}/api/chaos/orchestration/import", base_url);

            let response = client
                .post(&url)
                .json(&serde_json::json!({
                    "content": content,
                    "format": format
                }))
                .send()
                .await?;

            if response.status().is_success() {
                let result: serde_json::Value = response.json().await?;
                println!(
                    "\u{2705} {}",
                    result["message"].as_str().unwrap_or("Orchestration imported")
                );

                // Now start it
                let _start_url = format!("{}/api/chaos/orchestration/start", base_url);
                // Note: This is a simplified version - would need to parse and send proper request
                println!("   Use the API to start the orchestration");
            } else {
                eprintln!("\u{274c} Failed to import orchestration: {}", response.status());
            }
        }

        OrchestrateCommands::Status { base_url } => {
            println!("\u{1f4ca} Checking orchestration status...");

            let client = reqwest::Client::new();
            let url = format!("{}/api/chaos/orchestration/status", base_url);

            let response = client.get(&url).send().await?;

            if response.status().is_success() {
                let status: serde_json::Value = response.json().await?;

                if status["is_running"].as_bool().unwrap_or(false) {
                    println!("\u{2705} Orchestration is running");
                    println!("   Name: {}", status["name"].as_str().unwrap_or("Unknown"));
                    println!(
                        "   Progress: {:.1}%",
                        status["progress"].as_f64().unwrap_or(0.0) * 100.0
                    );
                } else {
                    println!("\u{23f8}\u{fe0f}  No orchestration currently running");
                }
            } else {
                eprintln!("\u{274c} Failed to get status: {}", response.status());
            }
        }

        OrchestrateCommands::Stop { base_url } => {
            println!("\u{1f6d1} Stopping orchestration...");

            let client = reqwest::Client::new();
            let url = format!("{}/api/chaos/orchestration/stop", base_url);

            let response = client.post(&url).send().await?;

            if response.status().is_success() {
                let result: serde_json::Value = response.json().await?;
                println!(
                    "\u{2705} {}",
                    result["message"].as_str().unwrap_or("Orchestration stopped")
                );
            } else {
                eprintln!("\u{274c} Failed to stop orchestration: {}", response.status());
            }
        }

        OrchestrateCommands::Validate { file } => {
            println!("\u{1f50d} Validating orchestration file: {}", file.display());

            // Check if file exists
            if !file.exists() {
                eprintln!("\u{274c} File not found: {}", file.display());
                return Err("File not found".into());
            }

            // Read and parse file
            let content = std::fs::read_to_string(&file)?;
            let is_json = file.extension().and_then(|s| s.to_str()) == Some("json");

            let parse_result: Result<serde_json::Value, String> = if is_json {
                serde_json::from_str::<serde_json::Value>(&content)
                    .map_err(|e| crate::config_commands::format_json_error(&content, e))
            } else {
                // Parse as YAML, then convert to JSON Value for uniform handling
                serde_yaml::from_str::<serde_yaml::Value>(&content)
                    .map_err(|e| crate::config_commands::format_yaml_error(&content, e))
                    .and_then(|yaml_val| {
                        serde_json::to_value(yaml_val)
                            .map_err(|e| format!("Failed to convert YAML to JSON: {}", e))
                    })
            };

            match parse_result {
                Ok(value) => {
                    // Validate structure
                    let mut errors = Vec::new();
                    let mut warnings = Vec::new();

                    // Check for required fields
                    if value.get("name").is_none() {
                        errors.push("Missing required field 'name'".to_string());
                    } else if !value["name"].is_string() {
                        errors.push("Field 'name' must be a string".to_string());
                    }

                    // Validate steps array
                    match value.get("steps") {
                        None => {
                            errors.push("Missing required field 'steps'".to_string());
                        }
                        Some(steps) => {
                            if let Some(steps_arr) = steps.as_array() {
                                if steps_arr.is_empty() {
                                    warnings.push(
                                        "Steps array is empty - orchestration won't do anything"
                                            .to_string(),
                                    );
                                }

                                // Validate each step
                                for (idx, step) in steps_arr.iter().enumerate() {
                                    let step_num = idx + 1;

                                    if !step.is_object() {
                                        errors.push(format!("Step #{} is not an object", step_num));
                                        continue;
                                    }

                                    // Check step name
                                    if step.get("name").is_none() {
                                        errors.push(format!(
                                            "Step #{} is missing 'name' field",
                                            step_num
                                        ));
                                    }

                                    // Check scenario
                                    match step.get("scenario") {
                                        None => {
                                            errors.push(format!(
                                                "Step #{} is missing 'scenario' field",
                                                step_num
                                            ));
                                        }
                                        Some(scenario) => {
                                            if scenario.get("name").is_none() {
                                                errors.push(format!(
                                                    "Step #{} scenario is missing 'name' field",
                                                    step_num
                                                ));
                                            }
                                            if scenario.get("config").is_none() {
                                                errors.push(format!(
                                                    "Step #{} scenario is missing 'config' field",
                                                    step_num
                                                ));
                                            }
                                        }
                                    }

                                    // Check duration
                                    if step.get("duration_seconds").is_none() {
                                        warnings.push(format!("Step #{} is missing 'duration_seconds' - using default", step_num));
                                    } else if !step["duration_seconds"].is_number() {
                                        errors.push(format!(
                                            "Step #{} 'duration_seconds' must be a number",
                                            step_num
                                        ));
                                    }

                                    // Check delay
                                    if let Some(delay) = step.get("delay_before_seconds") {
                                        if !delay.is_number() {
                                            errors.push(format!(
                                                "Step #{} 'delay_before_seconds' must be a number",
                                                step_num
                                            ));
                                        }
                                    }
                                }
                            } else {
                                errors.push("Field 'steps' must be an array".to_string());
                            }
                        }
                    }

                    // Print results
                    if !errors.is_empty() {
                        println!("\u{274c} Orchestration file has errors:");
                        for error in &errors {
                            println!("   \u{2717} {}", error);
                        }
                        return Err("Validation failed".into());
                    }

                    println!("\u{2705} Orchestration file is valid");

                    // Show summary
                    if let Some(name) = value.get("name").and_then(|v| v.as_str()) {
                        println!("\n\u{1f4ca} Summary:");
                        println!("   Name: {}", name);
                        if let Some(desc) = value.get("description").and_then(|v| v.as_str()) {
                            println!("   Description: {}", desc);
                        }
                        if let Some(steps) = value.get("steps").and_then(|v| v.as_array()) {
                            println!("   Steps: {}", steps.len());
                        }
                    }

                    if !warnings.is_empty() {
                        println!("\n\u{26a0}\u{fe0f}  Warnings:");
                        for warning in warnings {
                            println!("   - {}", warning);
                        }
                    }
                }
                Err(error_msg) => {
                    println!("\u{274c} Orchestration file validation failed:\n");
                    println!("{}", error_msg);
                    return Err("Invalid orchestration file".into());
                }
            }
        }

        OrchestrateCommands::Template { output, format } => {
            println!("\u{1f4dd} Generating orchestration template...");

            let template = if format == "json" {
                serde_json::to_string_pretty(&serde_json::json!({
                    "name": "example_orchestration",
                    "description": "Example chaos orchestration",
                    "steps": [
                        {
                            "name": "warmup",
                            "scenario": {
                                "name": "network_degradation",
                                "config": {
                                    "enabled": true,
                                    "latency": {
                                        "enabled": true,
                                        "fixed_delay_ms": 100
                                    }
                                }
                            },
                            "duration_seconds": 60,
                            "delay_before_seconds": 0,
                            "continue_on_failure": false
                        },
                        {
                            "name": "peak_load",
                            "scenario": {
                                "name": "peak_traffic",
                                "config": {
                                    "enabled": true,
                                    "rate_limit": {
                                        "enabled": true,
                                        "requests_per_second": 100
                                    }
                                }
                            },
                            "duration_seconds": 120,
                            "delay_before_seconds": 10,
                            "continue_on_failure": true
                        }
                    ],
                    "parallel": false,
                    "loop_orchestration": false,
                    "max_iterations": 1,
                    "tags": ["example", "test"]
                }))?
            } else {
                "name: example_orchestration
description: Example chaos orchestration
steps:
  - name: warmup
    scenario:
      name: network_degradation
      config:
        enabled: true
        latency:
          enabled: true
          fixed_delay_ms: 100
    duration_seconds: 60
    delay_before_seconds: 0
    continue_on_failure: false
  - name: peak_load
    scenario:
      name: peak_traffic
      config:
        enabled: true
        rate_limit:
          enabled: true
          requests_per_second: 100
    duration_seconds: 120
    delay_before_seconds: 10
    continue_on_failure: true
parallel: false
loop_orchestration: false
max_iterations: 1
tags:
  - example
  - test
"
                .to_string()
            };

            std::fs::write(&output, template)?;
            println!("\u{2705} Template saved to: {}", output.display());
        }
    }

    Ok(())
}

/// Handle AI-powered spec suggestion command
#[allow(clippy::too_many_arguments)]
pub(crate) async fn handle_suggest(
    from: Option<PathBuf>,
    from_description: Option<String>,
    format: String,
    output: Option<PathBuf>,
    num_suggestions: usize,
    include_examples: bool,
    domain: Option<String>,
    llm_provider: String,
    llm_model: Option<String>,
    llm_endpoint: Option<String>,
    llm_api_key: Option<String>,
    temperature: f64,
    print_json: bool,
) -> anyhow::Result<()> {
    use mockforge_core::intelligent_behavior::{
        config::BehaviorModelConfig, OutputFormat, SpecSuggestionEngine, SuggestionConfig,
        SuggestionInput,
    };

    // Determine output format
    let output_format = format.parse::<OutputFormat>().map_err(|e| anyhow::anyhow!("{}", e))?;

    // Build LLM config
    let default_model = match llm_provider.to_lowercase().as_str() {
        "openai" => "gpt-4o-mini",
        "anthropic" => "claude-3-5-sonnet-20241022",
        "ollama" => "llama3.1",
        _ => "gpt-4o-mini",
    };

    let llm_config = BehaviorModelConfig {
        llm_provider: llm_provider.clone(),
        model: llm_model.unwrap_or_else(|| default_model.to_string()),
        api_endpoint: llm_endpoint,
        api_key: llm_api_key,
        temperature,
        max_tokens: 4000,
        ..Default::default()
    };

    // Build suggestion config
    let suggestion_config = SuggestionConfig {
        llm_config,
        output_format,
        num_suggestions,
        include_examples,
        domain_hint: domain,
    };

    // Parse input
    let input = if let Some(description) = from_description {
        SuggestionInput::Description { text: description }
    } else if let Some(input_path) = from {
        let content = tokio::fs::read_to_string(&input_path).await?;
        let json_value: serde_json::Value = serde_json::from_str(&content)?;

        // Try to detect input type
        if let Some(method) = json_value.get("method").and_then(|v| v.as_str()) {
            // Single endpoint format
            SuggestionInput::Endpoint {
                method: method.to_string(),
                path: json_value
                    .get("path")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| anyhow::anyhow!("Missing 'path' field in endpoint input"))?
                    .to_string(),
                request: json_value.get("request").cloned(),
                response: json_value.get("response").cloned(),
                description: json_value
                    .get("description")
                    .and_then(|v| v.as_str())
                    .map(String::from),
            }
        } else if json_value.get("openapi").is_some() || json_value.get("paths").is_some() {
            // Partial OpenAPI spec
            SuggestionInput::PartialSpec { spec: json_value }
        } else if let Some(paths_array) = json_value.get("paths").and_then(|v| v.as_array()) {
            // List of paths
            let paths = paths_array.iter().filter_map(|v| v.as_str().map(String::from)).collect();
            SuggestionInput::Paths { paths }
        } else {
            return Err(anyhow::anyhow!(
                "Unable to detect input type. Expected 'method' field for endpoint, \
                 'openapi' for spec, or 'paths' array"
            ));
        }
    } else {
        return Err(anyhow::anyhow!(
            "Must provide either --from <file> or --from-description <text>"
        ));
    };

    println!("\u{1f916} Generating API specification suggestions...");
    println!("   Provider: {}", llm_provider);
    println!("   Model: {}", suggestion_config.llm_config.model);
    println!("   Suggestions: {}", num_suggestions);
    if let Some(ref d) = suggestion_config.domain_hint {
        println!("   Domain: {}", d);
    }
    println!();

    // Create engine and generate suggestions
    let engine = SpecSuggestionEngine::new(suggestion_config);
    let result = engine.suggest(&input).await?;

    // Print results
    if print_json {
        println!("{}", serde_json::to_string_pretty(&result)?);
    } else {
        println!("\u{2705} Generated {} endpoint suggestions", result.metadata.endpoint_count);
        if let Some(domain) = &result.metadata.detected_domain {
            println!("   Detected domain: {}", domain);
        }
        println!();

        // Print endpoint suggestions
        println!("\u{1f4dd} Suggested Endpoints:");
        for (i, suggestion) in result.suggestions.iter().enumerate() {
            println!("\n{}. {} {}", i + 1, suggestion.method, suggestion.path);
            println!("   {}", suggestion.description);
            if !suggestion.parameters.is_empty() {
                println!("   Parameters:");
                for param in &suggestion.parameters {
                    let req = if param.required {
                        "required"
                    } else {
                        "optional"
                    };
                    println!(
                        "     - {} ({}): {} [{}]",
                        param.name, param.location, param.data_type, req
                    );
                }
            }
            if !suggestion.reasoning.is_empty() {
                println!("   \u{1f4a1} {}", suggestion.reasoning);
            }
        }
        println!();

        // Save specs to file(s)
        if let Some(base_path) = output {
            match output_format {
                OutputFormat::OpenAPI => {
                    if let Some(spec) = &result.openapi_spec {
                        let yaml = serde_yaml::to_string(spec)?;
                        tokio::fs::write(&base_path, yaml).await?;
                        println!("\u{2705} OpenAPI spec saved to: {}", base_path.display());
                    } else {
                        println!("\u{26a0}\u{fe0f}  No OpenAPI spec generated");
                    }
                }
                OutputFormat::MockForge => {
                    if let Some(config) = &result.mockforge_config {
                        let yaml = serde_yaml::to_string(config)?;
                        tokio::fs::write(&base_path, yaml).await?;
                        println!("\u{2705} MockForge config saved to: {}", base_path.display());
                    } else {
                        println!("\u{26a0}\u{fe0f}  No MockForge config generated");
                    }
                }
                OutputFormat::Both => {
                    // Save both with different extensions
                    let openapi_path = base_path.with_extension("openapi.yaml");
                    let mockforge_path = base_path.with_extension("mockforge.yaml");

                    if let Some(spec) = &result.openapi_spec {
                        let yaml = serde_yaml::to_string(spec)?;
                        tokio::fs::write(&openapi_path, yaml).await?;
                        println!("\u{2705} OpenAPI spec saved to: {}", openapi_path.display());
                    }

                    if let Some(config) = &result.mockforge_config {
                        let yaml = serde_yaml::to_string(config)?;
                        tokio::fs::write(&mockforge_path, yaml).await?;
                        println!(
                            "\u{2705} MockForge config saved to: {}",
                            mockforge_path.display()
                        );
                    }
                }
            }
        } else {
            println!("\u{1f4a1} Tip: Use --output <file> to save the generated specification");
        }
    }

    Ok(())
}