mockforge-ui 0.3.88

Admin UI for MockForge - web-based interface for managing mock servers
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
//! Behavioral cloning handlers for Admin UI
//!
//! This module provides API endpoints for managing flows and scenarios
//! in the Admin UI.

use axum::{
    extract::{Path, Query, State},
    response::Json,
};
use mockforge_recorder::behavioral_cloning::{
    flow_recorder::{FlowRecorder, FlowRecordingConfig},
    FlowCompiler, ScenarioStorage,
};
use mockforge_recorder::RecorderDatabase;
use serde::Deserialize;
use serde_json::{json, Value};
use std::collections::HashMap;

use crate::handlers::AdminState;
use crate::models::ApiResponse;

/// Get list of flows
pub async fn get_flows(
    State(_state): State<AdminState>,
    Query(params): Query<HashMap<String, String>>,
) -> Json<ApiResponse<Value>> {
    // Get database path from config or use default
    let db_path = params
        .get("db_path")
        .cloned()
        .unwrap_or_else(|| "./mockforge-recordings.db".to_string());

    let limit = params.get("limit").and_then(|s| s.parse::<usize>().ok()).unwrap_or(50);

    match RecorderDatabase::new(&db_path).await {
        Ok(db) => {
            let recorder = FlowRecorder::new(db.clone(), FlowRecordingConfig::default());
            match recorder.list_flows(Some(limit)).await {
                Ok(flows) => {
                    let flows_json: Vec<Value> = flows
                        .into_iter()
                        .map(|flow| {
                            json!({
                                "id": flow.id,
                                "name": flow.name,
                                "description": flow.description,
                                "created_at": flow.created_at,
                                "tags": flow.tags,
                                "step_count": flow.steps.len(),
                            })
                        })
                        .collect();

                    Json(ApiResponse {
                        success: true,
                        data: Some(json!({
                            "flows": flows_json,
                            "total": flows_json.len()
                        })),
                        error: None,
                        timestamp: chrono::Utc::now(),
                    })
                }
                Err(e) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Failed to list flows: {}", e)),
                    timestamp: chrono::Utc::now(),
                }),
            }
        }
        Err(e) => Json(ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Failed to connect to database: {}", e)),
            timestamp: chrono::Utc::now(),
        }),
    }
}

/// Get flow details with timeline
pub async fn get_flow(
    State(_state): State<AdminState>,
    Path(flow_id): Path<String>,
    Query(params): Query<HashMap<String, String>>,
) -> Json<ApiResponse<Value>> {
    let db_path = params
        .get("db_path")
        .cloned()
        .unwrap_or_else(|| "./mockforge-recordings.db".to_string());

    match RecorderDatabase::new(&db_path).await {
        Ok(db) => {
            let recorder = FlowRecorder::new(db.clone(), FlowRecordingConfig::default());
            match recorder.get_flow(&flow_id).await {
                Ok(Some(flow)) => {
                    // Build timeline data
                    let steps: Vec<Value> = flow
                        .steps
                        .iter()
                        .enumerate()
                        .map(|(idx, step)| {
                            json!({
                                "index": idx,
                                "request_id": step.request_id,
                                "step_label": step.step_label,
                                "timing_ms": step.timing_ms,
                            })
                        })
                        .collect();

                    Json(ApiResponse {
                        success: true,
                        data: Some(json!({
                            "id": flow.id,
                            "name": flow.name,
                            "description": flow.description,
                            "created_at": flow.created_at,
                            "tags": flow.tags,
                            "steps": steps,
                            "step_count": steps.len(),
                        })),
                        error: None,
                        timestamp: chrono::Utc::now(),
                    })
                }
                Ok(None) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Flow not found: {}", flow_id)),
                    timestamp: chrono::Utc::now(),
                }),
                Err(e) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Failed to get flow: {}", e)),
                    timestamp: chrono::Utc::now(),
                }),
            }
        }
        Err(e) => Json(ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Failed to connect to database: {}", e)),
            timestamp: chrono::Utc::now(),
        }),
    }
}

/// Tag a flow
#[derive(Deserialize)]
pub struct TagFlowRequest {
    pub name: Option<String>,
    pub description: Option<String>,
    pub tags: Option<Vec<String>>,
}

