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
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
//! Enhanced Analytics API handlers with persistent storage
//!
//! This module provides comprehensive analytics endpoints that combine:
//! - Real-time metrics from Prometheus
//! - Historical data from the analytics database
//! - Advanced queries (time-series, trends, patterns)

use axum::{
    extract::{Query, State},
    http::StatusCode,
    Json,
};
use chrono::Utc;
use mockforge_analytics::{AnalyticsDatabase, AnalyticsFilter, Granularity, OverviewMetrics};
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use tracing::{debug, error};

use crate::models::ApiResponse;

/// Enhanced analytics state with both Prometheus and database access
#[derive(Clone)]
pub struct AnalyticsV2State {
    pub db: Arc<AnalyticsDatabase>,
}

impl AnalyticsV2State {
    pub fn new(db: AnalyticsDatabase) -> Self {
        Self { db: Arc::new(db) }
    }
}

/// Query parameters for analytics endpoints
#[derive(Debug, Deserialize)]
pub struct AnalyticsQuery {
    /// Start time (Unix timestamp)
    pub start_time: Option<i64>,
    /// End time (Unix timestamp)
    pub end_time: Option<i64>,
    /// Duration in seconds (alternative to start/end)
    #[serde(default = "default_duration")]
    pub duration: i64,
    /// Protocol filter (HTTP, gRPC, WebSocket, etc.)
    pub protocol: Option<String>,
    /// Endpoint filter
    pub endpoint: Option<String>,
    /// Method filter (GET, POST, etc.)
    pub method: Option<String>,
    /// Status code filter
    pub status_code: Option<i32>,
    /// Workspace ID filter
    pub workspace_id: Option<String>,
    /// Environment filter (dev, staging, prod)
    pub environment: Option<String>,
    /// Limit results
    #[serde(default = "default_limit")]
    pub limit: i64,
    /// Granularity for time-series data
    #[serde(default = "default_granularity")]
    pub granularity: String,
}

fn default_duration() -> i64 {
    3600 // 1 hour
}

fn default_limit() -> i64 {
    100
}

fn default_granularity() -> String {
    "minute".to_string()
}

impl AnalyticsQuery {
    /// Convert to AnalyticsFilter
    fn to_filter(&self) -> AnalyticsFilter {
        let (start_time, end_time) =
            if let (Some(start), Some(end)) = (self.start_time, self.end_time) {
                (Some(start), Some(end))
            } else {
                let end = Utc::now().timestamp();
                let start = end - self.duration;
                (Some(start), Some(end))
            };

        AnalyticsFilter {
            start_time,
            end_time,
            protocol: self.protocol.clone(),
            endpoint: self.endpoint.clone(),
            method: self.method.clone(),
            status_code: self.status_code,
            workspace_id: self.workspace_id.clone(),
            environment: self.environment.clone(),
            limit: Some(self.limit),
        }
    }

    /// Parse granularity string
    fn get_granularity(&self) -> Granularity {
        match self.granularity.as_str() {
            "minute" => Granularity::Minute,
            "hour" => Granularity::Hour,
            "day" => Granularity::Day,
            _ => Granularity::Minute,
        }
    }
}

// ============================================================================
// REST API Endpoints
// ============================================================================