pub async fn tag_flow(
    State(_state): State<AdminState>,
    Path(flow_id): Path<String>,
    Query(params): Query<HashMap<String, String>>,
    Json(payload): Json<TagFlowRequest>,
) -> Json<ApiResponse<Value>> {
    let db_path = params
        .get("db_path")
        .cloned()
        .unwrap_or_else(|| "./mockforge-recordings.db".to_string());

    match RecorderDatabase::new(&db_path).await {
        Ok(db) => {
            let _recorder = FlowRecorder::new(db.clone(), FlowRecordingConfig::default());
            match db
                .update_flow_metadata(
                    &flow_id,
                    payload.name.as_deref(),
                    payload.description.as_deref(),
                    Some(&payload.tags.unwrap_or_default()),
                )
                .await
            {
                Ok(_) => Json(ApiResponse {
                    success: true,
                    data: Some(json!({
                        "message": "Flow tagged successfully",
                        "flow_id": flow_id
                    })),
                    error: None,
                    timestamp: chrono::Utc::now(),
                }),
                Err(e) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Failed to tag flow: {}", e)),
                    timestamp: chrono::Utc::now(),
                }),
            }
        }
        Err(e) => Json(ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Failed to connect to database: {}", e)),
            timestamp: chrono::Utc::now(),
        }),
    }
}

/// Compile flow to scenario
#[derive(Deserialize)]
pub struct CompileFlowRequest {
    pub scenario_name: String,
    pub flex_mode: Option<bool>,
}

pub async fn compile_flow(
    State(_state): State<AdminState>,
    Path(flow_id): Path<String>,
    Query(params): Query<HashMap<String, String>>,
    Json(payload): Json<CompileFlowRequest>,
) -> Json<ApiResponse<Value>> {
    let db_path = params
        .get("db_path")
        .cloned()
        .unwrap_or_else(|| "./mockforge-recordings.db".to_string());

    match RecorderDatabase::new(&db_path).await {
        Ok(db) => {
            let recorder = FlowRecorder::new(db.clone(), FlowRecordingConfig::default());
            match recorder.get_flow(&flow_id).await {
                Ok(Some(flow)) => {
                    let compiler = FlowCompiler::new(db.clone());
                    let strict_mode = !payload.flex_mode.unwrap_or(false);
                    match compiler
                        .compile_flow(&flow, payload.scenario_name.clone(), strict_mode)
                        .await
                    {
                        Ok(scenario) => {
                            // Store the scenario
                            let storage = ScenarioStorage::new(db);
                            match storage.store_scenario_auto_version(&scenario).await {
                                Ok(version) => Json(ApiResponse {
                                    success: true,
                                    data: Some(json!({
                                        "scenario_id": scenario.id,
                                        "scenario_name": scenario.name,
                                        "version": version,
                                        "message": "Flow compiled successfully"
                                    })),
                                    error: None,
                                    timestamp: chrono::Utc::now(),
                                }),
                                Err(e) => Json(ApiResponse {
                                    success: false,
                                    data: None,
                                    error: Some(format!("Failed to store scenario: {}", e)),
                                    timestamp: chrono::Utc::now(),
                                }),
                            }
                        }
                        Err(e) => Json(ApiResponse {
                            success: false,
                            data: None,
                            error: Some(format!("Failed to compile flow: {}", e)),
                            timestamp: chrono::Utc::now(),
                        }),
                    }
                }
                Ok(None) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Flow not found: {}", flow_id)),
                    timestamp: chrono::Utc::now(),
                }),
                Err(e) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Failed to get flow: {}", e)),
                    timestamp: chrono::Utc::now(),
                }),
            }
        }
        Err(e) => Json(ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Failed to connect to database: {}", e)),
            timestamp: chrono::Utc::now(),
        }),
    }
}