/// GET /api/v2/analytics/overview
///
/// Get dashboard overview metrics including:
/// - Total requests, errors, error rate
/// - Latency percentiles (avg, p50, p95, p99)
/// - Active connections, throughput
/// - Top protocols and endpoints
pub async fn get_overview(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<AnalyticsQuery>,
) -> Result<Json<ApiResponse<OverviewMetrics>>, StatusCode> {
    debug!("Fetching analytics overview for duration: {}s", query.duration);

    match state.db.get_overview_metrics(query.duration).await {
        Ok(overview) => Ok(Json(ApiResponse::success(overview))),
        Err(e) => {
            error!("Failed to get overview metrics: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

/// GET /api/v2/analytics/requests
///
/// Get request count time-series data
#[derive(Debug, Serialize)]
pub struct TimeSeriesResponse {
    pub series: Vec<SeriesData>,
}

#[derive(Debug, Serialize)]
pub struct SeriesData {
    pub label: String,
    pub data: Vec<DataPoint>,
}

#[derive(Debug, Serialize)]
pub struct DataPoint {
    pub timestamp: i64,
    pub value: f64,
}

pub async fn get_requests_timeseries(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<AnalyticsQuery>,
) -> Result<Json<ApiResponse<TimeSeriesResponse>>, StatusCode> {
    debug!("Fetching request time-series");

    let filter = query.to_filter();
    let granularity = query.get_granularity();

    match state.db.get_request_time_series(&filter, granularity).await {
        Ok(time_series) => {
            let series = time_series
                .into_iter()
                .map(|ts| SeriesData {
                    label: ts.label,
                    data: ts
                        .data
                        .into_iter()
                        .map(|point| DataPoint {
                            timestamp: point.timestamp,
                            value: point.value,
                        })
                        .collect(),
                })
                .collect();

            Ok(Json(ApiResponse::success(TimeSeriesResponse { series })))
        }
        Err(e) => {
            error!("Failed to get request time-series: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

/// GET /api/v2/analytics/latency
///
/// Get latency trends (percentiles over time)
#[derive(Debug, Serialize)]
pub struct LatencyResponse {
    pub trends: Vec<LatencyTrendData>,
}

#[derive(Debug, Serialize)]
pub struct LatencyTrendData {
    pub timestamp: i64,
    pub p50: f64,
    pub p95: f64,
    pub p99: f64,
    pub avg: f64,
    pub min: f64,
    pub max: f64,
}

pub async fn get_latency_trends(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<AnalyticsQuery>,
) -> Result<Json<ApiResponse<LatencyResponse>>, StatusCode> {
    debug!("Fetching latency trends");

    let filter = query.to_filter();

    match state.db.get_latency_trends(&filter).await {
        Ok(trends) => {
            let trend_data = trends
                .into_iter()
                .map(|t| LatencyTrendData {
                    timestamp: t.timestamp,
                    p50: t.p50,
                    p95: t.p95,
                    p99: t.p99,
                    avg: t.avg,
                    min: t.min,
                    max: t.max,
                })
                .collect();

            Ok(Json(ApiResponse::success(LatencyResponse { trends: trend_data })))
        }
        Err(e) => {
            error!("Failed to get latency trends: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

/// GET /api/v2/analytics/errors
///
/// Get error summary (grouped by type and category)
#[derive(Debug, Serialize)]
pub struct ErrorResponse {
    pub errors: Vec<ErrorSummaryData>,
}

#[derive(Debug, Serialize)]
pub struct ErrorSummaryData {
    pub error_type: String,
    pub error_category: String,
    pub count: i64,
    pub endpoints: Vec<String>,
    pub last_occurrence: String,
}

pub async fn get_error_summary(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<AnalyticsQuery>,
) -> Result<Json<ApiResponse<ErrorResponse>>, StatusCode> {
    debug!("Fetching error summary");

    let filter = query.to_filter();

    match state.db.get_error_summary(&filter, query.limit).await {
        Ok(errors) => {
            let error_data = errors
                .into_iter()
                .map(|e| ErrorSummaryData {
                    error_type: e.error_type,
                    error_category: e.error_category,
                    count: e.count,
                    endpoints: e.endpoints,
                    last_occurrence: e.last_occurrence.to_rfc3339(),
                })
                .collect();

            Ok(Json(ApiResponse::success(ErrorResponse { errors: error_data })))
        }
        Err(e) => {
            error!("Failed to get error summary: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

/// GET /api/v2/analytics/endpoints
///
/// Get top endpoints by traffic
#[derive(Debug, Serialize)]
pub struct EndpointsResponse {
    pub endpoints: Vec<EndpointData>,
}

#[derive(Debug, Serialize)]
pub struct EndpointData {
    pub endpoint: String,
    pub protocol: String,
    pub method: Option<String>,
    pub total_requests: i64,
    pub total_errors: i64,
    pub error_rate: f64,
    pub avg_latency_ms: f64,
    pub p95_latency_ms: f64,
    pub bytes_sent: i64,
    pub bytes_received: i64,
}

pub async fn get_top_endpoints(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<AnalyticsQuery>,
) -> Result<Json<ApiResponse<EndpointsResponse>>, StatusCode> {
    debug!("Fetching top {} endpoints", query.limit);

    match state.db.get_top_endpoints(query.limit, query.workspace_id.as_deref()).await {
        Ok(endpoints) => {
            let endpoint_data = endpoints
                .into_iter()
                .map(|e| {
                    let error_rate = if e.total_requests > 0 {
                        (e.total_errors as f64 / e.total_requests as f64) * 100.0
                    } else {
                        0.0
                    };

                    EndpointData {
                        endpoint: e.endpoint,
                        protocol: e.protocol,
                        method: e.method,
                        total_requests: e.total_requests,
                        total_errors: e.total_errors,
                        error_rate,
                        avg_latency_ms: e.avg_latency_ms.unwrap_or(0.0),
                        p95_latency_ms: e.p95_latency_ms.unwrap_or(0.0),
                        bytes_sent: e.total_bytes_sent,
                        bytes_received: e.total_bytes_received,
                    }
                })
                .collect();

            Ok(Json(ApiResponse::success(EndpointsResponse {
                endpoints: endpoint_data,
            })))
        }
        Err(e) => {
            error!("Failed to get top endpoints: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

/// GET /api/v2/analytics/protocols
///
/// Get traffic breakdown by protocol
#[derive(Debug, Serialize)]
pub struct ProtocolsResponse {
    pub protocols: Vec<ProtocolData>,
}

#[derive(Debug, Serialize)]
pub struct ProtocolData {
    pub protocol: String,
    pub request_count: i64,
    pub error_count: i64,
    pub avg_latency_ms: f64,
}

pub async fn get_protocol_breakdown(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<AnalyticsQuery>,
) -> Result<Json<ApiResponse<ProtocolsResponse>>, StatusCode> {
    debug!("Fetching protocol breakdown");

    match state.db.get_top_protocols(10, query.workspace_id.as_deref()).await {
        Ok(protocols) => {
            let protocol_data = protocols
                .into_iter()
                .map(|p| ProtocolData {
                    protocol: p.protocol,
                    request_count: p.request_count,
                    error_count: p.error_count,
                    avg_latency_ms: p.avg_latency_ms,
                })
                .collect();

            Ok(Json(ApiResponse::success(ProtocolsResponse {
                protocols: protocol_data,
            })))
        }
        Err(e) => {
            error!("Failed to get protocol breakdown: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

/// GET /api/v2/analytics/traffic-patterns
///
/// Get traffic patterns for heatmap visualization
#[derive(Debug, Serialize)]
pub struct TrafficPatternsResponse {
    pub patterns: Vec<TrafficPatternData>,
}

#[derive(Debug, Serialize)]
pub struct TrafficPatternData {
    pub date: String,
    pub hour: i32,
    pub day_of_week: i32,
    pub request_count: i64,
    pub error_count: i64,
    pub avg_latency_ms: f64,
}

#[derive(Debug, Deserialize)]
pub struct TrafficPatternsQuery {
    #[serde(default = "default_pattern_days")]
    pub days: i64,
    pub workspace_id: Option<String>,
}

fn default_pattern_days() -> i64 {
    30
}

pub async fn get_traffic_patterns(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<TrafficPatternsQuery>,
) -> Result<Json<ApiResponse<TrafficPatternsResponse>>, StatusCode> {
    debug!("Fetching traffic patterns for {} days", query.days);

    match state.db.get_traffic_patterns(query.days, query.workspace_id.as_deref()).await {
        Ok(patterns) => {
            let pattern_data = patterns
                .into_iter()
                .map(|p| TrafficPatternData {
                    date: p.date,
                    hour: p.hour,
                    day_of_week: p.day_of_week,
                    request_count: p.request_count,
                    error_count: p.error_count,
                    avg_latency_ms: p.avg_latency_ms.unwrap_or(0.0),
                })
                .collect();

            Ok(Json(ApiResponse::success(TrafficPatternsResponse {
                patterns: pattern_data,
            })))
        }
        Err(e) => {
            error!("Failed to get traffic patterns: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

/// GET /api/v2/analytics/export/csv
///
/// Export analytics data to CSV format
pub async fn export_csv(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<AnalyticsQuery>,
) -> Result<(StatusCode, String), StatusCode> {
    debug!("Exporting analytics to CSV");

    let filter = query.to_filter();
    let mut buffer = Vec::new();

    match state.db.export_to_csv(&mut buffer, &filter).await {
        Ok(_) => {
            let csv_data = String::from_utf8(buffer).unwrap_or_default();
            Ok((StatusCode::OK, csv_data))
        }
        Err(e) => {
            error!("Failed to export to CSV: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

/// GET /api/v2/analytics/export/json
///
/// Export analytics data to JSON format
pub async fn export_json(
    State(state): State<AnalyticsV2State>,
    Query(query): Query<AnalyticsQuery>,
) -> Result<(StatusCode, String), StatusCode> {
    debug!("Exporting analytics to JSON");

    let filter = query.to_filter();

    match state.db.export_to_json(&filter).await {
        Ok(json) => Ok((StatusCode::OK, json)),
        Err(e) => {
            error!("Failed to export to JSON: {}", e);
            Err(StatusCode::INTERNAL_SERVER_ERROR)
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_analytics_query_to_filter() {
        let query = AnalyticsQuery {
            start_time: Some(100),
            end_time: Some(200),
            duration: 3600,
            protocol: Some("HTTP".to_string()),
            endpoint: Some("/api/test".to_string()),
            method: Some("GET".to_string()),
            status_code: Some(200),
            workspace_id: None,
            environment: Some("prod".to_string()),
            limit: 50,
            granularity: "minute".to_string(),
        };

        let filter = query.to_filter();
        assert_eq!(filter.start_time, Some(100));
        assert_eq!(filter.end_time, Some(200));
        assert_eq!(filter.protocol, Some("HTTP".to_string()));
        assert_eq!(filter.limit, Some(50));
    }

    #[test]
    fn test_granularity_parsing() {
        let query = AnalyticsQuery {
            start_time: None,
            end_time: None,
            duration: 3600,
            protocol: None,
            endpoint: None,
            method: None,
            status_code: None,
            workspace_id: None,
            environment: None,
            limit: 100,
            granularity: "hour".to_string(),
        };

        assert_eq!(query.get_granularity(), Granularity::Hour);
    }
}