/// Get list of scenarios
pub async fn get_scenarios(
    State(_state): State<AdminState>,
    Query(params): Query<HashMap<String, String>>,
) -> Json<ApiResponse<Value>> {
    let db_path = params
        .get("db_path")
        .cloned()
        .unwrap_or_else(|| "./mockforge-recordings.db".to_string());

    let limit = params.get("limit").and_then(|s| s.parse::<usize>().ok()).unwrap_or(50);

    match RecorderDatabase::new(&db_path).await {
        Ok(db) => {
            let storage = ScenarioStorage::new(db);
            match storage.list_scenarios(Some(limit)).await {
                Ok(scenarios) => {
                    let scenarios_json: Vec<Value> = scenarios
                        .into_iter()
                        .map(|s| {
                            json!({
                                "id": s.id,
                                "name": s.name,
                                "version": s.version,
                                "description": s.description,
                                "created_at": s.created_at,
                                "updated_at": s.updated_at,
                                "tags": s.tags,
                            })
                        })
                        .collect();

                    Json(ApiResponse {
                        success: true,
                        data: Some(json!({
                            "scenarios": scenarios_json,
                            "total": scenarios_json.len()
                        })),
                        error: None,
                        timestamp: chrono::Utc::now(),
                    })
                }
                Err(e) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Failed to list scenarios: {}", e)),
                    timestamp: chrono::Utc::now(),
                }),
            }
        }
        Err(e) => Json(ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Failed to connect to database: {}", e)),
            timestamp: chrono::Utc::now(),
        }),
    }
}

/// Get scenario details
pub async fn get_scenario(
    State(_state): State<AdminState>,
    Path(scenario_id): Path<String>,
    Query(params): Query<HashMap<String, String>>,
) -> Json<ApiResponse<Value>> {
    let db_path = params
        .get("db_path")
        .cloned()
        .unwrap_or_else(|| "./mockforge-recordings.db".to_string());

    match RecorderDatabase::new(&db_path).await {
        Ok(db) => {
            let storage = ScenarioStorage::new(db);
            match storage.get_scenario(&scenario_id).await {
                Ok(Some(scenario)) => {
                    let steps: Vec<Value> = scenario
                        .steps
                        .iter()
                        .map(|step| {
                            json!({
                                "step_id": step.step_id,
                                "label": step.label,
                                "method": step.request.method,
                                "path": step.request.path,
                                "status_code": step.response.status_code,
                                "timing_ms": step.timing_ms,
                            })
                        })
                        .collect();

                    Json(ApiResponse {
                        success: true,
                        data: Some(json!({
                            "id": scenario.id,
                            "name": scenario.name,
                            "description": scenario.description,
                            "strict_mode": scenario.strict_mode,
                            "steps": steps,
                            "step_count": steps.len(),
                            "state_variables": scenario.state_variables.len(),
                        })),
                        error: None,
                        timestamp: chrono::Utc::now(),
                    })
                }
                Ok(None) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Scenario not found: {}", scenario_id)),
                    timestamp: chrono::Utc::now(),
                }),
                Err(e) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Failed to get scenario: {}", e)),
                    timestamp: chrono::Utc::now(),
                }),
            }
        }
        Err(e) => Json(ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Failed to connect to database: {}", e)),
            timestamp: chrono::Utc::now(),
        }),
    }
}

/// Export scenario
pub async fn export_scenario(
    State(_state): State<AdminState>,
    Path(scenario_id): Path<String>,
    Query(params): Query<HashMap<String, String>>,
) -> Json<ApiResponse<Value>> {
    let db_path = params
        .get("db_path")
        .cloned()
        .unwrap_or_else(|| "./mockforge-recordings.db".to_string());

    let format = params.get("format").cloned().unwrap_or_else(|| "yaml".to_string());

    match RecorderDatabase::new(&db_path).await {
        Ok(db) => {
            let storage = ScenarioStorage::new(db);
            match storage.export_scenario(&scenario_id, &format).await {
                Ok(content) => Json(ApiResponse {
                    success: true,
                    data: Some(json!({
                        "scenario_id": scenario_id,
                        "format": format,
                        "content": content,
                    })),
                    error: None,
                    timestamp: chrono::Utc::now(),
                }),
                Err(e) => Json(ApiResponse {
                    success: false,
                    data: None,
                    error: Some(format!("Failed to export scenario: {}", e)),
                    timestamp: chrono::Utc::now(),
                }),
            }
        }
        Err(e) => Json(ApiResponse {
            success: false,
            data: None,
            error: Some(format!("Failed to connect to database: {}", e)),
            timestamp: chrono::Utc::now(),
        }),
    }
}